vendor: 6,124 bytes, lines 1-9
1var oA=e=>{throw TypeError(e)};var mg=(e,n,r)=>n.has(e)||oA("Cannot "+r);var se=(e,n,r)=>(mg(e,n,"read from private field"),r?r.call(e):n.get(e)),$e=(e,n,r)=>n.has(e)?oA("Cannot add the same private member more than once"):n instanceof WeakSet?n.add(e):n.set(e,r),ze=(e,n,r,s)=>(mg(e,n,"write to private field"),s?s.call(e,r):n.set(e,r),r),Qe=(e,n,r)=>(mg(e,n,"access private method"),r);var Nu=(e,n,r,s)=>({set _(i){ze(e,n,i,r)},get _(){return se(e,n,s)}});function b5(e,n){for(var r=0;r<n.length;r++){const s=n[r];if(typeof s!="string"&&!Array.isArray(s)){for(const i in s)if(i!=="default"&&!(i in e)){const o=Object.getOwnPropertyDescriptor(s,i);o&&Object.defineProperty(e,i,o.get?o:{enumerable:!0,get:()=>s[i]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))s(i);new MutationObserver(i=>{for(const o of i)if(o.type==="childList")for(const a of o.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&s(a)}).observe(document,{childList:!0,subtree:!0});function r(i){const o={};return i.integrity&&(o.integrity=i.integrity),i.referrerPolicy&&(o.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?o.credentials="include":i.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function s(i){if(i.ep)return;i.ep=!0;const o=r(i);fetch(i.href,o)}})();function C2(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var T2={exports:{}},yf={},z2={exports:{}},at={};/** 2 * @license React 3 * react.production.min.js 4 * 5 * Copyright (c) Facebook, Inc. and its affiliates. 6 * 7 * This source code is licensed under the MIT license found in the 8 * LICENSE file in the root directory of this source tree. 9 */var cu=Symbol.for("react.element"),A5=Symbol.for("react.portal"),v5=Symbol.for("react.fragment"),_5=Symbol.for("react.strict_mode"),j5=Symbol.for("react.profiler"),w5=Symbol.for("react.provider"),S5=Symbol.for("react.context"),k5=Symbol.for("react.forward_ref"),C5=Symbol.for("react.suspense"),T5=Symbol.for("react.memo"),z5=Symbol.for("react.lazy"),aA=Symbol.iterator;function N5(e){return e===null||typeof e!="object"?null:(e=aA&&e[aA]||e["@@iterator"],typeof e=="function"?e:null)}var N2={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},R2=Object.assign,E2={};function od(e,n,r){this.props=e,this.context=n,this.refs=E2,this.updater=r||N2}od.prototype.isReactComponent={};od.prototype.setState=function(e,n){if(typeof e!="object"&&typeof e!="function"&&e!=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,e,n,"setState")};od.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function P2(){}P2.prototype=od.prototype;function Vy(e,n,r){this.props=e,this.context=n,this.refs=E2,this.updater=r||N2}var Zy=Vy.prototype=new P2;Zy.constructor=Vy;R2(Zy,od.prototype);Zy.isPureReactComponent=!0;var lA=Array.isArray,q2=Object.prototype.hasOwnProperty,Ky={current:null},D2={key:!0,ref:!0,__self:!0,__source:!0};function O2(e,n,r){var s,i={},o=null,a=null;if(n!=null)for(s in n.ref!==void 0&&(a=n.ref),n.key!==void 0&&(o=""+n.key),n)q2.call(n,s)&&!D2.hasOwnProperty(s)&&(i[s]=n[s]);var l=arguments.length-2;if(l===1)i.children=r;else if(1<l){for(var d=Array(l),c=0;c<l;c++)d[c]=arguments[c+2];i.children=d}if(e&&e.defaultProps)for(s in l=e.defaultProps,l)i[s]===void 0&&(i[s]=l[s]);return{$$typeof:cu,type:e,key:o,ref:a,props:i,_owner:Ky.current}}function R5(e,n){return{$$typeof:cu,type:e.type,key:n,ref:e.ref,props:e.props,_owner:e._owner}}function Yy(e){return typeof e=="object"&&e!==null&&e.$$typeof===cu}function E5(e){var n={"=":"=0",":":"=2"};return"$"+e.replace(/[=:]/g,function(r){return n[r]})}var dA=/\/+/g;function xg(e,n){return typeof e=="object"&&e!==null&&e.key!=null?E5(""+e.key):n.toString(36)}function Fp(e,n,r,s,i){var o=typeof e;(o==="undefined"||o==="boolean")&&(e=null);var a=!1;if(e===null)a=!0;else switch(o){case"string":case"number":a=!0;break;case"object":switch(e.$$typeof){case cu:case A5:a=!0}}if(a)return a=e,i=i(a),e=s===""?"."+xg(a,0):s,lA(i)?(r="",e!=null&&(r=e.replace(dA,"$&/")+"/"),Fp(i,n,r,"",function(c){return c})):i!=null&&(Yy(i)&&(i=R5(i,r+(!i.key||a&&a.key===i.key?"":(""+i.key).replace(dA,"$&/")+"/")+e)),n.push(i)),1;if(a=0,s=s===""?".":s+":",lA(e))for(var l=0;l<e.length;l++){o=e[l];var d=s+xg(o,l);a+=Fp(o,n,r,d,i)}else if(d=N5(e),typeof d=="function")for(e=d.call(e),l=0;!(o=e.next()).done;)o=o.value,d=s+xg(o,l++),a+=Fp(o,n,r,d,i);else if(o==="object")throw n=String(e),Error("Objects are not valid as a React child (found: "+(n==="[object Object]"?"object with keys {"+Object.keys(e).join(", ")+"}":n)+"). If you meant to render a collection of children, use an array instead.");return a}function Ru(e,n,r){if(e==null)return e;var s=[],i=0;return Fp(e,s,"","",function(o){return n.call(r,o,i++)}),s}function P5(e){if(e._status===-1){var n=e._result;n=n(),n.then(function(r){(e._status===0||e._status===-1)&&(e._status=1,e._result=r)},function(r){(e._status===0||e._status===-1)&&(e._status=2,e._result=r)}),e._status===-1&&(e._status=0,e._result=n)}if(e._status===1)return e._result.default;throw e._result}var Un={current:null},Bp={transition:null},q5={ReactCurrentDispatcher:Un,ReactCurrentBatchConfig:Bp,ReactCurrentOwner:Ky};function I2(){throw Error("act(...) is not supported in production builds of React.")}at.Children={map:Ru,forEach:function(e,n,r){Ru(e,function(){n.apply(this,arguments)},r)},count:function(e){var n=0;return Ru(e,function(){n++}),n},toArray:function(e){return Ru(e,function(n){return n})||[]},only:function(e){if(!Yy(e))throw Error("React.Children.only expected to receive a single React element child.");return e}};at.Component=od;at.Fragment=v5;at.Profiler=j5;at.PureComponent=Vy;at.StrictMode=_5;at.Suspense=C5;
vendor: 8,708 bytes, lines 9-33
9at.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=q5;at.act=I2;at.cloneElement=function(e,n,r){if(e==null)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+e+".");var s=R2({},e.props),i=e.key,o=e.ref,a=e._owner;if(n!=null){if(n.ref!==void 0&&(o=n.ref,a=Ky.current),n.key!==void 0&&(i=""+n.key),e.type&&e.type.defaultProps)var l=e.type.defaultProps;for(d in n)q2.call(n,d)&&!D2.hasOwnProperty(d)&&(s[d]=n[d]===void 0&&l!==void 0?l[d]:n[d])}var d=arguments.length-2;if(d===1)s.children=r;else if(1<d){l=Array(d);for(var c=0;c<d;c++)l[c]=arguments[c+2];s.children=l}return{$$typeof:cu,type:e.type,key:i,ref:o,props:s,_owner:a}};at.createContext=function(e){return e={$$typeof:S5,_currentValue:e,_currentValue2:e,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null},e.Provider={$$typeof:w5,_context:e},e.Consumer=e};at.createElement=O2;at.createFactory=function(e){var n=O2.bind(null,e);return n.type=e,n};at.createRef=function(){return{current:null}};at.forwardRef=function(e){return{$$typeof:k5,render:e}};at.isValidElement=Yy;at.lazy=function(e){return{$$typeof:z5,_payload:{_status:-1,_result:e},_init:P5}};at.memo=function(e,n){return{$$typeof:T5,type:e,compare:n===void 0?null:n}};at.startTransition=function(e){var n=Bp.transition;Bp.transition={};try{e()}finally{Bp.transition=n}};at.unstable_act=I2;at.useCallback=function(e,n){return Un.current.useCallback(e,n)};at.useContext=function(e){return Un.current.useContext(e)};at.useDebugValue=function(){};at.useDeferredValue=function(e){return Un.current.useDeferredValue(e)};at.useEffect=function(e,n){return Un.current.useEffect(e,n)};at.useId=function(){return Un.current.useId()};at.useImperativeHandle=function(e,n,r){return Un.current.useImperativeHandle(e,n,r)};at.useInsertionEffect=function(e,n){return Un.current.useInsertionEffect(e,n)};at.useLayoutEffect=function(e,n){return Un.current.useLayoutEffect(e,n)};at.useMemo=function(e,n){return Un.current.useMemo(e,n)};at.useReducer=function(e,n,r){return Un.current.useReducer(e,n,r)};at.useRef=function(e){return Un.current.useRef(e)};at.useState=function(e){return Un.current.useState(e)};at.useSyncExternalStore=function(e,n,r){return Un.current.useSyncExternalStore(e,n,r)};at.useTransition=function(){return Un.current.useTransition()};at.version="18.3.1";z2.exports=at;var g=z2.exports;const ut=C2(g),D5=b5({__proto__:null,default:ut},[g]);/** 10 * @license React 11 * react-jsx-runtime.production.min.js 12 * 13 * Copyright (c) Facebook, Inc. and its affiliates. 14 * 15 * This source code is licensed under the MIT license found in the 16 * LICENSE file in the root directory of this source tree. 17 */var O5=g,I5=Symbol.for("react.element"),L5=Symbol.for("react.fragment"),W5=Object.prototype.hasOwnProperty,$5=O5.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,M5={key:!0,ref:!0,__self:!0,__source:!0};function L2(e,n,r){var s,i={},o=null,a=null;r!==void 0&&(o=""+r),n.key!==void 0&&(o=""+n.key),n.ref!==void 0&&(a=n.ref);for(s in n)W5.call(n,s)&&!M5.hasOwnProperty(s)&&(i[s]=n[s]);if(e&&e.defaultProps)for(s in n=e.defaultProps,n)i[s]===void 0&&(i[s]=n[s]);return{$$typeof:I5,type:e,key:o,ref:a,props:i,_owner:$5.current}}yf.Fragment=L5;yf.jsx=L2;yf.jsxs=L2;T2.exports=yf;var t=T2.exports,Zm={},W2={exports:{}},_r={},$2={exports:{}},M2={};/** 18 * @license React 19 * scheduler.production.min.js 20 * 21 * Copyright (c) Facebook, Inc. and its affiliates. 22 * 23 * This source code is licensed under the MIT license found in the 24 * LICENSE file in the root directory of this source tree. 25 */(function(e){function n(k,q){var $=k.length;k.push(q);e:for(;0<$;){var I=$-1>>>1,B=k[I];if(0<i(B,q))k[I]=q,k[$]=B,$=I;else break e}}function r(k){return k.length===0?null:k[0]}function s(k){if(k.length===0)return null;var q=k[0],$=k.pop();if($!==q){k[0]=$;e:for(var I=0,B=k.length,J=B>>>1;I<J;){var ae=2*(I+1)-1,te=k[ae],U=ae+1,W=k[U];if(0>i(te,$))U<B&&0>i(W,te)?(k[I]=W,k[U]=$,I=U):(k[I]=te,k[ae]=$,I=ae);else if(U<B&&0>i(W,$))k[I]=W,k[U]=$,I=U;else break e}}return q}function i(k,q){var $=k.sortIndex-q.sortIndex;return $!==0?$:k.id-q.id}if(typeof performance=="object"&&typeof performance.now=="function"){var o=performance;e.unstable_now=function(){return o.now()}}else{var a=Date,l=a.now();e.unstable_now=function(){return a.now()-l}}var d=[],c=[],f=1,p=null,u=3,h=!1,y=!1,m=!1,b=typeof setTimeout=="function"?setTimeout:null,A=typeof clearTimeout=="function"?clearTimeout:null,v=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function x(k){for(var q=r(c);q!==null;){if(q.callback===null)s(c);else if(q.startTime<=k)s(c),q.sortIndex=q.expirationTime,n(d,q);else break;q=r(c)}}function _(k){if(m=!1,x(k),!y)if(r(d)!==null)y=!0,D(j);else{var q=r(c);q!==null&&M(_,q.startTime-k)}}function j(k,q){y=!1,m&&(m=!1,A(T),T=-1),h=!0;var $=u;try{for(x(q),p=r(d);p!==null&&(!(p.expirationTime>q)||k&&!R());){var I=p.callback;if(typeof I=="function"){p.callback=null,u=p.priorityLevel;var B=I(p.expirationTime<=q);q=e.unstable_now(),typeof B=="function"?p.callback=B:p===r(d)&&s(d),x(q)}else s(d);p=r(d)}if(p!==null)var J=!0;else{var ae=r(c);ae!==null&&M(_,ae.startTime-q),J=!1}return J}finally{p=null,u=$,h=!1}}var C=!1,S=null,T=-1,L=5,E=-1;function R(){return!(e.unstable_now()-E<L)}function N(){if(S!==null){var k=e.unstable_now();E=k;var q=!0;try{q=S(!0,k)}finally{q?O():(C=!1,S=null)}}else C=!1}var O;if(typeof v=="function")O=function(){v(N)};else if(typeof MessageChannel<"u"){var z=new MessageChannel,P=z.port2;z.port1.onmessage=N,O=function(){P.postMessage(null)}}else O=function(){b(N,0)};function D(k){S=k,C||(C=!0,O())}function M(k,q){T=b(function(){k(e.unstable_now())},q)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(k){k.callback=null},e.unstable_continueExecution=function(){y||h||(y=!0,D(j))},e.unstable_forceFrameRate=function(k){0>k||125<k?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):L=0<k?Math.floor(1e3/k):5},e.unstable_getCurrentPriorityLevel=function(){return u},e.unstable_getFirstCallbackNode=function(){return r(d)},e.unstable_next=function(k){switch(u){case 1:case 2:case 3:var q=3;break;default:q=u}var $=u;u=q;try{return k()}finally{u=$}},e.unstable_pauseExecution=function(){},e.unstable_requestPaint=function(){},e.unstable_runWithPriority=function(k,q){switch(k){case 1:case 2:case 3:case 4:case 5:break;default:k=3}var $=u;u=k;try{return q()}finally{u=$}},e.unstable_scheduleCallback=function(k,q,$){var I=e.unstable_now();switch(typeof $=="object"&&$!==null?($=$.delay,$=typeof $=="number"&&0<$?I+$:I):$=I,k){case 1:var B=-1;break;case 2:B=250;break;case 5:B=1073741823;break;case 4:B=1e4;break;default:B=5e3}return B=$+B,k={id:f++,callback:q,priorityLevel:k,startTime:$,expirationTime:B,sortIndex:-1},$>I?(k.sortIndex=$,n(c,k),r(d)===null&&k===r(c)&&(m?(A(T),T=-1):m=!0,M(_,$-I))):(k.sortIndex=B,n(d,k),y||h||(y=!0,D(j))),k},e.unstable_shouldYield=R,e.unstable_wrapCallback=function(k){var q=u;return function(){var $=u;u=q;try{return k.apply(this,arguments)}finally{u=$}}}})(M2);$2.exports=M2;var F5=$2.exports;/** 26 * @license React 27 * react-dom.production.min.js 28 * 29 * Copyright (c) Facebook, Inc. and its affiliates. 30 * 31 * This source code is licensed under the MIT license found in the 32 * LICENSE file in the root directory of this source tree. 33 */var B5=g,vr=F5;function Se(e){for(var n="https://reactjs.org/docs/error-decoder.html?invariant="+e,r=1;r<arguments.length;r++)n+="&args[]="+encodeURIComponent(arguments[r]);return"Minified React error #"+e+"; visit "+n+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var F2=new Set,_c={};function va(e,n){Fl(e,n),Fl(e+"Capture",n)}function Fl(e,n){for(_c[e]=n,e=0;e<n.length;e++)F2.add(n[e])}var Gs=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Km=Object.prototype.hasOwnProperty,U5=/^[: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]*$/,cA={},uA={};function H5(e){return Km.call(uA,e)?!0:Km.call(cA,e)?!1:U5.test(e)?uA[e]=!0:(cA[e]=!0,!1)}
vendor: 4,304 bytes, line 33
33function V5(e,n,r,s){if(r!==null&&r.type===0)return!1;switch(typeof n){case"function":case"symbol":return!0;case"boolean":return s?!1:r!==null?!r.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function Z5(e,n,r,s){if(n===null||typeof n>"u"||V5(e,n,r,s))return!0;if(s)return!1;if(r!==null)switch(r.type){case 3:return!n;case 4:return n===!1;case 5:return isNaN(n);case 6:return isNaN(n)||1>n}return!1}function Hn(e,n,r,s,i,o,a){this.acceptsBooleans=n===2||n===3||n===4,this.attributeName=s,this.attributeNamespace=i,this.mustUseProperty=r,this.propertyName=e,this.type=n,this.sanitizeURL=o,this.removeEmptyString=a}var Sn={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){Sn[e]=new Hn(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var n=e[0];Sn[n]=new Hn(n,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){Sn[e]=new Hn(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){Sn[e]=new Hn(e,2,!1,e,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(e){Sn[e]=new Hn(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){Sn[e]=new Hn(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){Sn[e]=new Hn(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){Sn[e]=new Hn(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){Sn[e]=new Hn(e,5,!1,e.toLowerCase(),null,!1,!1)});var Xy=/[\-:]([a-z])/g;function Gy(e){return e[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(e){var n=e.replace(Xy,Gy);Sn[n]=new Hn(n,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var n=e.replace(Xy,Gy);Sn[n]=new Hn(n,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var n=e.replace(Xy,Gy);Sn[n]=new Hn(n,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){Sn[e]=new Hn(e,1,!1,e.toLowerCase(),null,!1,!1)});Sn.xlinkHref=new Hn("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){Sn[e]=new Hn(e,1,!1,e.toLowerCase(),null,!0,!0)});function Jy(e,n,r,s){var i=Sn.hasOwnProperty(n)?Sn[n]:null;(i!==null?i.type!==0:s||!(2<n.length)||n[0]!=="o"&&n[0]!=="O"||n[1]!=="n"&&n[1]!=="N")&&(Z5(n,r,i,s)&&(r=null),s||i===null?H5(n)&&(r===null?e.removeAttribute(n):e.setAttribute(n,""+r)):i.mustUseProperty?e[i.propertyName]=r===null?i.type===3?!1:"":r:(n=i.attributeName,s=i.attributeNamespace,r===null?e.removeAttribute(n):(i=i.type,r=i===3||i===4&&r===!0?"":""+r,s?e.setAttributeNS(s,n,r):e.setAttribute(n,r))))}
vendor: 1,109 bytes, lines 33-34
33var oi=B5.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,Eu=Symbol.for("react.element"),nl=Symbol.for("react.portal"),rl=Symbol.for("react.fragment"),Qy=Symbol.for("react.strict_mode"),Ym=Symbol.for("react.profiler"),B2=Symbol.for("react.provider"),U2=Symbol.for("react.context"),eb=Symbol.for("react.forward_ref"),Xm=Symbol.for("react.suspense"),Gm=Symbol.for("react.suspense_list"),tb=Symbol.for("react.memo"),Si=Symbol.for("react.lazy"),H2=Symbol.for("react.offscreen"),pA=Symbol.iterator;function wd(e){return e===null||typeof e!="object"?null:(e=pA&&e[pA]||e["@@iterator"],typeof e=="function"?e:null)}var Lt=Object.assign,yg;function Qd(e){if(yg===void 0)try{throw Error()}catch(r){var n=r.stack.trim().match(/\n( *(at )?)/);yg=n&&n[1]||""}return` 34`+yg+e}var bg=!1;function Ag(e,n){if(!e||bg)return"";bg=!0;var r=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(n)if(n=function(){throw Error()},Object.defineProperty(n.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(n,[])}catch(c){var s=c}Reflect.construct(e,[],n)}
vendor: 14,198 bytes, lines 34-37
34else{try{n.call()}catch(c){s=c}e.call(n.prototype)}else{try{throw Error()}catch(c){s=c}e()}}catch(c){if(c&&s&&typeof c.stack=="string"){for(var i=c.stack.split(` 35`),o=s.stack.split(` 36`),a=i.length-1,l=o.length-1;1<=a&&0<=l&&i[a]!==o[l];)l--;for(;1<=a&&0<=l;a--,l--)if(i[a]!==o[l]){if(a!==1||l!==1)do if(a--,l--,0>l||i[a]!==o[l]){var d=` 37`+i[a].replace(" at new "," at ");return e.displayName&&d.includes("<anonymous>")&&(d=d.replace("<anonymous>",e.displayName)),d}while(1<=a&&0<=l);break}}}finally{bg=!1,Error.prepareStackTrace=r}return(e=e?e.displayName||e.name:"")?Qd(e):""}function K5(e){switch(e.tag){case 5:return Qd(e.type);case 16:return Qd("Lazy");case 13:return Qd("Suspense");case 19:return Qd("SuspenseList");case 0:case 2:case 15:return e=Ag(e.type,!1),e;case 11:return e=Ag(e.type.render,!1),e;case 1:return e=Ag(e.type,!0),e;default:return""}}function Jm(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case rl:return"Fragment";case nl:return"Portal";case Ym:return"Profiler";case Qy:return"StrictMode";case Xm:return"Suspense";case Gm:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case U2:return(e.displayName||"Context")+".Consumer";case B2:return(e._context.displayName||"Context")+".Provider";case eb:var n=e.render;return e=e.displayName,e||(e=n.displayName||n.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case tb:return n=e.displayName||null,n!==null?n:Jm(e.type)||"Memo";case Si:n=e._payload,e=e._init;try{return Jm(e(n))}catch{}}return null}function Y5(e){var n=e.type;switch(e.tag){case 24:return"Cache";case 9:return(n.displayName||"Context")+".Consumer";case 10:return(n._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=n.render,e=e.displayName||e.name||"",n.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return n;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return Jm(n);case 8:return n===Qy?"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 n=="function")return n.displayName||n.name||null;if(typeof n=="string")return n}return null}function oo(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function V2(e){var n=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(n==="checkbox"||n==="radio")}function X5(e){var n=V2(e)?"checked":"value",r=Object.getOwnPropertyDescriptor(e.constructor.prototype,n),s=""+e[n];if(!e.hasOwnProperty(n)&&typeof r<"u"&&typeof r.get=="function"&&typeof r.set=="function"){var i=r.get,o=r.set;return Object.defineProperty(e,n,{configurable:!0,get:function(){return i.call(this)},set:function(a){s=""+a,o.call(this,a)}}),Object.defineProperty(e,n,{enumerable:r.enumerable}),{getValue:function(){return s},setValue:function(a){s=""+a},stopTracking:function(){e._valueTracker=null,delete e[n]}}}}function Pu(e){e._valueTracker||(e._valueTracker=X5(e))}function Z2(e){if(!e)return!1;var n=e._valueTracker;if(!n)return!0;var r=n.getValue(),s="";return e&&(s=V2(e)?e.checked?"true":"false":e.value),e=s,e!==r?(n.setValue(e),!0):!1}function xh(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function Qm(e,n){var r=n.checked;return Lt({},n,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:r??e._wrapperState.initialChecked})}function hA(e,n){var r=n.defaultValue==null?"":n.defaultValue,s=n.checked!=null?n.checked:n.defaultChecked;r=oo(n.value!=null?n.value:r),e._wrapperState={initialChecked:s,initialValue:r,controlled:n.type==="checkbox"||n.type==="radio"?n.checked!=null:n.value!=null}}function K2(e,n){n=n.checked,n!=null&&Jy(e,"checked",n,!1)}function ex(e,n){K2(e,n);var r=oo(n.value),s=n.type;if(r!=null)s==="number"?(r===0&&e.value===""||e.value!=r)&&(e.value=""+r):e.value!==""+r&&(e.value=""+r);else if(s==="submit"||s==="reset"){e.removeAttribute("value");return}n.hasOwnProperty("value")?tx(e,n.type,r):n.hasOwnProperty("defaultValue")&&tx(e,n.type,oo(n.defaultValue)),n.checked==null&&n.defaultChecked!=null&&(e.defaultChecked=!!n.defaultChecked)}function fA(e,n,r){if(n.hasOwnProperty("value")||n.hasOwnProperty("defaultValue")){var s=n.type;if(!(s!=="submit"&&s!=="reset"||n.value!==void 0&&n.value!==null))return;n=""+e._wrapperState.initialValue,r||n===e.value||(e.value=n),e.defaultValue=n}r=e.name,r!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,r!==""&&(e.name=r)}function tx(e,n,r){(n!=="number"||xh(e.ownerDocument)!==e)&&(r==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+r&&(e.defaultValue=""+r))}var ec=Array.isArray;function bl(e,n,r,s){if(e=e.options,n){n={};for(var i=0;i<r.length;i++)n["$"+r[i]]=!0;for(r=0;r<e.length;r++)i=n.hasOwnProperty("$"+e[r].value),e[r].selected!==i&&(e[r].selected=i),i&&s&&(e[r].defaultSelected=!0)}else{for(r=""+oo(r),n=null,i=0;i<e.length;i++){if(e[i].value===r){e[i].selected=!0,s&&(e[i].defaultSelected=!0);return}n!==null||e[i].disabled||(n=e[i])}n!==null&&(n.selected=!0)}}function nx(e,n){if(n.dangerouslySetInnerHTML!=null)throw Error(Se(91));return Lt({},n,{value:void 0,defaultValue:void 0,children:""+e._wrapperState.initialValue})}function gA(e,n){var r=n.value;if(r==null){if(r=n.children,n=n.defaultValue,r!=null){if(n!=null)throw Error(Se(92));if(ec(r)){if(1<r.length)throw Error(Se(93));r=r[0]}n=r}n==null&&(n=""),r=n}e._wrapperState={initialValue:oo(r)}}function Y2(e,n){var r=oo(n.value),s=oo(n.defaultValue);r!=null&&(r=""+r,r!==e.value&&(e.value=r),n.defaultValue==null&&e.defaultValue!==r&&(e.defaultValue=r)),s!=null&&(e.defaultValue=""+s)}function mA(e){var n=e.textContent;n===e._wrapperState.initialValue&&n!==""&&n!==null&&(e.value=n)}function X2(e){switch(e){case"svg":return"http://www.w3.org/2000/svg";case"math":return"http://www.w3.org/1998/Math/MathML";default:return"http://www.w3.org/1999/xhtml"}}function rx(e,n){return e==null||e==="http://www.w3.org/1999/xhtml"?X2(n):e==="http://www.w3.org/2000/svg"&&n==="foreignObject"?"http://www.w3.org/1999/xhtml":e}var qu,G2=function(e){return typeof MSApp<"u"&&MSApp.execUnsafeLocalFunction?function(n,r,s,i){MSApp.execUnsafeLocalFunction(function(){return e(n,r,s,i)})}:e}(function(e,n){if(e.namespaceURI!=="http://www.w3.org/2000/svg"||"innerHTML"in e)e.innerHTML=n;else{for(qu=qu||document.createElement("div"),qu.innerHTML="<svg>"+n.valueOf().toString()+"</svg>",n=qu.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;n.firstChild;)e.appendChild(n.firstChild)}});function jc(e,n){if(n){var r=e.firstChild;if(r&&r===e.lastChild&&r.nodeType===3){r.nodeValue=n;return}}e.textContent=n}var lc={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},G5=["Webkit","ms","Moz","O"];Object.keys(lc).forEach(function(e){G5.forEach(function(n){n=n+e.charAt(0).toUpperCase()+e.substring(1),lc[n]=lc[e]})});function J2(e,n,r){return n==null||typeof n=="boolean"||n===""?"":r||typeof n!="number"||n===0||lc.hasOwnProperty(e)&&lc[e]?(""+n).trim():n+"px"}function Q2(e,n){e=e.style;for(var r in n)if(n.hasOwnProperty(r)){var s=r.indexOf("--")===0,i=J2(r,n[r],s);r==="float"&&(r="cssFloat"),s?e.setProperty(r,i):e[r]=i}}var J5=Lt({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 sx(e,n){if(n){if(J5[e]&&(n.children!=null||n.dangerouslySetInnerHTML!=null))throw Error(Se(137,e));if(n.dangerouslySetInnerHTML!=null){if(n.children!=null)throw Error(Se(60));if(typeof n.dangerouslySetInnerHTML!="object"||!("__html"in n.dangerouslySetInnerHTML))throw Error(Se(61))}if(n.style!=null&&typeof n.style!="object")throw Error(Se(62))}}function ix(e,n){if(e.indexOf("-")===-1)return typeof n.is=="string";switch(e){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 ox=null;function nb(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var ax=null,Al=null,vl=null;function xA(e){if(e=hu(e)){if(typeof ax!="function")throw Error(Se(280));var n=e.stateNode;n&&(n=jf(n),ax(e.stateNode,e.type,n))}}function ew(e){Al?vl?vl.push(e):vl=[e]:Al=e}function tw(){if(Al){var e=Al,n=vl;if(vl=Al=null,xA(e),n)for(e=0;e<n.length;e++)xA(n[e])}}function nw(e,n){return e(n)}function rw(){}var vg=!1;function sw(e,n,r){if(vg)return e(n,r);vg=!0;try{return nw(e,n,r)}finally{vg=!1,(Al!==null||vl!==null)&&(rw(),tw())}}function wc(e,n){var r=e.stateNode;if(r===null)return null;var s=jf(r);if(s===null)return null;r=s[n];e:switch(n){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(s=!s.disabled)||(e=e.type,s=!(e==="button"||e==="input"||e==="select"||e==="textarea")),e=!s;break e;default:e=!1}if(e)return null;if(r&&typeof r!="function")throw Error(Se(231,n,typeof r));return r}var lx=!1;if(Gs)try{var Sd={};Object.defineProperty(Sd,"passive",{get:function(){lx=!0}}),window.addEventListener("test",Sd,Sd),window.removeEventListener("test",Sd,Sd)}catch{lx=!1}function Q5(e,n,r,s,i,o,a,l,d){var c=Array.prototype.slice.call(arguments,3);try{n.apply(r,c)}catch(f){this.onError(f)}}var dc=!1,yh=null,bh=!1,dx=null,e6={onError:function(e){dc=!0,yh=e}};function t6(e,n,r,s,i,o,a,l,d){dc=!1,yh=null,Q5.apply(e6,arguments)}function n6(e,n,r,s,i,o,a,l,d){if(t6.apply(this,arguments),dc){if(dc){var c=yh;dc=!1,yh=null}else throw Error(Se(198));bh||(bh=!0,dx=c)}}function _a(e){var n=e,r=e;if(e.alternate)for(;n.return;)n=n.return;else{e=n;do n=e,n.flags&4098&&(r=n.return),e=n.return;while(e)}return n.tag===3?r:null}function iw(e){if(e.tag===13){var n=e.memoizedState;if(n===null&&(e=e.alternate,e!==null&&(n=e.memoizedState)),n!==null)return n.dehydrated}return null}function yA(e){if(_a(e)!==e)throw Error(Se(188))}function r6(e){var n=e.alternate;if(!n){if(n=_a(e),n===null)throw Error(Se(188));return n!==e?null:e}for(var r=e,s=n;;){var i=r.return;if(i===null)break;var o=i.alternate;if(o===null){if(s=i.return,s!==null){r=s;continue}break}if(i.child===o.child){for(o=i.child;o;){if(o===r)return yA(i),e;if(o===s)return yA(i),n;o=o.sibling}throw Error(Se(188))}if(r.return!==s.return)r=i,s=o;else{for(var a=!1,l=i.child;l;){if(l===r){a=!0,r=i,s=o;break}if(l===s){a=!0,s=i,r=o;break}l=l.sibling}if(!a){for(l=o.child;l;){if(l===r){a=!0,r=o,s=i;break}if(l===s){a=!0,s=o,r=i;break}l=l.sibling}if(!a)throw Error(Se(189))}}if(r.alternate!==s)throw Error(Se(190))}if(r.tag!==3)throw Error(Se(188));return r.stateNode.current===r?e:n}function ow(e){return e=r6(e),e!==null?aw(e):null}function aw(e){if(e.tag===5||e.tag===6)return e;for(e=e.child;e!==null;){var n=aw(e);if(n!==null)return n;e=e.sibling}return null}var lw=vr.unstable_scheduleCallback,bA=vr.unstable_cancelCallback,s6=vr.unstable_shouldYield,i6=vr.unstable_requestPaint,Qt=vr.unstable_now,o6=vr.unstable_getCurrentPriorityLevel,rb=vr.unstable_ImmediatePriority,dw=vr.unstable_UserBlockingPriority,Ah=vr.unstable_NormalPriority,a6=vr.unstable_LowPriority,cw=vr.unstable_IdlePriority,bf=null,ws=null;function l6(e){if(ws&&typeof ws.onCommitFiberRoot=="function")try{ws.onCommitFiberRoot(bf,e,void 0,(e.current.flags&128)===128)}catch{}}var Qr=Math.clz32?Math.clz32:u6,d6=Math.log,c6=Math.LN2;function u6(e){return e>>>=0,e===0?32:31-(d6(e)/c6|0)|0}var Du=64,Ou=4194304;function tc(e){switch(e&-e){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 e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function vh(e,n){var r=e.pendingLanes;if(r===0)return 0;var s=0,i=e.suspendedLanes,o=e.pingedLanes,a=r&268435455;if(a!==0){var l=a&~i;l!==0?s=tc(l):(o&=a,o!==0&&(s=tc(o)))}else a=r&~i,a!==0?s=tc(a):o!==0&&(s=tc(o));if(s===0)return 0;if(n!==0&&n!==s&&!(n&i)&&(i=s&-s,o=n&-n,i>=o||i===16&&(o&4194240)!==0))return n;if(s&4&&(s|=r&16),n=e.entangledLanes,n!==0)for(e=e.entanglements,n&=s;0<n;)r=31-Qr(n),i=1<<r,s|=e[r],n&=~i;return s}function p6(e,n){switch(e){case 1:case 2:case 4:return n+250;case 8:case 16:case 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 n+5e3;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return-1;case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function h6(e,n){for(var r=e.suspendedLanes,s=e.pingedLanes,i=e.expirationTimes,o=e.pendingLanes;0<o;){var a=31-Qr(o),l=1<<a,d=i[a];d===-1?(!(l&r)||l&s)&&(i[a]=p6(l,n)):d<=n&&(e.expiredLanes|=l),o&=~l}}function cx(e){return e=e.pendingLanes&-1073741825,e!==0?e:e&1073741824?1073741824:0}function uw(){var e=Du;return Du<<=1,!(Du&4194240)&&(Du=64),e}function _g(e){for(var n=[],r=0;31>r;r++)n.push(e);return n}
vendor: 2,630 bytes, line 37
37function uu(e,n,r){e.pendingLanes|=n,n!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,n=31-Qr(n),e[n]=r}function f6(e,n){var r=e.pendingLanes&~n;e.pendingLanes=n,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=n,e.mutableReadLanes&=n,e.entangledLanes&=n,n=e.entanglements;var s=e.eventTimes;for(e=e.expirationTimes;0<r;){var i=31-Qr(r),o=1<<i;n[i]=0,s[i]=-1,e[i]=-1,r&=~o}}function sb(e,n){var r=e.entangledLanes|=n;for(e=e.entanglements;r;){var s=31-Qr(r),i=1<<s;i&n|e[s]&n&&(e[s]|=n),r&=~i}}var xt=0;function pw(e){return e&=-e,1<e?4<e?e&268435455?16:536870912:4:1}var hw,ib,fw,gw,mw,ux=!1,Iu=[],Zi=null,Ki=null,Yi=null,Sc=new Map,kc=new Map,Ti=[],g6="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset submit".split(" ");function AA(e,n){switch(e){case"focusin":case"focusout":Zi=null;break;case"dragenter":case"dragleave":Ki=null;break;case"mouseover":case"mouseout":Yi=null;break;case"pointerover":case"pointerout":Sc.delete(n.pointerId);break;case"gotpointercapture":case"lostpointercapture":kc.delete(n.pointerId)}}function kd(e,n,r,s,i,o){return e===null||e.nativeEvent!==o?(e={blockedOn:n,domEventName:r,eventSystemFlags:s,nativeEvent:o,targetContainers:[i]},n!==null&&(n=hu(n),n!==null&&ib(n)),e):(e.eventSystemFlags|=s,n=e.targetContainers,i!==null&&n.indexOf(i)===-1&&n.push(i),e)}function m6(e,n,r,s,i){switch(n){case"focusin":return Zi=kd(Zi,e,n,r,s,i),!0;case"dragenter":return Ki=kd(Ki,e,n,r,s,i),!0;case"mouseover":return Yi=kd(Yi,e,n,r,s,i),!0;case"pointerover":var o=i.pointerId;return Sc.set(o,kd(Sc.get(o)||null,e,n,r,s,i)),!0;case"gotpointercapture":return o=i.pointerId,kc.set(o,kd(kc.get(o)||null,e,n,r,s,i)),!0}return!1}function xw(e){var n=Uo(e.target);if(n!==null){var r=_a(n);if(r!==null){if(n=r.tag,n===13){if(n=iw(r),n!==null){e.blockedOn=n,mw(e.priority,function(){fw(r)});return}}else if(n===3&&r.stateNode.current.memoizedState.isDehydrated){e.blockedOn=r.tag===3?r.stateNode.containerInfo:null;return}}}e.blockedOn=null}function Up(e){if(e.blockedOn!==null)return!1;for(var n=e.targetContainers;0<n.length;){var r=px(e.domEventName,e.eventSystemFlags,n[0],e.nativeEvent);if(r===null){r=e.nativeEvent;var s=new r.constructor(r.type,r);ox=s,r.target.dispatchEvent(s),ox=null}else return n=hu(r),n!==null&&ib(n),e.blockedOn=r,!1;n.shift()}return!0}function vA(e,n,r){Up(e)&&r.delete(n)}function x6(){ux=!1,Zi!==null&&Up(Zi)&&(Zi=null),Ki!==null&&Up(Ki)&&(Ki=null),Yi!==null&&Up(Yi)&&(Y
vendor: 12,371 bytes, line 37
37i=null),Sc.forEach(vA),kc.forEach(vA)}function Cd(e,n){e.blockedOn===n&&(e.blockedOn=null,ux||(ux=!0,vr.unstable_scheduleCallback(vr.unstable_NormalPriority,x6)))}function Cc(e){function n(i){return Cd(i,e)}if(0<Iu.length){Cd(Iu[0],e);for(var r=1;r<Iu.length;r++){var s=Iu[r];s.blockedOn===e&&(s.blockedOn=null)}}for(Zi!==null&&Cd(Zi,e),Ki!==null&&Cd(Ki,e),Yi!==null&&Cd(Yi,e),Sc.forEach(n),kc.forEach(n),r=0;r<Ti.length;r++)s=Ti[r],s.blockedOn===e&&(s.blockedOn=null);for(;0<Ti.length&&(r=Ti[0],r.blockedOn===null);)xw(r),r.blockedOn===null&&Ti.shift()}var _l=oi.ReactCurrentBatchConfig,_h=!0;function y6(e,n,r,s){var i=xt,o=_l.transition;_l.transition=null;try{xt=1,ob(e,n,r,s)}finally{xt=i,_l.transition=o}}function b6(e,n,r,s){var i=xt,o=_l.transition;_l.transition=null;try{xt=4,ob(e,n,r,s)}finally{xt=i,_l.transition=o}}function ob(e,n,r,s){if(_h){var i=px(e,n,r,s);if(i===null)Eg(e,n,s,jh,r),AA(e,s);else if(m6(i,e,n,r,s))s.stopPropagation();else if(AA(e,s),n&4&&-1<g6.indexOf(e)){for(;i!==null;){var o=hu(i);if(o!==null&&hw(o),o=px(e,n,r,s),o===null&&Eg(e,n,s,jh,r),o===i)break;i=o}i!==null&&s.stopPropagation()}else Eg(e,n,s,null,r)}}var jh=null;function px(e,n,r,s){if(jh=null,e=nb(s),e=Uo(e),e!==null)if(n=_a(e),n===null)e=null;else if(r=n.tag,r===13){if(e=iw(n),e!==null)return e;e=null}else if(r===3){if(n.stateNode.current.memoizedState.isDehydrated)return n.tag===3?n.stateNode.containerInfo:null;e=null}else n!==e&&(e=null);return jh=e,null}function yw(e){switch(e){case"cancel":case"click":case"close":case"contextmenu":case"copy":case"cut":case"auxclick":case"dblclick":case"dragend":case"dragstart":case"drop":case"focusin":case"focusout":case"input":case"invalid":case"keydown":case"keypress":case"keyup":case"mousedown":case"mouseup":case"paste":case"pause":case"play":case"pointercancel":case"pointerdown":case"pointerup":case"ratechange":case"reset":case"resize":case"seeked":case"submit":case"touchcancel":case"touchend":case"touchstart":case"volumechange":case"change":case"selectionchange":case"textInput":case"compositionstart":case"compositionend":case"compositionupdate":case"beforeblur":case"afterblur":case"beforeinput":case"blur":case"fullscreenchange":case"focus":case"hashchange":case"popstate":case"select":case"selectstart":return 1;case"drag":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"mousemove":case"mouseout":case"mouseover":case"pointermove":case"pointerout":case"pointerover":case"scroll":case"toggle":case"touchmove":case"wheel":case"mouseenter":case"mouseleave":case"pointerenter":case"pointerleave":return 4;case"message":switch(o6()){case rb:return 1;case dw:return 4;case Ah:case a6:return 16;case cw:return 536870912;default:return 16}default:return 16}}var Bi=null,ab=null,Hp=null;function bw(){if(Hp)return Hp;var e,n=ab,r=n.length,s,i="value"in Bi?Bi.value:Bi.textContent,o=i.length;for(e=0;e<r&&n[e]===i[e];e++);var a=r-e;for(s=1;s<=a&&n[r-s]===i[o-s];s++);return Hp=i.slice(e,1<s?1-s:void 0)}function Vp(e){var n=e.keyCode;return"charCode"in e?(e=e.charCode,e===0&&n===13&&(e=13)):e=n,e===10&&(e=13),32<=e||e===13?e:0}function Lu(){return!0}function _A(){return!1}function jr(e){function n(r,s,i,o,a){this._reactName=r,this._targetInst=i,this.type=s,this.nativeEvent=o,this.target=a,this.currentTarget=null;for(var l in e)e.hasOwnProperty(l)&&(r=e[l],this[l]=r?r(o):o[l]);return this.isDefaultPrevented=(o.defaultPrevented!=null?o.defaultPrevented:o.returnValue===!1)?Lu:_A,this.isPropagationStopped=_A,this}return Lt(n.prototype,{preventDefault:function(){this.defaultPrevented=!0;var r=this.nativeEvent;r&&(r.preventDefault?r.preventDefault():typeof r.returnValue!="unknown"&&(r.returnValue=!1),this.isDefaultPrevented=Lu)},stopPropagation:function(){var r=this.nativeEvent;r&&(r.stopPropagation?r.stopPropagation():typeof r.cancelBubble!="unknown"&&(r.cancelBubble=!0),this.isPropagationStopped=Lu)},persist:function(){},isPersistent:Lu}),n}var ad={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},lb=jr(ad),pu=Lt({},ad,{view:0,detail:0}),A6=jr(pu),jg,wg,Td,Af=Lt({},pu,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:db,button:0,buttons:0,relatedTarget:function(e){return e.relatedTarget===void 0?e.fromElement===e.srcElement?e.toElement:e.fromElement:e.relatedTarget},movementX:function(e){return"movementX"in e?e.movementX:(e!==Td&&(Td&&e.type==="mousemove"?(jg=e.screenX-Td.screenX,wg=e.screenY-Td.screenY):wg=jg=0,Td=e),jg)},movementY:function(e){return"movementY"in e?e.movementY:wg}}),jA=jr(Af),v6=Lt({},Af,{dataTransfer:0}),_6=jr(v6),j6=Lt({},pu,{relatedTarget:0}),Sg=jr(j6),w6=Lt({},ad,{animationName:0,elapsedTime:0,pseudoElement:0}),S6=jr(w6),k6=Lt({},ad,{clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}}),C6=jr(k6),T6=Lt({},ad,{data:0}),wA=jr(T6),z6={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},N6={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},R6={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function E6(e){var n=this.nativeEvent;return n.getModifierState?n.getModifierState(e):(e=R6[e])?!!n[e]:!1}function db(){return E6}var P6=Lt({},pu,{key:function(e){if(e.key){var n=z6[e.key]||e.key;if(n!=="Unidentified")return n}return e.type==="keypress"?(e=Vp(e),e===13?"Enter":String.fromCharCode(e)):e.type==="keydown"||e.type==="keyup"?N6[e.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:db,charCode:function(e){return e.type==="keypress"?Vp(e):0},keyCode:function(e){return e.type==="keydown"||e.type==="keyup"?e.keyCode:0},which:function(e){return e.type==="keypress"?Vp(e):e.type==="keydown"||e.type==="keyup"?e.keyCode:0}}),q6=jr(P6),D6=Lt({},Af,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),SA=jr(D6),O6=Lt({},pu,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:db}),I6=jr(O6),L6=Lt({},ad,{propertyName:0,elapsedTime:0,pseudoElement:0}),W6=jr(L6),$6=Lt({},Af,{deltaX:function(e){return"deltaX"in e?e.deltaX:"wheelDeltaX"in e?-e.wheelDeltaX:0},deltaY:function(e){return"deltaY"in e?e.deltaY:"wheelDeltaY"in e?-e.wheelDeltaY:"wheelDelta"in e?-e.wheelDelta:0},deltaZ:0,deltaMode:0}),M6=jr($6),F6=[9,13,27,32],cb=Gs&&"CompositionEvent"in window,cc=null;Gs&&"documentMode"in document&&(cc=document.documentMode);var B6=Gs&&"TextEvent"in window&&!cc,Aw=Gs&&(!cb||cc&&8<cc&&11>=cc),kA=" ",CA=!1;function vw(e,n){switch(e){case"keyup":return F6.indexOf(n.keyCode)!==-1;case"keydown":return n.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function _w(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var sl=!1;function U6(e,n){switch(e){case"compositionend":return _w(n);case"keypress":return n.which!==32?null:(CA=!0,kA);case"textInput":return e=n.data,e===kA&&CA?null:e;default:return null}}function H6(e,n){if(sl)return e==="compositionend"||!cb&&vw(e,n)?(e=bw(),Hp=ab=Bi=null,sl=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(n.ctrlKey||n.altKey||n.metaKey)||n.ctrlKey&&n.altKey){if(n.char&&1<n.char.length)return n.char;if(n.which)return String.fromCharCode(n.which)}return null;case"compositionend":return Aw&&n.locale!=="ko"?null:n.data;default:return null}}var V6={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function TA(e){var n=e&&e.nodeName&&e.nodeName.toLowerCase();return n==="input"?!!V6[e.type]:n==="textarea"}function jw(e,n,r,s){ew(s),n=wh(n,"onChange"),0<n.length&&(r=new lb("onChange","change",null,r,s),e.push({event:r,listeners:n}))}var uc=null,Tc=null;function Z6(e){qw(e,0)}function vf(e){var n=al(e);if(Z2(n))return e}function K6(e,n){if(e==="change")return n}var ww=!1;if(Gs){var kg;if(Gs){var Cg="oninput"in document;if(!Cg){var zA=document.createElement("div");zA.setAttribute("oninput","return;"),Cg=typeof zA.oninput=="function"}kg=Cg}else kg=!1;ww=kg&&(!document.documentMode||9<document.documentMode)}function NA(){uc&&(uc.detachEvent("onpropertychange",Sw),Tc=uc=null)}function Sw(e){if(e.propertyName==="value"&&vf(Tc)){var n=[];jw(n,Tc,e,nb(e)),sw(Z6,n)}}function Y6(e,n,r){e==="focusin"?(NA(),uc=n,Tc=r,uc.attachEvent("onpropertychange",Sw)):e==="focusout"&&NA()}function X6(e){if(e==="selectionchange"||e==="keyup"||e==="keydown")return vf(Tc)}function G6(e,n){if(e==="click")return vf(n)}function J6(e,n){if(e==="input"||e==="change")return vf(n)}function Q6(e,n){return e===n&&(e!==0||1/e===1/n)||e!==e&&n!==n}var ts=typeof Object.is=="function"?Object.is:Q6;function zc(e,n){if(ts(e,n))return!0;if(typeof e!="object"||e===null||typeof n!="object"||n===null)return!1;var r=Object.keys(e),s=Object.keys(n);if(r.length!==s.length)return!1;for(s=0;s<r.length;s++){var i=r[s];if(!Km.call(n,i)||!ts(e[i],n[i]))return!1}return!0}function RA(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function EA(e,n){var r=RA(e);e=0;for(var s;r;){if(r.nodeType===3){if(s=e+r.textContent.length,e<=n&&s>=n)return{node:r,offset:n-e};e=s}e:{for(;r;){if(r.nextSibling){r=r.nextSibling;break e}r=r.parentNode}r=void 0}r=RA(r)}}function kw(e,n){return e&&n?e===n?!0:e&&e.nodeType===3?!1:n&&n.nodeType===3?kw(e,n.parentNode):"contains"in e?e.contains(n):e.compareDocumentPosition?!!(e.compareDocumentPosition(n)&16):!1:!1}function Cw(){for(var e=window,n=xh();n instanceof e.HTMLIFrameElement;){try{var r=typeof n.contentWindow.location.href=="string"}catch{r=!1}if(r)e=n.contentWindow;else break;n=xh(e.document)}return n}function ub(e){var n=e&&e.nodeName&&e.nodeName.toLowerCase();return n&&(n==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||n==="textarea"||e.contentEditable==="true")}function eC(e){var n=Cw(),r=e.focusedElem,s=e.selectionRange;if(n!==r&&r&&r.ownerDocument&&kw(r.ownerDocument.documentElement,r)){if(s!==null&&ub(r)){if(n=s.start,e=s.end,e===void 0&&(e=n),"selectionStart"in r)r.selectionStart=n,r.selectionEnd=Math.min(e,r.value.length);else if(e=(n=r.ownerDocument||document)&&n.defaultView||window,e.getSelection){e=e.getSelection();var i=r.textContent.length,o=Math.min(s.start,i);s=s.end===void 0?o:Math.min(s.end,i),!e.extend&&o>s&&(i=s,s=o,o=i),i=EA(r,o);var a=EA(r,s);i&&a&&(e.rangeCount!==1||e.anchorNode!==i.node||e.anchorOffset!==i.offset||e.focusNode!==a.node||e.focusOffset!==a.offset)&&(n=n.createRange(),n.setStart(i.node,i.offset),e.removeAllRanges(),o>s?(e.addRange(n),e.extend(a.node,a.offset)):(n.setEnd(a.node,a.offset),e.addRange(n)))}}for(n=[],e=r;e=e.parentNode;)e.nodeType===1&&n.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof r.focus=="function"&&r.focus(),r=0;r<n.length;r++)e=n[r],e.element.scrollLeft=e.left,e.element.scrollTop=e.top}}var tC=Gs&&"documentMode"in document&&11>=document.documentMode,il=null,hx=null,pc=null,fx=!1;function PA(e,n,r){var s=r.window===r?r.document:r.nodeType===9?r:r.ownerDocument;fx||il==null||il!==xh(s)||(s=il,"selectionStart"in s&&ub(s)?s={start:s.selectionStart,end:s.selectionEnd}:(s=(s.ownerDocument&&s.ownerDocument.defaultView||window).getSelection(),s={anchorNode:s.anchorNode,anchorOffset:s.anchorOffset,focusNode:s.focusNode,focusOffset:s.focusOffset}),pc&&zc(pc,s)||(pc=s,s=wh(hx,"onSelect"),0<s.length&&(n=new lb("onSelect","select",null,n,r),e.push({event:n,listeners:s}),n.target=il)))}function Wu(e,n){var r={};return r[e.toLowerCase()]=n.toLowerCase(),r["Webkit"+e]="webkit"+n,r["Moz"+e]="moz"+n,r}var ol={animationend:Wu("Animation","AnimationEnd"),animationiteration:Wu("Animation","AnimationIteration"),animationstart:Wu("Animation","AnimationStart"),transitionend:Wu("Transition","TransitionEnd")},Tg={},Tw={};
vendor: 5,643 bytes, line 37
37Gs&&(Tw=document.createElement("div").style,"AnimationEvent"in window||(delete ol.animationend.animation,delete ol.animationiteration.animation,delete ol.animationstart.animation),"TransitionEvent"in window||delete ol.transitionend.transition);function _f(e){if(Tg[e])return Tg[e];if(!ol[e])return e;var n=ol[e],r;for(r in n)if(n.hasOwnProperty(r)&&r in Tw)return Tg[e]=n[r];return e}var zw=_f("animationend"),Nw=_f("animationiteration"),Rw=_f("animationstart"),Ew=_f("transitionend"),Pw=new Map,qA="abort auxClick cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" ");function co(e,n){Pw.set(e,n),va(n,[e])}for(var zg=0;zg<qA.length;zg++){var Ng=qA[zg],nC=Ng.toLowerCase(),rC=Ng[0].toUpperCase()+Ng.slice(1);co(nC,"on"+rC)}co(zw,"onAnimationEnd");co(Nw,"onAnimationIteration");co(Rw,"onAnimationStart");co("dblclick","onDoubleClick");co("focusin","onFocus");co("focusout","onBlur");co(Ew,"onTransitionEnd");Fl("onMouseEnter",["mouseout","mouseover"]);Fl("onMouseLeave",["mouseout","mouseover"]);Fl("onPointerEnter",["pointerout","pointerover"]);Fl("onPointerLeave",["pointerout","pointerover"]);va("onChange","change click focusin focusout input keydown keyup selectionchange".split(" "));va("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" "));va("onBeforeInput",["compositionend","keypress","textInput","paste"]);va("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" "));va("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" "));va("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var nc="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),sC=new Set("cancel close invalid load scroll toggle".split(" ").concat(nc));function DA(e,n,r){var s=e.type||"unknown-event";e.currentTarget=r,n6(s,n,void 0,e),e.currentTarget=null}function qw(e,n){n=(n&4)!==0;for(var r=0;r<e.length;r++){var s=e[r],i=s.event;s=s.listeners;e:{var o=void 0;if(n)for(var a=s.length-1;0<=a;a--){var l=s[a],d=l.instance,c=l.currentTarget;if(l=l.listener,d!==o&&i.isPropagationStopped())break e;DA(i,l,c),o=d}else for(a=0;a<s.length;a++){if(l=s[a],d=l.instance,c=l.currentTarget,l=l.listener,d!==o&&i.isPropagationStopped())break e;DA(i,l,c),o=d}}}if(bh)throw e=dx,bh=!1,dx=null,e}function St(e,n){var r=n[bx];r===void 0&&(r=n[bx]=new Set);var s=e+"__bubble";r.has(s)||(Dw(n,e,2,!1),r.add(s))}function Rg(e,n,r){var s=0;n&&(s|=4),Dw(r,e,s,n)}var $u="_reactListening"+Math.random().toString(36).slice(2);function Nc(e){if(!e[$u]){e[$u]=!0,F2.forEach(function(r){r!=="selectionchange"&&(sC.has(r)||Rg(r,!1,e),Rg(r,!0,e))});var n=e.nodeType===9?e:e.ownerDocument;n===null||n[$u]||(n[$u]=!0,Rg("selectionchange",!1,n))}}function Dw(e,n,r,s){switch(yw(n)){case 1:var i=y6;break;case 4:i=b6;break;default:i=ob}r=i.bind(null,n,r,e),i=void 0,!lx||n!=="touchstart"&&n!=="touchmove"&&n!=="wheel"||(i=!0),s?i!==void 0?e.addEventListener(n,r,{capture:!0,passive:i}):e.addEventListener(n,r,!0):i!==void 0?e.addEventListener(n,r,{passive:i}):e.addEventListener(n,r,!1)}function Eg(e,n,r,s,i){var o=s;if(!(n&1)&&!(n&2)&&s!==null)e:for(;;){if(s===null)return;var a=s.tag;if(a===3||a===4){var l=s.stateNode.containerInfo;if(l===i||l.nodeType===8&&l.parentNode===i)break;if(a===4)for(a=s.return;a!==null;){var d=a.tag;if((d===3||d===4)&&(d=a.stateNode.containerInfo,d===i||d.nodeType===8&&d.parentNode===i))return;a=a.return}for(;l!==null;){if(a=Uo(l),a===null)return;if(d=a.tag,d===5||d===6){s=o=a;continue e}l=l.parentNode}}s=s.return}sw(function(){var c=o,f=nb(r),p=[];e:{var u=Pw.get(e);if(u!==void 0){var h=lb,y=e;switch(e){case"keypress":if(Vp(r)===0)break e;case"keydown":case"keyup":h=q6;break;case"focusin":y="focus",h=Sg;break;case"focusout":y="blur",h=Sg;break;case"beforeblur":case"afterblur":h=Sg;break;case"click":if(r.button===2)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":h=jA;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":h=_6;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":h=I6;break;case zw:case Nw:case Rw:h=S6;break;case Ew:h=W6;break;case"scroll":h=A6;break;case"wheel":h=M6;break;case"copy":case"cut":case"paste":h=C6;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":h=SA}var m=(n&4)!==0,b=!m&&e==="scroll",A=m?u!==null?u+"Capture":null:u;m=[];for(var v=c,x;v!==null;){x=v;var _=x.stateNode;if(x.tag===5&&_!==null&&(x=_,A!==null&&(_=wc(v,A),_!=null&&m.push(Rc(v,_,x)))),b)break;v=v.return}0<m.length&&(u=new h(u,y,null,r,f),p.push({event:u,listeners:m}))}}if(!(n&7)){e:{if(u=e==="mouseover"||e==="pointerover",h=e==="mouseout"||e==="pointerout",u&&r!==o
vendor: 6,100 bytes, lines 37-38
37x&&(y=r.relatedTarget||r.fromElement)&&(Uo(y)||y[Js]))break e;if((h||u)&&(u=f.window===f?f:(u=f.ownerDocument)?u.defaultView||u.parentWindow:window,h?(y=r.relatedTarget||r.toElement,h=c,y=y?Uo(y):null,y!==null&&(b=_a(y),y!==b||y.tag!==5&&y.tag!==6)&&(y=null)):(h=null,y=c),h!==y)){if(m=jA,_="onMouseLeave",A="onMouseEnter",v="mouse",(e==="pointerout"||e==="pointerover")&&(m=SA,_="onPointerLeave",A="onPointerEnter",v="pointer"),b=h==null?u:al(h),x=y==null?u:al(y),u=new m(_,v+"leave",h,r,f),u.target=b,u.relatedTarget=x,_=null,Uo(f)===c&&(m=new m(A,v+"enter",y,r,f),m.target=x,m.relatedTarget=b,_=m),b=_,h&&y)t:{for(m=h,A=y,v=0,x=m;x;x=Na(x))v++;for(x=0,_=A;_;_=Na(_))x++;for(;0<v-x;)m=Na(m),v--;for(;0<x-v;)A=Na(A),x--;for(;v--;){if(m===A||A!==null&&m===A.alternate)break t;m=Na(m),A=Na(A)}m=null}else m=null;h!==null&&OA(p,u,h,m,!1),y!==null&&b!==null&&OA(p,b,y,m,!0)}}e:{if(u=c?al(c):window,h=u.nodeName&&u.nodeName.toLowerCase(),h==="select"||h==="input"&&u.type==="file")var j=K6;else if(TA(u))if(ww)j=J6;else{j=X6;var C=Y6}else(h=u.nodeName)&&h.toLowerCase()==="input"&&(u.type==="checkbox"||u.type==="radio")&&(j=G6);if(j&&(j=j(e,c))){jw(p,j,r,f);break e}C&&C(e,u,c),e==="focusout"&&(C=u._wrapperState)&&C.controlled&&u.type==="number"&&tx(u,"number",u.value)}switch(C=c?al(c):window,e){case"focusin":(TA(C)||C.contentEditable==="true")&&(il=C,hx=c,pc=null);break;case"focusout":pc=hx=il=null;break;case"mousedown":fx=!0;break;case"contextmenu":case"mouseup":case"dragend":fx=!1,PA(p,r,f);break;case"selectionchange":if(tC)break;case"keydown":case"keyup":PA(p,r,f)}var S;if(cb)e:{switch(e){case"compositionstart":var T="onCompositionStart";break e;case"compositionend":T="onCompositionEnd";break e;case"compositionupdate":T="onCompositionUpdate";break e}T=void 0}else sl?vw(e,r)&&(T="onCompositionEnd"):e==="keydown"&&r.keyCode===229&&(T="onCompositionStart");T&&(Aw&&r.locale!=="ko"&&(sl||T!=="onCompositionStart"?T==="onCompositionEnd"&&sl&&(S=bw()):(Bi=f,ab="value"in Bi?Bi.value:Bi.textContent,sl=!0)),C=wh(c,T),0<C.length&&(T=new wA(T,e,null,r,f),p.push({event:T,listeners:C}),S?T.data=S:(S=_w(r),S!==null&&(T.data=S)))),(S=B6?U6(e,r):H6(e,r))&&(c=wh(c,"onBeforeInput"),0<c.length&&(f=new wA("onBeforeInput","beforeinput",null,r,f),p.push({event:f,listeners:c}),f.data=S))}qw(p,n)})}function Rc(e,n,r){return{instance:e,listener:n,currentTarget:r}}function wh(e,n){for(var r=n+"Capture",s=[];e!==null;){var i=e,o=i.stateNode;i.tag===5&&o!==null&&(i=o,o=wc(e,r),o!=null&&s.unshift(Rc(e,o,i)),o=wc(e,n),o!=null&&s.push(Rc(e,o,i))),e=e.return}return s}function Na(e){if(e===null)return null;do e=e.return;while(e&&e.tag!==5);return e||null}function OA(e,n,r,s,i){for(var o=n._reactName,a=[];r!==null&&r!==s;){var l=r,d=l.alternate,c=l.stateNode;if(d!==null&&d===s)break;l.tag===5&&c!==null&&(l=c,i?(d=wc(r,o),d!=null&&a.unshift(Rc(r,d,l))):i||(d=wc(r,o),d!=null&&a.push(Rc(r,d,l)))),r=r.return}a.length!==0&&e.push({event:n,listeners:a})}var iC=/\r\n?/g,oC=/\u0000|\uFFFD/g;function IA(e){return(typeof e=="string"?e:""+e).replace(iC,` 38`).replace(oC,"")}function Mu(e,n,r){if(n=IA(n),IA(e)!==n&&r)throw Error(Se(425))}function Sh(){}var gx=null,mx=null;function xx(e,n){return e==="textarea"||e==="noscript"||typeof n.children=="string"||typeof n.children=="number"||typeof n.dangerouslySetInnerHTML=="object"&&n.dangerouslySetInnerHTML!==null&&n.dangerouslySetInnerHTML.__html!=null}var yx=typeof setTimeout=="function"?setTimeout:void 0,aC=typeof clearTimeout=="function"?clearTimeout:void 0,LA=typeof Promise=="function"?Promise:void 0,lC=typeof queueMicrotask=="function"?queueMicrotask:typeof LA<"u"?function(e){return LA.resolve(null).then(e).catch(dC)}:yx;function dC(e){setTimeout(function(){throw e})}function Pg(e,n){var r=n,s=0;do{var i=r.nextSibling;if(e.removeChild(r),i&&i.nodeType===8)if(r=i.data,r==="/$"){if(s===0){e.removeChild(i),Cc(n);return}s--}else r!=="$"&&r!=="$?"&&r!=="$!"||s++;r=i}while(r);Cc(n)}function Xi(e){for(;e!=null;e=e.nextSibling){var n=e.nodeType;if(n===1||n===3)break;if(n===8){if(n=e.data,n==="$"||n==="$!"||n==="$?")break;if(n==="/$")return null}}return e}function WA(e){e=e.previousSibling;for(var n=0;e;){if(e.nodeType===8){var r=e.data;if(r==="$"||r==="$!"||r==="$?"){if(n===0)return e;n--}else r==="/$"&&n++}e=e.previousSibling}return null}var ld=Math.random().toString(36).slice(2),As="__reactFiber$"+ld,Ec="__reactProps$"+ld,Js="__reactContainer$"+ld,bx="__reactEvents$"+ld,cC="__reactListeners$"+ld,uC="__reactHandles$"+ld;function Uo(e){var n=e[As];if(n)return n;for(var r=e.parentNode;r;){if(n=r[Js]||r[As]){if(r=n.alternate,n.child!==null||r!==null&&r.child!==null)for(e=WA(e);e!==null;){if(r=e[As])return r;e=WA(e)}return n}e=r,r=e.parentNode}return null}function hu(e){return e=e[As]||e[Js],!e||e.tag!==5&&e.tag!==6&&e.tag!==13&&e.tag!==3?null:e}function al(e){if(e.tag===5||e.tag===6)return e.stateNode;throw Error(Se(33))}function jf(e){return e[Ec]||null}var Ax=[],ll=-1;function uo(e){return{current:e}}function Ct(e){0>ll||(e.current=Ax[ll],Ax[ll]=null,ll--)}function jt(e,n){ll++,Ax[ll]=e.current,e.current=n}var ao={},Nn=uo(ao),ar=uo(!1),ca=ao;function Bl(e,n){var r=e.type.contextTypes;if(!r)return ao;var s=e.stateNode;if(s&&s.__reactInternalMemoizedUnmaskedChildContext===n)return s.__reactInternalMemoizedMaskedChildContext;var i={},o;for(o in r)i[o]=n[o];return s&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=n,e.__reactInternalMemoizedMaskedChildContext=i),i}function lr(e){return e=e.childContextTypes,e!=null}function kh(){Ct(ar),Ct(Nn)}function $A(e,n,r){if(Nn.current!==ao)throw Error(Se(168));jt(Nn,n),jt(ar,r)}function Ow(e,n,r){var s=e.stateNode;if(n=n.childContextTypes,typeof s.getChildContext!="function")return r;s=s.getChildContext();for(var i in s)if(!(i in n))throw Error(Se(108,Y5(e)||"Unknown",i));return Lt({},r,s)}function Ch(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||ao,ca=Nn.current,jt(Nn,e),jt(ar,ar.current),!0}function MA(e,n,r){var s=e.stateNode;if(!s)throw Error(Se(169));r?(e=Ow(e,n,ca),s.__reactInternalMemoizedMergedChildContext=e,Ct(ar),Ct(Nn),jt
vendor: 13,978 bytes, line 38
38(Nn,e)):Ct(ar),jt(ar,r)}var Os=null,wf=!1,qg=!1;function Iw(e){Os===null?Os=[e]:Os.push(e)}function pC(e){wf=!0,Iw(e)}function po(){if(!qg&&Os!==null){qg=!0;var e=0,n=xt;try{var r=Os;for(xt=1;e<r.length;e++){var s=r[e];do s=s(!0);while(s!==null)}Os=null,wf=!1}catch(i){throw Os!==null&&(Os=Os.slice(e+1)),lw(rb,po),i}finally{xt=n,qg=!1}}return null}var dl=[],cl=0,Th=null,zh=0,zr=[],Nr=0,ua=null,Bs=1,Us="";function Do(e,n){dl[cl++]=zh,dl[cl++]=Th,Th=e,zh=n}function Lw(e,n,r){zr[Nr++]=Bs,zr[Nr++]=Us,zr[Nr++]=ua,ua=e;var s=Bs;e=Us;var i=32-Qr(s)-1;s&=~(1<<i),r+=1;var o=32-Qr(n)+i;if(30<o){var a=i-i%5;o=(s&(1<<a)-1).toString(32),s>>=a,i-=a,Bs=1<<32-Qr(n)+i|r<<i|s,Us=o+e}else Bs=1<<o|r<<i|s,Us=e}function pb(e){e.return!==null&&(Do(e,1),Lw(e,1,0))}function hb(e){for(;e===Th;)Th=dl[--cl],dl[cl]=null,zh=dl[--cl],dl[cl]=null;for(;e===ua;)ua=zr[--Nr],zr[Nr]=null,Us=zr[--Nr],zr[Nr]=null,Bs=zr[--Nr],zr[Nr]=null}var Ar=null,br=null,Et=!1,Jr=null;function Ww(e,n){var r=Er(5,null,null,0);r.elementType="DELETED",r.stateNode=n,r.return=e,n=e.deletions,n===null?(e.deletions=[r],e.flags|=16):n.push(r)}function FA(e,n){switch(e.tag){case 5:var r=e.type;return n=n.nodeType!==1||r.toLowerCase()!==n.nodeName.toLowerCase()?null:n,n!==null?(e.stateNode=n,Ar=e,br=Xi(n.firstChild),!0):!1;case 6:return n=e.pendingProps===""||n.nodeType!==3?null:n,n!==null?(e.stateNode=n,Ar=e,br=null,!0):!1;case 13:return n=n.nodeType!==8?null:n,n!==null?(r=ua!==null?{id:Bs,overflow:Us}:null,e.memoizedState={dehydrated:n,treeContext:r,retryLane:1073741824},r=Er(18,null,null,0),r.stateNode=n,r.return=e,e.child=r,Ar=e,br=null,!0):!1;default:return!1}}function vx(e){return(e.mode&1)!==0&&(e.flags&128)===0}function _x(e){if(Et){var n=br;if(n){var r=n;if(!FA(e,n)){if(vx(e))throw Error(Se(418));n=Xi(r.nextSibling);var s=Ar;n&&FA(e,n)?Ww(s,r):(e.flags=e.flags&-4097|2,Et=!1,Ar=e)}}else{if(vx(e))throw Error(Se(418));e.flags=e.flags&-4097|2,Et=!1,Ar=e}}}function BA(e){for(e=e.return;e!==null&&e.tag!==5&&e.tag!==3&&e.tag!==13;)e=e.return;Ar=e}function Fu(e){if(e!==Ar)return!1;if(!Et)return BA(e),Et=!0,!1;var n;if((n=e.tag!==3)&&!(n=e.tag!==5)&&(n=e.type,n=n!=="head"&&n!=="body"&&!xx(e.type,e.memoizedProps)),n&&(n=br)){if(vx(e))throw $w(),Error(Se(418));for(;n;)Ww(e,n),n=Xi(n.nextSibling)}if(BA(e),e.tag===13){if(e=e.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(Se(317));e:{for(e=e.nextSibling,n=0;e;){if(e.nodeType===8){var r=e.data;if(r==="/$"){if(n===0){br=Xi(e.nextSibling);break e}n--}else r!=="$"&&r!=="$!"&&r!=="$?"||n++}e=e.nextSibling}br=null}}else br=Ar?Xi(e.stateNode.nextSibling):null;return!0}function $w(){for(var e=br;e;)e=Xi(e.nextSibling)}function Ul(){br=Ar=null,Et=!1}function fb(e){Jr===null?Jr=[e]:Jr.push(e)}var hC=oi.ReactCurrentBatchConfig;function zd(e,n,r){if(e=r.ref,e!==null&&typeof e!="function"&&typeof e!="object"){if(r._owner){if(r=r._owner,r){if(r.tag!==1)throw Error(Se(309));var s=r.stateNode}if(!s)throw Error(Se(147,e));var i=s,o=""+e;return n!==null&&n.ref!==null&&typeof n.ref=="function"&&n.ref._stringRef===o?n.ref:(n=function(a){var l=i.refs;a===null?delete l[o]:l[o]=a},n._stringRef=o,n)}if(typeof e!="string")throw Error(Se(284));if(!r._owner)throw Error(Se(290,e))}return e}function Bu(e,n){throw e=Object.prototype.toString.call(n),Error(Se(31,e==="[object Object]"?"object with keys {"+Object.keys(n).join(", ")+"}":e))}function UA(e){var n=e._init;return n(e._payload)}function Mw(e){function n(A,v){if(e){var x=A.deletions;x===null?(A.deletions=[v],A.flags|=16):x.push(v)}}function r(A,v){if(!e)return null;for(;v!==null;)n(A,v),v=v.sibling;return null}function s(A,v){for(A=new Map;v!==null;)v.key!==null?A.set(v.key,v):A.set(v.index,v),v=v.sibling;return A}function i(A,v){return A=eo(A,v),A.index=0,A.sibling=null,A}function o(A,v,x){return A.index=x,e?(x=A.alternate,x!==null?(x=x.index,x<v?(A.flags|=2,v):x):(A.flags|=2,v)):(A.flags|=1048576,v)}function a(A){return e&&A.alternate===null&&(A.flags|=2),A}function l(A,v,x,_){return v===null||v.tag!==6?(v=Mg(x,A.mode,_),v.return=A,v):(v=i(v,x),v.return=A,v)}function d(A,v,x,_){var j=x.type;return j===rl?f(A,v,x.props.children,_,x.key):v!==null&&(v.elementType===j||typeof j=="object"&&j!==null&&j.$$typeof===Si&&UA(j)===v.type)?(_=i(v,x.props),_.ref=zd(A,v,x),_.return=A,_):(_=Qp(x.type,x.key,x.props,null,A.mode,_),_.ref=zd(A,v,x),_.return=A,_)}function c(A,v,x,_){return v===null||v.tag!==4||v.stateNode.containerInfo!==x.containerInfo||v.stateNode.implementation!==x.implementation?(v=Fg(x,A.mode,_),v.return=A,v):(v=i(v,x.children||[]),v.return=A,v)}function f(A,v,x,_,j){return v===null||v.tag!==7?(v=la(x,A.mode,_,j),v.return=A,v):(v=i(v,x),v.return=A,v)}function p(A,v,x){if(typeof v=="string"&&v!==""||typeof v=="number")return v=Mg(""+v,A.mode,x),v.return=A,v;if(typeof v=="object"&&v!==null){switch(v.$$typeof){case Eu:return x=Qp(v.type,v.key,v.props,null,A.mode,x),x.ref=zd(A,null,v),x.return=A,x;case nl:return v=Fg(v,A.mode,x),v.return=A,v;case Si:var _=v._init;return p(A,_(v._payload),x)}if(ec(v)||wd(v))return v=la(v,A.mode,x,null),v.return=A,v;Bu(A,v)}return null}function u(A,v,x,_){var j=v!==null?v.key:null;if(typeof x=="string"&&x!==""||typeof x=="number")return j!==null?null:l(A,v,""+x,_);if(typeof x=="object"&&x!==null){switch(x.$$typeof){case Eu:return x.key===j?d(A,v,x,_):null;case nl:return x.key===j?c(A,v,x,_):null;case Si:return j=x._init,u(A,v,j(x._payload),_)}if(ec(x)||wd(x))return j!==null?null:f(A,v,x,_,null);Bu(A,x)}return null}function h(A,v,x,_,j){if(typeof _=="string"&&_!==""||typeof _=="number")return A=A.get(x)||null,l(v,A,""+_,j);if(typeof _=="object"&&_!==null){switch(_.$$typeof){case Eu:return A=A.get(_.key===null?x:_.key)||null,d(v,A,_,j);case nl:return A=A.get(_.key===null?x:_.key)||null,c(v,A,_,j);case Si:var C=_._init;return h(A,v,x,C(_._payload),j)}if(ec(_)||wd(_))return A=A.get(x)||null,f(v,A,_,j,null);Bu(v,_)}return null}function y(A,v,x,_){for(var j=null,C=null,S=v,T=v=0,L=null;S!==null&&T<x.length;T++){S.index>T?(L=S,S=null):L=S.sibling;var E=u(A,S,x[T],_);if(E===null){S===null&&(S=L);break}e&&S&&E.alternate===null&&n(A,S),v=o(E,v,T),C===null?j=E:C.sibling=E,C=E,S=L}if(T===x.length)return r(A,S),Et&&Do(A,T),j;if(S===null){for(;T<x.length;T++)S=p(A,x[T],_),S!==null&&(v=o(S,v,T),C===null?j=S:C.sibling=S,C=S);return Et&&Do(A,T),j}for(S=s(A,S);T<x.length;T++)L=h(S,A,T,x[T],_),L!==null&&(e&&L.alternate!==null&&S.delete(L.key===null?T:L.key),v=o(L,v,T),C===null?j=L:C.sibling=L,C=L);return e&&S.forEach(function(R){return n(A,R)}),Et&&Do(A,T),j}function m(A,v,x,_){var j=wd(x);if(typeof j!="function")throw Error(Se(150));if(x=j.call(x),x==null)throw Error(Se(151));for(var C=j=null,S=v,T=v=0,L=null,E=x.next();S!==null&&!E.done;T++,E=x.next()){S.index>T?(L=S,S=null):L=S.sibling;var R=u(A,S,E.value,_);if(R===null){S===null&&(S=L);break}e&&S&&R.alternate===null&&n(A,S),v=o(R,v,T),C===null?j=R:C.sibling=R,C=R,S=L}if(E.done)return r(A,S),Et&&Do(A,T),j;if(S===null){for(;!E.done;T++,E=x.next())E=p(A,E.value,_),E!==null&&(v=o(E,v,T),C===null?j=E:C.sibling=E,C=E);return Et&&Do(A,T),j}for(S=s(A,S);!E.done;T++,E=x.next())E=h(S,A,T,E.value,_),E!==null&&(e&&E.alternate!==null&&S.delete(E.key===null?T:E.key),v=o(E,v,T),C===null?j=E:C.sibling=E,C=E);return e&&S.forEach(function(N){return n(A,N)}),Et&&Do(A,T),j}function b(A,v,x,_){if(typeof x=="object"&&x!==null&&x.type===rl&&x.key===null&&(x=x.props.children),typeof x=="object"&&x!==null){switch(x.$$typeof){case Eu:e:{for(var j=x.key,C=v;C!==null;){if(C.key===j){if(j=x.type,j===rl){if(C.tag===7){r(A,C.sibling),v=i(C,x.props.children),v.return=A,A=v;break e}}else if(C.elementType===j||typeof j=="object"&&j!==null&&j.$$typeof===Si&&UA(j)===C.type){r(A,C.sibling),v=i(C,x.props),v.ref=zd(A,C,x),v.return=A,A=v;break e}r(A,C);break}else n(A,C);C=C.sibling}x.type===rl?(v=la(x.props.children,A.mode,_,x.key),v.return=A,A=v):(_=Qp(x.type,x.key,x.props,null,A.mode,_),_.ref=zd(A,v,x),_.return=A,A=_)}return a(A);case nl:e:{for(C=x.key;v!==null;){if(v.key===C)if(v.tag===4&&v.stateNode.containerInfo===x.containerInfo&&v.stateNode.implementation===x.implementation){r(A,v.sibling),v=i(v,x.children||[]),v.return=A,A=v;break e}else{r(A,v);break}else n(A,v);v=v.sibling}v=Fg(x,A.mode,_),v.return=A,A=v}return a(A);case Si:return C=x._init,b(A,v,C(x._payload),_)}if(ec(x))return y(A,v,x,_);if(wd(x))return m(A,v,x,_);Bu(A,x)}return typeof x=="string"&&x!==""||typeof x=="number"?(x=""+x,v!==null&&v.tag===6?(r(A,v.sibling),v=i(v,x),v.return=A,A=v):(r(A,v),v=Mg(x,A.mode,_),v.return=A,A=v),a(A)):r(A,v)}return b}var Hl=Mw(!0),Fw=Mw(!1),Nh=uo(null),Rh=null,ul=null,gb=null;function mb(){gb=ul=Rh=null}function xb(e){var n=Nh.current;Ct(Nh),e._currentValue=n}function jx(e,n,r){for(;e!==null;){var s=e.alternate;if((e.childLanes&n)!==n?(e.childLanes|=n,s!==null&&(s.childLanes|=n)):s!==null&&(s.childLanes&n)!==n&&(s.childLanes|=n),e===r)break;e=e.return}}function jl(e,n){Rh=e,gb=ul=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&n&&(or=!0),e.firstContext=null)}function Dr(e){var n=e._currentValue;if(gb!==e)if(e={context:e,memoizedValue:n,next:null},ul===null){if(Rh===null)throw Error(Se(308));ul=e,Rh.dependencies={lanes:0,firstContext:e}}else ul=ul.next=e;return n}var Ho=null;function yb(e){Ho===null?Ho=[e]:Ho.push(e)}function Bw(e,n,r,s){var i=n.interleaved;return i===null?(r.next=r,yb(n)):(r.next=i.next,i.next=r),n.interleaved=r,Qs(e,s)}function Qs(e,n){e.lanes|=n;var r=e.alternate;for(r!==null&&(r.lanes|=n),r=e,e=e.return;e!==null;)e.childLanes|=n,r=e.alternate,r!==null&&(r.childLanes|=n),r=e,e=e.return;return r.tag===3?r.stateNode:null}var ki=!1;function bb(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Uw(e,n){e=e.updateQueue,n.updateQueue===e&&(n.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function Vs(e,n){return{eventTime:e,lane:n,tag:0,payload:null,callback:null,next:null}}function Gi(e,n,r){var s=e.updateQueue;if(s===null)return null;if(s=s.shared,pt&2){var i=s.pending;return i===null?n.next=n:(n.next=i.next,i.next=n),s.pending=n,Qs(e,r)}return i=s.interleaved,i===null?(n.next=n,yb(s)):(n.next=i.next,i.next=n),s.interleaved=n,Qs(e,r)}function Zp(e,n,r){if(n=n.updateQueue,n!==null&&(n=n.shared,(r&4194240)!==0)){var s=n.lanes;s&=e.pendingLanes,r|=s,n.lanes=r,sb(e,r)}}function HA(e,n){var r=e.updateQueue,s=e.alternate;if(s!==null&&(s=s.updateQueue,r===s)){var i=null,o=null;if(r=r.firstBaseUpdate,r!==null){do{var a={eventTime:r.eventTime,lane:r.lane,tag:r.tag,payload:r.payload,callback:r.callback,next:null};o===null?i=o=a:o=o.next=a,r=r.next}while(r!==null);o===null?i=o=n:o=o.next=n}else i=o=n;r={baseState:s.baseState,firstBaseUpdate:i,lastBaseUpdate:o,shared:s.shared,effects:s.effects},e.updateQueue=r;return}e=r.lastBaseUpdate,e===null?r.firstBaseUpdate=n:e.next=n,r.lastBaseUpdate=n}function Eh(e,n,r,s){var i=e.updateQueue;ki=!1;var o=i.firstBaseUpdate,a=i.lastBaseUpdate,l=i.shared.pending;if(l!==null){i.shared.pending=null;var d=l,c=d.next;d.next=null,a===null?o=c:a.next=c,a=d;var f=e.alternate;f!==null&&(f=f.updateQueue,l=f.lastBaseUpdate,l!==a&&(l===null?f.firstBaseUpdate=c:l.next=c,f.lastBaseUpdate=d))}if(o!==null){var p=i.baseState;a=0,f=c=d=null,l=o;do{var u=l.lane,h=l.eventTime;if((s&u)===u){f!==null&&(f=f.next={eventTime:h,lane:0,tag:l.tag,payload:l.payload,callback:l.callback,next:null});e:{var y=e,m=l;switch(u=n,h=r,m.tag){case 1:if(y=m.payload,typeof y=="function"){p=y.call(h,p,u);break e}p=y;break e;case 3:y.flags=y.flags&-65537|128;case 0:if(y=m.payload,u=typeof y=="function"?y.call(h,p,u):y,u==null)break e;p=Lt({},p,u);break e;case 2:ki=!0}}l.callback!==null&&l.lane!==0&&(e.flags|=64,u=i.effects,u===null?i.effects=[l]:u.push(l))}else h={eventTime:h,lane:u,tag:l.tag,payload:l.payload,callback:l.callback,next:null},f===null?(c=f=h,d=p):f=f.next=h,a|=u;if(l=l.next,l===null){if(l=i.shared.pending,l===null)break;u=l,l=u.next,u.next=null,i.lastBaseUpdate=u,i.shared.pending=null}}while(!0);if(f===null&&(d=p),i.baseState=d,i.firstBaseUpdate=c,i.lastBaseUpdate=f,n=i.shared.interleaved,n!==null){i=n;do a|=i.lane,i=i.next;while(i!==n)}else o===null&&(i.shared.lanes=0);ha|=a,e.lanes=a,e.memoizedState=p}}function VA(e,n,r){if(e=n.effects,n.effects=null,e!==null)for(n=0;n<e.length;n++){var s=e[n],i=s.callback;if(i!==null){if(s.callback=null,s=r,typeof i!="function")throw Error(Se(191,i));i.call(s)}}}var fu={},Ss=uo(fu),Pc=uo(fu),qc=uo(fu);function Vo(e){if(e===fu)throw Error(Se(174));return e}function Ab(e,n){switch(jt(qc,n),jt(Pc,e),jt(Ss,fu),e=n.nodeType,e){case 9:case 11:n=(n=n.documentElement)?n.namespaceURI:rx(null,"");break;default:e=e===8?n.parentNode:n,n=e.namespaceURI||null,e=e.tagName,n=rx(n,e)}Ct(Ss),jt(Ss,n)}function Vl(){Ct(Ss),Ct(Pc),Ct(qc)}function Hw(e){Vo(qc.current);var n=Vo(Ss.current),r=rx(n,e.type);n!==r&&(jt(Pc,e),jt(Ss,r))}function vb(e){Pc.current===e&&(Ct(Ss),Ct(Pc))}var Dt=uo(0);function Ph(e){for(var n=e;n!==null;){if(n.tag===13){var r=n.memoizedState;if(r!==null&&(r=r.dehydrated,r===null||r.data==="$?"||r.data==="$!"))return n}else if(n.tag===19&&n.memoizedProps.revealOrder!==void 0){if(n.flags&128)return n}else if(n.child!==null){n.child.return=n,n=n.child;continue}if(n===e)break;for(;n.sibling===null;){if(n.return===null||n.return===e)return null;n=n.return}n.sibling.return=n.return,n=n.sibling}return null}var Dg=[];function _b(){for(var e=0;e<Dg.length;e++)Dg[e]._workInProgressVersionPrimary=null;Dg.length=0}var Kp=oi.ReactCurrentDispatcher,Og=oi.ReactCurrentBatchConfig,pa=0,Ot=null,on=null,xn=null,qh=!1,hc=!1,Dc=0,fC=0;function kn(){throw Error(Se(321))}function jb(e,n){if(n===null)return!1;for(var r=0;r<n.length&&r<e.length;r++)if(!ts(e[r],n[r]))return!1;return!0}function wb(e,n,r,s,i,o){if(pa=o,Ot=n,n.memoizedState=null,n.updateQueue=null,n.lanes=0,Kp.current=e===null||e.memoizedState===null?yC:bC,e=r(s,i),hc){o=0;
vendor: 3,099 bytes, line 38
38do{if(hc=!1,Dc=0,25<=o)throw Error(Se(301));o+=1,xn=on=null,n.updateQueue=null,Kp.current=AC,e=r(s,i)}while(hc)}if(Kp.current=Dh,n=on!==null&&on.next!==null,pa=0,xn=on=Ot=null,qh=!1,n)throw Error(Se(300));return e}function Sb(){var e=Dc!==0;return Dc=0,e}function hs(){var e={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return xn===null?Ot.memoizedState=xn=e:xn=xn.next=e,xn}function Or(){if(on===null){var e=Ot.alternate;e=e!==null?e.memoizedState:null}else e=on.next;var n=xn===null?Ot.memoizedState:xn.next;if(n!==null)xn=n,on=e;else{if(e===null)throw Error(Se(310));on=e,e={memoizedState:on.memoizedState,baseState:on.baseState,baseQueue:on.baseQueue,queue:on.queue,next:null},xn===null?Ot.memoizedState=xn=e:xn=xn.next=e}return xn}function Oc(e,n){return typeof n=="function"?n(e):n}function Ig(e){var n=Or(),r=n.queue;if(r===null)throw Error(Se(311));r.lastRenderedReducer=e;var s=on,i=s.baseQueue,o=r.pending;if(o!==null){if(i!==null){var a=i.next;i.next=o.next,o.next=a}s.baseQueue=i=o,r.pending=null}if(i!==null){o=i.next,s=s.baseState;var l=a=null,d=null,c=o;do{var f=c.lane;if((pa&f)===f)d!==null&&(d=d.next={lane:0,action:c.action,hasEagerState:c.hasEagerState,eagerState:c.eagerState,next:null}),s=c.hasEagerState?c.eagerState:e(s,c.action);else{var p={lane:f,action:c.action,hasEagerState:c.hasEagerState,eagerState:c.eagerState,next:null};d===null?(l=d=p,a=s):d=d.next=p,Ot.lanes|=f,ha|=f}c=c.next}while(c!==null&&c!==o);d===null?a=s:d.next=l,ts(s,n.memoizedState)||(or=!0),n.memoizedState=s,n.baseState=a,n.baseQueue=d,r.lastRenderedState=s}if(e=r.interleaved,e!==null){i=e;do o=i.lane,Ot.lanes|=o,ha|=o,i=i.next;while(i!==e)}else i===null&&(r.lanes=0);return[n.memoizedState,r.dispatch]}function Lg(e){var n=Or(),r=n.queue;if(r===null)throw Error(Se(311));r.lastRenderedReducer=e;var s=r.dispatch,i=r.pending,o=n.memoizedState;if(i!==null){r.pending=null;var a=i=i.next;do o=e(o,a.action),a=a.next;while(a!==i);ts(o,n.memoizedState)||(or=!0),n.memoizedState=o,n.baseQueue===null&&(n.baseState=o),r.lastRenderedState=o}return[o,s]}function Vw(){}function Zw(e,n){var r=Ot,s=Or(),i=n(),o=!ts(s.memoizedState,i);if(o&&(s.memoizedState=i,or=!0),s=s.queue,kb(Xw.bind(null,r,s,e),[e]),s.getSnapshot!==n||o||xn!==null&&xn.memoizedState.tag&1){if(r.flags|=2048,Ic(9,Yw.bind(null,r,s,i,n),void 0,null),yn===null)throw Error(Se(349));pa&30||Kw(r,n,i)}return i}function Kw(e,n,r){e.flags|=16384,e={getSnapshot:n,value:r},n=Ot.updateQueue,n===null?(n={lastEffect:null,stores:null},Ot.updateQueue=n,n.stores=[e]):(r=n.stores,r===null?n.stores=[e]:r.push(e))}function Yw(e,n,r,s){n.value=r,n.getSnapshot=s,Gw(n)&&Jw(e)}function Xw(e,n,r){return r(function(){Gw(n)&&Jw(e)})}function Gw(e){var n=e.getSnapshot;e=e.value;try{var r=n();return!ts(e,r)}catch{return!0}}function Jw(e){var n=Qs(e,1);n!==null&&es(n,e,1,-1)}function ZA(e){var n=hs();return typeof e=="function"&&(e=e()),n.memoizedState=n.baseState=e,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:Oc,lastRenderedState:e},n.queue=e,e=e.dispatch=xC.bind(null,Ot,e),[n.memoizedState,e]}
vendor: 10,081 bytes, lines 38-40
38function Ic(e,n,r,s){return e={tag:e,create:n,destroy:r,deps:s,next:null},n=Ot.updateQueue,n===null?(n={lastEffect:null,stores:null},Ot.updateQueue=n,n.lastEffect=e.next=e):(r=n.lastEffect,r===null?n.lastEffect=e.next=e:(s=r.next,r.next=e,e.next=s,n.lastEffect=e)),e}function Qw(){return Or().memoizedState}function Yp(e,n,r,s){var i=hs();Ot.flags|=e,i.memoizedState=Ic(1|n,r,void 0,s===void 0?null:s)}function Sf(e,n,r,s){var i=Or();s=s===void 0?null:s;var o=void 0;if(on!==null){var a=on.memoizedState;if(o=a.destroy,s!==null&&jb(s,a.deps)){i.memoizedState=Ic(n,r,o,s);return}}Ot.flags|=e,i.memoizedState=Ic(1|n,r,o,s)}function KA(e,n){return Yp(8390656,8,e,n)}function kb(e,n){return Sf(2048,8,e,n)}function eS(e,n){return Sf(4,2,e,n)}function tS(e,n){return Sf(4,4,e,n)}function nS(e,n){if(typeof n=="function")return e=e(),n(e),function(){n(null)};if(n!=null)return e=e(),n.current=e,function(){n.current=null}}function rS(e,n,r){return r=r!=null?r.concat([e]):null,Sf(4,4,nS.bind(null,n,e),r)}function Cb(){}function sS(e,n){var r=Or();n=n===void 0?null:n;var s=r.memoizedState;return s!==null&&n!==null&&jb(n,s[1])?s[0]:(r.memoizedState=[e,n],e)}function iS(e,n){var r=Or();n=n===void 0?null:n;var s=r.memoizedState;return s!==null&&n!==null&&jb(n,s[1])?s[0]:(e=e(),r.memoizedState=[e,n],e)}function oS(e,n,r){return pa&21?(ts(r,n)||(r=uw(),Ot.lanes|=r,ha|=r,e.baseState=!0),n):(e.baseState&&(e.baseState=!1,or=!0),e.memoizedState=r)}function gC(e,n){var r=xt;xt=r!==0&&4>r?r:4,e(!0);var s=Og.transition;Og.transition={};try{e(!1),n()}finally{xt=r,Og.transition=s}}function aS(){return Or().memoizedState}function mC(e,n,r){var s=Qi(e);if(r={lane:s,action:r,hasEagerState:!1,eagerState:null,next:null},lS(e))dS(n,r);else if(r=Bw(e,n,r,s),r!==null){var i=Fn();es(r,e,s,i),cS(r,n,s)}}function xC(e,n,r){var s=Qi(e),i={lane:s,action:r,hasEagerState:!1,eagerState:null,next:null};if(lS(e))dS(n,i);else{var o=e.alternate;if(e.lanes===0&&(o===null||o.lanes===0)&&(o=n.lastRenderedReducer,o!==null))try{var a=n.lastRenderedState,l=o(a,r);if(i.hasEagerState=!0,i.eagerState=l,ts(l,a)){var d=n.interleaved;d===null?(i.next=i,yb(n)):(i.next=d.next,d.next=i),n.interleaved=i;return}}catch{}finally{}r=Bw(e,n,i,s),r!==null&&(i=Fn(),es(r,e,s,i),cS(r,n,s))}}function lS(e){var n=e.alternate;return e===Ot||n!==null&&n===Ot}function dS(e,n){hc=qh=!0;var r=e.pending;r===null?n.next=n:(n.next=r.next,r.next=n),e.pending=n}function cS(e,n,r){if(r&4194240){var s=n.lanes;s&=e.pendingLanes,r|=s,n.lanes=r,sb(e,r)}}var Dh={readContext:Dr,useCallback:kn,useContext:kn,useEffect:kn,useImperativeHandle:kn,useInsertionEffect:kn,useLayoutEffect:kn,useMemo:kn,useReducer:kn,useRef:kn,useState:kn,useDebugValue:kn,useDeferredValue:kn,useTransition:kn,useMutableSource:kn,useSyncExternalStore:kn,useId:kn,unstable_isNewReconciler:!1},yC={readContext:Dr,useCallback:function(e,n){return hs().memoizedState=[e,n===void 0?null:n],e},useContext:Dr,useEffect:KA,useImperativeHandle:function(e,n,r){return r=r!=null?r.concat([e]):null,Yp(4194308,4,nS.bind(null,n,e),r)},useLayoutEffect:function(e,n){return Yp(4194308,4,e,n)},useInsertionEffect:function(e,n){return Yp(4,2,e,n)},useMemo:function(e,n){var r=hs();return n=n===void 0?null:n,e=e(),r.memoizedState=[e,n],e},useReducer:function(e,n,r){var s=hs();return n=r!==void 0?r(n):n,s.memoizedState=s.baseState=n,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:n},s.queue=e,e=e.dispatch=mC.bind(null,Ot,e),[s.memoizedState,e]},useRef:function(e){var n=hs();return e={current:e},n.memoizedState=e},useState:ZA,useDebugValue:Cb,useDeferredValue:function(e){return hs().memoizedState=e},useTransition:function(){var e=ZA(!1),n=e[0];return e=gC.bind(null,e[1]),hs().memoizedState=e,[n,e]},useMutableSource:function(){},useSyncExternalStore:function(e,n,r){var s=Ot,i=hs();if(Et){if(r===void 0)throw Error(Se(407));r=r()}else{if(r=n(),yn===null)throw Error(Se(349));pa&30||Kw(s,n,r)}i.memoizedState=r;var o={value:r,getSnapshot:n};return i.queue=o,KA(Xw.bind(null,s,o,e),[e]),s.flags|=2048,Ic(9,Yw.bind(null,s,o,r,n),void 0,null),r},useId:function(){var e=hs(),n=yn.identifierPrefix;if(Et){var r=Us,s=Bs;r=(s&~(1<<32-Qr(s)-1)).toString(32)+r,n=":"+n+"R"+r,r=Dc++,0<r&&(n+="H"+r.toString(32)),n+=":"}else r=fC++,n=":"+n+"r"+r.toString(32)+":";return e.memoizedState=n},unstable_isNewReconciler:!1},bC={readContext:Dr,useCallback:sS,useContext:Dr,useEffect:kb,useImperativeHandle:rS,useInsertionEffect:eS,useLayoutEffect:tS,useMemo:iS,useReducer:Ig,useRef:Qw,useState:function(){return Ig(Oc)},useDebugValue:Cb,useDeferredValue:function(e){var n=Or();return oS(n,on.memoizedState,e)},useTransition:function(){var e=Ig(Oc)[0],n=Or().memoizedState;return[e,n]},useMutableSource:Vw,useSyncExternalStore:Zw,useId:aS,unstable_isNewReconciler:!1},AC={readContext:Dr,useCallback:sS,useContext:Dr,useEffect:kb,useImperativeHandle:rS,useInsertionEffect:eS,useLayoutEffect:tS,useMemo:iS,useReducer:Lg,useRef:Qw,useState:function(){return Lg(Oc)},useDebugValue:Cb,useDeferredValue:function(e){var n=Or();return on===null?n.memoizedState=e:oS(n,on.memoizedState,e)},useTransition:function(){var e=Lg(Oc)[0],n=Or().memoizedState;return[e,n]},useMutableSource:Vw,useSyncExternalStore:Zw,useId:aS,unstable_isNewReconciler:!1};function Kr(e,n){if(e&&e.defaultProps){n=Lt({},n),e=e.defaultProps;for(var r in e)n[r]===void 0&&(n[r]=e[r]);return n}return n}function wx(e,n,r,s){n=e.memoizedState,r=r(s,n),r=r==null?n:Lt({},n,r),e.memoizedState=r,e.lanes===0&&(e.updateQueue.baseState=r)}var kf={isMounted:function(e){return(e=e._reactInternals)?_a(e)===e:!1},enqueueSetState:function(e,n,r){e=e._reactInternals;var s=Fn(),i=Qi(e),o=Vs(s,i);o.payload=n,r!=null&&(o.callback=r),n=Gi(e,o,i),n!==null&&(es(n,e,i,s),Zp(n,e,i))},enqueueReplaceState:function(e,n,r){e=e._reactInternals;var s=Fn(),i=Qi(e),o=Vs(s,i);o.tag=1,o.payload=n,r!=null&&(o.callback=r),n=Gi(e,o,i),n!==null&&(es(n,e,i,s),Zp(n,e,i))},enqueueForceUpdate:function(e,n){e=e._reactInternals;var r=Fn(),s=Qi(e),i=Vs(r,s);i.tag=2,n!=null&&(i.callback=n),n=Gi(e,i,s),n!==null&&(es(n,e,s,r),Zp(n,e,s))}};function YA(e,n,r,s,i,o,a){return e=e.stateNode,typeof e.shouldComponentUpdate=="function"?e.shouldComponentUpdate(s,o,a):n.prototype&&n.prototype.isPureReactComponent?!zc(r,s)||!zc(i,o):!0}function uS(e,n,r){var s=!1,i=ao,o=n.contextType;return typeof o=="object"&&o!==null?o=Dr(o):(i=lr(n)?ca:Nn.current,s=n.contextTypes,o=(s=s!=null)?Bl(e,i):ao),n=new n(r,o),e.memoizedState=n.state!==null&&n.state!==void 0?n.state:null,n.updater=kf,e.stateNode=n,n._reactInternals=e,s&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=i,e.__reactInternalMemoizedMaskedChildContext=o),n}function XA(e,n,r,s){e=n.state,typeof n.componentWillReceiveProps=="function"&&n.componentWillReceiveProps(r,s),typeof n.UNSAFE_componentWillReceiveProps=="function"&&n.UNSAFE_componentWillReceiveProps(r,s),n.state!==e&&kf.enqueueReplaceState(n,n.state,null)}function Sx(e,n,r,s){var i=e.stateNode;i.props=r,i.state=e.memoizedState,i.refs={},bb(e);var o=n.contextType;typeof o=="object"&&o!==null?i.context=Dr(o):(o=lr(n)?ca:Nn.current,i.context=Bl(e,o)),i.state=e.memoizedState,o=n.getDerivedStateFromProps,typeof o=="function"&&(wx(e,n,o,r),i.state=e.memoizedState),typeof n.getDerivedStateFromProps=="function"||typeof i.getSnapshotBeforeUpdate=="function"||typeof i.UNSAFE_componentWillMount!="function"&&typeof i.componentWillMount!="function"||(n=i.state,typeof i.componentWillMount=="function"&&i.componentWillMount(),typeof i.UNSAFE_componentWillMount=="function"&&i.UNSAFE_componentWillMount(),n!==i.state&&kf.enqueueReplaceState(i,i.state,null),Eh(e,r,i,s),i.state=e.memoizedState),typeof i.componentDidMount=="function"&&(e.flags|=4194308)}function Zl(e,n){try{var r="",s=n;do r+=K5(s),s=s.return;while(s);var i=r}catch(o){i=` 39Error generating stack: `+o.message+` 40`+o.stack}return{value:e,source:n,stack:i,digest:null}}function Wg(e,n,r){return{value:e,source:null,stack:r??null,digest:n??null}}function kx(e,n){try{console.error(n.value)}catch(r){setTimeout(function(){throw r})}}var vC=typeof WeakMap=="function"?WeakMap:Map;function pS(e,n,r){r=Vs(-1,r),r.tag=3,r.payload={element:null};var s=n.value;return r.callback=function(){Ih||(Ih=!0,Ox=s),kx(e,n)},r}function hS(e,n,r){r=Vs(-1,r),r.tag=3;var s=e.type.getDerivedStateFromError;if(typeof s=="function"){var i=n.value;r.payload=function(){return s(i)},r.callback=function(){kx(e,n)}}var o=e.stateNode;return o!==null&&typeof o.componentDidCatch=="function"&&(r.callback=function(){kx(e,n),typeof s!="function"&&(Ji===null?Ji=new Set([this]):Ji.add(this));var a=n.stack;this.componentDidCatch(n.value,{componentStack:a!==null?a:""})}),r}function GA(e,n,r){var s=e.pingCache;if(s===null){s=e.pingCache=new vC;var i=new Set;s.set(n,i)}else i=s.get(n),i===void 0&&(i=new Set,s.set(n,i));i.has(r)||(i.add(r),e=DC.bind(null,e,n,r),n.then(e,e))}function JA(e){do{var n;if((n=e.tag===13)&&(n=e.memoizedState,n=n!==null?n.dehydrated!==null:!0),n)return e;e=e.return}while(e!==null);return null}function QA(e,n,r,s,i){return e.mode&1?(e.flags|=65536,e.lanes=i,e):(e===n?e.flags|=65536:(e.flags|=128,r.flags|=131072,r.flags&=-52805,r.tag===1&&(r.alternate===null?r.tag=17:(n=Vs(-1,1),n.tag=2,Gi(r,n,1))),r.lanes|=1),e)}var _C=oi.ReactCurrentOwner,or=!1;function Ln(e,n,r,s){n.child=e===null?Fw(n,null,r,s):Hl(n,e.child,r,s)}function e1(e,n,r,s,i){r=r.render;var o=n.ref;return jl(n,i),s=wb(e,n,r,s,o,i),r=Sb(),e!==null&&!or?(n.updateQueue=e.updateQueue,n.flags&=-2053,e.lanes&=~i,ei(e,n,i)):(Et&&r&&pb(n),n.flags|=1,Ln(e,n,s,i),n.child)}function t1(e,n,r,s,i){if(e===null){var o=r.type;return typeof o=="function"&&!Db(o)&&o.defaultProps===void 0&&r.compare===null&&r.defaultProps===void 0?(n.tag=15,n.type=o,fS(e,n,o,s,i)):(e=Qp(r.type,null,s,n,n.mode,i),e.ref=n.ref,e.return=n,n.child=e)}if(o=e.child,!(e.lanes&i)){var a=o.memoizedProps;if(r=r.compare,r=r!==null?r:zc,r(a,s)&&e.ref===n.ref)return ei(e,n,i)}return n.flags|=1,e=eo(o,s),e.ref=n.ref,e.return=n,n.child=e}function fS(e,n,r,s,i){if(e!==null){var o=e.memoizedProps;
vendor: 4,338 bytes, line 40
40if(zc(o,s)&&e.ref===n.ref)if(or=!1,n.pendingProps=s=o,(e.lanes&i)!==0)e.flags&131072&&(or=!0);else return n.lanes=e.lanes,ei(e,n,i)}return Cx(e,n,r,s,i)}function gS(e,n,r){var s=n.pendingProps,i=s.children,o=e!==null?e.memoizedState:null;if(s.mode==="hidden")if(!(n.mode&1))n.memoizedState={baseLanes:0,cachePool:null,transitions:null},jt(hl,mr),mr|=r;else{if(!(r&1073741824))return e=o!==null?o.baseLanes|r:r,n.lanes=n.childLanes=1073741824,n.memoizedState={baseLanes:e,cachePool:null,transitions:null},n.updateQueue=null,jt(hl,mr),mr|=e,null;n.memoizedState={baseLanes:0,cachePool:null,transitions:null},s=o!==null?o.baseLanes:r,jt(hl,mr),mr|=s}else o!==null?(s=o.baseLanes|r,n.memoizedState=null):s=r,jt(hl,mr),mr|=s;return Ln(e,n,i,r),n.child}function mS(e,n){var r=n.ref;(e===null&&r!==null||e!==null&&e.ref!==r)&&(n.flags|=512,n.flags|=2097152)}function Cx(e,n,r,s,i){var o=lr(r)?ca:Nn.current;return o=Bl(n,o),jl(n,i),r=wb(e,n,r,s,o,i),s=Sb(),e!==null&&!or?(n.updateQueue=e.updateQueue,n.flags&=-2053,e.lanes&=~i,ei(e,n,i)):(Et&&s&&pb(n),n.flags|=1,Ln(e,n,r,i),n.child)}function n1(e,n,r,s,i){if(lr(r)){var o=!0;Ch(n)}else o=!1;if(jl(n,i),n.stateNode===null)Xp(e,n),uS(n,r,s),Sx(n,r,s,i),s=!0;else if(e===null){var a=n.stateNode,l=n.memoizedProps;a.props=l;var d=a.context,c=r.contextType;typeof c=="object"&&c!==null?c=Dr(c):(c=lr(r)?ca:Nn.current,c=Bl(n,c));var f=r.getDerivedStateFromProps,p=typeof f=="function"||typeof a.getSnapshotBeforeUpdate=="function";p||typeof a.UNSAFE_componentWillReceiveProps!="function"&&typeof a.componentWillReceiveProps!="function"||(l!==s||d!==c)&&XA(n,a,s,c),ki=!1;var u=n.memoizedState;a.state=u,Eh(n,s,a,i),d=n.memoizedState,l!==s||u!==d||ar.current||ki?(typeof f=="function"&&(wx(n,r,f,s),d=n.memoizedState),(l=ki||YA(n,r,l,s,u,d,c))?(p||typeof a.UNSAFE_componentWillMount!="function"&&typeof a.componentWillMount!="function"||(typeof a.componentWillMount=="function"&&a.componentWillMount(),typeof a.UNSAFE_componentWillMount=="function"&&a.UNSAFE_componentWillMount()),typeof a.componentDidMount=="function"&&(n.flags|=4194308)):(typeof a.componentDidMount=="function"&&(n.flags|=4194308),n.memoizedProps=s,n.memoizedState=d),a.props=s,a.state=d,a.context=c,s=l):(typeof a.componentDidMount=="function"&&(n.flags|=4194308),s=!1)}else{a=n.stateNode,Uw(e,n),l=n.memoizedProps,c=n.type===n.elementType?l:Kr(n.type,l),a.props=c,p=n.pendingProps,u=a.context,d=r.contextType,typeof d=="object"&&d!==null?d=Dr(d):(d=lr(r)?ca:Nn.current,d=Bl(n,d));var h=r.getDerivedStateFromProps;(f=typeof h=="function"||typeof a.getSnapshotBeforeUpdate=="function")||typeof a.UNSAFE_componentWillReceiveProps!="function"&&typeof a.componentWillReceiveProps!="function"||(l!==p||u!==d)&&XA(n,a,s,d),ki=!1,u=n.memoizedState,a.state=u,Eh(n,s,a,i);var y=n.memoizedState;l!==p||u!==y||ar.current||ki?(typeof h=="function"&&(wx(n,r,h,s),y=n.memoizedState),(c=ki||YA(n,r,c,s,u,y,d)||!1)?(f||typeof a.UNSAFE_componentWillUpdate!="function"&&typeof a.componentWillUpdate!="function"||(typeof a.componentWillUpdate=="function"&&a.componentWillUpdate(s,y,d),typeof a.UNSAFE_componentWillUpdate=="function"&&a.UNSAFE_componentWillUpdate(s,y,d)),typeof a.componentDidUpdate=="function"&&(n.flags|=4),typeof a.getSnapshotBeforeUpdate=="function"&&(n.flags|=1024)):(typeof a.componentDidUpdate!="function"||l===e.memoizedProps&&u===e.memoizedState||(n.flags|=4),typeof a.getSnapshotBeforeUpdate!="function"||l===e.memoizedProps&&u===e.memoizedState||(n.flags|=1024),n.memoizedProps=s,n.memoizedState=y),a.props=s,a.state=y,a.context=d,s=c):(typeof a.componentDidUpdate!="function"||l===e.memoizedProps&&u===e.memoizedState||(n.flags|=4),typeof a.getSnapshotBeforeUpdate!="function"||l===e.memoizedProps&&u===e.memoizedState||(n.flags|=1024),s=!1)}return Tx(e,n,r,s,o,i)}function Tx(e,n,r,s,i,o){mS(e,n);var a=(n.flags&128)!==0;if(!s&&!a)return i&&MA(n,r,!1),ei(e,n,o);s=n.stateNode,_C.current=n;var l=a&&typeof r.getDerivedStateFromError!="function"?null:s.render();return n.flags|=1,e!==null&&a?(n.child=Hl(n,e.child,null,o),n.child=Hl(n,null,l,o)):Ln(e,n,l,o),n.memoizedState=s.state,i&&MA(n,r,!0),n.child}function xS(e){var n=e.stateNode;n.pendingContext?$A(e,n.pendingContext,n.pendingContext!==n.context):n.context&&$A(e,n.context,!1),Ab(e,n.containerInfo)}function r1(e,n,r,s,i){return Ul(),fb(i),n.flags|=256,Ln(e,n,r,s
vendor: 5,939 bytes, line 40
40),n.child}var zx={dehydrated:null,treeContext:null,retryLane:0};function Nx(e){return{baseLanes:e,cachePool:null,transitions:null}}function yS(e,n,r){var s=n.pendingProps,i=Dt.current,o=!1,a=(n.flags&128)!==0,l;if((l=a)||(l=e!==null&&e.memoizedState===null?!1:(i&2)!==0),l?(o=!0,n.flags&=-129):(e===null||e.memoizedState!==null)&&(i|=1),jt(Dt,i&1),e===null)return _x(n),e=n.memoizedState,e!==null&&(e=e.dehydrated,e!==null)?(n.mode&1?e.data==="$!"?n.lanes=8:n.lanes=1073741824:n.lanes=1,null):(a=s.children,e=s.fallback,o?(s=n.mode,o=n.child,a={mode:"hidden",children:a},!(s&1)&&o!==null?(o.childLanes=0,o.pendingProps=a):o=zf(a,s,0,null),e=la(e,s,r,null),o.return=n,e.return=n,o.sibling=e,n.child=o,n.child.memoizedState=Nx(r),n.memoizedState=zx,e):Tb(n,a));if(i=e.memoizedState,i!==null&&(l=i.dehydrated,l!==null))return jC(e,n,a,s,l,i,r);if(o){o=s.fallback,a=n.mode,i=e.child,l=i.sibling;var d={mode:"hidden",children:s.children};return!(a&1)&&n.child!==i?(s=n.child,s.childLanes=0,s.pendingProps=d,n.deletions=null):(s=eo(i,d),s.subtreeFlags=i.subtreeFlags&14680064),l!==null?o=eo(l,o):(o=la(o,a,r,null),o.flags|=2),o.return=n,s.return=n,s.sibling=o,n.child=s,s=o,o=n.child,a=e.child.memoizedState,a=a===null?Nx(r):{baseLanes:a.baseLanes|r,cachePool:null,transitions:a.transitions},o.memoizedState=a,o.childLanes=e.childLanes&~r,n.memoizedState=zx,s}return o=e.child,e=o.sibling,s=eo(o,{mode:"visible",children:s.children}),!(n.mode&1)&&(s.lanes=r),s.return=n,s.sibling=null,e!==null&&(r=n.deletions,r===null?(n.deletions=[e],n.flags|=16):r.push(e)),n.child=s,n.memoizedState=null,s}function Tb(e,n){return n=zf({mode:"visible",children:n},e.mode,0,null),n.return=e,e.child=n}function Uu(e,n,r,s){return s!==null&&fb(s),Hl(n,e.child,null,r),e=Tb(n,n.pendingProps.children),e.flags|=2,n.memoizedState=null,e}function jC(e,n,r,s,i,o,a){if(r)return n.flags&256?(n.flags&=-257,s=Wg(Error(Se(422))),Uu(e,n,a,s)):n.memoizedState!==null?(n.child=e.child,n.flags|=128,null):(o=s.fallback,i=n.mode,s=zf({mode:"visible",children:s.children},i,0,null),o=la(o,i,a,null),o.flags|=2,s.return=n,o.return=n,s.sibling=o,n.child=s,n.mode&1&&Hl(n,e.child,null,a),n.child.memoizedState=Nx(a),n.memoizedState=zx,o);if(!(n.mode&1))return Uu(e,n,a,null);if(i.data==="$!"){if(s=i.nextSibling&&i.nextSibling.dataset,s)var l=s.dgst;return s=l,o=Error(Se(419)),s=Wg(o,s,void 0),Uu(e,n,a,s)}if(l=(a&e.childLanes)!==0,or||l){if(s=yn,s!==null){switch(a&-a){case 4:i=2;break;case 16:i=8;break;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:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:i=32;break;case 536870912:i=268435456;break;default:i=0}i=i&(s.suspendedLanes|a)?0:i,i!==0&&i!==o.retryLane&&(o.retryLane=i,Qs(e,i),es(s,e,i,-1))}return qb(),s=Wg(Error(Se(421))),Uu(e,n,a,s)}return i.data==="$?"?(n.flags|=128,n.child=e.child,n=OC.bind(null,e),i._reactRetry=n,null):(e=o.treeContext,br=Xi(i.nextSibling),Ar=n,Et=!0,Jr=null,e!==null&&(zr[Nr++]=Bs,zr[Nr++]=Us,zr[Nr++]=ua,Bs=e.id,Us=e.overflow,ua=n),n=Tb(n,s.children),n.flags|=4096,n)}function s1(e,n,r){e.lanes|=n;var s=e.alternate;s!==null&&(s.lanes|=n),jx(e.return,n,r)}function $g(e,n,r,s,i){var o=e.memoizedState;o===null?e.memoizedState={isBackwards:n,rendering:null,renderingStartTime:0,last:s,tail:r,tailMode:i}:(o.isBackwards=n,o.rendering=null,o.renderingStartTime=0,o.last=s,o.tail=r,o.tailMode=i)}function bS(e,n,r){var s=n.pendingProps,i=s.revealOrder,o=s.tail;if(Ln(e,n,s.children,r),s=Dt.current,s&2)s=s&1|2,n.flags|=128;else{if(e!==null&&e.flags&128)e:for(e=n.child;e!==null;){if(e.tag===13)e.memoizedState!==null&&s1(e,r,n);else if(e.tag===19)s1(e,r,n);else if(e.child!==null){e.child.return=e,e=e.child;continue}if(e===n)break e;for(;e.sibling===null;){if(e.return===null||e.return===n)break e;e=e.return}e.sibling.return=e.return,e=e.sibling}s&=1}if(jt(Dt,s),!(n.mode&1))n.memoizedState=null;else switch(i){case"forwards":for(r=n.child,i=null;r!==null;)e=r.alternate,e!==null&&Ph(e)===null&&(i=r),r=r.sibling;r=i,r===null?(i=n.child,n.child=null):(i=r.sibling,r.sibling=null),$g(n,!1,i,r,o);break;case"backwards":for(r=null,i=n.child,n.child=null;i!==null;){if(e=i.alternate,e!==null&&Ph(e)===null){n.child=i;break}e=i.sibling,i.sibling=r,r=i,i=e}$g(n,!0,r,null,o);break;case"together":$g(n,!1,null,null,void 0);break;default:n.memoizedState=null}return n.child}function Xp(e,n){!(n.mode&1)&&e!==null&&(e.alternate=null,n.alternate=null,n.flags|=2)}function ei(e,n,r){if(e!==null&&(n.dependencies=e.dependencies),ha|=n.lanes,!(r&n.childLanes))return null;if(e!==null&&n.child!==e.child)throw Error(Se(153));if(n.child!==null){for(e=n.child,r=eo(e,e.pendingProps),n.child=r,r.return=n;e.sibling!==null;)e=e.sibling,r=r.sibling=eo(e,e.pendingProps),r.return=n;r.sibling=null}return n.child}function wC(e,n,r){switch(n.tag){case 3:xS(n),Ul();break;case 5:Hw(n);break;case 1:lr(n.type)&&Ch(n);break;case 4:Ab(n,n.stateNode.containerInfo);break;case 10:var s=n.type._context,i=n.memoizedProps.value;jt(Nh,s._currentValue),s._currentValue=i;break;case 13:if(s=n.memoizedState,s!==null)return s.dehydrated!==null?(jt(Dt,Dt.current&1),n.flags|=128,null):r&n.child.childLanes?yS(e,n,r):(jt(Dt,Dt.current&1),e=ei(e,n,r),e!==null?e.sibling:null);jt(Dt,Dt.current&1);break;case 19:if(s=(r&n.childLanes)!==0,e.flags&128){if(s)return bS(e,n,r);n.flags|=128}if(i=n.memoizedState,i!==null&&(i.rendering=null,i.tail=null,i.lastEffect=null),jt(Dt,Dt.current),s)break;return null;case 22:case 23:return n.lanes=0,gS(e,n,r)}return ei(e,n,r)}var AS,Rx,vS,_S;AS=function(e,n){for(var r=n.child;r!==null;){if(r.tag===5||r.tag===6)e.appendChild(r.stateNode);else if(r.tag!==4&&r.child!==null){r.child.return=r,r=r.child;continue}if(r===n)break;for(;r.sibling===null;){if(r.return===null||r.return===n)return;r=r.return}r.sibling.return=r.return,r=r.sibling}};Rx=function(){};
vendor: 4,208 bytes, line 40
40vS=function(e,n,r,s){var i=e.memoizedProps;if(i!==s){e=n.stateNode,Vo(Ss.current);var o=null;switch(r){case"input":i=Qm(e,i),s=Qm(e,s),o=[];break;case"select":i=Lt({},i,{value:void 0}),s=Lt({},s,{value:void 0}),o=[];break;case"textarea":i=nx(e,i),s=nx(e,s),o=[];break;default:typeof i.onClick!="function"&&typeof s.onClick=="function"&&(e.onclick=Sh)}sx(r,s);var a;r=null;for(c in i)if(!s.hasOwnProperty(c)&&i.hasOwnProperty(c)&&i[c]!=null)if(c==="style"){var l=i[c];for(a in l)l.hasOwnProperty(a)&&(r||(r={}),r[a]="")}else c!=="dangerouslySetInnerHTML"&&c!=="children"&&c!=="suppressContentEditableWarning"&&c!=="suppressHydrationWarning"&&c!=="autoFocus"&&(_c.hasOwnProperty(c)?o||(o=[]):(o=o||[]).push(c,null));for(c in s){var d=s[c];if(l=i!=null?i[c]:void 0,s.hasOwnProperty(c)&&d!==l&&(d!=null||l!=null))if(c==="style")if(l){for(a in l)!l.hasOwnProperty(a)||d&&d.hasOwnProperty(a)||(r||(r={}),r[a]="");for(a in d)d.hasOwnProperty(a)&&l[a]!==d[a]&&(r||(r={}),r[a]=d[a])}else r||(o||(o=[]),o.push(c,r)),r=d;else c==="dangerouslySetInnerHTML"?(d=d?d.__html:void 0,l=l?l.__html:void 0,d!=null&&l!==d&&(o=o||[]).push(c,d)):c==="children"?typeof d!="string"&&typeof d!="number"||(o=o||[]).push(c,""+d):c!=="suppressContentEditableWarning"&&c!=="suppressHydrationWarning"&&(_c.hasOwnProperty(c)?(d!=null&&c==="onScroll"&&St("scroll",e),o||l===d||(o=[])):(o=o||[]).push(c,d))}r&&(o=o||[]).push("style",r);var c=o;(n.updateQueue=c)&&(n.flags|=4)}};_S=function(e,n,r,s){r!==s&&(n.flags|=4)};function Nd(e,n){if(!Et)switch(e.tailMode){case"hidden":n=e.tail;for(var r=null;n!==null;)n.alternate!==null&&(r=n),n=n.sibling;r===null?e.tail=null:r.sibling=null;break;case"collapsed":r=e.tail;for(var s=null;r!==null;)r.alternate!==null&&(s=r),r=r.sibling;s===null?n||e.tail===null?e.tail=null:e.tail.sibling=null:s.sibling=null}}function Cn(e){var n=e.alternate!==null&&e.alternate.child===e.child,r=0,s=0;if(n)for(var i=e.child;i!==null;)r|=i.lanes|i.childLanes,s|=i.subtreeFlags&14680064,s|=i.flags&14680064,i.return=e,i=i.sibling;else for(i=e.child;i!==null;)r|=i.lanes|i.childLanes,s|=i.subtreeFlags,s|=i.flags,i.return=e,i=i.sibling;return e.subtreeFlags|=s,e.childLanes=r,n}function SC(e,n,r){var s=n.pendingProps;switch(hb(n),n.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return Cn(n),null;case 1:return lr(n.type)&&kh(),Cn(n),null;case 3:return s=n.stateNode,Vl(),Ct(ar),Ct(Nn),_b(),s.pendingContext&&(s.context=s.pendingContext,s.pendingContext=null),(e===null||e.child===null)&&(Fu(n)?n.flags|=4:e===null||e.memoizedState.isDehydrated&&!(n.flags&256)||(n.flags|=1024,Jr!==null&&(Wx(Jr),Jr=null))),Rx(e,n),Cn(n),null;case 5:vb(n);var i=Vo(qc.current);if(r=n.type,e!==null&&n.stateNode!=null)vS(e,n,r,s,i),e.ref!==n.ref&&(n.flags|=512,n.flags|=2097152);else{if(!s){if(n.stateNode===null)throw Error(Se(166));return Cn(n),null}if(e=Vo(Ss.current),Fu(n)){s=n.stateNode,r=n.type;var o=n.memoizedProps;switch(s[As]=n,s[Ec]=o,e=(n.mode&1)!==0,r){case"dialog":St("cancel",s),St("close",s);break;case"iframe":case"object":case"embed":St("load",s);break;case"video":case"audio":for(i=0;i<nc.length;i++)St(nc[i],s);break;case"source":St("error",s);break;case"img":case"image":case"link":St("error",s),St("load",s);break;case"details":St("toggle",s);break;case"input":hA(s,o),St("invalid",s);break;case"select":s._wrapperState={wasMultiple:!!o.multiple},St("invalid",s);break;case"textarea":gA(s,o),St("invalid",s)}sx(r,o),i=null;for(var a in o)if(o.hasOwnProperty(a)){var l=o[a];a==="children"?typeof l=="string"?s.textContent!==l&&(o.suppressHydrationWarning!==!0&&Mu(s.textContent,l,e),i=["children",l]):typeof l=="number"&&s.textContent!==""+l&&(o.suppressHydrationWarning!==!0&&Mu(s.textContent,l,e),i=["children",""+l]):_c.hasOwnProperty(a)&&l!=null&&a==="onScroll"&&St("scroll",s)}switch(r){case"input":Pu(s),fA(s,o,!0);break;case"textarea":Pu(s),mA(s);break;case"select":case"option":break;default:typeof o.onClick=="function"&&(s.onclick=Sh)}s=i,n.updateQueue=s,s!==null&&(n.flags|=4)}else{a=i.nodeType===9?i:i.ownerDocument,e==="http://www.w3.org/1999/xhtml"&&(e=X2(r)),e==="http://www.w3.org/1999/xhtml"?r==="script"?(e=a.createElement("div"),e.innerHTML="<script><\/script>
40",e=e.removeChild(e.firstChild)):typeof s.is=="string"?e=a.createElement(r,{is:s.is}):(e=a.createElement(r),r==="select"&&(a=e,s.multiple?a.multiple=!0:s.size&&(a.size=s.size))):e=a.createElementNS(e,r),e[As]=n,e[Ec]=s,AS(e,n,!1,!1),n.stateNode=e;e:{switch(a=ix(r,s),r){case"dialog":St("cancel",e),St("close",e),i=s;break;case"iframe":case"object":case"embed":St("load",e),i=s;break;case"video":case"audio":for(i=0;i<nc.length;i++)St(nc[i],e);i=s;break;case"source":St("error",e),i=s;break;case"img":case"image":case"link":St("error",e),St("load",e),i=s;break;case"details":St("toggle",e),i=s;break;case"input":hA(e,s),i=Qm(e,s),St("invalid",e);break;case"option":i=s;break;case"select":e._wrapperState={wasMultiple:!!s.multiple},i=Lt({},s,{value:void 0}),St("invalid",e);break;case"textarea":gA(e,s),i=nx(e,s),St("invalid",e);break;default:i=s}sx(r,i),l=i;for(o in l)if(l.hasOwnProperty(o)){var d=l[o];o==="style"?Q2(e,d):o==="dangerouslySetInnerHTML"?(d=d?d.__html:void 0,d!=null&&G2(e,d)):o==="children"?typeof d=="string"?(r!=="textarea"||d!=="")&&jc(e,d):typeof d=="number"&&jc(e,""+d):o!=="suppressContentEditableWarning"&&o!=="suppressHydrationWarning"&&o!=="autoFocus"&&(_c.hasOwnProperty(o)?d!=null&&o==="onScroll"&&St("scroll",e):d!=null&&Jy(e,o,d,a))}switch(r){case"input":Pu(e),fA(e,s,!1);break;case"textarea":Pu(e),mA(e);break;case"option":s.value!=null&&e.setAttribute("value",""+oo(s.value));break;case"select":e.multiple=!!s.multiple,o=s.value,o!=null?bl(e,!!s.multiple,o,!1):s.defaultValue!=null&&bl(e,!!s.multiple,s.defaultValue,!0);break;default:typeof i.onClick=="function"&&(e.onclick=Sh)}switch(r){case"button":case"input":case"select":case"textarea":s=!!s.autoFocus;break e;case"img":s=!0;break e;default:s=!1}}s&&(n.flags|=4)}n.ref!==null&&(n.flags|=512,n.flags|=2097152)}return Cn(n),null;case 6:if(e&&n.stateNode!=null)_S(e,n,e.memoizedProps,s);else{if(typeof s!="string"&&n.stateNode===null)throw Error(Se(166));if(r=Vo(qc.current),Vo(Ss.current),Fu(n)){if(s=n.stateNode,r=n.memoizedProps,s[As]=n,(o=s.nodeValue!==r)&&(e=Ar,e!==null))switch(e.tag){case 3:Mu(s.nodeValue,r,(e.mode&1)!==0);break;case 5:e.memoizedProps.suppressHydrationWarning!==!0&&Mu(s.nodeValue,r,(e.mode&1)!==0)}o&&(n.flags|=4)}else s=(r.nodeType===9?r:r.ownerDocument).createTextNode(s),s[As]=n,n.stateNode=s}return Cn(n),null;case 13:if(Ct(Dt),s=n.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(Et&&br!==null&&n.mode&1&&!(n.flags&128))$w(),Ul(),n.flags|=98560,o=!1;else if(o=Fu(n),s!==null&&s.dehydrated!==null){if(e===null){if(!o)throw Error(Se(318));if(o=n.memoizedState,o=o!==null?o.dehydrated:null,!o)throw Error(Se(317));o[As]=n}else Ul(),!(n.flags&128)&&(n.memoizedState=null),n.flags|=4;Cn(n),o=!1}else Jr!==null&&(Wx(Jr),Jr=null),o=!0;if(!o)return n.flags&65536?n:null}return n.flags&128?(n.lanes=r,n):(s=s!==null,s!==(e!==null&&e.memoizedState!==null)&&s&&(n.child.flags|=8192,n.mode&1&&(e===null||Dt.current&1?ln===0&&(ln=3):qb())),n.updateQueue!==null&&(n.flags|=4),Cn(n),null);case 4:return Vl(),Rx(e,n),e===null&&Nc(n.stateNode.containerInfo),Cn(n),null;case 10:return xb(n.type._context),Cn(n),null;case 17:return lr(n.type)&&kh(),Cn(n),null;case 19:if(Ct(Dt),o=n.memoizedState,o===null)return Cn(n),null;if(s=(n.flags&128)!==0,a=o.rendering,a===null)if(s)Nd(o,!1);else{if(ln!==0||e!==null&&e.flags&128)for(e=n.child;e!==null;){if(a=Ph(e),a!==null){for(n.flags|=128,Nd(o,!1),s=a.updateQueue,s!==null&&(n.updateQueue=s,n.flags|=4),n.subtreeFlags=0,s=r,r=n.child;r!==null;)o=r,e=s,o.flags&=14680066,a=o.alternate,a===null?(o.childLanes=0,o.lanes=e,o.child=null,o.subtreeFlags=0,o.memoizedProps=null,o.memoizedState=null,o.updateQueue=null,o.dependencies=null,o.stateNode=null):(o.childLanes=a.childLanes,o.lanes=a.lanes,o.child=a.child,o.subtreeFlags=0,o.deletions=null,o.memoizedProps=a.memoizedProps,o.memoizedState=a.memoizedState,o.updateQueue=a.updateQueue,o.type=a.type,e=a.dependencies,o.dependencies=e===null?null:{lanes:e.lanes,firstContext:e.firstContext}),r=r.sibling;return jt(Dt,Dt.current&1|2),n.child}e=e.sibling}o.tail!==null&&Qt()>Kl&&(n.flags|=128,s=!0,Nd(o,!1),n.lanes=4194304)}else{if(!s)if(e=Ph(a),e!==null){if(n.flags|=128,s=!0,r=e.updateQueue,r!==null&&(n.updateQueue=r,n.flags|=4),Nd(o,!0),o.tail===null&&o.tailMode==="hidden"&&!a.alternate&&!Et)return Cn(n),null}else 2*Qt()-o.renderingStartTime>Kl&&r!==1073741824&&(n.flags|=128,s=!0,Nd(o,!1),n.lanes=4194304);o.isBackwards?(a.sibling=n.child,n.child=a):(r=o.last,r!==null?r.sibling=a:n.child=a,o.last=a)}return o.tail!==null?(n=o.tail,o.rendering=n,o.tail=n.sibling,o.renderingStartTime=Qt(),n.sibling=null,r=Dt.current,jt(Dt,s?r&1|2:r&1),n):(Cn(n),null);case 22:case 23:return Pb(),s=n.memoizedState!==null,e!==null&&e.memoizedState!==null!==s&&(n.flags|=8192),s&&n.mode&1?mr&1073741824&&(Cn(n),n.subtreeFlags&6&&(n.flags|=8192)):Cn(n),null;case 24:return null;case 25:return null}throw Error(Se(156,n.tag))}function kC(e,n){switch(hb(n),n.tag){case 1:return lr(n.type)&&kh(),e=n.flags,e&65536?(n.flags=e&-65537|128,n):null;
vendor: 26,298 bytes, line 40
40case 3:return Vl(),Ct(ar),Ct(Nn),_b(),e=n.flags,e&65536&&!(e&128)?(n.flags=e&-65537|128,n):null;case 5:return vb(n),null;case 13:if(Ct(Dt),e=n.memoizedState,e!==null&&e.dehydrated!==null){if(n.alternate===null)throw Error(Se(340));Ul()}return e=n.flags,e&65536?(n.flags=e&-65537|128,n):null;case 19:return Ct(Dt),null;case 4:return Vl(),null;case 10:return xb(n.type._context),null;case 22:case 23:return Pb(),null;case 24:return null;default:return null}}var Hu=!1,zn=!1,CC=typeof WeakSet=="function"?WeakSet:Set,qe=null;function pl(e,n){var r=e.ref;if(r!==null)if(typeof r=="function")try{r(null)}catch(s){Vt(e,n,s)}else r.current=null}function Ex(e,n,r){try{r()}catch(s){Vt(e,n,s)}}var i1=!1;function TC(e,n){if(gx=_h,e=Cw(),ub(e)){if("selectionStart"in e)var r={start:e.selectionStart,end:e.selectionEnd};else e:{r=(r=e.ownerDocument)&&r.defaultView||window;var s=r.getSelection&&r.getSelection();if(s&&s.rangeCount!==0){r=s.anchorNode;var i=s.anchorOffset,o=s.focusNode;s=s.focusOffset;try{r.nodeType,o.nodeType}catch{r=null;break e}var a=0,l=-1,d=-1,c=0,f=0,p=e,u=null;t:for(;;){for(var h;p!==r||i!==0&&p.nodeType!==3||(l=a+i),p!==o||s!==0&&p.nodeType!==3||(d=a+s),p.nodeType===3&&(a+=p.nodeValue.length),(h=p.firstChild)!==null;)u=p,p=h;for(;;){if(p===e)break t;if(u===r&&++c===i&&(l=a),u===o&&++f===s&&(d=a),(h=p.nextSibling)!==null)break;p=u,u=p.parentNode}p=h}r=l===-1||d===-1?null:{start:l,end:d}}else r=null}r=r||{start:0,end:0}}else r=null;for(mx={focusedElem:e,selectionRange:r},_h=!1,qe=n;qe!==null;)if(n=qe,e=n.child,(n.subtreeFlags&1028)!==0&&e!==null)e.return=n,qe=e;else for(;qe!==null;){n=qe;try{var y=n.alternate;if(n.flags&1024)switch(n.tag){case 0:case 11:case 15:break;case 1:if(y!==null){var m=y.memoizedProps,b=y.memoizedState,A=n.stateNode,v=A.getSnapshotBeforeUpdate(n.elementType===n.type?m:Kr(n.type,m),b);A.__reactInternalSnapshotBeforeUpdate=v}break;case 3:var x=n.stateNode.containerInfo;x.nodeType===1?x.textContent="":x.nodeType===9&&x.documentElement&&x.removeChild(x.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(Se(163))}}catch(_){Vt(n,n.return,_)}if(e=n.sibling,e!==null){e.return=n.return,qe=e;break}qe=n.return}return y=i1,i1=!1,y}function fc(e,n,r){var s=n.updateQueue;if(s=s!==null?s.lastEffect:null,s!==null){var i=s=s.next;do{if((i.tag&e)===e){var o=i.destroy;i.destroy=void 0,o!==void 0&&Ex(n,r,o)}i=i.next}while(i!==s)}}function Cf(e,n){if(n=n.updateQueue,n=n!==null?n.lastEffect:null,n!==null){var r=n=n.next;do{if((r.tag&e)===e){var s=r.create;r.destroy=s()}r=r.next}while(r!==n)}}function Px(e){var n=e.ref;if(n!==null){var r=e.stateNode;switch(e.tag){case 5:e=r;break;default:e=r}typeof n=="function"?n(e):n.current=e}}function jS(e){var n=e.alternate;n!==null&&(e.alternate=null,jS(n)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(n=e.stateNode,n!==null&&(delete n[As],delete n[Ec],delete n[bx],delete n[cC],delete n[uC])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function wS(e){return e.tag===5||e.tag===3||e.tag===4}function o1(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||wS(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function qx(e,n,r){var s=e.tag;if(s===5||s===6)e=e.stateNode,n?r.nodeType===8?r.parentNode.insertBefore(e,n):r.insertBefore(e,n):(r.nodeType===8?(n=r.parentNode,n.insertBefore(e,r)):(n=r,n.appendChild(e)),r=r._reactRootContainer,r!=null||n.onclick!==null||(n.onclick=Sh));else if(s!==4&&(e=e.child,e!==null))for(qx(e,n,r),e=e.sibling;e!==null;)qx(e,n,r),e=e.sibling}function Dx(e,n,r){var s=e.tag;if(s===5||s===6)e=e.stateNode,n?r.insertBefore(e,n):r.appendChild(e);else if(s!==4&&(e=e.child,e!==null))for(Dx(e,n,r),e=e.sibling;e!==null;)Dx(e,n,r),e=e.sibling}var vn=null,Gr=!1;function ui(e,n,r){for(r=r.child;r!==null;)SS(e,n,r),r=r.sibling}function SS(e,n,r){if(ws&&typeof ws.onCommitFiberUnmount=="function")try{ws.onCommitFiberUnmount(bf,r)}catch{}switch(r.tag){case 5:zn||pl(r,n);case 6:var s=vn,i=Gr;vn=null,ui(e,n,r),vn=s,Gr=i,vn!==null&&(Gr?(e=vn,r=r.stateNode,e.nodeType===8?e.parentNode.removeChild(r):e.removeChild(r)):vn.removeChild(r.stateNode));break;case 18:vn!==null&&(Gr?(e=vn,r=r.stateNode,e.nodeType===8?Pg(e.parentNode,r):e.nodeType===1&&Pg(e,r),Cc(e)):Pg(vn,r.stateNode));break;case 4:s=vn,i=Gr,vn=r.stateNode.containerInfo,Gr=!0,ui(e,n,r),vn=s,Gr=i;break;case 0:case 11:case 14:case 15:if(!zn&&(s=r.updateQueue,s!==null&&(s=s.lastEffect,s!==null))){i=s=s.next;do{var o=i,a=o.destroy;o=o.tag,a!==void 0&&(o&2||o&4)&&Ex(r,n,a),i=i.next}while(i!==s)}ui(e,n,r);break;case 1:if(!zn&&(pl(r,n),s=r.stateNode,typeof s.componentWillUnmount=="function"))try{s.props=r.memoizedProps,s.state=r.memoizedState,s.componentWillUnmount()}catch(l){Vt(r,n,l)}ui(e,n,r);break;case 21:ui(e,n,r);break;case 22:r.mode&1?(zn=(s=zn)||r.memoizedState!==null,ui(e,n,r),zn=s):ui(e,n,r);break;default:ui(e,n,r)}}function a1(e){var n=e.updateQueue;if(n!==null){e.updateQueue=null;var r=e.stateNode;r===null&&(r=e.stateNode=new CC),n.forEach(function(s){var i=IC.bind(null,e,s);r.has(s)||(r.add(s),s.then(i,i))})}}function Wr(e,n){var r=n.deletions;if(r!==null)for(var s=0;s<r.length;s++){var i=r[s];try{var o=e,a=n,l=a;e:for(;l!==null;){switch(l.tag){case 5:vn=l.stateNode,Gr=!1;break e;case 3:vn=l.stateNode.containerInfo,Gr=!0;break e;case 4:vn=l.stateNode.containerInfo,Gr=!0;break e}l=l.return}if(vn===null)throw Error(Se(160));SS(o,a,i),vn=null,Gr=!1;var d=i.alternate;d!==null&&(d.return=null),i.return=null}catch(c){Vt(i,n,c)}}if(n.subtreeFlags&12854)for(n=n.child;n!==null;)kS(n,e),n=n.sibling}function kS(e,n){var r=e.alternate,s=e.flags;switch(e.tag){case 0:case 11:case 14:case 15:if(Wr(n,e),os(e),s&4){try{fc(3,e,e.return),Cf(3,e)}catch(m){Vt(e,e.return,m)}try{fc(5,e,e.return)}catch(m){Vt(e,e.return,m)}}break;case 1:Wr(n,e),os(e),s&512&&r!==null&&pl(r,r.return);break;case 5:if(Wr(n,e),os(e),s&512&&r!==null&&pl(r,r.return),e.flags&32){var i=e.stateNode;try{jc(i,"")}catch(m){Vt(e,e.return,m)}}if(s&4&&(i=e.stateNode,i!=null)){var o=e.memoizedProps,a=r!==null?r.memoizedProps:o,l=e.type,d=e.updateQueue;if(e.updateQueue=null,d!==null)try{l==="input"&&o.type==="radio"&&o.name!=null&&K2(i,o),ix(l,a);var c=ix(l,o);for(a=0;a<d.length;a+=2){var f=d[a],p=d[a+1];f==="style"?Q2(i,p):f==="dangerouslySetInnerHTML"?G2(i,p):f==="children"?jc(i,p):Jy(i,f,p,c)}switch(l){case"input":ex(i,o);break;case"textarea":Y2(i,o);break;case"select":var u=i._wrapperState.wasMultiple;i._wrapperState.wasMultiple=!!o.multiple;var h=o.value;h!=null?bl(i,!!o.multiple,h,!1):u!==!!o.multiple&&(o.defaultValue!=null?bl(i,!!o.multiple,o.defaultValue,!0):bl(i,!!o.multiple,o.multiple?[]:"",!1))}i[Ec]=o}catch(m){Vt(e,e.return,m)}}break;case 6:if(Wr(n,e),os(e),s&4){if(e.stateNode===null)throw Error(Se(162));i=e.stateNode,o=e.memoizedProps;try{i.nodeValue=o}catch(m){Vt(e,e.return,m)}}break;case 3:if(Wr(n,e),os(e),s&4&&r!==null&&r.memoizedState.isDehydrated)try{Cc(n.containerInfo)}catch(m){Vt(e,e.return,m)}break;case 4:Wr(n,e),os(e);break;case 13:Wr(n,e),os(e),i=e.child,i.flags&8192&&(o=i.memoizedState!==null,i.stateNode.isHidden=o,!o||i.alternate!==null&&i.alternate.memoizedState!==null||(Rb=Qt())),s&4&&a1(e);break;case 22:if(f=r!==null&&r.memoizedState!==null,e.mode&1?(zn=(c=zn)||f,Wr(n,e),zn=c):Wr(n,e),os(e),s&8192){if(c=e.memoizedState!==null,(e.stateNode.isHidden=c)&&!f&&e.mode&1)for(qe=e,f=e.child;f!==null;){for(p=qe=f;qe!==null;){switch(u=qe,h=u.child,u.tag){case 0:case 11:case 14:case 15:fc(4,u,u.return);break;case 1:pl(u,u.return);var y=u.stateNode;if(typeof y.componentWillUnmount=="function"){s=u,r=u.return;try{n=s,y.props=n.memoizedProps,y.state=n.memoizedState,y.componentWillUnmount()}catch(m){Vt(s,r,m)}}break;case 5:pl(u,u.return);break;case 22:if(u.memoizedState!==null){d1(p);continue}}h!==null?(h.return=u,qe=h):d1(p)}f=f.sibling}e:for(f=null,p=e;;){if(p.tag===5){if(f===null){f=p;try{i=p.stateNode,c?(o=i.style,typeof o.setProperty=="function"?o.setProperty("display","none","important"):o.display="none"):(l=p.stateNode,d=p.memoizedProps.style,a=d!=null&&d.hasOwnProperty("display")?d.display:null,l.style.display=J2("display",a))}catch(m){Vt(e,e.return,m)}}}else if(p.tag===6){if(f===null)try{p.stateNode.nodeValue=c?"":p.memoizedProps}catch(m){Vt(e,e.return,m)}}else if((p.tag!==22&&p.tag!==23||p.memoizedState===null||p===e)&&p.child!==null){p.child.return=p,p=p.child;continue}if(p===e)break e;for(;p.sibling===null;){if(p.return===null||p.return===e)break e;f===p&&(f=null),p=p.return}f===p&&(f=null),p.sibling.return=p.return,p=p.sibling}}break;case 19:Wr(n,e),os(e),s&4&&a1(e);break;case 21:break;default:Wr(n,e),os(e)}}function os(e){var n=e.flags;if(n&2){try{e:{for(var r=e.return;r!==null;){if(wS(r)){var s=r;break e}r=r.return}throw Error(Se(160))}switch(s.tag){case 5:var i=s.stateNode;s.flags&32&&(jc(i,""),s.flags&=-33);var o=o1(e);Dx(e,o,i);break;case 3:case 4:var a=s.stateNode.containerInfo,l=o1(e);qx(e,l,a);break;default:throw Error(Se(161))}}catch(d){Vt(e,e.return,d)}e.flags&=-3}n&4096&&(e.flags&=-4097)}function zC(e,n,r){qe=e,CS(e)}function CS(e,n,r){for(var s=(e.mode&1)!==0;qe!==null;){var i=qe,o=i.child;if(i.tag===22&&s){var a=i.memoizedState!==null||Hu;if(!a){var l=i.alternate,d=l!==null&&l.memoizedState!==null||zn;l=Hu;var c=zn;if(Hu=a,(zn=d)&&!c)for(qe=i;qe!==null;)a=qe,d=a.child,a.tag===22&&a.memoizedState!==null?c1(i):d!==null?(d.return=a,qe=d):c1(i);for(;o!==null;)qe=o,CS(o),o=o.sibling;qe=i,Hu=l,zn=c}l1(e)}else i.subtreeFlags&8772&&o!==null?(o.return=i,qe=o):l1(e)}}function l1(e){for(;qe!==null;){var n=qe;if(n.flags&8772){var r=n.alternate;try{if(n.flags&8772)switch(n.tag){case 0:case 11:case 15:zn||Cf(5,n);break;case 1:var s=n.stateNode;if(n.flags&4&&!zn)if(r===null)s.componentDidMount();else{var i=n.elementType===n.type?r.memoizedProps:Kr(n.type,r.memoizedProps);s.componentDidUpdate(i,r.memoizedState,s.__reactInternalSnapshotBeforeUpdate)}var o=n.updateQueue;o!==null&&VA(n,o,s);break;case 3:var a=n.updateQueue;if(a!==null){if(r=null,n.child!==null)switch(n.child.tag){case 5:r=n.child.stateNode;break;case 1:r=n.child.stateNode}VA(n,a,r)}break;case 5:var l=n.stateNode;if(r===null&&n.flags&4){r=l;var d=n.memoizedProps;switch(n.type){case"button":case"input":case"select":case"textarea":d.autoFocus&&r.focus();break;case"img":d.src&&(r.src=d.src)}}break;case 6:break;case 4:break;case 12:break;case 13:if(n.memoizedState===null){var c=n.alternate;if(c!==null){var f=c.memoizedState;if(f!==null){var p=f.dehydrated;p!==null&&Cc(p)}}}break;case 19:case 17:case 21:case 22:case 23:case 25:break;default:throw Error(Se(163))}zn||n.flags&512&&Px(n)}catch(u){Vt(n,n.return,u)}}if(n===e){qe=null;break}if(r=n.sibling,r!==null){r.return=n.return,qe=r;break}qe=n.return}}function d1(e){for(;qe!==null;){var n=qe;if(n===e){qe=null;break}var r=n.sibling;if(r!==null){r.return=n.return,qe=r;break}qe=n.return}}function c1(e){for(;qe!==null;){var n=qe;try{switch(n.tag){case 0:case 11:case 15:var r=n.return;try{Cf(4,n)}catch(d){Vt(n,r,d)}break;case 1:var s=n.stateNode;if(typeof s.componentDidMount=="function"){var i=n.return;try{s.componentDidMount()}catch(d){Vt(n,i,d)}}var o=n.return;try{Px(n)}catch(d){Vt(n,o,d)}break;case 5:var a=n.return;try{Px(n)}catch(d){Vt(n,a,d)}}}catch(d){Vt(n,n.return,d)}if(n===e){qe=null;break}var l=n.sibling;if(l!==null){l.return=n.return,qe=l;break}qe=n.return}}var NC=Math.ceil,Oh=oi.ReactCurrentDispatcher,zb=oi.ReactCurrentOwner,qr=oi.ReactCurrentBatchConfig,pt=0,yn=null,nn=null,wn=0,mr=0,hl=uo(0),ln=0,Lc=null,ha=0,Tf=0,Nb=0,gc=null,rr=null,Rb=0,Kl=1/0,Ps=null,Ih=!1,Ox=null,Ji=null,Vu=!1,Ui=null,Lh=0,mc=0,Ix=null,Gp=-1,Jp=0;function Fn(){return pt&6?Qt():Gp!==-1?Gp:Gp=Qt()}function Qi(e){return e.mode&1?pt&2&&wn!==0?wn&-wn:hC.transition!==null?(Jp===0&&(Jp=uw()),Jp):(e=xt,e!==0||(e=window.event,e=e===void 0?16:yw(e.type)),e):1}function es(e,n,r,s){if(50<mc)throw mc=0,Ix=null,Error(Se(185));uu(e,r,s),(!(pt&2)||e!==yn)&&(e===yn&&(!(pt&2)&&(Tf|=r),ln===4&&zi(e,wn)),dr(e,s),r===1&&pt===0&&!(n.mode&1)&&(Kl=Qt()+500,wf&&po()))}function dr(e,n){var r=e.callbackNode;h6(e,n);var s=vh(e,e===yn?wn:0);if(s===0)r!==null&&bA(r),e.callbackNode=null,e.callbackPriority=0;else if(n=s&-s,e.callbackPriority!==n){if(r!=null&&bA(r),n===1)e.tag===0?pC(u1.bind(null,e)):Iw(u1.bind(null,e)),lC(function(){!(pt&6)&&po()}),r=null;else{switch(pw(s)){case 1:r=rb;break;case 4:r=dw;break;case 16:r=Ah;break;case 536870912:r=cw;break;default:r=Ah}r=DS(r,TS.bind(null,e))}e.callbackPriority=n,e.callbackNode=r}}function TS(e,n){if(Gp=-1,Jp=0,pt&6)throw Error(Se(327));var r=e.callbackNode;if(wl()&&e.callbackNode!==r)return null;var s=vh(e,e===yn?wn:0);if(s===0)return null;if(s&30||s&e.expiredLanes||n)n=Wh(e,s);else{n=s;var i=pt;pt|=2;var o=NS();(yn!==e||wn!==n)&&(Ps=null,Kl=Qt()+500,aa(e,n));do try{PC();break}catch(l){zS(e,l)}while(!0);mb(),Oh.current=o,pt=i,nn!==null?n=0:(yn=null,wn=0,n=ln)}if(n!==0){if(n===2&&(i=cx(e),i!==0&&(s=i,n=Lx(e,i))),n===1)throw r=Lc,aa(e,0),zi(e,s),dr(e,Qt()),r;if(n===6)zi(e,s);else{if(i=e.current.alternate,!(s&30)&&!RC(i)&&(n=Wh(e,s),n===2&&(o=cx(e),o!==0&&(s=o,n=Lx(e,o))),n===1))throw r=Lc,aa(e,0),zi(e,s),dr(e,Qt()),r;switch(e.finishedWork=i,e.finishedLanes=s,n){case 0:case 1:throw Error(Se(345));case 2:Oo(e,rr,Ps);break;case 3:if(zi(e,s),(s&130023424)===s&&(n=Rb+500-Qt(),10<n)){if(vh(e,0)!==0)break;if(i=e.suspendedLanes,(i&s)!==s){Fn(),e.pingedLanes|=e.suspendedLanes&i;break}e.timeoutHandle=yx(Oo.bind(null,e,rr,Ps),n);break}Oo(e,rr,Ps);break;case 4:if(zi(e,s),(s&4194240)===s)break;for(n=e.eventTimes,i=-1;0<s;){var a=31-Qr(s);o=1<<a,a=n[a],a>i&&(i=a),s&=~o}if(s=i,s=Qt()-s,s=(120>s?120:480>s?480:1080>s?1080:1920>s?1920:3e3>s?3e3:4320>s?4320:1960*NC(s/1960))-s,10<s){e.timeoutHandle=yx(Oo.bind(null,e,rr,Ps),s);break}Oo(e,rr,Ps);break;case 5:Oo(e,rr,Ps);break;default:throw Error(Se(329))}}}return dr(e,Qt()),e.callbackNode===r?TS.bind(null,e):null}function Lx(e,n){var r=gc;return e.current.memoizedState.isDehydrated&&(aa(e,n).flags|=256),e=Wh(e,n),e!==2&&(n=rr,rr=r,n!==null&&Wx(n)),e}function Wx(e){rr===null?rr=e:rr.push.apply(rr,e)}function RC(e){for(var n=e;;){if(n.flags&16384){var r=n.updateQueue;if(r!==null&&(r=r.stores,r!==null))for(var s=0;s<r.length;s++){var i=r[s],o=i.getSnapshot;i=i.value;try{if(!ts(o(),i))return!1}catch{return!1}}}if(r=n.child,n.subtreeFlags&16384&&r!==null)r.return=n,n=r;else{if(n===e)break;for(;n.sibling===null;){if(n.return===null||n.return===e)return!0;n=n.return}n.sibling.return=n.return,n=n.sibling}}return!0}function zi(e,n){for(n&=~Nb,n&=~Tf,e.suspendedLanes|=n,e.pingedLanes&=~n,e=e.expirationTimes;0<n;){var r=31-Qr(n),s=1<<r;e[r]=-1,n&=~s}}function u1(e){if(pt&6)throw Error(Se(327));wl();var n=vh(e,0);if(!(n&1))return dr(e,Qt()),null;var r=Wh(e,n);if(e.tag!==0&&r===2){var s=cx(e);s!==0&&(n=s,r=Lx(e,s))}if(r===1)throw r=Lc,aa(e,0),zi(e,n),dr(e,Qt()),r;if(r===6)throw Error(Se(345));return e.finishedWork=e.current.alternate,e.finishedLanes=n,Oo(e,rr,Ps),dr(e,Qt()),null}function Eb(e,n){var r=pt;pt|=1;try{return e(n)}finally{pt=r,pt===0&&(Kl=Qt()+500,wf&&po())}}function fa(e){Ui!==null&&Ui.tag===0&&!(pt&6)&&wl();var n=pt;pt|=1;var r=qr.transition,s=xt;try{if(qr.transition=null,xt=1,e)return e()}finally{xt=s,qr.transition=r,pt=n,!(pt&6)&&po()}}function Pb(){mr=hl.current,Ct(hl)}function aa(e,n){e.finishedWork=null,e.finishedLanes=0;var r=e.timeoutHandle;if(r!==-1&&(e.timeoutHandle=-1,aC(r)),nn!==null)for(r=nn.return;r!==null;){var s=r;switch(hb(s),s.tag){case 1:s=s.type.childContextTypes,s!=null&&kh();break;case 3:Vl(),Ct(ar),Ct(Nn),_b();break;case 5:vb(s);break;case 4:Vl();break;case 13:Ct(Dt);break;case 19:Ct(Dt);break;case 10:xb(s.type._context);break;case 22:case 23:Pb()}r=r.return}if(yn=e,nn=e=eo(e.current,null),wn=mr=n,ln=0,Lc=null,Nb=Tf=ha=0,rr=gc=null,Ho!==null){for(n=0;n<Ho.length;n++)if(r=Ho[n],s=r.interleaved,s!==null){r.interleaved=null;var i=s.next,o=r.pending;if(o!==null){var a=o.next;o.next=i,s.next=a}r.pending=s}Ho=null}return e}function zS(e,n){do{var r=nn;try{if(mb(),Kp.current=Dh,qh){for(var s=Ot.memoizedState;s!==null;){var i=s.queue;i!==null&&(i.pending=null),s=s.next}qh=!1}if(pa=0,xn=on=Ot=null,hc=!1,Dc=0,zb.current=null,r===null||r.return===null){ln=1,Lc=n,nn=null;break}e:{var o=e,a=r.return,l=r,d=n;if(n=wn,l.flags|=32768,d!==null&&typeof d=="object"&&typeof d.then=="function"){var c=d,f=l,p=f.tag;if(!(f.mode&1)&&(p===0||p===11||p===15)){var u=f.alternate;u?(f.updateQueue=u.updateQueue,f.memoizedState=u.memoizedState,f.lanes=u.lanes):(f.updateQueue=null,f.memoizedState=null)}var h=JA(a);if(h!==null){h.flags&=-257,QA(h,a,l,o,n),h.mode&1&&GA(o,c,n),n=h,d=c;var y=n.updateQueue;if(y===null){var m=new Set;m.add(d),n.updateQueue=m}else y.add(d);break e}else{if(!(n&1)){GA(o,c,n),qb();break e}d=Error(Se(426))}}else if(Et&&l.mode&1){var b=JA(a);if(b!==null){!(b.flags&65536)&&(b.flags|=256),QA(b,a,l,o,n),fb(Zl(d,l));break e}}o=d=Zl(d,l),ln!==4&&(ln=2),gc===null?gc=[o]:gc.push(o),o=a;do{switch(o.tag){case 3:o.flags|=65536,n&=-n,o.lanes|=n;var A=pS(o,d,n);HA(o,A);break e;case 1:l=d;var v=o.type,x=o.stateNode;if(!(o.flags&128)&&(typeof v.getDerivedStateFromError=="function"||x!==null&&typeof x.componentDidCatch=="function"&&(Ji===null||!Ji.has(x)))){o.flags|=65536,n&=-n,o.lanes|=n;var _=hS(o,l,n);HA(o,_);break e}}o=o.return}while(o!==null)}ES(r)}catch(j){n=j,nn===r&&r!==null&&(nn=r=r.return);continue}break}while(!0)}function NS(){var e=Oh.current;return Oh.current=Dh,e===null?Dh:e}function qb(){(ln===0||ln===3||ln===2)&&(ln=4),yn===null||!(ha&268435455)&&!(Tf&268435455)||zi(yn,wn)}function Wh(e,n){var r=pt;pt|=2;var s=NS();(yn!==e||wn!==n)&&(Ps=null,aa(e,n));do try{EC();break}catch(i){zS(e,i)}while(!0);if(mb(),pt=r,Oh.current=s,nn!==null)throw Error(Se(261));return yn=null,wn=0,ln}function EC(){for(;nn!==null;)RS(nn)}function PC(){for(;nn!==null&&!s6();)RS(nn)}function RS(e){var n=qS(e.alternate,e,mr);e.memoizedProps=e.pendingProps,n===null?ES(e):nn=n,zb.current=null}function ES(e){var n=e;do{var r=n.alternate;if(e=n.return,n.flags&32768){if(r=kC(r,n),r!==null){r.flags&=32767,nn=r;return}if(e!==null)e.flags|=32768,e.subtreeFlags=0,e.deletions=null;else{ln=6,nn=null;return}}else if(r=SC(r,n,mr),r!==null){nn=r;return}if(n=n.sibling,n!==null){nn=n;return}nn=n=e}while(n!==null);ln===0&&(ln=5)}function Oo(e,n,r){var s=xt,i=qr.transition;try{qr.transition=null,xt=1,qC(e,n,r,s)}finally{qr.transition=i,xt=s}return null}function qC(e,n,r,s){do wl();while(Ui!==null);if(pt&6)throw Error(Se(327));r=e.finishedWork;var i=e.finishedLanes;if(r===null)return null;if(e.finishedWork=null,e.finishedLanes=0,r===e.current)throw Error(Se(177));e.callbackNode=null,e.callbackPriority=0;var o=r.lanes|r.childLanes;if(f6(e,o),e===yn&&(nn=yn=null,wn=0),!(r.subtreeFlags&2064)&&!(r.flags&2064)||Vu||(Vu=!0,DS(Ah,function(){return wl(),null})),o=(r.flags&15990)!==0,r.subtreeFlags&15990||o){o=qr.transition,qr.transition=null;var a=xt;xt=1;var l=pt;pt|=4,zb.current=null,TC(e,r),kS(r,e),eC(mx),_h=!!gx,mx=gx=null,e.current=r,zC(r),i6(),pt=l,xt=a,qr.transition=o}else e.current=r;if(Vu&&(Vu=!1,Ui=e,Lh=i),o=e.pendingLanes,o===0&&(Ji=null),l6(r.stateNode),dr(e,Qt()),n!==null)for(s=e.onRecoverableError,r=0;r<n.length;r++)i=n[r],s(i.value,{componentStack:i.stack,digest:i.digest});if(Ih)throw Ih=!1,e=Ox,Ox=null,e;return Lh&1&&e.tag!==0&&wl(),o=e.pendingLanes,o&1?e===Ix?mc++:(mc=0,Ix=e):mc=0,po(),null}function wl(){if(Ui!==null){var e=pw(Lh),n=qr.transition,r=xt;try{if(qr.transition=null,xt=16>e?16:e,Ui===null)var s=!1;else{if(e=Ui,Ui=null,Lh=0,pt&6)throw Error(Se(331));var i=pt;for(pt|=4,qe=e.current;qe!==null;){var o=qe,a=o.child;if(qe.flags&16){var l=o.deletions;if(l!==null){for(var d=0;d<l.length;d++){var c=l[d];for(qe=c;qe!==null;){var f=qe;switch(f.tag){case 0:case 11:case 15:fc(8,f,o)}var p=f.child;if(p!==null)p.return=f,qe=p;else for(;qe!==null;){f=qe;var u=f.sibling,h=f.return;if(jS(f),f===c){qe=null;break}if(u!==null){u.return=h,qe=u;break}qe=h}}}var y=o.alternate;if(y!==null){var m=y.child;if(m!==null){y.child=null;do{var b=m.sibling;m.sibling=null,m=b}while(m!==null)}}qe=o}}if(o.subtreeFlags&2064&&a!==null)a.return=o,qe=a;else e:for(;qe!==null;){if(o=qe,o.flags&2048)switch(o.tag){case 0:case 11:case 15:fc(9,o,o.return)}var A=o.sibling;if(A!==null){A.return=o.return,qe=A;break e}qe=o.return}}var v=e.current;for(qe=v;qe!==null;){a=qe;var x=a.child;if(a.subtreeFlags&2064&&x!==null)x.return=a,qe=x;else e:for(a=v;qe!==null;){if(l=qe,l.flags&2048)try{switch(l.tag){case 0:case 11:case 15:Cf(9,l)}}catch(j){Vt(l,l.return,j)}if(l===a){qe=null;break e}var _=l.sibling;if(_!==null){_.return=l.return,qe=_;break e}qe=l.return}}if(pt=i,po(),ws&&typeof ws.onPostCommitFiberRoot=="function")try{ws.onPostCommitFiberRoot(bf,e)}catch{}s=!0}return s}finally{xt=r,qr.transition=n}}return!1}function p1(e,n,r){n=Zl(r,n),n=pS(e,n,1),e=Gi(e,n,1),n=Fn(),e!==null&&(uu(e,1,n),dr(e,n))}function Vt(e,n,r){if(e.tag===3)p1(e,e,r);else for(;n!==null;){if(n.tag===3){p1(n,e,r);break}else if(n.tag===1){var s=n.stateNode;if(typeof n.type.getDerivedStateFromError=="function"||typeof s.componentDidCatch=="function"&&(Ji===null||!Ji.has(s))){e=Zl(r,e),e=hS(n,e,1),n=Gi(n,e,1),e=Fn(),n!==null&&(uu(n,1,e),dr(n,e));break}}n=n.return}}function DC(e,n,r){var s=e.pingCache;s!==null&&s.delete(n),n=Fn(),e.pingedLanes|=e.suspendedLanes&r,yn===e&&(wn&r)===r&&(ln===4||ln===3&&(wn&130023424)===wn&&500>Qt()-Rb?aa(e,0):Nb|=r),dr(e,n)}function PS(e,n){n===0&&(e.mode&1?(n=Ou,Ou<<=1,!(Ou&130023424)&&(Ou=4194304)):n=1);var r=Fn();e=Qs(e,n),e!==null&&(uu(e,n,r),dr(e,r))}function OC(e){var n=e.memoizedState,r=0;n!==null&&(r=n.retryLane),PS(e,r)}function IC(e,n){var r=0;switch(e.tag){case 13:var s=e.stateNode,i=e.memoizedState;i!==null&&(r=i.retryLane);break;case 19:s=e.stateNode;break;default:throw Error(Se(314))}s!==null&&s.delete(n),PS(e,r)}var qS;qS=function(e,n,r){if(e!==null)if(e.memoizedProps!==n.pendingProps||ar.current)or=!0;else{if(!(e.lanes&r)&&!(n.flags&128))return or=!1,wC(e,n,r);or=!!(e.flags&131072)}else or=!1,Et&&n.flags&1048576&&Lw(n,zh,n.index);switch(n.lanes=0,n.tag){case 2:var s=n.type;Xp(e,n),e=n.pendingProps;var i=Bl(n,Nn.current);jl(n,r),i=wb(null,n,s,e,i,r);var o=Sb();return n.flags|=1,typeof i=="object"&&i!==null&&typeof i.render=="function"&&i.$$typeof===void 0?(n.tag=1,n.memoizedState=null,n.updateQueue=null,lr(s)?(o=!0,Ch(n)):o=!1,n.memoizedState=i.state!==null&&i.state!==void 0?i.state:null,bb(n),i.updater=kf,n.stateNode=i,i._reactInternals=n,Sx(n,s,e,r),n=Tx(null,n,s,!0,o,r)):(n.tag=0,Et&&o&&pb(n),Ln(null,n,i,r),n=n.child),n;case 16:s=n.elementType;e:{switch(Xp(e,n),e=n.pendingProps,i=s._init,s=i(s._payload),n.type=s,i=n.tag=WC(s),e=Kr(s,e),i){case 0:n=Cx(null,n,s,e,r);break e;case 1:n=n1(null,n,s,e,r);break e;case 11:n=e1(null,n,s,e,r);break e;case 14:n=t1(null,n,s,Kr(s.type,e),r);break e}throw Error(Se(306,s,""))}return n;case 0:return s=n.type,i=n.pendingProps,i=n.elementType===s?i:Kr(s,i),Cx(e,n,s,i,r);case 1:return s=n.type,i=n.pendingProps,i=n.elementType===s?i:Kr(s,i),n1(e,n,s,i,r);case 3:e:{if(xS(n),e===null)throw Error(Se(387));s=n.pendingProps,o=n.memoizedState,i=o.element,Uw(e,n),Eh(n,s,null,r);var a=n.memoizedState;if(s=a.element,o.isDehydrated)if(o={element:s,isDehydrated:!1,cache:a.cache,pendingSuspenseBoundaries:a.pendingSuspenseBoundaries,transitions:a.transitions},n.updateQueue.baseState=o,n.memoizedState=o,n.flags&256){i=Zl(Error(Se(423)),n),n=r1(e,n,s,r,i);break e}else if(s!==i){i=Zl(Error(Se(424)),n),n=r1(e,n,s,r,i);break e}else for(br=Xi(n.stateNode.containerInfo.firstChild),Ar=n,Et=!0,Jr=null,r=Fw(n,null,s,r),n.child=r;r;)r.flags=r.flags&-3|4096,r=r.sibling;else{if(Ul(),s===i){n=ei(e,n,r);break e}Ln(e,n,s,r)}n=n.child}return n;case 5:return Hw(n),e===null&&_x(n),s=n.type,i=n.pendingProps,o=e!==null?e.memoizedProps:null,a=i.children,xx(s,i)?a=null:o!==null&&xx(s,o)&&(n.flags|=32),mS(e,n),Ln(e,n,a,r),n.child;case 6:return e===null&&_x(n),null;case 13:return yS(e,n,r);case 4:return Ab(n,n.stateNode.containerInfo),s=n.pendingProps,e===null?n.child=Hl(n,null,s,r):Ln(e,n,s,r),n.child;case 11:return s=n.type,i=n.pendingProps,i=n.elementType===s?i:Kr(s,i),e1(e,n,s,i,r);case 7:return Ln(e,n,n.pendingProps,r),n.child;case 8:return Ln(e,n,n.pendingProps.children,r),n.child;case 12:return Ln(e,n,n.pendingProps.children,r),n.child;case 10:e:{if(s=n.type._context,i=n.pendingProps,o=n.memoizedProps,a=i.value,jt(Nh,s._currentValue),s._currentValue=a,o!==null)if(ts(o.value,a)){if(o.children===i.children&&!ar.current){n=ei(e,n,r);break e}}else for(o=n.child,o!==null&&(o.return=n);o!==null;){var l=o.dependencies;if(l!==null){a=o.child;for(var d=l.firstContext;d!==null;){if(d.context===s){if(o.tag===1){d=Vs(-1,r&-r),d.tag=2;var c=o.updateQueue;if(c!==null){c=c.shared;var f=c.pending;f===null?d.next=d:(d.next=f.next,f.next=d),c.pending=d}}o.lanes|=r,d=o.alternate,d!==null&&(d.lanes|=r),jx(o.return,r,n),l.lanes|=r;break}d=d.next}}else if(o.tag===10)a=o.type===n.type?null:o.child;else if(o.tag===18){if(a=o.return,a===null)throw Error(Se(341));a.lanes|=r,l=a.alternate,l!==null&&(l.lanes|=r),jx(a,r,n),a=o.sibling}else a=o.child;if(a!==null)a.return=o;else for(a=o;a!==null;){if(a===n){a=null;break}if(o=a.sibling,o!==null){o.return=a.return,a=o;break}a=a.return}o=a}Ln(e,n,i.children,r),n=n.child}return n;case 9:return i=n.type,s=n.pendingProps.children,jl(n,r),i=Dr(i),s=s(i),n.flags|=1,Ln(e,n,s,r),n.child;case 14:return s=n.type,i=Kr(s,n.pendingProps),i=Kr(s.type,i),t1(e,n,s,i,r);case 15:return fS(e,n,n.type,n.pendingProps,r);case 17:return s=n.type,i=n.pendingProps,i=n.elementType===s?i:Kr(s,i),Xp(e,n),n.tag=1,lr(s)?(e=!0,Ch(n)):e=!1,jl(n,r),uS(n,s,i),Sx(n,s,i,r),Tx(null,n,s,!0,e,r);case 19:return bS(e,n,r);case 22:return gS(e,n,r)}throw Error(Se(156,n.tag))};function DS(e,n){return lw(e,n)}function LC(e,n,r,s){this.tag=e,this.key=r,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=n,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=s,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}
vendor: 3,991 bytes, line 40
40function Er(e,n,r,s){return new LC(e,n,r,s)}function Db(e){return e=e.prototype,!(!e||!e.isReactComponent)}function WC(e){if(typeof e=="function")return Db(e)?1:0;if(e!=null){if(e=e.$$typeof,e===eb)return 11;if(e===tb)return 14}return 2}function eo(e,n){var r=e.alternate;return r===null?(r=Er(e.tag,n,e.key,e.mode),r.elementType=e.elementType,r.type=e.type,r.stateNode=e.stateNode,r.alternate=e,e.alternate=r):(r.pendingProps=n,r.type=e.type,r.flags=0,r.subtreeFlags=0,r.deletions=null),r.flags=e.flags&14680064,r.childLanes=e.childLanes,r.lanes=e.lanes,r.child=e.child,r.memoizedProps=e.memoizedProps,r.memoizedState=e.memoizedState,r.updateQueue=e.updateQueue,n=e.dependencies,r.dependencies=n===null?null:{lanes:n.lanes,firstContext:n.firstContext},r.sibling=e.sibling,r.index=e.index,r.ref=e.ref,r}function Qp(e,n,r,s,i,o){var a=2;if(s=e,typeof e=="function")Db(e)&&(a=1);else if(typeof e=="string")a=5;else e:switch(e){case rl:return la(r.children,i,o,n);case Qy:a=8,i|=8;break;case Ym:return e=Er(12,r,n,i|2),e.elementType=Ym,e.lanes=o,e;case Xm:return e=Er(13,r,n,i),e.elementType=Xm,e.lanes=o,e;case Gm:return e=Er(19,r,n,i),e.elementType=Gm,e.lanes=o,e;case H2:return zf(r,i,o,n);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case B2:a=10;break e;case U2:a=9;break e;case eb:a=11;break e;case tb:a=14;break e;case Si:a=16,s=null;break e}throw Error(Se(130,e==null?e:typeof e,""))}return n=Er(a,r,n,i),n.elementType=e,n.type=s,n.lanes=o,n}function la(e,n,r,s){return e=Er(7,e,s,n),e.lanes=r,e}function zf(e,n,r,s){return e=Er(22,e,s,n),e.elementType=H2,e.lanes=r,e.stateNode={isHidden:!1},e}function Mg(e,n,r){return e=Er(6,e,null,n),e.lanes=r,e}function Fg(e,n,r){return n=Er(4,e.children!==null?e.children:[],e.key,n),n.lanes=r,n.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},n}function $C(e,n,r,s,i){this.tag=n,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=_g(0),this.expirationTimes=_g(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=_g(0),this.identifierPrefix=s,this.onRecoverableError=i,this.mutableSourceEagerHydrationData=null}function Ob(e,n,r,s,i,o,a,l,d){return e=new $C(e,n,r,l,d),n===1?(n=1,o===!0&&(n|=8)):n=0,o=Er(3,null,null,n),e.current=o,o.stateNode=e,o.memoizedState={element:s,isDehydrated:r,cache:null,transitions:null,pendingSuspenseBoundaries:null},bb(o),e}function MC(e,n,r){var s=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:nl,key:s==null?null:""+s,children:e,containerInfo:n,implementation:r}}function OS(e){if(!e)return ao;e=e._reactInternals;e:{if(_a(e)!==e||e.tag!==1)throw Error(Se(170));var n=e;do{switch(n.tag){case 3:n=n.stateNode.context;break e;case 1:if(lr(n.type)){n=n.stateNode.__reactInternalMemoizedMergedChildContext;break e}}n=n.return}while(n!==null);throw Error(Se(171))}if(e.tag===1){var r=e.type;if(lr(r))return Ow(e,r,n)}return n}function IS(e,n,r,s,i,o,a,l,d){return e=Ob(r,s,!0,e,i,o,a,l,d),e.context=OS(null),r=e.current,s=Fn(),i=Qi(r),o=Vs(s,i),o.callback=n??null,Gi(r,o,i),e.current.lanes=i,uu(e,i,s),dr(e,s),e}function Nf(e,n,r,s){var i=n.current,o=Fn(),a=Qi(i);return r=OS(r),n.context===null?n.context=r:n.pendingContext=r,n=Vs(o,a),n.payload={element:e},s=s===void 0?null:s,s!==null&&(n.callback=s),e=Gi(i,n,a),e!==null&&(es(e,i,a,o),Zp(e,i,a)),a}function $h(e){if(e=e.current,!e.child)return null;switch(e.child.tag){case 5:return e.child.stateNode;default:return e.child.stateNode}}function h1(e,n){if(e=e.memoizedState,e!==null&&e.dehydrated!==null){var r=e.retryLane;e.retryLane=r!==0&&r<n?r:n}}function Ib(e,n){h1(e,n),(e=e.alternate)&&h1(e,n)}function FC(){return null}var LS=typeof reportError=="function"?reportError:function(e){console.error(e)};
vendor: 5,228 bytes, line 40
40function Lb(e){this._internalRoot=e}Rf.prototype.render=Lb.prototype.render=function(e){var n=this._internalRoot;if(n===null)throw Error(Se(409));Nf(e,n,null,null)};Rf.prototype.unmount=Lb.prototype.unmount=function(){var e=this._internalRoot;if(e!==null){this._internalRoot=null;var n=e.containerInfo;fa(function(){Nf(null,e,null,null)}),n[Js]=null}};function Rf(e){this._internalRoot=e}Rf.prototype.unstable_scheduleHydration=function(e){if(e){var n=gw();e={blockedOn:null,target:e,priority:n};for(var r=0;r<Ti.length&&n!==0&&n<Ti[r].priority;r++);Ti.splice(r,0,e),r===0&&xw(e)}};function Wb(e){return!(!e||e.nodeType!==1&&e.nodeType!==9&&e.nodeType!==11)}function Ef(e){return!(!e||e.nodeType!==1&&e.nodeType!==9&&e.nodeType!==11&&(e.nodeType!==8||e.nodeValue!==" react-mount-point-unstable "))}function f1(){}function BC(e,n,r,s,i){if(i){if(typeof s=="function"){var o=s;s=function(){var c=$h(a);o.call(c)}}var a=IS(n,s,e,0,null,!1,!1,"",f1);return e._reactRootContainer=a,e[Js]=a.current,Nc(e.nodeType===8?e.parentNode:e),fa(),a}for(;i=e.lastChild;)e.removeChild(i);if(typeof s=="function"){var l=s;s=function(){var c=$h(d);l.call(c)}}var d=Ob(e,0,!1,null,null,!1,!1,"",f1);return e._reactRootContainer=d,e[Js]=d.current,Nc(e.nodeType===8?e.parentNode:e),fa(function(){Nf(n,d,r,s)}),d}function Pf(e,n,r,s,i){var o=r._reactRootContainer;if(o){var a=o;if(typeof i=="function"){var l=i;i=function(){var d=$h(a);l.call(d)}}Nf(n,a,e,i)}else a=BC(r,n,e,i,s);return $h(a)}hw=function(e){switch(e.tag){case 3:var n=e.stateNode;if(n.current.memoizedState.isDehydrated){var r=tc(n.pendingLanes);r!==0&&(sb(n,r|1),dr(n,Qt()),!(pt&6)&&(Kl=Qt()+500,po()))}break;case 13:fa(function(){var s=Qs(e,1);if(s!==null){var i=Fn();es(s,e,1,i)}}),Ib(e,1)}};ib=function(e){if(e.tag===13){var n=Qs(e,134217728);if(n!==null){var r=Fn();es(n,e,134217728,r)}Ib(e,134217728)}};fw=function(e){if(e.tag===13){var n=Qi(e),r=Qs(e,n);if(r!==null){var s=Fn();es(r,e,n,s)}Ib(e,n)}};gw=function(){return xt};mw=function(e,n){var r=xt;try{return xt=e,n()}finally{xt=r}};ax=function(e,n,r){switch(n){case"input":if(ex(e,r),n=r.name,r.type==="radio"&&n!=null){for(r=e;r.parentNode;)r=r.parentNode;for(r=r.querySelectorAll("input[name="+JSON.stringify(""+n)+'][type="radio"]'),n=0;n<r.length;n++){var s=r[n];if(s!==e&&s.form===e.form){var i=jf(s);if(!i)throw Error(Se(90));Z2(s),ex(s,i)}}}break;case"textarea":Y2(e,r);break;case"select":n=r.value,n!=null&&bl(e,!!r.multiple,n,!1)}};nw=Eb;rw=fa;var UC={usingClientEntryPoint:!1,Events:[hu,al,jf,ew,tw,Eb]},Rd={findFiberByHostInstance:Uo,bundleType:0,version:"18.3.1",rendererPackageName:"react-dom"},HC={bundleType:Rd.bundleType,version:Rd.version,rendererPackageName:Rd.rendererPackageName,rendererConfig:Rd.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:oi.ReactCurrentDispatcher,findHostInstanceByFiber:function(e){return e=ow(e),e===null?null:e.stateNode},findFiberByHostInstance:Rd.findFiberByHostInstance||FC,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.3.1-next-f1338f8080-20240426"};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"){var Zu=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!Zu.isDisabled&&Zu.supportsFiber)try{bf=Zu.inject(HC),ws=Zu}catch{}}_r.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=UC;_r.createPortal=function(e,n){var r=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!Wb(n))throw Error(Se(200));return MC(e,n,null,r)};_r.createRoot=function(e,n){if(!Wb(e))throw Error(Se(299));var r=!1,s="",i=LS;return n!=null&&(n.unstable_strictMode===!0&&(r=!0),n.identifierPrefix!==void 0&&(s=n.identifierPrefix),n.onRecoverableError!==void 0&&(i=n.onRecoverableError)),n=Ob(e,1,!1,null,null,r,!1,s,i),e[Js]=n.current,Nc(e.nodeType===8?e.parentNode:e),new Lb(n)};_r.findDOMNode=function(e){if(e==null)return null;if(e.nodeType===1)return e;var n=e._reactInternals;if(n===void 0)throw typeof e.render=="function"?Error(Se(188)):(e=Object.keys(e).join(","),Error(Se(268,e)));return e=ow(n),e=e===null?null:e.stateNode,e};_r.flushSync=function(e){return fa(e)};_r.hydrate=function(e,n,r){if(!Ef(n))throw Error(Se(200));return Pf(null,e,n,!0,r)};_r.hydrateRoot=function(e,n,r){if(!Wb(e))throw Error(Se(405));var s=r!=null&&r.hydratedSources||null,i=!1,o="",a=LS;if(r!=null&&(r.unstable_strictMode===!0&&(i=!0),r.identifierPrefix!==void 0&&(o=r.identifierPrefix),r.onRecoverableError!==void 0&&(a=r.onRecoverableError)),n=IS(n,null,e,1,r??null,i,!1,o,a),e[Js]=n.current,Nc(e),s)for(e=0;e<s.length;e++)r=s[e],i=r._getVersion,i=i(r._source),n.mutableSourceEagerHydrationData==null?n.mutableSourceEagerHydrationData=[r,i]:n.mutableSourceEagerHydrationData.push(r,i);return new Rf(n)};_r.render=function(e,n,r){if(!Ef(n))throw Error(Se(200));return Pf(null,e,n,!1,r)};_r.unmountComponentAtNode=function(e){if(!Ef(e))throw Error(Se(40));return e._reactRootContainer?(fa(function(){Pf(null,null,e,!1,function(){e._reactRootContainer=null,e[Js]=null})}),!0):!1};_r.unstable_batchedUpdates=Eb;
40_r.unstable_renderSubtreeIntoContainer=function(e,n,r,s){if(!Ef(r))throw Error(Se(200));if(e==null||e._reactInternals===void 0)throw Error(Se(38));return Pf(e,n,r,!1,s)};_r.version="18.3.1-next-f1338f8080-20240426";function WS(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(WS)}catch(e){console.error(e)}}WS(),W2.exports=_r;var VC=W2.exports,g1=VC;Zm.createRoot=g1.createRoot,Zm.hydrateRoot=g1.hydrateRoot;var dd=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},Jo,qi,Nl,f2,ZC=(f2=class extends dd{constructor(){super();$e(this,Jo);$e(this,qi);$e(this,Nl);ze(this,Nl,n=>{if(typeof window<"u"&&window.addEventListener){const r=()=>n();return window.addEventListener("visibilitychange",r,!1),()=>{window.removeEventListener("visibilitychange",r)}}})}onSubscribe(){se(this,qi)||this.setEventListener(se(this,Nl))}onUnsubscribe(){var n;this.hasListeners()||((n=se(this,qi))==null||n.call(this),ze(this,qi,void 0))}setEventListener(n){var r;ze(this,Nl,n),(r=se(this,qi))==null||r.call(this),ze(this,qi,n(s=>{typeof s=="boolean"?this.setFocused(s):this.onFocus()}))}setFocused(n){se(this,Jo)!==n&&(ze(this,Jo,n),this.onFocus())}onFocus(){const n=this.isFocused();this.listeners.forEach(r=>{r(n)})}isFocused(){var n;return typeof se(this,Jo)=="boolean"?se(this,Jo):((n=globalThis.document)==null?void 0:n.visibilityState)!=="hidden"}},Jo=new WeakMap,qi=new WeakMap,Nl=new WeakMap,f2),$b=new ZC,KC={setTimeout:(e,n)=>setTimeout(e,n),clearTimeout:e=>clearTimeout(e),setInterval:(e,n)=>setInterval(e,n),clearInterval:e=>clearInterval(e)},Di,Hy,g2,YC=(g2=class{constructor(){$e(this,Di,KC);$e(this,Hy,!1)}setTimeoutProvider(e){ze(this,Di,e)}setTimeout(e,n){return se(this,Di).setTimeout(e,n)}clearTimeout(e){se(this,Di).clearTimeout(e)}setInterval(e,n){return se(this,Di).setInterval(e,n)}clearInterval(e){se(this,Di).clearInterval(e)}},Di=new WeakMap,Hy=new WeakMap,g2),Zo=new YC;function XC(e){setTimeout(e,0)}var GC=typeof window>"u"||"Deno"in globalThis;function Wn(){}function JC(e,n){return typeof e=="function"?e(n):e}function $x(e){return typeof e=="number"&&e>=0&&e!==1/0}function $S(e,n){return Math.max(e+(n||0)-Date.now(),0)}function to(e,n){return typeof e=="function"?e(n):e}function Tr(e,n){return typeof e=="function"?e(n):e}function m1(e,n){const{type:r="all",exact:s,fetchStatus:i,predicate:o,queryKey:a,stale:l}=e;if(a){if(s){if(n.queryHash!==Mb(a,n.options))return!1}else if(!Wc(n.queryKey,a))return!1}if(r!=="all"){const d=n.isActive();if(r==="active"&&!d||r==="inactive"&&d)return!1}return!(typeof l=="boolean"&&n.isStale()!==l||i&&i!==n.state.fetchStatus||o&&!o(n))}function x1(e,n){const{exact:r,status:s,predicate:i,mutationKey:o}=e;if(o){if(!n.options.mutationKey)return!1;if(r){if(ga(n.options.mutationKey)!==ga(o))return!1}else if(!Wc(n.options.mutationKey,o))return!1}return!(s&&n.state.status!==s||i&&!i(n))}function Mb(e,n){return((n==null?void 0:n.queryKeyHashFn)||ga)(e)}function ga(e){return JSON.stringify(e,(n,r)=>Mx(r)?Object.keys(r).sort().reduce((s,i)=>(s[i]=r[i],s),{}):r)}function Wc(e,n){return e===n?!0:typeof e!=typeof n?!1:e&&n&&typeof e=="object"&&typeof n=="object"?Object.keys(n).every(r=>Wc(e[r],n[r])):!1}var QC=Object.prototype.hasOwnProperty;function MS(e,n,r=0){if(e===n)return e;if(r>500)return n;const s=y1(e)&&y1(n);if(!s&&!(Mx(e)&&Mx(n)))return n;const o=(s?e:Object.keys(e)).length,a=s?n:Object.keys(n),l=a.length,d=s?new Array(l):{};let c=0;for(let f=0;f<l;f++){const p=s?f:a[f],u=e[p],h=n[p];if(u===h){d[p]=u,(s?f<o:QC.call(e,p))&&c++;continue}if(u===null||h===null||typeof u!="object"||typeof h!="object"){d[p]=h;continue}const y=MS(u,h,r+1);d[p]=y,y===u&&c++}return o===l&&c===o?e:d}function Mh(e,n){if(!n||Object.keys(e).length!==Object.keys(n).length)return!1;for(const r in e)if(e[r]!==n[r])return!1;return!0}function y1(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Mx(e){if(!b1(e))return!1;const n=e.constructor;if(n===void 0)return!0;const r=n.prototype;return!(!b1(r)||!r.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function b1(e){return Object.prototype.toString.call(e)==="[object Object]"}function eT(e){return new Promise(n=>{Zo.setTimeout(n,e)})}function Fx(e,n,r){return typeof r.structuralSharing=="function"?r.structuralSharing(e,n):r.structuralSharing!==!1?MS(e,n):n}function tT(e,n,r=0){const s=[...e,n];return r&&s.length>r?s.slice(1):s}
40function nT(e,n,r=0){const s=[n,...e];return r&&s.length>r?s.slice(0,-1):s}var Fb=Symbol();function FS(e,n){return!e.queryFn&&(n!=null&&n.initialPromise)?()=>n.initialPromise:!e.queryFn||e.queryFn===Fb?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function Bb(e,n){return typeof e=="function"?e(...n):!!e}function rT(e,n,r){let s=!1,i;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(i??(i=n()),s||(s=!0,i.aborted?r():i.addEventListener("abort",r,{once:!0})),i)}),e}var $c=(()=>{let e=()=>GC;return{isServer(){return e()},setIsServer(n){e=n}}})();function Bx(){let e,n;const r=new Promise((i,o)=>{e=i,n=o});r.status="pending",r.catch(()=>{});function s(i){Object.assign(r,i),delete r.resolve,delete r.reject}return r.resolve=i=>{s({status:"fulfilled",value:i}),e(i)},r.reject=i=>{s({status:"rejected",reason:i}),n(i)},r}var sT=XC;function iT(){let e=[],n=0,r=l=>{l()},s=l=>{l()},i=sT;const o=l=>{n?e.push(l):i(()=>{r(l)})},a=()=>{const l=e;e=[],l.length&&i(()=>{s(()=>{l.forEach(d=>{r(d)})})})};return{batch:l=>{let d;n++;try{d=l()}finally{n--,n||a()}return d},batchCalls:l=>(...d)=>{o(()=>{l(...d)})},schedule:o,setNotifyFunction:l=>{r=l},setBatchNotifyFunction:l=>{s=l},setScheduler:l=>{i=l}}}var an=iT(),Rl,Oi,El,m2,oT=(m2=class extends dd{constructor(){super();$e(this,Rl,!0);$e(this,Oi);$e(this,El);ze(this,El,n=>{if(typeof window<"u"&&window.addEventListener){const r=()=>n(!0),s=()=>n(!1);return window.addEventListener("online",r,!1),window.addEventListener("offline",s,!1),()=>{window.removeEventListener("online",r),window.removeEventListener("offline",s)}}})}onSubscribe(){se(this,Oi)||this.setEventListener(se(this,El))}onUnsubscribe(){var n;this.hasListeners()||((n=se(this,Oi))==null||n.call(this),ze(this,Oi,void 0))}setEventListener(n){var r;ze(this,El,n),(r=se(this,Oi))==null||r.call(this),ze(this,Oi,n(this.setOnline.bind(this)))}setOnline(n){se(this,Rl)!==n&&(ze(this,Rl,n),this.listeners.forEach(s=>{s(n)}))}isOnline(){return se(this,Rl)}},Rl=new WeakMap,Oi=new WeakMap,El=new WeakMap,m2),Fh=new oT;function aT(e){return Math.min(1e3*2**e,3e4)}function BS(e){return(e??"online")==="online"?Fh.isOnline():!0}var Ux=class extends Error{constructor(e){super("CancelledError"),this.revert=e==null?void 0:e.revert,this.silent=e==null?void 0:e.silent}};function US(e){let n=!1,r=0,s;const i=Bx(),o=()=>i.status!=="pending",a=m=>{var b;if(!o()){const A=new Ux(m);u(A),(b=e.onCancel)==null||b.call(e,A)}},l=()=>{n=!0},d=()=>{n=!1},c=()=>$b.isFocused()&&(e.networkMode==="always"||Fh.isOnline())&&e.canRun(),f=()=>BS(e.networkMode)&&e.canRun(),p=m=>{o()||(s==null||s(),i.resolve(m))},u=m=>{o()||(s==null||s(),i.reject(m))},h=()=>new Promise(m=>{var b;s=A=>{(o()||c())&&m(A)},(b=e.onPause)==null||b.call(e)}).then(()=>{var m;s=void 0,o()||(m=e.onContinue)==null||m.call(e)}),y=()=>{if(o())return;let m;const b=r===0?e.initialPromise:void 0;try{m=b??e.fn()}catch(A){m=Promise.reject(A)}Promise.resolve(m).then(p).catch(A=>{var C;if(o())return;const v=e.retry??($c.isServer()?0:3),x=e.retryDelay??aT,_=typeof x=="function"?x(r,A):x,j=v===!0||typeof v=="number"&&r<v||typeof v=="function"&&v(r,A);if(n||!j){u(A);return}r++,(C=e.onFail)==null||C.call(e,r,A),eT(_).then(()=>c()?void 0:h()).then(()=>{n?u(A):y()})})};return{promise:i,status:()=>i.status,cancel:a,continue:()=>(s==null||s(),i),cancelRetry:l,continueRetry:d,canStart:f,start:()=>(f()?y():h().then(y),i)}}var Qo,x2,HS=(x2=class{constructor(){$e(this,Qo)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),$x(this.gcTime)&&ze(this,Qo,Zo.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??($c.isServer()?1/0:5*60*1e3))}clearGcTimeout(){se(this,Qo)&&(Zo.clearTimeout(se(this,Qo)),ze(this,Qo,void 0))}},Qo=new WeakMap,x2),ea,Pl,Cr,ta,gn,iu,na,xr,VS,Rs,y2,lT=(y2=class extends HS{constructor(n){super();$e(this,xr);$e(this,ea);$e(this,Pl);$e(this,Cr);$e(this,ta);$e(this,gn);$e(this,iu);$e(this,na);ze(this,na,!1),ze(this,iu,n.defaultOptions),this.setOptions(n.options),this.observers=[],ze(this,ta,n.client),ze(this,Cr,se(this,ta).getQueryCache()),this.queryKey=n.queryKey,this.queryHash=n.queryHash,ze(this,ea,v1(this.options)),this.state=n.state??se(this,ea),this.scheduleGc()}get meta(){return this.options.meta}get promise(){var n;return(n=se(this,gn))==null?void 0:n.promise}setOptions(n){if(this.options={...se(this,iu),...n},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const r=v1(this.options);r.data!==void 0&&(this.setState(A1(r.data,r.dataUpdatedAt)),ze(this,ea,r))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&se(this,Cr).remove(this)}setData(n,r){const s=Fx(this.state.data,n,this.options);return Qe(this,xr,Rs).call(this,{data:s,type:"success",dataUpdatedAt:r==null?void 0:r.updatedAt,manual:r==null?void 0:r.manual}),s}setState(n,r){Qe(this,xr,Rs).call(this,{type:"setState",state:n,setStateOptions:r})}cancel(n){var s,i;const r=(s=se(this,gn))==null?void 0:s.promise;return(i=se(this,gn))==null||i.cancel(n),r?r.then(Wn).catch(Wn):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return se(this,ea)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(n=>Tr(n.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Fb||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdate
40Count>0}isStatic(){return this.getObserversCount()>0?this.observers.some(n=>to(n.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(n=>n.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(n=0){return this.state.data===void 0?!0:n==="static"?!1:this.state.isInvalidated?!0:!$S(this.state.dataUpdatedAt,n)}onFocus(){var r;const n=this.observers.find(s=>s.shouldFetchOnWindowFocus());n==null||n.refetch({cancelRefetch:!1}),(r=se(this,gn))==null||r.continue()}onOnline(){var r;const n=this.observers.find(s=>s.shouldFetchOnReconnect());n==null||n.refetch({cancelRefetch:!1}),(r=se(this,gn))==null||r.continue()}addObserver(n){this.observers.includes(n)||(this.observers.push(n),this.clearGcTimeout(),se(this,Cr).notify({type:"observerAdded",query:this,observer:n}))}removeObserver(n){this.observers.includes(n)&&(this.observers=this.observers.filter(r=>r!==n),this.observers.length||(se(this,gn)&&(se(this,na)||Qe(this,xr,VS).call(this)?se(this,gn).cancel({revert:!0}):se(this,gn).cancelRetry()),this.scheduleGc()),se(this,Cr).notify({type:"observerRemoved",query:this,observer:n}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||Qe(this,xr,Rs).call(this,{type:"invalidate"})}async fetch(n,r){var d,c,f,p,u,h,y,m,b,A,v,x;if(this.state.fetchStatus!=="idle"&&((d=se(this,gn))==null?void 0:d.status())!=="rejected"){if(this.state.data!==void 0&&(r!=null&&r.cancelRefetch))this.cancel({silent:!0});else if(se(this,gn))return se(this,gn).continueRetry(),se(this,gn).promise}if(n&&this.setOptions(n),!this.options.queryFn){const _=this.observers.find(j=>j.options.queryFn);_&&this.setOptions(_.options)}const s=new AbortController,i=_=>{Object.defineProperty(_,"signal",{enumerable:!0,get:()=>(ze(this,na,!0),s.signal)})},o=()=>{const _=FS(this.options,r),C=(()=>{const S={client:se(this,ta),queryKey:this.queryKey,meta:this.meta};return i(S),S})();return ze(this,na,!1),this.options.persister?this.options.persister(_,C,this):_(C)},l=(()=>{const _={fetchOptions:r,options:this.options,queryKey:this.queryKey,client:se(this,ta),state:this.state,fetchFn:o};return i(_),_})();(c=this.options.behavior)==null||c.onFetch(l,this),ze(this,Pl,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((f=l.fetchOptions)==null?void 0:f.meta))&&Qe(this,xr,Rs).call(this,{type:"fetch",meta:(p=l.fetchOptions)==null?void 0:p.meta}),ze(this,gn,US({initialPromise:r==null?void 0:r.initialPromise,fn:l.fetchFn,onCancel:_=>{_ instanceof Ux&&_.revert&&this.setState({...se(this,Pl),fetchStatus:"idle"}),s.abort()},onFail:(_,j)=>{Qe(this,xr,Rs).call(this,{type:"failed",failureCount:_,error:j})},onPause:()=>{Qe(this,xr,Rs).call(this,{type:"pause"})},onContinue:()=>{Qe(this,xr,Rs).call(this,{type:"continue"})},retry:l.options.retry,retryDelay:l.options.retryDelay,networkMode:l.options.networkMode,canRun:()=>!0}));try{const _=await se(this,gn).start();if(_===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(_),(h=(u=se(this,Cr).config).onSuccess)==null||h.call(u,_,this),(m=(y=se(this,Cr).config).onSettled)==null||m.call(y,_,this.state.error,this),_}catch(_){if(_ instanceof Ux){if(_.silent)return se(this,gn).promise;if(_.revert){if(this.state.data===void 0)throw _;return this.state.data}}throw Qe(this,xr,Rs).call(this,{type:"error",error:_}),(A=(b=se(this,Cr).config).onError)==null||A.call(b,_,this),(x=(v=se(this,Cr).config).onSettled)==null||x.call(v,this.state.data,_,this),_}finally{this.scheduleGc()}}},ea=new WeakMap,Pl=new WeakMap,Cr=new WeakMap,ta=new WeakMap,gn=new WeakMap,iu=new WeakMap,na=new WeakMap,xr=new WeakSet,VS=function(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"},Rs=function(n){const r=s=>{switch(n.type){case"failed":return{...s,fetchFailureCount:n.failureCount,fetchFailureReason:n.error};case"pause":return{...s,fetchStatus:"paused"};case"continue":return{...s,fetchStatus:"fetching"};case"fetch":return{...s,...ZS(s.data,this.options),fetchMeta:n.meta??null};case"success":const i={...s,...A1(n.data,n.dataUpdatedAt),dataUpdateCount:s.dataUpdateCount+1,...!n.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return ze(this,Pl,n.manual?i:void 0),i;case"error":const o=n.error;
vendor: 4,079 bytes, line 40
40return{...s,error:o,errorUpdateCount:s.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:s.fetchFailureCount+1,fetchFailureReason:o,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...s,isInvalidated:!0};case"setState":return{...s,...n.state}}};this.state=r(this.state),an.batch(()=>{this.observers.forEach(s=>{s.onQueryUpdate()}),se(this,Cr).notify({query:this,type:"updated",action:n})})},y2);function ZS(e,n){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:BS(n.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function A1(e,n){return{data:e,dataUpdatedAt:n??Date.now(),error:null,isInvalidated:!1,status:"success"}}function v1(e){const n=typeof e.initialData=="function"?e.initialData():e.initialData,r=n!==void 0,s=r?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:n,dataUpdateCount:0,dataUpdatedAt:r?s??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:r?"success":"pending",fetchStatus:"idle"}}var er,lt,ou,In,ra,ql,Ls,Ii,au,Dl,Ol,sa,ia,Li,Il,ft,rc,Hx,Vx,Zx,Kx,Yx,Xx,Gx,KS,b2,dT=(b2=class extends dd{constructor(n,r){super();$e(this,ft);$e(this,er);$e(this,lt);$e(this,ou);$e(this,In);$e(this,ra);$e(this,ql);$e(this,Ls);$e(this,Ii);$e(this,au);$e(this,Dl);$e(this,Ol);$e(this,sa);$e(this,ia);$e(this,Li);$e(this,Il,new Set);this.options=r,ze(this,er,n),ze(this,Ii,null),ze(this,Ls,Bx()),this.bindMethods(),this.setOptions(r)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(se(this,lt).addObserver(this),_1(se(this,lt),this.options)?Qe(this,ft,rc).call(this):this.updateResult(),Qe(this,ft,Kx).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Jx(se(this,lt),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Jx(se(this,lt),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,Qe(this,ft,Yx).call(this),Qe(this,ft,Xx).call(this),se(this,lt).removeObserver(this)}setOptions(n){const r=this.options,s=se(this,lt);if(this.options=se(this,er).defaultQueryOptions(n),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof Tr(this.options.enabled,se(this,lt))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");Qe(this,ft,Gx).call(this),se(this,lt).setOptions(this.options),r._defaulted&&!Mh(this.options,r)&&se(this,er).getQueryCache().notify({type:"observerOptionsUpdated",query:se(this,lt),observer:this});const i=this.hasListeners();i&&j1(se(this,lt),s,this.options,r)&&Qe(this,ft,rc).call(this),this.updateResult(),i&&(se(this,lt)!==s||Tr(this.options.enabled,se(this,lt))!==Tr(r.enabled,se(this,lt))||to(this.options.staleTime,se(this,lt))!==to(r.staleTime,se(this,lt)))&&Qe(this,ft,Hx).call(this);const o=Qe(this,ft,Vx).call(this);i&&(se(this,lt)!==s||Tr(this.options.enabled,se(this,lt))!==Tr(r.enabled,se(this,lt))||o!==se(this,Li))&&Qe(this,ft,Zx).call(this,o)}getOptimisticResult(n){const r=se(this,er).getQueryCache().build(se(this,er),n),s=this.createResult(r,n);return uT(this,s)&&(ze(this,In,s),ze(this,ql,this.options),ze(this,ra,se(this,lt).state)),s}getCurrentResult(){return se(this,In)}trackResult(n,r){return new Proxy(n,{get:(s,i)=>(this.trackProp(i),r==null||r(i),i==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&se(this,Ls).status==="pending"&&se(this,Ls).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(s,i))})}trackProp(n){se(this,Il).add(n)}getCurrentQuery(){return se(this,lt)}refetch({...n}={}){return this.fetch({...n})}fetchOptimistic(n){const r=se(this,er).defaultQueryOptions(n),s=se(this,er).getQueryCache().build(se(this,er),r);return s.fetch().then(()=>this.createResult(s,r))}fetch(n){return Qe(this,ft,rc).call(this,{...n,cancelRefetch:n.cancelRefetch??!0}).then(()=>
vendor: 2,414 bytes, line 40
40(this.updateResult(),se(this,In)))}createResult(n,r){var L;const s=se(this,lt),i=this.options,o=se(this,In),a=se(this,ra),l=se(this,ql),c=n!==s?n.state:se(this,ou),{state:f}=n;let p={...f},u=!1,h;if(r._optimisticResults){const E=this.hasListeners(),R=!E&&_1(n,r),N=E&&j1(n,s,r,i);(R||N)&&(p={...p,...ZS(f.data,n.options)}),r._optimisticResults==="isRestoring"&&(p.fetchStatus="idle")}let{error:y,errorUpdatedAt:m,status:b}=p;h=p.data;let A=!1;if(r.placeholderData!==void 0&&h===void 0&&b==="pending"){let E;o!=null&&o.isPlaceholderData&&r.placeholderData===(l==null?void 0:l.placeholderData)?(E=o.data,A=!0):E=typeof r.placeholderData=="function"?r.placeholderData((L=se(this,Ol))==null?void 0:L.state.data,se(this,Ol)):r.placeholderData,E!==void 0&&(b="success",h=Fx(o==null?void 0:o.data,E,r),u=!0)}if(r.select&&h!==void 0&&!A)if(o&&h===(a==null?void 0:a.data)&&r.select===se(this,au))h=se(this,Dl);else try{ze(this,au,r.select),h=r.select(h),h=Fx(o==null?void 0:o.data,h,r),ze(this,Dl,h),ze(this,Ii,null)}catch(E){ze(this,Ii,E)}se(this,Ii)&&(y=se(this,Ii),h=se(this,Dl),m=Date.now(),b="error");const v=p.fetchStatus==="fetching",x=b==="pending",_=b==="error",j=x&&v,C=h!==void 0,T={status:b,fetchStatus:p.fetchStatus,isPending:x,isSuccess:b==="success",isError:_,isInitialLoading:j,isLoading:j,data:h,dataUpdatedAt:p.dataUpdatedAt,error:y,errorUpdatedAt:m,failureCount:p.fetchFailureCount,failureReason:p.fetchFailureReason,errorUpdateCount:p.errorUpdateCount,isFetched:n.isFetched(),isFetchedAfterMount:p.dataUpdateCount>c.dataUpdateCount||p.errorUpdateCount>c.errorUpdateCount,isFetching:v,isRefetching:v&&!x,isLoadingError:_&&!C,isPaused:p.fetchStatus==="paused",isPlaceholderData:u,isRefetchError:_&&C,isStale:Ub(n,r),refetch:this.refetch,promise:se(this,Ls),isEnabled:Tr(r.enabled,n)!==!1};if(this.options.experimental_prefetchInRender){const E=T.data!==void 0,R=T.status==="error"&&!E,N=P=>{R?P.reject(T.error):E&&P.resolve(T.data)},O=()=>{const P=ze(this,Ls,T.promise=Bx());N(P)},z=se(this,Ls);switch(z.status){case"pending":n.queryHash===s.queryHash&&N(z);break;case"fulfilled":(R||T.data!==z.value)&&O();break;case"rejected":(!R||T.error!==z.reason)&&O();break}}return T}updateResult(){const n=se(this,In),r=this.createResult(se(this,lt),this.options);if(ze(this,ra,se(this,lt).state),ze(this,ql,this.options),se(this,ra).data!==void 0&&ze(this,Ol,se(this,lt)),Mh(r,n))return;ze(this,In,r);const s=()=>
vendor: 5,920 bytes, line 40
40{if(!n)return!0;const{notifyOnChangeProps:i}=this.options,o=typeof i=="function"?i():i;if(o==="all"||!o&&!se(this,Il).size)return!0;const a=new Set(o??se(this,Il));return this.options.throwOnError&&a.add("error"),Object.keys(se(this,In)).some(l=>{const d=l;return se(this,In)[d]!==n[d]&&a.has(d)})};Qe(this,ft,KS).call(this,{listeners:s()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&Qe(this,ft,Kx).call(this)}},er=new WeakMap,lt=new WeakMap,ou=new WeakMap,In=new WeakMap,ra=new WeakMap,ql=new WeakMap,Ls=new WeakMap,Ii=new WeakMap,au=new WeakMap,Dl=new WeakMap,Ol=new WeakMap,sa=new WeakMap,ia=new WeakMap,Li=new WeakMap,Il=new WeakMap,ft=new WeakSet,rc=function(n){Qe(this,ft,Gx).call(this);let r=se(this,lt).fetch(this.options,n);return n!=null&&n.throwOnError||(r=r.catch(Wn)),r},Hx=function(){Qe(this,ft,Yx).call(this);const n=to(this.options.staleTime,se(this,lt));if($c.isServer()||se(this,In).isStale||!$x(n))return;const s=$S(se(this,In).dataUpdatedAt,n)+1;ze(this,sa,Zo.setTimeout(()=>{se(this,In).isStale||this.updateResult()},s))},Vx=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(se(this,lt)):this.options.refetchInterval)??!1},Zx=function(n){Qe(this,ft,Xx).call(this),ze(this,Li,n),!($c.isServer()||Tr(this.options.enabled,se(this,lt))===!1||!$x(se(this,Li))||se(this,Li)===0)&&ze(this,ia,Zo.setInterval(()=>{(this.options.refetchIntervalInBackground||$b.isFocused())&&Qe(this,ft,rc).call(this)},se(this,Li)))},Kx=function(){Qe(this,ft,Hx).call(this),Qe(this,ft,Zx).call(this,Qe(this,ft,Vx).call(this))},Yx=function(){se(this,sa)&&(Zo.clearTimeout(se(this,sa)),ze(this,sa,void 0))},Xx=function(){se(this,ia)&&(Zo.clearInterval(se(this,ia)),ze(this,ia,void 0))},Gx=function(){const n=se(this,er).getQueryCache().build(se(this,er),this.options);if(n===se(this,lt))return;const r=se(this,lt);ze(this,lt,n),ze(this,ou,n.state),this.hasListeners()&&(r==null||r.removeObserver(this),n.addObserver(this))},KS=function(n){an.batch(()=>{n.listeners&&this.listeners.forEach(r=>{r(se(this,In))}),se(this,er).getQueryCache().notify({query:se(this,lt),type:"observerResultsUpdated"})})},b2);function cT(e,n){return Tr(n.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&n.retryOnMount===!1)}function _1(e,n){return cT(e,n)||e.state.data!==void 0&&Jx(e,n,n.refetchOnMount)}function Jx(e,n,r){if(Tr(n.enabled,e)!==!1&&to(n.staleTime,e)!=="static"){const s=typeof r=="function"?r(e):r;return s==="always"||s!==!1&&Ub(e,n)}return!1}function j1(e,n,r,s){return(e!==n||Tr(s.enabled,e)===!1)&&(!r.suspense||e.state.status!=="error")&&Ub(e,r)}function Ub(e,n){return Tr(n.enabled,e)!==!1&&e.isStaleByTime(to(n.staleTime,e))}function uT(e,n){return!Mh(e.getCurrentResult(),n)}function w1(e){return{onFetch:(n,r)=>{var f,p,u,h,y;const s=n.options,i=(u=(p=(f=n.fetchOptions)==null?void 0:f.meta)==null?void 0:p.fetchMore)==null?void 0:u.direction,o=((h=n.state.data)==null?void 0:h.pages)||[],a=((y=n.state.data)==null?void 0:y.pageParams)||[];let l={pages:[],pageParams:[]},d=0;const c=async()=>{let m=!1;const b=x=>{rT(x,()=>n.signal,()=>m=!0)},A=FS(n.options,n.fetchOptions),v=async(x,_,j)=>{if(m)return Promise.reject();if(_==null&&x.pages.length)return Promise.resolve(x);const S=(()=>{const R={client:n.client,queryKey:n.queryKey,pageParam:_,direction:j?"backward":"forward",meta:n.options.meta};return b(R),R})(),T=await A(S),{maxPages:L}=n.options,E=j?nT:tT;return{pages:E(x.pages,T,L),pageParams:E(x.pageParams,_,L)}};if(i&&o.length){const x=i==="backward",_=x?pT:S1,j={pages:o,pageParams:a},C=_(s,j);l=await v(j,C,x)}else{const x=e??o.length;do{const _=d===0?a[0]??s.initialPageParam:S1(s,l);if(d>0&&_==null)break;l=await v(l,_),d++}while(d<x)}return l};n.options.persister?n.fetchFn=()=>{var m,b;return(b=(m=n.options).persister)==null?void 0:b.call(m,c,{client:n.client,queryKey:n.queryKey,meta:n.options.meta,signal:n.signal},r)}:n.fetchFn=c}}}function S1(e,{pages:n,pageParams:r}){const s=n.length-1;return n.length>0?e.getNextPageParam(n[s],n,r[s],r):void 0}function pT(e,{pages:n,pageParams:r}){var s;return n.length>0?(s=e.getPreviousPageParam)==null?void 0:s.call(e,n[0],n,r[0],r):void 0}var lu,ms,Tn,oa,xs,ji,A2,hT=(A2=class extends HS{constructor(n){super();$e(this,xs);$e(this,lu);$e(this,ms);$e(this,Tn);$e(this,oa);ze(this,lu,n.client),this.mutationId=n.mutationId,ze(this,Tn,n.mutationCache),ze(this,ms,[]),this.state=n.state||YS(),this.setOptions(n.options),this.scheduleGc()}setOptions(n){this.options=n,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(n){se(this,ms).includes(n)||(se(this,ms).push(n),this.clearGcTimeout(),se(this,Tn).notify({type:"observerAdded",mutation:this,observer:n}))}removeObserver(n){ze(this,ms,se(this,ms).filter(r=>r!==n)),this.scheduleGc(),se(this,Tn).notify({type:"observerRemoved",mutation:this,observer:n})}optionalRemove(){se(this,ms).length||(this.state.status==="pending"?this.scheduleGc():se(this,Tn).remove(this))}continue(){var n;return((n=se(this,oa))==null?void 0:n.continue())??this.execute(this.state.variables)}async execute(n){var a,l,d,c,f,p,u,h,y,m,b,A,v,x,_,j,C,S;const r=()=>{Qe(this,xs,ji).call(this,{type:"continue"})},s={client:se(this,lu),meta:this.options.meta,mutationKey:this.options.mutationKey};ze(this,oa,US({fn:()=>this.options.mutationFn?this.options.mutationFn(n,s):Promise.reject(new Error("No mutationFn found")),onFail:(T,L)=>{Qe(this,xs,ji).call(this,{type:"failed",failureCount:T,error:L})},onPause:()=>{Qe(this,xs,ji).call(this,{type:"pause"})},onContinue:r,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>se(this,Tn).canRun(this)}));const i=this.state.status==="pending",o=!se(this,oa).canStart();try{if(i)r();else{Qe(this,xs,ji).call(this,{type:"pending",variables:n,isPaused:o}),se(this,Tn).config.onMutate&&await se(this,Tn).config.onMutate(n,this,s);
40const L=await((l=(a=this.options).onMutate)==null?void 0:l.call(a,n,s));L!==this.state.context&&Qe(this,xs,ji).call(this,{type:"pending",context:L,variables:n,isPaused:o})}const T=await se(this,oa).start();return await((c=(d=se(this,Tn).config).onSuccess)==null?void 0:c.call(d,T,n,this.state.context,this,s)),await((p=(f=this.options).onSuccess)==null?void 0:p.call(f,T,n,this.state.context,s)),await((h=(u=se(this,Tn).config).onSettled)==null?void 0:h.call(u,T,null,this.state.variables,this.state.context,this,s)),await((m=(y=this.options).onSettled)==null?void 0:m.call(y,T,null,n,this.state.context,s)),Qe(this,xs,ji).call(this,{type:"success",data:T}),T}catch(T){try{await((A=(b=se(this,Tn).config).onError)==null?void 0:A.call(b,T,n,this.state.context,this,s))}catch(L){Promise.reject(L)}try{await((x=(v=this.options).onError)==null?void 0:x.call(v,T,n,this.state.context,s))}catch(L){Promise.reject(L)}try{await((j=(_=se(this,Tn).config).onSettled)==null?void 0:j.call(_,void 0,T,this.state.variables,this.state.context,this,s))}catch(L){Promise.reject(L)}try{await((S=(C=this.options).onSettled)==null?void 0:S.call(C,void 0,T,n,this.state.context,s))}catch(L){Promise.reject(L)}throw Qe(this,xs,ji).call(this,{type:"error",error:T}),T}finally{se(this,Tn).runNext(this)}}},lu=new WeakMap,ms=new WeakMap,Tn=new WeakMap,oa=new WeakMap,xs=new WeakSet,ji=function(n){const r=s=>{switch(n.type){case"failed":return{...s,failureCount:n.failureCount,failureReason:n.error};case"pause":return{...s,isPaused:!0};case"continue":return{...s,isPaused:!1};case"pending":return{...s,context:n.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:n.isPaused,status:"pending",variables:n.variables,submittedAt:Date.now()};case"success":return{...s,data:n.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...s,data:void 0,error:n.error,failureCount:s.failureCount+1,failureReason:n.error,isPaused:!1,status:"error"}}};this.state=r(this.state),an.batch(()=>{se(this,ms).forEach(s=>{s.onMutationUpdate(n)}),se(this,Tn).notify({mutation:this,type:"updated",action:n})})},A2);function YS(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Ws,Xr,du,v2,fT=(v2=class extends dd{constructor(n={}){super();$e(this,Ws);$e(this,Xr);$e(this,du);this.config=n,ze(this,Ws,new Set),ze(this,Xr,new Map),ze(this,du,0)}build(n,r,s){const i=new hT({client:n,mutationCache:this,mutationId:++Nu(this,du)._,options:n.defaultMutationOptions(r),state:s});return this.add(i),i}add(n){se(this,Ws).add(n);const r=Ku(n);if(typeof r=="string"){const s=se(this,Xr).get(r);s?s.push(n):se(this,Xr).set(r,[n])}this.notify({type:"added",mutation:n})}remove(n){if(se(this,Ws).delete(n)){const r=Ku(n);if(typeof r=="string"){const s=se(this,Xr).get(r);if(s)if(s.length>1){const i=s.indexOf(n);i!==-1&&s.splice(i,1)}else s[0]===n&&se(this,Xr).delete(r)}}this.notify({type:"removed",mutation:n})}canRun(n){const r=Ku(n);if(typeof r=="string"){const s=se(this,Xr).get(r),i=s==null?void 0:s.find(o=>o.state.status==="pending");return!i||i===n}else return!0}runNext(n){var s;const r=Ku(n);if(typeof r=="string"){const i=(s=se(this,Xr).get(r))==null?void 0:s.find(o=>o!==n&&o.state.isPaused);return(i==null?void 0:i.continue())??Promise.resolve()}else return Promise.resolve()}clear(){an.batch(()=>{se(this,Ws).forEach(n=>{this.notify({type:"removed",mutation:n})}),se(this,Ws).clear(),se(this,Xr).clear()})}getAll(){return Array.from(se(this,Ws))}find(n){const r={exact:!0,...n};return this.getAll().find(s=>x1(r,s))}findAll(n={}){return this.getAll().filter(r=>x1(n,r))}notify(n){an.batch(()=>{this.listeners.forEach(r=>{r(n)})})}resumePausedMutations(){const n=this.getAll().filter(r=>
vendor: 5,164 bytes, line 40
40r.state.isPaused);return an.batch(()=>Promise.all(n.map(r=>r.continue().catch(Wn))))}},Ws=new WeakMap,Xr=new WeakMap,du=new WeakMap,v2);function Ku(e){var n;return(n=e.options.scope)==null?void 0:n.id}var $s,Wi,tr,Ms,Xs,eh,Qx,_2,gT=(_2=class extends dd{constructor(r,s){super();$e(this,Xs);$e(this,$s);$e(this,Wi);$e(this,tr);$e(this,Ms);ze(this,$s,r),this.setOptions(s),this.bindMethods(),Qe(this,Xs,eh).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(r){var i;const s=this.options;this.options=se(this,$s).defaultMutationOptions(r),Mh(this.options,s)||se(this,$s).getMutationCache().notify({type:"observerOptionsUpdated",mutation:se(this,tr),observer:this}),s!=null&&s.mutationKey&&this.options.mutationKey&&ga(s.mutationKey)!==ga(this.options.mutationKey)?this.reset():((i=se(this,tr))==null?void 0:i.state.status)==="pending"&&se(this,tr).setOptions(this.options)}onUnsubscribe(){var r;this.hasListeners()||(r=se(this,tr))==null||r.removeObserver(this)}onMutationUpdate(r){Qe(this,Xs,eh).call(this),Qe(this,Xs,Qx).call(this,r)}getCurrentResult(){return se(this,Wi)}reset(){var r;(r=se(this,tr))==null||r.removeObserver(this),ze(this,tr,void 0),Qe(this,Xs,eh).call(this),Qe(this,Xs,Qx).call(this)}mutate(r,s){var i;return ze(this,Ms,s),(i=se(this,tr))==null||i.removeObserver(this),ze(this,tr,se(this,$s).getMutationCache().build(se(this,$s),this.options)),se(this,tr).addObserver(this),se(this,tr).execute(r)}},$s=new WeakMap,Wi=new WeakMap,tr=new WeakMap,Ms=new WeakMap,Xs=new WeakSet,eh=function(){var s;const r=((s=se(this,tr))==null?void 0:s.state)??YS();ze(this,Wi,{...r,isPending:r.status==="pending",isSuccess:r.status==="success",isError:r.status==="error",isIdle:r.status==="idle",mutate:this.mutate,reset:this.reset})},Qx=function(r){an.batch(()=>{var s,i,o,a,l,d,c,f;if(se(this,Ms)&&this.hasListeners()){const p=se(this,Wi).variables,u=se(this,Wi).context,h={client:se(this,$s),meta:this.options.meta,mutationKey:this.options.mutationKey};if((r==null?void 0:r.type)==="success"){try{(i=(s=se(this,Ms)).onSuccess)==null||i.call(s,r.data,p,u,h)}catch(y){Promise.reject(y)}try{(a=(o=se(this,Ms)).onSettled)==null||a.call(o,r.data,null,p,u,h)}catch(y){Promise.reject(y)}}else if((r==null?void 0:r.type)==="error"){try{(d=(l=se(this,Ms)).onError)==null||d.call(l,r.error,p,u,h)}catch(y){Promise.reject(y)}try{(f=(c=se(this,Ms)).onSettled)==null||f.call(c,void 0,r.error,p,u,h)}catch(y){Promise.reject(y)}}}this.listeners.forEach(p=>{p(se(this,Wi))})})},_2),ys,j2,mT=(j2=class extends dd{constructor(n={}){super();$e(this,ys);this.config=n,ze(this,ys,new Map)}build(n,r,s){const i=r.queryKey,o=r.queryHash??Mb(i,r);let a=this.get(o);return a||(a=new lT({client:n,queryKey:i,queryHash:o,options:n.defaultQueryOptions(r),state:s,defaultOptions:n.getQueryDefaults(i)}),this.add(a)),a}add(n){se(this,ys).has(n.queryHash)||(se(this,ys).set(n.queryHash,n),this.notify({type:"added",query:n}))}remove(n){const r=se(this,ys).get(n.queryHash);r&&(n.destroy(),r===n&&se(this,ys).delete(n.queryHash),this.notify({type:"removed",query:n}))}clear(){an.batch(()=>{this.getAll().forEach(n=>{this.remove(n)})})}get(n){return se(this,ys).get(n)}getAll(){return[...se(this,ys).values()]}find(n){const r={exact:!0,...n};return this.getAll().find(s=>m1(r,s))}findAll(n={}){const r=this.getAll();return Object.keys(n).length>0?r.filter(s=>m1(n,s)):r}notify(n){an.batch(()=>{this.listeners.forEach(r=>{r(n)})})}onFocus(){an.batch(()=>{this.getAll().forEach(n=>{n.onFocus()})})}onOnline(){an.batch(()=>{this.getAll().forEach(n=>{n.onOnline()})})}},ys=new WeakMap,j2),Ut,$i,Mi,Ll,Wl,Fi,$l,Ml,w2,XS=(w2=class{constructor(e={}){$e(this,Ut);$e(this,$i);$e(this,Mi);$e(this,Ll);$e(this,Wl);$e(this,Fi);$e(this,$l);$e(this,Ml);ze(this,Ut,e.queryCache||new mT),ze(this,$i,e.mutationCache||new fT),ze(this,Mi,e.defaultOptions||{}),ze(this,Ll,new Map),ze(this,Wl,new Map),ze(this,Fi,0)}mount(){Nu(this,Fi)._++,se(this,Fi)===1&&(ze(this,$l,$b.subscribe(async e=>{e&&(await this.resumePausedMutations(),se(this,Ut).onFocus())})),ze(this,Ml,Fh.subscribe(async e=>{e&&(await this.resumePausedMutations(),se(this,Ut).onOnline())})))}unmount(){var e,n;Nu(this,Fi)._--,se(this,Fi)===0&&((e=se(this,$l))==null||e.call(this),ze(this,$l,void 0),(n=se(this,Ml))==null||n.call(this),ze(this,Ml,void 0))}isFetching(e){return se(this,Ut).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return se(this,$i).findAll({...e,status:"pending"}).length}getQueryData(e){var r;const n=this.defaultQueryOptions({queryKey:e});return(r=se(this,Ut).get(n.queryHash))==null?void 0:r.state.data}ensureQueryData(e){const n=this.defaultQueryOptions(e),r=se(this,Ut).build(this,n),s=r.state.data;return s===void 0?this.fetchQuery(e):(e.revalidateIfStale&&r.isStaleByTime(to(n.staleTime,r))&&this.prefetchQuery(n),Promise.resolve(s))}getQueriesData(e){return se(this,Ut).findAll(e).map(({queryKey:n,state:r})=>{const s=r.data;return[n,s]})}setQueryData(e,n,r){const s=this.defaultQueryOptions({queryKey:e}),i=se(this,Ut).get(s.queryHash),o=i==null?void 0:i.state.data,a=JC(n,o);if(a!==void 0)return se(this,Ut).build(this,s).setData(a,{...r,manual:!0})}
40setQueriesData(e,n,r){return an.batch(()=>se(this,Ut).findAll(e).map(({queryKey:s})=>[s,this.setQueryData(s,n,r)]))}getQueryState(e){var r;const n=this.defaultQueryOptions({queryKey:e});return(r=se(this,Ut).get(n.queryHash))==null?void 0:r.state}removeQueries(e){const n=se(this,Ut);an.batch(()=>{n.findAll(e).forEach(r=>{n.remove(r)})})}resetQueries(e,n){const r=se(this,Ut);return an.batch(()=>(r.findAll(e).forEach(s=>{s.reset()}),this.refetchQueries({type:"active",...e},n)))}cancelQueries(e,n={}){const r={revert:!0,...n},s=an.batch(()=>se(this,Ut).findAll(e).map(i=>i.cancel(r)));return Promise.all(s).then(Wn).catch(Wn)}invalidateQueries(e,n={}){return an.batch(()=>(se(this,Ut).findAll(e).forEach(r=>{r.invalidate()}),(e==null?void 0:e.refetchType)==="none"?Promise.resolve():this.refetchQueries({...e,type:(e==null?void 0:e.refetchType)??(e==null?void 0:e.type)??"active"},n)))}refetchQueries(e,n={}){const r={...n,cancelRefetch:n.cancelRefetch??!0},s=an.batch(()=>se(this,Ut).findAll(e).filter(i=>!i.isDisabled()&&!i.isStatic()).map(i=>{let o=i.fetch(void 0,r);return r.throwOnError||(o=o.catch(Wn)),i.state.fetchStatus==="paused"?Promise.resolve():o}));return Promise.all(s).then(Wn)}fetchQuery(e){const n=this.defaultQueryOptions(e);
40n.retry===void 0&&(n.retry=!1);const r=se(this,Ut).build(this,n);return r.isStaleByTime(to(n.staleTime,r))?r.fetch(n):Promise.resolve(r.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Wn).catch(Wn)}fetchInfiniteQuery(e){return e.behavior=w1(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Wn).catch(Wn)}ensureInfiniteQueryData(e){return e.behavior=w1(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return Fh.isOnline()?se(this,$i).resumePausedMutations():Promise.resolve()}getQueryCache(){return se(this,Ut)}getMutationCache(){return se(this,$i)}getDefaultOptions(){return se(this,Mi)}setDefaultOptions(e){ze(this,Mi,e)}setQueryDefaults(e,n){se(this,Ll).set(ga(e),{queryKey:e,defaultOptions:n})}getQueryDefaults(e){const n=[...se(this,Ll).values()],r={};return n.forEach(s=>{Wc(e,s.queryKey)&&Object.assign(r,s.defaultOptions)}),r}setMutationDefaults(e,n){se(this,Wl).set(ga(e),{mutationKey:e,defaultOptions:n})}getMutationDefaults(e){const n=[...se(this,Wl).values()],r={};return n.forEach(s=>{Wc(e,s.mutationKey)&&Object.assign(r,s.defaultOptions)}),r}defaultQueryOptions(e){if(e._defaulted)return e;const n={...se(this,Mi).queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return n.queryHash||(n.queryHash=Mb(n.queryKey,n)),n.refetchOnReconnect===void 0&&(n.refetchOnReconnect=n.networkMode!=="always"),n.throwOnError===void 0&&(n.throwOnError=!!n.suspense),!n.networkMode&&n.persister&&(n.networkMode="offlineFirst"),n.queryFn===Fb&&(n.enabled=!1),n}defaultMutationOptions(e){return e!=null&&e._defaulted?e:{...se(this,Mi).mutations,...(e==null?void 0:e.mutationKey)&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){se(this,Ut).clear(),se(this,$i).clear()}},Ut=new WeakMap,$i=new WeakMap,Mi=new WeakMap,Ll=new WeakMap,Wl=new WeakMap,Fi=new WeakMap,$l=new WeakMap,Ml=new WeakMap,w2),GS=g.createContext(void 0),rt=e=>{const n=g.useContext(GS);if(!n)throw new Error("No QueryClient set, use QueryClientProvider to set one");return n},JS=({client:e,children:n})=>(g.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),t.jsx(GS.Provider,{value:e,children:n})),QS=g.createContext(!1),xT=()=>g.useContext(QS);QS.Provider;function yT(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var bT=g.createContext(yT()),AT=()=>g.useContext(bT),vT=(e,n,r)=>{const s=r!=null&&r.state.error&&typeof e.throwOnError=="function"?Bb(e.throwOnError,[r.state.error,r]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||s)&&(n.isReset()||(e.retryOnMount=!1))},_T=e=>{g.useEffect(()=>{e.clearReset()},[e])},jT=({result:e,errorResetBoundary:n,throwOnError:r,query:s,suspense:i})=>e.isError&&!n.isReset()&&!e.isFetching&&s&&(i&&e.data===void 0||Bb(r,[e.error,s])),wT=e=>{if(e.suspense){const r=i=>i==="static"?i:Math.max(i??1e3,1e3),s=e.staleTime;e.staleTime=typeof s=="function"?(...i)=>r(s(...i)):r(s),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},ST=(e,n)=>e.isLoading&&e.isFetching&&!n,kT=(e,n)=>(e==null?void 0:e.suspense)&&n.isPending,k1=(e,n,r)=>n.fetchOptimistic(e).catch(()=>{r.clearReset()});function CT(e,n,r){var u,h,y,m;const s=xT(),i=AT(),o=rt(),a=o.defaultQueryOptions(e);(h=(u=o.getDefaultOptions().queries)==null?void 0:u._experimental_beforeQuery)==null||h.call(u,a);const l=o.getQueryCache().get(a.queryHash);a._optimisticResults=s?"isRestoring":"optimistic",wT(a),vT(a,i,l),_T(i);const d=!o.getQueryCache().get(a.queryHash),[c]=g.useState(()=>new n(o,a)),f=c.getOptimisticResult(a),p=!s&&e.subscribed!==!1;if(g.useSyncExternalStore(g.useCallback(b=>{const A=p?c.subscribe(an.batchCalls(b)):Wn;return c.updateResult(),A},[c,p]),()=>c.getCurrentResult(),()=>c.getCurrentResult()),g.useEffect(()=>{c.setOptions(a)},[a,c]),kT(a,f))throw k1(a,c,i);if(jT({result:f,errorResetBoundary:i,throwOnError:a.throwOnError,query:l,suspense:a.suspense}))throw f.error;if((m=(y=o.getDefaultOptions().queries)==null?void 0:y._experimental_afterQuery)==null||m.call(y,a,f),a.experimental_prefetchInRender&&!$c.isServer()&&ST(f,s)){const b=d?k1(a,c,i):l==null?void 0:l.promise;b==null||b.catch(Wn).finally(()=>{c.updateResult()})}return a.notifyOnChangeProps?f:c.trackResult(f)}function Ae(e,n){return CT(e,dT)}function _n(e,n){const r=rt(),[s]=g.useState(()=>new gT(r,e));g.useEffect(()=>{s.setOptions(e)},[s,e]);const i=g.useSyncExternalStore(g.useCallback(a=>s.subscribe(an.batchCalls(a)),[s]),()=>s.getCurrentResult(),()=>s.getCurrentResult()),o=g.useCallback((a,l)=>{s.mutate(a,l).catch(Wn)},[s]);if(i.error&&Bb(s.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:o,mutateAsync:i.mutate}}/** 41 * @remix-run/router v1.23.2 42 * 43 * Copyright (c) Remix Software Inc. 44 * 45 * This source code is licensed under the MIT license found in the 46 * LICENSE.md file in the root directory of this source tree. 47 * 48 * @license MIT 49 */function Mc(){return Mc=Object.assign?Object.assign.bind():function(e){for(var n=1;n<arguments.length;n++){var r=arguments[n];
vendor: 9,249 bytes, lines 49-58
49for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])}return e},Mc.apply(this,arguments)}var Hi;(function(e){e.Pop="POP",e.Push="PUSH",e.Replace="REPLACE"})(Hi||(Hi={}));const C1="popstate";function TT(e){e===void 0&&(e={});function n(s,i){let{pathname:o,search:a,hash:l}=s.location;return ey("",{pathname:o,search:a,hash:l},i.state&&i.state.usr||null,i.state&&i.state.key||"default")}function r(s,i){return typeof i=="string"?i:Bh(i)}return NT(n,r,null,e)}function It(e,n){if(e===!1||e===null||typeof e>"u")throw new Error(n)}function Hb(e,n){if(!e){typeof console<"u"&&console.warn(n);try{throw new Error(n)}catch{}}}function zT(){return Math.random().toString(36).substr(2,8)}function T1(e,n){return{usr:e.state,key:e.key,idx:n}}function ey(e,n,r,s){return r===void 0&&(r=null),Mc({pathname:typeof e=="string"?e:e.pathname,search:"",hash:""},typeof n=="string"?cd(n):n,{state:r,key:n&&n.key||s||zT()})}function Bh(e){let{pathname:n="/",search:r="",hash:s=""}=e;return r&&r!=="?"&&(n+=r.charAt(0)==="?"?r:"?"+r),s&&s!=="#"&&(n+=s.charAt(0)==="#"?s:"#"+s),n}function cd(e){let n={};if(e){let r=e.indexOf("#");r>=0&&(n.hash=e.substr(r),e=e.substr(0,r));let s=e.indexOf("?");s>=0&&(n.search=e.substr(s),e=e.substr(0,s)),e&&(n.pathname=e)}return n}function NT(e,n,r,s){s===void 0&&(s={});let{window:i=document.defaultView,v5Compat:o=!1}=s,a=i.history,l=Hi.Pop,d=null,c=f();c==null&&(c=0,a.replaceState(Mc({},a.state,{idx:c}),""));function f(){return(a.state||{idx:null}).idx}function p(){l=Hi.Pop;let b=f(),A=b==null?null:b-c;c=b,d&&d({action:l,location:m.location,delta:A})}function u(b,A){l=Hi.Push;let v=ey(m.location,b,A);c=f()+1;let x=T1(v,c),_=m.createHref(v);try{a.pushState(x,"",_)}catch(j){if(j instanceof DOMException&&j.name==="DataCloneError")throw j;i.location.assign(_)}o&&d&&d({action:l,location:m.location,delta:1})}function h(b,A){l=Hi.Replace;let v=ey(m.location,b,A);c=f();let x=T1(v,c),_=m.createHref(v);a.replaceState(x,"",_),o&&d&&d({action:l,location:m.location,delta:0})}function y(b){let A=i.location.origin!=="null"?i.location.origin:i.location.href,v=typeof b=="string"?b:Bh(b);return v=v.replace(/ $/,"%20"),It(A,"No window.location.(origin|href) available to create URL for href: "+v),new URL(v,A)}let m={get action(){return l},get location(){return e(i,a)},listen(b){if(d)throw new Error("A history only accepts one active listener");return i.addEventListener(C1,p),d=b,()=>{i.removeEventListener(C1,p),d=null}},createHref(b){return n(i,b)},createURL:y,encodeLocation(b){let A=y(b);return{pathname:A.pathname,search:A.search,hash:A.hash}},push:u,replace:h,go(b){return a.go(b)}};return m}var z1;(function(e){e.data="data",e.deferred="deferred",e.redirect="redirect",e.error="error"})(z1||(z1={}));function RT(e,n,r){return r===void 0&&(r="/"),ET(e,n,r)}function ET(e,n,r,s){let i=typeof n=="string"?cd(n):n,o=Yl(i.pathname||"/",r);if(o==null)return null;let a=e4(e);PT(a);let l=null;for(let d=0;l==null&&d<a.length;++d){let c=UT(o);l=FT(a[d],c)}return l}function e4(e,n,r,s){n===void 0&&(n=[]),r===void 0&&(r=[]),s===void 0&&(s="");let i=(o,a,l)=>{let d={relativePath:l===void 0?o.path||"":l,caseSensitive:o.caseSensitive===!0,childrenIndex:a,route:o};d.relativePath.startsWith("/")&&(It(d.relativePath.startsWith(s),'Absolute route path "'+d.relativePath+'" nested under path '+('"'+s+'" is not valid. An absolute child route path ')+"must start with the combined path of all its parent routes."),d.relativePath=d.relativePath.slice(s.length));let c=no([s,d.relativePath]),f=r.concat(d);o.children&&o.children.length>0&&(It(o.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+c+'".')),e4(o.children,n,f,c)),!(o.path==null&&!o.index)&&n.push({path:c,score:$T(c,o.index),routesMeta:f})};return e.forEach((o,a)=>{var l;if(o.path===""||!((l=o.path)!=null&&l.includes("?")))i(o,a);else for(let d of t4(o.path))i(o,a,d)}),n}function t4(e){let n=e.split("/");if(n.length===0)return[];let[r,...s]=n,i=r.endsWith("?"),o=r.replace(/\?$/,"");if(s.length===0)return i?[o,""]:[o];let a=t4(s.join("/")),l=[];return l.push(...a.map(d=>d===""?o:[o,d].join("/"))),i&&l.push(...a),l.map(d=>e.startsWith("/")&&d===""?"/":d)}function PT(e){e.sort((n,r)=>n.score!==r.score?r.score-n.score:MT(n.routesMeta.map(s=>s.childrenIndex),r.routesMeta.map(s=>s.childrenIndex)))}const qT=/^:[\w-]+$/,DT=3,OT=2,IT=1,LT=10,WT=-2,N1=e=>e==="*";function $T(e,n){let r=e.split("/"),s=r.length;return r.some(N1)&&(s+=WT),n&&(s+=OT),r.filter(i=>!N1(i)).reduce((i,o)=>i+(qT.test(o)?DT:o===""?IT:LT),s)}function MT(e,n){return e.length===n.length&&e.slice(0,-1).every((s,i)=>s===n[i])?e[e.length-1]-n[n.length-1]:0}function FT(e,n,r){let{routesMeta:s}=e,i={},o="/",a=[];for(let l=0;l<s.length;++l){let d=s[l],c=l===s.length-1,f=o==="/"?n:n.slice(o.length)||"/",p=ty({path:d.relativePath,caseSensitive:d.caseSensitive,end:c},f),u=d.route;if(!p)return null;Object.assign(i,p.params),a.push({params:i,pathname:no([o,p.pathname]),pathnameBase:YT(no([o,p.pathnameBase])),route:u}),p.pathnameBase!=="/"&&(o=no([o,p.pathnameBase]))}return a}function ty(e,n){typeof e=="string"&&(e={path:e,caseSensitive:!1,end:!0});let[r,s]=BT(e.path,e.caseSensitive,e.end),i=n.match(r);if(!i)return null;let o=i[0],a=o.replace(/(.)\/+$/,"$1"),l=i.slice(1);return{params:s.reduce((c,f,p)=>{let{paramName:u,isOptional:h}=f;if(u==="*"){let m=l[p]||"";a=o.slice(0,o.length-m.length).replace(/(.)\/+$/,"$1")}const y=l[p];return h&&!y?c[u]=void 0:c[u]=(y||"").replace(/%2F/g,"/"),c},{}),pathname:o,pathnameBase:a,pattern:e}}function BT(e,n,r){n===void 0&&(n=!1),r===void 0&&(r=!0),Hb(e==="*"||!e.endsWith("*")||e.endsWith("/*"),'Route path "'+e+'" will be treated as if it were '+('"'+e.replace(/\*$/,"/*")+'" because the `*` character must ')+"always follow a `/` in the pattern. To get rid of this warning, "+('please change the route path to "'+e.replace(/\*$/,"/*")+'".'));let s=[],i="^"+e.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(a,l,d)=>(s.push({paramName:l,isOptional:d!=null}),d?"/?([^\\/]+)?":"/([^\\/]+)"));return e.endsWith("*")?(s.push({paramName:"*"}),i+=e==="*"||e==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):r?i+="\\/*$":e!==""&&e!=="/"&&(i+="(?:(?=\\/|$))"),[new RegExp(i,n?void 0:"i"),s]}function UT(e){try{return e.split("/").map(n=>decodeURIComponent(n).replace(/\//g,"%2F")).join("/")}catch(n){return Hb(!1,'The URL path "'+e+'" could not be decoded because it is is a malformed URL segment. This is probably due to a bad percent '+("encoding ("+n+").")),e}}function Yl(e,n){if(n==="/")return e;if(!e.toLowerCase().startsWith(n.toLowerCase()))return null;let r=n.endsWith("/")?n.length-1:n.length,s=e.charAt(r);return s&&s!=="/"?null:e.slice(r)||"/"}const HT=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,VT=e=>HT.test(e);function ZT(e,n){n===void 0&&(n="/");let{pathname:r,search:s="",hash:i=""}=typeof e=="string"?cd(e):e,o;if(r)if(VT(r))o=r;else{if(r.includes("//")){let a=r;r=r.replace(/\/\/+/g,"/"),Hb(!1,"Pathnames cannot have embedded double slashes - normalizing "+(a+" -> "+r))}r.startsWith("/")?o=R1(r.substring(1),"/"):o=R1(r,n)}else o=n;return{pathname:o,search:XT(s),hash:GT(i)}}function R1(e,n){let r=n.replace(/\/+$/,"").split("/");return e.split("/").forEach(i=>{i===".."?r.length>1&&r.pop():i!=="."&&r.push(i)}),r.length>1?r.join("/"):"/"}function Bg(e,n,r,s){return"Cannot include a '"+e+"' character in a manually specified "+("`to."+n+"` field ["+JSON.stringify(s)+"]. Please separate it out to the ")+("`to."+r+"` field. Alternatively you may provide the full path as ")+'a string in <Link to="..."> and the router will parse it for you.'}function KT(e){return e.filter((n,r)=>r===0||n.route.path&&n.route.path.length>0)}function Vb(e,n){let r=KT(e);return n?r.map((s,i)=>i===r.length-1?s.pathname:s.pathnameBase):r.map(s=>s.pathnameBase)}function Zb(e,n,r,s){s===void 0&&(s=!1);let i;typeof e=="string"?i=cd(e):(i=Mc({},e),It(!i.pathname||!i.pathname.includes("?"),Bg("?","pathname","search",i)),It(!i.pathname||!i.pathname.includes("#"),Bg("#","pathname","hash",i)),It(!i.search||!i.search.includes("#"),Bg("#","search","hash",i)));let o=e===""||i.pathname==="",a=o?"/":i.pathname,l;if(a==null)l=r;else{let p=n.length-1;if(!s&&a.startsWith("..")){let u=a.split("/");for(;u[0]==="..";)u.shift(),p-=1;i.pathname=u.join("/")}l=p>=0?n[p]:"/"}let d=ZT(i,l),c=a&&a!=="/"&&a.endsWith("/"),f=(o||a===".")&&r.endsWith("/");return!d.pathname.endsWith("/")&&(c||f)&&(d.pathname+="/"),d}const no=e=>e.join("/").replace(/\/\/+/g,"/"),YT=e=>e.replace(/\/+$/,"").replace(/^\/*/,"/"),XT=e=>!e||e==="?"?"":e.startsWith("?")?e:"?"+e,GT=e=>!e||e==="#"?"":e.startsWith("#")?e:"#"+e;function JT(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.internal=="boolean"&&"data"in e}const n4=["post","put","patch","delete"];new Set(n4);const QT=["get",...n4];new Set(QT);/** 50 * React Router v6.30.3 51 * 52 * Copyright (c) Remix Software Inc. 53 * 54 * This source code is licensed under the MIT license found in the 55 * LICENSE.md file in the root directory of this source tree. 56 * 57 * @license MIT 58 */function Fc(){return Fc=Object.assign?Object.assign.bind():function(e){for(var n=1;n<arguments.length;n++){var r=arguments[n];
vendor: 8,891 bytes, lines 58-67
58for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])}return e},Fc.apply(this,arguments)}const qf=g.createContext(null),r4=g.createContext(null),ai=g.createContext(null),Df=g.createContext(null),li=g.createContext({outlet:null,matches:[],isDataRoute:!1}),s4=g.createContext(null);function ez(e,n){let{relative:r}=n===void 0?{}:n;ud()||It(!1);let{basename:s,navigator:i}=g.useContext(ai),{hash:o,pathname:a,search:l}=Of(e,{relative:r}),d=a;return s!=="/"&&(d=a==="/"?s:no([s,a])),i.createHref({pathname:d,search:l,hash:o})}function ud(){return g.useContext(Df)!=null}function ja(){return ud()||It(!1),g.useContext(Df).location}function i4(e){g.useContext(ai).static||g.useLayoutEffect(e)}function gt(){let{isDataRoute:e}=g.useContext(li);return e?hz():tz()}function tz(){ud()||It(!1);let e=g.useContext(qf),{basename:n,future:r,navigator:s}=g.useContext(ai),{matches:i}=g.useContext(li),{pathname:o}=ja(),a=JSON.stringify(Vb(i,r.v7_relativeSplatPath)),l=g.useRef(!1);return i4(()=>{l.current=!0}),g.useCallback(function(c,f){if(f===void 0&&(f={}),!l.current)return;if(typeof c=="number"){s.go(c);return}let p=Zb(c,JSON.parse(a),o,f.relative==="path");e==null&&n!=="/"&&(p.pathname=p.pathname==="/"?n:no([n,p.pathname])),(f.replace?s.replace:s.push)(p,f.state,f)},[n,s,a,o,e])}function di(){let{matches:e}=g.useContext(li),n=e[e.length-1];return n?n.params:{}}function Of(e,n){let{relative:r}=n===void 0?{}:n,{future:s}=g.useContext(ai),{matches:i}=g.useContext(li),{pathname:o}=ja(),a=JSON.stringify(Vb(i,s.v7_relativeSplatPath));return g.useMemo(()=>Zb(e,JSON.parse(a),o,r==="path"),[e,a,o,r])}function nz(e,n){return rz(e,n)}function rz(e,n,r,s){ud()||It(!1);let{navigator:i}=g.useContext(ai),{matches:o}=g.useContext(li),a=o[o.length-1],l=a?a.params:{};a&&a.pathname;let d=a?a.pathnameBase:"/";a&&a.route;let c=ja(),f;if(n){var p;let b=typeof n=="string"?cd(n):n;d==="/"||(p=b.pathname)!=null&&p.startsWith(d)||It(!1),f=b}else f=c;let u=f.pathname||"/",h=u;if(d!=="/"){let b=d.replace(/^\//,"").split("/");h="/"+u.replace(/^\//,"").split("/").slice(b.length).join("/")}let y=RT(e,{pathname:h}),m=lz(y&&y.map(b=>Object.assign({},b,{params:Object.assign({},l,b.params),pathname:no([d,i.encodeLocation?i.encodeLocation(b.pathname).pathname:b.pathname]),pathnameBase:b.pathnameBase==="/"?d:no([d,i.encodeLocation?i.encodeLocation(b.pathnameBase).pathname:b.pathnameBase])})),o,r,s);return n&&m?g.createElement(Df.Provider,{value:{location:Fc({pathname:"/",search:"",hash:"",state:null,key:"default"},f),navigationType:Hi.Pop}},m):m}function sz(){let e=pz(),n=JT(e)?e.status+" "+e.statusText:e instanceof Error?e.message:JSON.stringify(e),r=e instanceof Error?e.stack:null,i={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return g.createElement(g.Fragment,null,g.createElement("h2",null,"Unexpected Application Error!"),g.createElement("h3",{style:{fontStyle:"italic"}},n),r?g.createElement("pre",{style:i},r):null,null)}const iz=g.createElement(sz,null);class oz extends g.Component{constructor(n){super(n),this.state={location:n.location,revalidation:n.revalidation,error:n.error}}static getDerivedStateFromError(n){return{error:n}}static getDerivedStateFromProps(n,r){return r.location!==n.location||r.revalidation!=="idle"&&n.revalidation==="idle"?{error:n.error,location:n.location,revalidation:n.revalidation}:{error:n.error!==void 0?n.error:r.error,location:r.location,revalidation:n.revalidation||r.revalidation}}componentDidCatch(n,r){console.error("React Router caught the following error during render",n,r)}render(){return this.state.error!==void 0?g.createElement(li.Provider,{value:this.props.routeContext},g.createElement(s4.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function az(e){let{routeContext:n,match:r,children:s}=e,i=g.useContext(qf);return i&&i.static&&i.staticContext&&(r.route.errorElement||r.route.ErrorBoundary)&&(i.staticContext._deepestRenderedBoundaryId=r.route.id),g.createElement(li.Provider,{value:n},s)}function lz(e,n,r,s){var i;if(n===void 0&&(n=[]),r===void 0&&(r=null),s===void 0&&(s=null),e==null){var o;if(!r)return null;if(r.errors)e=r.matches;else if((o=s)!=null&&o.v7_partialHydration&&n.length===0&&!r.initialized&&r.matches.length>0)e=r.matches;else return null}let a=e,l=(i=r)==null?void 0:i.errors;if(l!=null){let f=a.findIndex(p=>p.route.id&&(l==null?void 0:l[p.route.id])!==void 0);f>=0||It(!1),a=a.slice(0,Math.min(a.length,f+1))}let d=!1,c=-1;if(r&&s&&s.v7_partialHydration)for(let f=0;f<a.length;f++){let p=a[f];if((p.route.HydrateFallback||p.route.hydrateFallbackElement)&&(c=f),p.route.id){let{loaderData:u,errors:h}=r,y=p.route.loader&&u[p.route.id]===void 0&&(!h||h[p.route.id]===void 0);if(p.route.lazy||y){d=!0,c>=0?a=a.slice(0,c+1):a=[a[0]];break}}}return a.reduceRight((f,p,u)=>{let h,y=!1,m=null,b=null;r&&(h=l&&p.route.id?l[p.route.id]:void 0,m=p.route.errorElement||iz,d&&(c<0&&u===0?(fz("route-fallback"),y=!0,b=null):c===u&&(y=!0,b=p.route.hydrateFallbackElement||null)));let A=n.concat(a.slice(0,u+1)),v=()=>{let x;return h?x=m:y?x=b:p.route.Component?x=g.createElement(p.route.Component,null):p.route.element?x=p.route.element:x=f,g.createElement(az,{match:p,routeContext:{outlet:f,matches:A,isDataRoute:r!=null},children:x})};return r&&(p.route.ErrorBoundary||p.route.errorElement||u===0)?g.createElement(oz,{location:r.location,revalidation:r.revalidation,component:m,error:h,children:v(),routeContext:{outlet:null,matches:A,isDataRoute:!0}}):v()},null)}var o4=function(e){return e.UseBlocker="useBlocker",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e}(o4||{}),a4=function(e){return e.UseBlocker="useBlocker",e.UseLoaderData="useLoaderData",e.UseActionData="useActionData",e.UseRouteError="useRouteError",e.UseNavigation="useNavigation",e.UseRouteLoaderData="useRouteLoaderData",e.UseMatches="useMatches",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e.UseRouteId="useRouteId",e}(a4||{});function dz(e){let n=g.useContext(qf);return n||It(!1),n}function cz(e){let n=g.useContext(r4);return n||It(!1),n}function uz(e){let n=g.useContext(li);return n||It(!1),n}function l4(e){let n=uz(),r=n.matches[n.matches.length-1];return r.route.id||It(!1),r.route.id}function pz(){var e;let n=g.useContext(s4),r=cz(),s=l4();return n!==void 0?n:(e=r.errors)==null?void 0:e[s]}function hz(){let{router:e}=dz(o4.UseNavigateStable),n=l4(a4.UseNavigateStable),r=g.useRef(!1);return i4(()=>{r.current=!0}),g.useCallback(function(i,o){o===void 0&&(o={}),r.current&&(typeof i=="number"?e.navigate(i):e.navigate(i,Fc({fromRouteId:n},o)))},[e,n])}const E1={};function fz(e,n,r){E1[e]||(E1[e]=!0)}function gz(e,n){e==null||e.v7_startTransition,e==null||e.v7_relativeSplatPath}function ks(e){let{to:n,replace:r,state:s,relative:i}=e;ud()||It(!1);let{future:o,static:a}=g.useContext(ai),{matches:l}=g.useContext(li),{pathname:d}=ja(),c=gt(),f=Zb(n,Vb(l,o.v7_relativeSplatPath),d,i==="path"),p=JSON.stringify(f);return g.useEffect(()=>c(JSON.parse(p),{replace:r,state:s,relative:i}),[c,p,i,r,s]),null}function Ve(e){It(!1)}function mz(e){let{basename:n="/",children:r=null,location:s,navigationType:i=Hi.Pop,navigator:o,static:a=!1,future:l}=e;ud()&&It(!1);let d=n.replace(/^\/*/,"/"),c=g.useMemo(()=>({basename:d,navigator:o,static:a,future:Fc({v7_relativeSplatPath:!1},l)}),[d,l,o,a]);typeof s=="string"&&(s=cd(s));let{pathname:f="/",search:p="",hash:u="",state:h=null,key:y="default"}=s,m=g.useMemo(()=>{let b=Yl(f,d);return b==null?null:{location:{pathname:b,search:p,hash:u,state:h,key:y},navigationType:i}},[d,f,p,u,h,y,i]);return m==null?null:g.createElement(ai.Provider,{value:c},g.createElement(Df.Provider,{children:r,value:m}))}function d4(e){let{children:n,location:r}=e;return nz(ny(n),r)}new Promise(()=>{});function ny(e,n){n===void 0&&(n=[]);let r=[];return g.Children.forEach(e,(s,i)=>{if(!g.isValidElement(s))return;let o=[...n,i];if(s.type===g.Fragment){r.push.apply(r,ny(s.props.children,o));return}s.type!==Ve&&It(!1),!s.props.index||!s.props.children||It(!1);let a={id:s.props.id||o.join("-"),caseSensitive:s.props.caseSensitive,element:s.props.element,Component:s.props.Component,index:s.props.index,path:s.props.path,loader:s.props.loader,action:s.props.action,errorElement:s.props.errorElement,ErrorBoundary:s.props.ErrorBoundary,hasErrorBoundary:s.props.ErrorBoundary!=null||s.props.errorElement!=null,shouldRevalidate:s.props.shouldRevalidate,handle:s.props.handle,lazy:s.props.lazy};s.props.children&&(a.children=ny(s.props.children,o)),r.push(a)}),r}/** 59 * React Router DOM v6.30.3 60 * 61 * Copyright (c) Remix Software Inc. 62 * 63 * This source code is licensed under the MIT license found in the 64 * LICENSE.md file in the root directory of this source tree. 65 * 66 * @license MIT 67 */function Uh(){return Uh=Object.assign?Object.assign.bind():function(e){for(var n=1;n<arguments.length;n++){var r=arguments[n];
67for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])}return e},Uh.apply(this,arguments)}function c4(e,n){if(e==null)return{};var r={},s=Object.keys(e),i,o;for(o=0;o<s.length;o++)i=s[o],!(n.indexOf(i)>=0)&&(r[i]=e[i]);return r}function xz(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function yz(e,n){return e.button===0&&(!n||n==="_self")&&!xz(e)}function ry(e){return e===void 0&&(e=""),new URLSearchParams(typeof e=="string"||Array.isArray(e)||e instanceof URLSearchParams?e:Object.keys(e).reduce((n,r)=>{let s=e[r];return n.concat(Array.isArray(s)?s.map(i=>[r,i]):[[r,s]])},[]))}function bz(e,n){let r=ry(e);return n&&n.forEach((s,i)=>{r.has(i)||n.getAll(i).forEach(o=>{r.append(i,o)})}),r}const Az=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","viewTransition"],vz=["aria-current","caseSensitive","className","end","style","to","viewTransition","children"],_z="6";try{window.__reactRouterVersion=_z}catch{}const jz=g.createContext({isTransitioning:!1}),wz="startTransition",P1=D5[wz];function Sz(e){let{basename:n,children:r,future:s,window:i}=e,o=g.useRef();o.current==null&&(o.current=TT({window:i,v5Compat:!0}));let a=o.current,[l,d]=g.useState({action:a.action,location:a.location}),{v7_startTransition:c}=s||{},f=g.useCallback(p=>{c&&P1?P1(()=>d(p)):d(p)},[d,c]);return g.useLayoutEffect(()=>a.listen(f),[a,f]),g.useEffect(()=>gz(s),[s]),g.createElement(mz,{basename:n,children:r,location:l.location,navigationType:l.action,navigator:a,future:s})}const kz=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",Cz=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,Kb=g.forwardRef(function(n,r){let{onClick:s,relative:i,reloadDocument:o,replace:a,state:l,target:d,to:c,preventScrollReset:f,viewTransition:p}=n,u=c4(n,Az),{basename:h}=g.useContext(ai),y,m=!1;if(typeof c=="string"&&Cz.test(c)&&(y=c,kz))try{let x=new URL(window.location.href),_=c.startsWith("//")?new URL(x.protocol+c):new URL(c),j=Yl(_.pathname,h);_.origin===x.origin&&j!=null?c=j+_.search+_.hash:m=!0}catch{}let b=ez(c,{relative:i}),A=Nz(c,{replace:a,state:l,target:d,preventScrollReset:f,relative:i,viewTransition:p});function v(x){s&&s(x),x.defaultPrevented||A(x)}return g.createElement("a",Uh({},u,{href:y||b,onClick:m||o?s:v,ref:r,target:d}))}),Tz=g.forwardRef(function(n,r){let{"aria-current":s="page",caseSensitive:i=!1,className:o="",end:a=!1,style:l,to:d,viewTransition:c,children:f}=n,p=c4(n,vz),u=Of(d,{relative:p.relative}),h=ja(),y=g.useContext(r4),{navigator:m,basename:b}=g.useContext(ai),A=y!=null&&Rz(u)&&c===!0,v=m.encodeLocation?m.encodeLocation(u).pathname:u.pathname,x=h.pathname,_=y&&y.navigation&&y.navigation.location?y.navigation.location.pathname:null;i||(x=x.toLowerCase(),_=_?_.toLowerCase():null,v=v.toLowerCase()),_&&b&&(_=Yl(_,b)||_);const j=v!=="/"&&v.endsWith("/")?v.length-1:v.length;let C=x===v||!a&&x.startsWith(v)&&x.charAt(j)==="/",S=_!=null&&(_===v||!a&&_.startsWith(v)&&_.charAt(v.length)==="/"),T={isActive:C,isPending:S,isTransitioning:A},L=C?s:void 0,E;typeof o=="function"?E=o(T):E=[o,C?"active":null,S?"pending":null,A?"transitioning":null].filter(Boolean).join(" ");let R=typeof l=="function"?l(T):l;return g.createElement(Kb,Uh({},p,{"aria-current":L,className:E,ref:r,style:R,to:d,viewTransition:c}),typeof f=="function"?f(T):f)});var sy;(function(e){e.UseScrollRestoration="useScrollRestoration",e.UseSubmit="useSubmit",e.UseSubmitFetcher="useSubmitFetcher",e.UseFetcher="useFetcher",e.useViewTransitionState="useViewTransitionState"})(sy||(sy={}));var q1;(function(e){e.UseFetcher="useFetcher",e.UseFetchers="useFetchers",e.UseScrollRestoration="useScrollRestoration"})(q1||(q1={}));function zz(e){let n=g.useContext(qf);return n||It(!1),n}function Nz(e,n){let{target:r,replace:s,state:i,preventScrollReset:o,relative:a,viewTransition:l}=n===void 0?{}:n,d=gt(),c=ja(),f=Of(e,{relative:a});return g.useCallback(p=>{if(yz(p,r)){p.preventDefault();let u=s!==void 0?s:Bh(c)===Bh(f);d(e,{replace:u,state:i,preventScrollReset:o,relative:a,viewTransition:l})}},[c,d,f,s,i,r,e,o,a,l])}function If(e){let n=g.useRef(ry(e)),r=g.useRef(!1),s=ja(),i=g.useMemo(()=>bz(s.search,r.current?null:n.current),[s.search]),o=gt(),a=g.useCallback((l,d)=>{const c=ry(typeof l=="function"?l(i):l);r.current=!0,o("?"+c,d)},[o,i]);return[i,a]}function Rz(e,n){n===void 0&&(n={});let r=g.useContext(jz);r==null&&It(!1);let{basename:s}=zz(sy.useViewTransitionState),i=Of(e,{relative:n.relative});if(!r.isTransitioning)return!1;let o=Yl(r.currentLocation.pathname,s)||r.currentLocation.pathname,a=Yl(r.nextLocation.pathname,s)||r.nextLocation.pathname;return ty(i.pathname,a)!=null||ty(i.pathname,o)!=null}function Lf(e,n){var r={};for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&n.indexOf(s)<0&&(r[s]=e[s]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,s=Object.getOwnPropertySymbols(e);i<s.length;i++)n.indexOf(s[i])<0&&Object.prototype.propertyIsEnumerable.call(e,s[i])&&(r[s[i]]=e[s[i]]);return r}function Ez(e,n,r,s){function i(o){return o instanceof r?o:new r(function(a){a(o)})}return new(r||(r=Promise))(function(o,a){function l(f){try{c(s.next(f))}catch(p){a(p)}}function d(f){try{c(s.throw(f))}catch(p){a(p)}}function c(f){f.done?o(f.value):i(f.value).then(l,d)}c((s=s.apply(e,n||[])).next())})}const Pz=e=>e?(...n)=>e(...n):(...n)=>fetch(...n);
67class Yb extends Error{constructor(n,r="FunctionsError",s){super(n),this.name=r,this.context=s}}class qz extends Yb{constructor(n){super("Failed to send a request to the Edge Function","FunctionsFetchError",n)}}class D1 extends Yb{constructor(n){super("Relay Error invoking the Edge Function","FunctionsRelayError",n)}}class O1 extends Yb{constructor(n){super("Edge Function returned a non-2xx status code","FunctionsHttpError",n)}}var iy;(function(e){e.Any="any",e.ApNortheast1="ap-northeast-1",e.ApNortheast2="ap-northeast-2",e.ApSouth1="ap-south-1",e.ApSoutheast1="ap-southeast-1",e.ApSoutheast2="ap-southeast-2",e.CaCentral1="ca-central-1",e.EuCentral1="eu-central-1",e.EuWest1="eu-west-1",e.EuWest2="eu-west-2",e.EuWest3="eu-west-3",e.SaEast1="sa-east-1",e.UsEast1="us-east-1",e.UsWest1="us-west-1",e.UsWest2="us-west-2"})(iy||(iy={}));class Dz{constructor(n,{headers:r={},customFetch:s,region:i=iy.Any}={}){this.url=n,this.headers=r,this.region=i,this.fetch=Pz(s)}setAuth(n){this.headers.Authorization=`Bearer ${n}`}invoke(n){return Ez(this,arguments,void 0,function*(r,s={}){var i;let o,a;try{const{headers:l,method:d,body:c,signal:f,timeout:p}=s;let u={},{region:h}=s;h||(h=this.region);const y=new URL(`${this.url}/${r}`);h&&h!=="any"&&(u["x-region"]=h,y.searchParams.set("forceFunctionRegion",h));let m;c&&(l&&!Object.prototype.hasOwnProperty.call(l,"Content-Type")||!l)?typeof Blob<"u"&&c instanceof Blob||c instanceof ArrayBuffer?(u["Content-Type"]="application/octet-stream",m=c):typeof c=="string"?(u["Content-Type"]="text/plain",m=c):typeof FormData<"u"&&c instanceof FormData?m=c:(u["Content-Type"]="application/json",m=JSON.stringify(c)):c&&typeof c!="string"&&!(typeof Blob<"u"&&c instanceof Blob)&&!(c instanceof ArrayBuffer)&&!(typeof FormData<"u"&&c instanceof FormData)?m=JSON.stringify(c):m=c;let b=f;p&&(a=new AbortController,o=setTimeout(()=>a.abort(),p),f?(b=a.signal,f.addEventListener("abort",()=>a.abort())):b=a.signal);const A=yield this.fetch(y.toString(),{method:d||"POST",headers:Object.assign(Object.assign(Object.assign({},u),this.headers),l),body:m,signal:b}).catch(j=>{throw new qz(j)}),v=A.headers.get("x-relay-error");if(v&&v==="true")throw new D1(A);if(!A.ok)throw new O1(A);let x=((i=A.headers.get("Content-Type"))!==null&&i!==void 0?i:"text/plain").split(";")[0].trim(),_;return x==="application/json"?_=yield A.json():x==="application/octet-stream"||x==="application/pdf"?_=yield A.blob():x==="text/event-stream"?_=A:x==="multipart/form-data"?_=yield A.formData():_=yield A.text(),{data:_,error:null,response:A}}catch(l){return{data:null,error:l,response:l instanceof O1||l instanceof D1?l.context:void 0}}finally{o&&clearTimeout(o)}})}}var Oz=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.co
67de=e.code}},Iz=class{constructor(e){var n,r,s;this.shouldThrowOnError=!1,this.method=e.method,this.url=e.url,this.headers=new Headers(e.headers),this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=(n=e.shouldThrowOnError)!==null&&n!==void 0?n:!1,this.signal=e.signal,this.isMaybeSingle=(r=e.isMaybeSingle)!==null&&r!==void 0?r:!1,this.urlLengthLimit=(s=e.urlLengthLimit)!==null&&s!==void 0?s:8e3,e.fetch?this.fetch=e.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(e,n){return this.headers=new Headers(this.headers),this.headers.set(e,n),this}then(e,n){var r=this;this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),this.method!=="GET"&&this.method!=="HEAD"&&this.headers.set("Content-Type","application/json");const s=this.fetch;let i=s(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async o=>{let a=null,l=null,d=null,c=o.status,f=o.statusText;if(o.ok){var p,u;if(r.method!=="HEAD"){var h;const b=await o.text();b===""||(r.headers.get("Accept")==="text/csv"||r.headers.get("Accept")&&(!((h=r.headers.get("Accept"))===null||h===void 0)&&h.includes("application/vnd.pgrst.plan+text"))?l=b:l=JSON.parse(b))}const y=(p=r.headers.get("Prefer"))===null||p===void 0?void 0:p.match(/count=(exact|planned|estimated)/),m=(u=o.headers.get("content-range"))===null||u===void 0?void 0:u.split("/");y&&m&&m.length>1&&(d=parseInt(m[1])),r.isMaybeSingle&&Array.isArray(l)&&(l.length>1?(a={code:"PGRST116",details:`Results contain ${l.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},l=null,d=null,c=406,f="Not Acceptable"):l.length===1?l=l[0]:l=null)}else{const y=await o.text();try{a=JSON.parse(y),Array.isArray(a)&&o.status===404&&(l=[],a=null,c=200,f="OK")}catch{o.status===404&&y===""?(c=204,f="No Content"):a={message:y}}if(a&&r.shouldThrowOnError)throw new Oz(a)}return{error:a,data:l,count:d,status:c,statusText:f}});return this.shouldThrowOnError||(i=i.catch(o=>{var a;let l="",d="",c="";const f=o==null?void 0:o.cause;if(f){var p,u,h,y;const A=(p=f==null?void 0:f.message)!==null&&p!==void 0?p:"",v=(u=f==null?void 0:f.code)!==null&&u!==void 0?u:"";l=`${(h=o==null?void 0:o.name)!==null&&h!==void 0?h:"FetchError"}: ${o==null?void 0:o.message}`,l+=` 68 69Caused by: ${(y=f==null?void 0:f.name)!==null&&y!==void 0?y:"Error"}: ${A}`,v&&(l+=` (${v})`),f!=null&&f.stack&&(l+=` 70${f.stack}`)}else{var m;l=(m=o==null?void 0:o.stack)!==null&&m!==void 0?m:""}const b=this.url.toString().length;return(o==null?void 0:o.name)==="AbortError"||(o==null?void 0:o.code)==="ABORT_ERR"?(c="",d="Request was aborted (timeout or manual cancellation)",b>this.urlLengthLimit&&(d+=`. Note: Your request URL is ${b} characters, which may exceed server limits. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [many IDs])), consider using an RPC function to pass values server-side.`)):((f==null?void 0:f.name)==="HeadersOverflowError"||(f==null?void 0:f.code)==="UND_ERR_HEADERS_OVERFLOW")&&(c="",d="HTTP headers exceeded server limits (typically 16KB)",b>this.urlLengthLimit&&(d+=`. Your request URL is ${b} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`)),{error:{message:`${(a=o==null?void 0:o.name)!==null&&a!==void 0?a:"FetchError"}: ${o==null?void 0:o.message}`,details:l,hint:d,code:c},data:null,count:null,status:0,statusText:""}})),i.then(e,n)}returns(){return this}overrideTypes(){return this}},Lz=class extends Iz{select(e){let n=!1;const r=(e??"*").split("").map(s=>/\s/.test(s)&&!n?"":(s==='"'&&(n=!n),s)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(e,{ascending:n=!0,nullsFirst:r,foreignTable:s,referencedTable:i=s}={}){const o=i?`${i}.order`:"order",a=this.url.searchParams.get(o);return this.url.searchParams.set(o,`${a?`${a},`:""}${e}.${n?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:n,referencedTable:r=n}={}){const s=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(s,`${e}`),this}range(e,n,{foreignTable:r,referencedTable:s=r}={}){const i=typeof s>"u"?"offset":`${s}.offset`,o=typeof s>"u"?"limit":`${s}.limit`;return this.url.searchParams.set(i,`${e}`),this.url.searchParams.set(o,`${n-e+1}`),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}
70explain({analyze:e=!1,verbose:n=!1,settings:r=!1,buffers:s=!1,wal:i=!1,format:o="text"}={}){var a;const l=[e?"analyze":null,n?"verbose":null,r?"settings":null,s?"buffers":null,i?"wal":null].filter(Boolean).join("|"),d=(a=this.headers.get("Accept"))!==null&&a!==void 0?a:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${o}; for="${d}"; options=${l};`),o==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(e){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${e}`),this}};const I1=new RegExp("[,()]");var Za=class extends Lz{eq(e,n){return this.url.searchParams.append(e,`eq.${n}`),this}neq(e,n){return this.url.searchParams.append(e,`neq.${n}`),this}gt(e,n){return this.url.searchParams.append(e,`gt.${n}`),this}gte(e,n){return this.url.searchParams.append(e,`gte.${n}`),this}lt(e,n){return this.url.searchParams.append(e,`lt.${n}`),this}lte(e,n){return this.url.searchParams.append(e,`lte.${n}`),this}like(e,n){return this.url.searchParams.append(e,`like.${n}`),this}likeAllOf(e,n){return this.url.searchParams.append(e,`like(all).{${n.join(",")}}`),this}likeAnyOf(e,n){return this.url.searchParams.append(e,`like(any).{${n.join(",")}}`),this}ilike(e,n){return this.url.searchParams.append(e,`ilike.${n}`),this}ilikeAllOf(e,n){return this.url.searchParams.append(e,`ilike(all).{${n.join(",")}}`),this}ilikeAnyOf(e,n){return this.url.searchParams.append(e,`ilike(any).{${n.join(",")}}`),this}regexMatch(e,n){return this.url.searchParams.append(e,`match.${n}`),this}regexIMatch(e,n){return this.url.searchParams.append(e,`imatch.${n}`),this}is(e,n){return this.url.searchParams.append(e,`is.${n}`),this}isDistinct(e,n){return this.url.searchParams.append(e,`isdistinct.${n}`),this}in(e,n){const r=Array.from(new Set(n)).map(s=>typeof s=="string"&&I1.test(s)?`"${s}"`:`${s}`).join(",");return this.url.searchParams.append(e,`in.(${r})`),this}notIn(e,n){const r=Array.from(new Set(n)).map(s=>typeof s=="string"&&I1.test(s)?`"${s}"`:`${s}`).join(",");return this.url.searchParams.append(e,`not.in.(${r})`),this}contains(e,n){return typeof n=="string"?this.url.searchParams.append(e,`cs.${n}`):Array.isArray(n)?this.url.searchParams.append(e,`cs.{${n.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(n)}`),this}containedBy(e,n){return typeof n=="string"?this.url.searchParams.append(e,`cd.${n}`):Array.isArray(n)?this.url.searchParams.append(e,`cd.{${n.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(n)}`),this}rangeGt(e,n){return this.url.searchParams.append(e,`sr.${n}`),this}rangeGte(e,n){return this.url.searchParams.append(e,`nxl.${n}`),this}rangeLt(e,n){return this.url.searchParams.append(e,`sl.${n}`),this}rangeLte(e,n){return this.url.searchParams.append(e,`nxr.${n}`),this}rangeAdjacent(e,n){return this.url.searchParams.append(e,`adj.${n}`),this}overlaps(e,n){return typeof n=="string"?this.url.searchParams.append(e,`ov.${n}`):this.url.searchParams.append(e,`ov.{${n.join(",")}}`),this}textSearch(e,n,{config:r,type:s}={}){let i="";s==="plain"?i="pl":s==="phrase"?i="ph":s==="websearch"&&(i="w");const o=r===void 0?"":`(${r})`;return this.url.searchParams.append(e,`${i}fts${o}.${n}`),this}match(e){return Object.entries(e).filter(([n,r])=>r!==void 0).forEach(([n,r])=>{this.url.searchParams.append(n,`eq.${r}`)}),this}not(e,n,r){return this.url.searchParams.append(e,`not.${n}.${r}`),this}or(e,{foreignTable:n,referencedTable:r=n}={}){const s=r?`${r}.or`:"or";return this.url.searchParams.append(s,`(${e})`),this}filter(e,n,r){return this.url.searchParams.append(e,`${n}.${r}`),this}},Wz=class{constructor(e,{headers:n={},schema:r,fetch:s,urlLengthLimit:i=8e3}){this.url=e,this.headers=new Headers(n),this.schema=r,this.fetch=s,this.urlLengthLimit=i}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(e,n){const{head:r=!1,count:s}=n??{},i=r?"HEAD":"GET";let o=!1;const a=(e??"*").split("").map(c=>/\s/.test(c)&&!o?"":(c==='"'&&(o=!o),c)).join(""),{url:l,headers:d}=this.cloneRequestState();return l.searchParams.set("select",a),s&&d.append("Prefer",`count=${s}`),new Za({method:i,url:l,headers:d,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}insert(e,{count:n,defaultToNull:r=!0}={}){var s;const i="POST",{url:o,headers:a}=this.cloneRequestState();if(n&&a.append("Prefer",`count=${n}`),r||a.append("Prefer","missing=default"),Array.isArray(e)){const l=e.reduce((d,c)=>d.concat(Object.keys(c)),[]);if(l.length>0){const d=[...new Set(l)].map(c=>`"${c}"`);o.searchParams.set("columns",d.join(","))}}return new Za({method:i,url:o,headers:a,schema:this.schema,body:e,fetch:(s=this.fetch)!==null&&s!==void 0?s:fetch,urlLengthLimit:this.urlLengthLimit})}upsert(e,{onConflict:n,ignoreDuplicates:r=!1,count:s,defaultToNull:i=!0}={}){var o;const a="POST",{url:l,headers:d}=this.cloneRequestState();if(d.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),n!==void 0&&l.searchParams.set("on_conflict",n),s&&d.append("Prefer",`count=${s}`),i||d.append("Prefer","missing=default"),Array.isArray(e)){const c=e.reduce((f,p)=>f.concat(Object.keys(p)),[]);if(c.length>0){const f=[...new Set(c)].map(p=>`"${p}"`);l.searchParams.set("columns",f.join(","))}}return new Za({method:a,url:l,headers:d,schema:this.schema,body:e,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch,urlLengthLimit:this.urlLengthLimit})}update(e,{count:n}={}){var r;const s="PATCH",{url:i,headers:o}=this.cloneRequestState();return n&&o.append("Prefer",`count=${n}`),new Za({method:s,url:i,headers:o,schema:this.schema,body:e,fetch:(r=this.fetch)!==null&&r!==void 0?r:fetch,urlLengthLimit:this.urlLengthLimit})}delete({count:e}={}){var n;const r="DELETE",{url:s,headers:i}=this.cloneRequestState();return e&&i.append("Prefer",`count=${e}`),new Za({method:r,url:s,headers:i,schema:this.schema,fetch:(n=this.fetch)!==null&&n!==void 0?n:fetch,urlLengthLimit:this.urlLengthLimit})}};function Bc(e){"@babel/helpers - typeof";return Bc=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(n){return typeof n}:function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},Bc(e)}function $z(e,n){if(Bc(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var s=r.call(e,n);if(Bc(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(n==="string"?String:Number)(e)}function Mz(e){var n=$z(e,"string");return Bc(n)=="symbol"?n:n+""}function Fz(e,n,r){return(n=Mz(n))in e?Object.defineProperty(e,n,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[n]=r,e}function L1(e,n){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);n&&(s=s.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,s)}return r}function Yu(e){for(var n=1;n<arguments.length;n++){var r=arguments[n]!=null?arguments[n]:{};
70n%2?L1(Object(r),!0).forEach(function(s){Fz(e,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):L1(Object(r)).forEach(function(s){Object.defineProperty(e,s,Object.getOwnPropertyDescriptor(r,s))})}return e}var Bz=class u4{constructor(n,{headers:r={},schema:s,fetch:i,timeout:o,urlLengthLimit:a=8e3}={}){this.url=n,this.headers=new Headers(r),this.schemaName=s,this.urlLengthLimit=a;const l=i??globalThis.fetch;o!==void 0&&o>0?this.fetch=(d,c)=>{const f=new AbortController,p=setTimeout(()=>f.abort(),o),u=c==null?void 0:c.signal;if(u){if(u.aborted)return clearTimeout(p),l(d,c);const h=()=>{clearTimeout(p),f.abort()};return u.addEventListener("abort",h,{once:!0}),l(d,Yu(Yu({},c),{},{signal:f.signal})).finally(()=>{clearTimeout(p),u.removeEventListener("abort",h)})}return l(d,Yu(Yu({},c),{},{signal:f.signal})).finally(()=>clearTimeout(p))}:this.fetch=l}from(n){if(!n||typeof n!="string"||n.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new Wz(new URL(`${this.url}/${n}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(n){return new u4(this.url,{headers:this.headers,schema:n,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}rpc(n,r={},{head:s=!1,get:i=!1,count:o}={}){var a;let l;const d=new URL(`${this.url}/rpc/${n}`);let c;const f=h=>h!==null&&typeof h=="object"&&(!Array.isArray(h)||h.some(f)),p=s&&Object.values(r).some(f);p?(l="POST",c=r):s||i?(l=s?"HEAD":"GET",Object.entries(r).filter(([h,y])=>y!==void 0).map(([h,y])=>[h,Array.isArray(y)?`{${y.join(",")}}`:`${y}`]).forEach(([h,y])=>{d.searchParams.append(h,y)})):(l="POST",c=r);const u=new Headers(this.headers);return p?u.set("Prefer",o?`count=${o},return=minimal`:"return=minimal"):o&&u.set("Prefer",`count=${o}`),new Za({method:l,url:d,headers:u,schema:this.schemaName,body:c,fetch:(a=this.fetch)!==null&&a!==void 0?a:fetch,urlLengthLimit:this.urlLengthLimit})}};class Uz{constructor(){}static detectEnvironment(){var n;if(typeof WebSocket<"u")return{type:"native",constructor:WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocket<"u")return{type:"native",constructor:globalThis.WebSocket};if(typeof global<"u"&&typeof global.WebSocket<"u")return{type:"native",constructor:global.WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocketPair<"u"&&typeof globalThis.WebSocket>"u")return{type:"cloudflare",error:"Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.",workaround:"Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime."};if(typeof globalThis<"u"&&globalThis.EdgeRuntime||typeof navigator<"u"&&(!((n=navigator.userAgent)===null||n===void 0)&&n.includes("Vercel-Edge")))return{type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};const r=globalThis.process;if(r){const s=r.versions;if(s&&s.node){const i=s.node,o=parseInt(i.replace(/^v/,"").split(".")[0]);return o>=22?typeof globalThis.WebSocket<"u"?{type:"native",constructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${o} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${o} detected without native WebSocket support.`,workaround:`For Node.js < 22, install "ws" package and provide it via the transport option: 71import ws from "ws" 72new RealtimeClient(url, { transport: ws })`}}}return{type:"unsupported",error:"Unknown JavaScript runtime without WebSocket support.",workaround:"Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation."}}static getWebSocketConstructor(){const n=this.detectEnvironment();if(n.constructor)return n.constructor;let r=n.error||"WebSocket not supported in this environment.";throw n.workaround&&(r+=` 73 74Suggested solution: ${n.workaround}`),new Error(r)}static isWebSocketSupported(){try{const n=this.detectEnvironment();return n.type==="native"||n.type==="ws"}catch{return!1}}}const Hz="2.100.1",Vz=`realtime-js/${Hz}`,Zz="1.0.0",p4="2.0.0",Kz=p4,Yz=1e4,Xz=100,Ni={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},h4={close:"phx_close",error:"phx_error",join:"phx_join",leave:"phx_leave",access_token:"access_token"},oy={connecting:"connecting",closing:"closing",closed:"closed"};class Gz{constructor(n){this.HEADER_LENGTH=1,this.USER_BROADCAST_PUSH_META_LENGTH=6,this.KINDS={userBroadcastPush:3,userBroadcast:4},this.BINARY_ENCODING=0,this.JSON_ENCODING=1,this.BROADCAST_EVENT="broadcast",this.allowedMetadataKeys=[],this.allowedMetadataKeys=n??[]}encode(n,r){if(n.event===this.BROADCAST_EVENT&&!(n.payload instanceof ArrayBuffer)&&typeof n.payload.event=="string")return r(this._binaryEncodeUserBroadcastPush(n));let s=[n.join_ref,n.ref,n.topic,n.event,n.payload];return r(JSON.stringify(s))}_binaryEncodeUserBroadcastPush(n){var r;return this._isArrayBuffer((r=n.payload)===null||r===void 0?void 0:r.payload)?this._encodeBinaryUserBroadcastPush(n):this._encodeJsonUserBroadcastPush(n)}_encodeBinaryUserBroadcastPush(n){var r,s;const i=(s=(r=n.payload)===null||r===void 0?void 0:r.payload)!==null&&s!==void 0?s:new ArrayBuffer(0);return this._encodeUserBroadcastPush(n,this.BINARY_ENCODING,i)}_encodeJsonUserBroadcastPush(n){var r,s;const i=(s=(r=n.payload)===null||r===void 0?void 0:r.payload)!==null&&s!==void 0?s:{},a=new TextEncoder().encode(JSON.stringify(i)).buffer;return this._encodeUserBroadcastPush(n,this.JSON_ENCODING,a)}_encodeUserBroadcastPush(n,r,s){var i,o;const a=n.topic,l=(i=n.ref)!==null&&i!==void 0?i:"",d=(o=n.join_ref)!==null&&o!==void 0?o:"",c=n.payload.event,f=this.allowedMetadataKeys?this._pick(n.payload,this.allowedMetadataKeys):{},p=Object.keys(f).length===0?"":JSON.stringify(f);
74if(d.length>255)throw new Error(`joinRef length ${d.length} exceeds maximum of 255`);if(l.length>255)throw new Error(`ref length ${l.length} exceeds maximum of 255`);if(a.length>255)throw new Error(`topic length ${a.length} exceeds maximum of 255`);if(c.length>255)throw new Error(`userEvent length ${c.length} exceeds maximum of 255`);if(p.length>255)throw new Error(`metadata length ${p.length} exceeds maximum of 255`);const u=this.USER_BROADCAST_PUSH_META_LENGTH+d.length+l.length+a.length+c.length+p.length,h=new ArrayBuffer(this.HEADER_LENGTH+u);let y=new DataView(h),m=0;y.setUint8(m++,this.KINDS.userBroadcastPush),y.setUint8(m++,d.length),y.setUint8(m++,l.length),y.setUint8(m++,a.length),y.setUint8(m++,c.length),y.setUint8(m++,p.length),y.setUint8(m++,r),Array.from(d,A=>y.setUint8(m++,A.charCodeAt(0))),Array.from(l,A=>y.setUint8(m++,A.charCodeAt(0))),Array.from(a,A=>y.setUint8(m++,A.charCodeAt(0))),Array.from(c,A=>y.setUint8(m++,A.charCodeAt(0))),Array.from(p,A=>y.setUint8(m++,A.charCodeAt(0)));var b=new Uint8Array(h.byteLength+s.byteLength);return b.set(new Uint8Array(h),0),b.set(new Uint8Array(s),h.byteLength),b.buffer}decode(n,r){if(this._isArrayBuffer(n)){let s=this._binaryDecode(n);return r(s)}if(typeof n=="string"){const s=JSON.parse(n),[i,o,a,l,d]=s;return r({join_ref:i,ref:o,topic:a,event:l,payload:d})}return r({})}_binaryDecode(n){const r=new DataView(n),s=r.getUint8(0),i=new TextDecoder;switch(s){case this.KINDS.userBroadcast:return this._decodeUserBroadcast(n,r,i)}}_decodeUserBroadcast(n,r,s){const i=r.getUint8(1),o=r.getUint8(2),a=r.getUint8(3),l=r.getUint8(4);let d=this.HEADER_LENGTH+4;const c=s.decode(n.slice(d,d+i));d=d+i;const f=s.decode(n.slice(d,d+o));d=d+o;const p=s.decode(n.slice(d,d+a));d=d+a;const u=n.slice(d,n.byteLength),h=l===this.JSON_ENCODING?JSON.parse(s.decode(u)):u,y={type:this.BROADCAST_EVENT,event:f,payload:h};return a>0&&(y.meta=JSON.parse(p)),{join_ref:null,ref:null,topic:c,event:this.BROADCAST_EVENT,payload:y}}_isArrayBuffer(n){var r;return n instanceof ArrayBuffer||((r=n==null?void 0:n.constructor)===null||r===void 0?void 0:r.name)==="ArrayBuffer"}_pick(n,r){return!n||typeof n!="object"?{}:Object.fromEntries(Object.entries(n).filter(([s])=>r.includes(s)))}}var _t;(function(e){e.abstime="abstime",e.bool="bool",e.date="date",e.daterange="daterange",e.float4="float4",e.float8="float8",e.int2="int2",e.int4="int4",e.int4range="int4range",e.int8="int8",e.int8range="int8range",e.json="json",e.jsonb="jsonb",e.money="money",e.numeric="numeric",e.oid="oid",e.reltime="reltime",e.text="text",e.time="time",e.timestamp="timestamp",e.timestamptz="timestamptz",e.timetz="timetz",e.tsrange="tsrange",e.tstzrange="tstzrange"})(_t||(_t={}));const W1=(e,n,r={})=>{var s;const i=(s=r.skipTypes)!==null&&s!==void 0?s:[];return n?Object.keys(n).reduce((o,a)=>(o[a]=Jz(a,e,n,i),o),{}):{}},Jz=(e,n,r,s)=>{const i=n.find(l=>l.name===e),o=i==null?void 0:i.type,a=r[e];return o&&!s.includes(o)?f4(o,a):ay(a)},f4=(e,n)=>{if(e.charAt(0)==="_"){const r=e.slice(1,e.length);return nN(n,r)}switch(e){case _t.bool:return Qz(n);case _t.float4:case _t.float8:case _t.int2:case _t.int4:case _t.int8:case _t.numeric:case _t.oid:return eN(n);case _t.json:case _t.jsonb:return tN(n);case _t.timestamp:return rN(n);case _t.abstime:case _t.date:case _t.daterange:case _t.int4range:case _t.int8range:case _t.money:case _t.reltime:case _t.text:case _t.time:case _t.timestamptz:case _t.timetz:case _t.tsrange:case _t.tstzrange:return ay(n);default:return ay(n)}},ay=e=>e,Qz=e=>{switch(e){case"t":return!0;case"f":return!1;default:return e}},eN=e=>{if(typeof e=="string"){const n=parseFloat(e);if(!Number.isNaN(n))return n}return e},tN=e=>{if(typeof e=="string")try{return JSON.parse(e)}catch{return e}return e},nN=(e,n)=>{if(typeof e!="string")return e;const r=e.length-1,s=e[r];if(e[0]==="{"&&s==="}"){let o;const a=e.slice(1,r);try{o=JSON.parse("["+a+"]")}catch{o=a?a.split(","):[]}return o.map(l=>f4(n,l))}return e},rN=e=>typeof e=="string"?e.replace(" ","T"):e,g4=e=>{const n=new URL(e);return n.protocol=n.protocol.replace(/^ws/i,"http"),n.pathname=n.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),n.pathname===""||n.pathname==="/"?n.pathname="/api/broadcast":n.pathname=n.pathname+"/api/broadcast",n.href};var xc=e=>typeof e=="function"?e:function(){return e},sN=typeof self<"u"?self:null,Ka=typeof window<"u"?window:null,gs=sN||Ka||globalThis,iN="2.0.0",oN=1e4,aN=1e3,bs={connecting:0,open:1,closing:2,closed:3},Zn={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},qs={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave"},ly={longpoll:"longpoll",websocket:"websocket"},lN={complete:4},dy="base64url.bearer.phx.",Xu=class{constructor(e,n,r,s){this.channel=e,this.event=n,this.payload=r||function(){return{}},this.receivedResp=null,this.timeout=s,this.timeoutTimer=null,this.recHo
vendor: 21,658 bytes, lines 74-75
74oks=[],this.sent=!1,this.ref=void 0}resend(e){this.timeout=e,this.reset(),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()}))}receive(e,n){return this.hasReceived(e)&&n(this.receivedResp.response),this.recHooks.push({status:e,callback:n}),this}reset(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=!1}destroy(){this.cancelRefEvent(),this.cancelTimeout()}matchReceive({status:e,response:n,_ref:r}){this.recHooks.filter(s=>s.status===e).forEach(s=>s.callback(n))}cancelRefEvent(){this.refEvent&&this.channel.off(this.refEvent)}cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=null}startTimeout(){this.timeoutTimer&&this.cancelTimeout(),this.ref=this.channel.socket.makeRef(),this.refEvent=this.channel.replyEventName(this.ref),this.channel.on(this.refEvent,e=>{this.cancelRefEvent(),this.cancelTimeout(),this.receivedResp=e,this.matchReceive(e)}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}trigger(e,n){this.channel.trigger(this.refEvent,{status:e,response:n})}},m4=class{constructor(e,n){this.callback=e,this.timerCalc=n,this.timer=void 0,this.tries=0}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))}},dN=class{constructor(e,n,r){this.state=Zn.closed,this.topic=e,this.params=xc(n||{}),this.socket=r,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new Xu(this,qs.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new m4(()=>{this.socket.isConnected()&&this.rejoin()},this.socket.rejoinAfterMs),this.stateChangeRefs.push(this.socket.onError(()=>this.rejoinTimer.reset())),this.stateChangeRefs.push(this.socket.onOpen(()=>{this.rejoinTimer.reset(),this.isErrored()&&this.rejoin()})),this.joinPush.receive("ok",()=>{this.state=Zn.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(s=>s.send()),this.pushBuffer=[]}),this.joinPush.receive("error",s=>{this.state=Zn.errored,this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,s),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.onClose(()=>{this.rejoinTimer.reset(),this.socket.hasLogger()&&this.socket.log("channel",`close ${this.topic}`),this.state=Zn.closed,this.socket.remove(this)}),this.onError(s=>{this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,s),this.isJoining()&&this.joinPush.reset(),this.state=Zn.errored,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.joinPush.receive("timeout",()=>{this.socket.hasLogger()&&this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),new Xu(this,qs.leave,xc({}),this.timeout).send(),this.state=Zn.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.on(qs.reply,(s,i)=>{this.trigger(this.replyEventName(i),s)})}join(e=this.timeout){if(this.joinedOnce)throw new Error("tried to join multiple times. 'join' can only be called a single time per channel instance");return this.timeout=e,this.joinedOnce=!0,this.rejoin(),this.joinPush}teardown(){this.pushBuffer.forEach(e=>e.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=Zn.closed,this.bindings=[]}onClose(e){this.on(qs.close,e)}onError(e){return this.on(qs.error,n=>e(n))}on(e,n){let r=this.bindingRef++;return this.bindings.push({event:e,ref:r,callback:n}),r}off(e,n){this.bindings=this.bindings.filter(r=>!(r.event===e&&(typeof n>"u"||n===r.ref)))}canPush(){return this.socket.isConnected()&&this.isJoined()}push(e,n,r=this.timeout){if(n=n||{},!this.joinedOnce)throw new Error(`tried to push '${e}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let s=new Xu(this,e,function(){return n},r);return this.canPush()?s.send():(s.startTimeout(),this.pushBuffer.push(s)),s}leave(e=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=Zn.leaving;let n=()=>{this.socket.hasLogger()&&this.socket.log("channel",`leave ${this.topic}`),this.trigger(qs.close,"leave")},r=new Xu(this,qs.leave,xc({}),e);return r.receive("ok",()=>n()).receive("timeout",()=>n()),r.send(),this.canPush()||r.trigger("ok",{}),r}onMessage(e,n,r){return n}filterBindings(e,n,r){return!0}isMember(e,n,r,s){return this.topic!==e?!1:s&&s!==this.joinRef()?(this.socket.hasLogger()&&this.socket.log("channel","dropping outdated message",{topic:e,event:n,payload:r,joinRef:s}),!1):!0}joinRef(){return this.joinPush.ref}rejoin(e=this.timeout){this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=Zn.joining,this.joinPush.resend(e))}trigger(e,n,r,s){let i=this.onMessage(e,n,r,s);if(n&&!i)throw new Error("channel onMessage callbacks must return the payload, modified or unmodified");let o=this.bindings.filter(a=>a.event===e&&this.filterBindings(a,n,r));for(let a=0;a<o.length;a++)o[a].callback(i,r,s||this.joinRef())}replyEventName(e){return`chan_reply_${e}`}isClosed(){return this.state===Zn.closed}isErrored(){return this.state===Zn.errored}isJoined(){return this.state===Zn.joined}isJoining(){return this.state===Zn.joining}isLeaving(){return this.state===Zn.leaving}},Hh=class{static request(e,n,r,s,i,o,a){if(gs.XDomainRequest){let l=new gs.XDomainRequest;return this.xdomainRequest(l,e,n,s,i,o,a)}else if(gs.XMLHttpRequest){let l=new gs.XMLHttpRequest;return this.xhrRequest(l,e,n,r,s,i,o,a)}else{if(gs.fetch&&gs.AbortController)return this.fetchRequest(e,n,r,s,i,o,a);throw new Error("No suitable XMLHttpRequest implementation found")}}static fetchRequest(e,n,r,s,i,o,a){let l={method:e,headers:r,body:s},d=null;return i&&(d=new AbortController,setTimeout(()=>d.abort(),i),l.signal=d.signal),gs.fetch(n,l).then(c=>c.text()).then(c=>this.parseJSON(c)).then(c=>a&&a(c)).catch(c=>{c.name==="AbortError"&&o?o():a&&a(null)}),d}static xdomainRequest(e,n,r,s,i,o,a){return e.timeout=i,e.open(n,r),e.onload=()=>{let l=this.parseJSON(e.responseText);a&&a(l)},o&&(e.ontimeout=o),e.onprogress=()=>{},e.send(s),e}static xhrRequest(e,n,r,s,i,o,a,l){e.open(n,r,!0),e.timeout=o;for(let[d,c]of Object.entries(s))e.setRequestHeader(d,c);return e.onerror=()=>l&&l(null),e.onreadystatechange=()=>{if(e.readyState===lN.complete&&l){let d=this.parseJSON(e.responseText);l(d)}},a&&(e.ontimeout=a),e.send(i),e}static parseJSON(e){if(!e||e==="")return null;try{return JSON.parse(e)}catch{return console&&console.log("failed to parse JSON response",e),null}}static serialize(e,n){let r=[];for(var s in e){if(!Object.prototype.hasOwnProperty.call(e,s))continue;let i=n?`${n}[${s}]`:s,o=e[s];typeof o=="object"?r.push(this.serialize(o,i)):r.push(encodeURIComponent(i)+"="+encodeURIComponent(o))}return r.join("&")}static appendParams(e,n){if(Object.keys(n).length===0)return e;let r=e.match(/\?/)?"&":"?";return`${e}${r}${this.serialize(n)}`}},cN=e=>{let n="",r=new Uint8Array(e),s=r.byteLength;for(let i=0;i<s;i++)n+=String.fromCharCode(r[i]);return btoa(n)},Ra=class{constructor(e,n){n&&n.length===2&&n[1].startsWith(dy)&&(this.authToken=atob(n[1].slice(dy.length))),this.endPoint=null,this.token=null,this.skipHeartbeat=!0,this.reqs=new Set,this.awaitingBatchAck=!1,this.currentBatch=null,this.currentBatchTimer=null,this.batchBuffer=[],this.onopen=function(){},this.onerror=function(){},this.onmessage=function(){},this.onclose=function(){},this.pollEndpoint=this.normalizeEndpoint(e),this.readyState=bs.connecting,setTimeout(()=>this.poll(),0)}normalizeEndpoint(e){return e.replace("ws://","http://").replace("wss://","https://").replace(new RegExp("(.*)/"+ly.websocket),"$1/"+ly.longpoll)}endpointURL(){return Hh.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(e,n,r){this.close(e,n,r),this.readyState=bs.connecting}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return this.readyState===bs.open||this.readyState===bs.connecting}poll(){const e={Accept:"application/json"};this.authToken&&(e["X-Phoenix-AuthToken"]=this.authToken),this.ajax("GET",e,null,()=>this.ontimeout(),n=>{if(n){var{status:r,token:s,messages:i}=n;if(r===410&&this.token!==null){this.onerror(410),this.closeAndRetry(3410,"session_gone",!1);return}this.token=s}else r=0;switch(r){case 200:i.forEach(o=>{setTimeout(()=>this.onmessage({data:o}),0)}),this.poll();break;case 204:this.poll();break;case 410:this.readyState=bs.open,this.onopen({}),this.poll();break;case 403:this.onerror(403),this.close(1008,"forbidden",!1);break;case 0:case 500:this.onerror(500),this.closeAndRetry(1011,"internal server error",500);break;default:throw new Error(`unhandled poll status ${r}`)}})}send(e){typeof e!="string"&&(e=cN(e)),this.currentBatch?this.currentBatch.push(e):this.awaitingBatchAck?this.batchBuffer.push(e):(this.currentBatch=[e],this.currentBatchTimer=setTimeout(()=>{this.batchSend(this.currentBatch),this.currentBatch=null},0))}batchSend(e){this.awaitingBatchAck=!0,this.ajax("POST",{"Content-Type":"application/x-ndjson"},e.join(` 75`),()=>this.onerror("timeout"),n=>{this.awaitingBatchAck=!1,!n||n.status!==200?(this.onerror(n&&n.status),this.closeAndRetry(1011,"internal server error",!1)):this.batchBuffer.length>0&&(this.batchSend(this.batchBuffer),this.batchBuffer=[])})}close(e,n,r){for(let i of this.reqs)i.abort();this.readyState=bs.closed;let s=Object.assign({code:1e3,reason:void 0,wasClean:!0},{code:e,reason:n,wasClean:r});this.batchBuffer=[],clearTimeout(this.currentBatchTimer),this.currentBatchTimer=null,typeof CloseEvent<"u"?this.onclose(new CloseEvent("close",s)):this.onclose(s)}ajax(e,n,r,s,i){let o,a=()=>{this.reqs.delete(o),s()};o=Hh.request(e,this.endpointURL(),n,r,this.timeout,a,l=>{this.reqs.delete(o),this.isActive()&&i(l)}),this.reqs.add(o)}},uN=class sc{constructor(n,r={}){let s=r.events||{state:"presence_state",diff:"presence_diff"};this.state={},this.pendingDiffs=[],this.channel=n,this.joinRef=null,this.caller={onJoin:function(){},onLeave:function(){},onSync:function(){}},this.channel.on(s.state,i=>{let{onJoin:o,onLeave:a,onSync:l}=this.caller;this.joinRef=this.channel.joinRef(),this.state=sc.syncState(this.state,i,o,a),this.pendingDiffs.forEach(d=>{this.state=sc.syncDiff(this.state,d,o,a)}),this.pendingDiffs=[],l()}),this.channel.on(s.diff,i=>{let{onJoin:o,onLeave:a,onSync:l}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(i):(this.state=sc.syncDiff(this.state,i,o,a),l())})}onJoin(n){this.caller.onJoin=n}onLeave(n){this.caller.onLeave=n}onSync(n){this.caller.onSync=n}list(n){return sc.list(this.state,n)}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel.joinRef()}static syncState(n,r,s,i){let o=this.clone(n),a={},l={};return this.map(o,(d,c)=>{r[d]||(l[d]=c)}),this.map(r,(d,c)=>{let f=o[d];if(f){let p=c.metas.map(m=>m.phx_ref),u=f.metas.map(m=>m.phx_ref),h=c.metas.filter(m=>u.indexOf(m.phx_ref)<0),y=f.metas.filter(m=>p.indexOf(m.phx_ref)<0);h.length>0&&(a[d]=c,a[d].metas=h),y.length>0&&(l[d]=this.clone(f),l[d].metas=y)}else a[d]=c}),this.syncDiff(o,{joins:a,leaves:l},s,i)}static syncDiff(n,r,s,i){let{joins:o,leaves:a}=this.clone(r);return s||(s=function(){}),i||(i=function(){}),this.map(o,(l,d)=>{let c=n[l];if(n[l]=this.clone(d),c){let f=n[l].metas.map(u=>u.phx_ref),p=c.metas.filter(u=>f.indexOf(u.phx_ref)<0);n[l].metas.unshift(...p)}s(l,c,d)}),this.map(a,(l,d)=>{let c=n[l];if(!c)return;let f=d.metas.map(p=>p.phx_ref);c.metas=c.metas.filter(p=>f.indexOf(p.phx_ref)<0),i(l,c,d),c.metas.length===0&&delete n[l]}),n}static list(n,r){return r||(r=function(s,i){return i}),this.map(n,(s,i)=>r(s,i))}static map(n,r){return Object.getOwnPropertyNames(n).map(s=>r(s,n[s]))}static clone(n){return JSON.parse(JSON.stringify(n))}},Gu={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(e,n){if(e.payload.constructor===ArrayBuffer)return n(this.binaryEncode(e));{let r=[e.join_ref,e.ref,e.topic,e.event,e.payload];return n(JSON.stringify(r))}},decode(e,n){if(e.constructor===ArrayBuffer)return n(this.binaryDecode(e));{let[r,s,i,o,a]=JSON.parse(e);return n({join_ref:r,ref:s,topic:i,event:o,payload:a})}},binaryEncode(e){let{join_ref:n,ref:r,event:s,topic:i,payload:o}=e,a=this.META_LENGTH+n.length+r.length+i.length+s.length,l=new ArrayBuffer(this.HEADER_LENGTH+a),d=new DataView(l),c=0;d.setUint8(c++,this.KINDS.push),d.setUint8(c++,n.length),d.setUint8(c++,r.length),d.setUint8(c++,i.length),d.setUint8(c++,s.length),Array.from(n,p=>d.setUint8(c++,p.charCodeAt(0))),Array.from(r,p=>d.setUint8(c++,p.charCodeAt(0))),Array.from(i,p=>d.setUint8(c++,p.charCodeAt(0))),Array.from(s,p=>d.setUint8(c++,p.charCodeAt(0)));var f=new Uint8Array(l.byteLength+o.byteLength);return f.set(new Uint8Array(l),0),f.set(new Uint8Array(o),l.byteLength),f.buffer},binaryDecode(e){let n=new DataView(e),r=n.getUint8(0),s=new TextDecoder;switch(r){case this.KINDS.push:return this.decodePush(e,n,s);case this.KINDS.reply:return this.decodeReply(e,n,s);case this.KINDS.broadcast:return this.decodeBroadcast(e,n,s)}},decodePush(e,n,r){let s=n.getUint8(1),i=n.getUint8(2),o=n.getUint8(3),a=this.HEADER_LENGTH+this.META_LENGTH-1,l=r.decode(e.slice(a,a+s));a=a+s;let d=r.decode(e.slice(a,a+i));a=a+i;let c=r.decode(e.slice(a,a+o));a=a+o;let f=e.slice(a,e.byteLength);return{join_ref:l,ref:null,topic:d,event:c,payload:f}},decodeReply(e,n,r){let s=n.getUint8(1),i=n.getUint8(2),o=n.getUint8(3),a=n.getUint8(4),l=this.HEADER_LENGTH+this.META_LENGTH,d=r.decode(e.slice(l,l+s));l=l+s;let c=r.decode(e.slice(l,l+i));l=l+i;let f=r.decode(e.slice(l,l+o));l=l+o;let p=r.decode(e.slice(l,l+a));l=l+a;let u=e.slice(l,e.byteLength),h={status:p,response:u};return{join_ref:d,ref:c,topic:f,event:qs.reply,payload:h}},decodeBroadcast(e,n,r){let s=n.getUint8(1),i=n.getUint8(2),o=this.HEADER_LENGTH+2,a=r.decode(e.slice(o,o+s));o=o+s;let l=r.decode(e.slice(o,o+i));o=o+i;let d=e.slice(o,e.byteLength);return{join_ref:null,ref:null,topic:a,event:l,payload:d}}},pN=class{constructor(e,n={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.fallbackRef=null,this.timeout=n.timeout||oN,this.transport=n.transport||gs.WebSocket||Ra,this.conn=void 0,this.primaryPassedHealthCheck=!1,this.longPollFallbackMs=n.longPollFallbackMs,this.fallbackTimer=null,this.sessionStore=n.sessionStorage||gs&&gs.sessionStorage,this.establishedConnections=0,this.defaultEncoder=Gu.encode.bind(Gu),this.defaultDecoder=Gu.decode.bind(Gu),this.closeWasClean=!0,this.disconnecting=!1,this.binaryType=n.binaryType||"arraybuffer",this.connectClock=1,this.pageHidden=!1,this.encode=void 0,this.decode=void 0,this.transport!==Ra?(this.encode=n.encode||this.defaultEncoder,this.decode=n.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let r=null;Ka&&Ka.addEventListener&&(Ka.addEventListener("pagehide",s=>{this.conn&&(this.disconnect(),r=this.connectClock)}),Ka.addEventListener("pageshow",s=>{r===this.connectClock&&(r=null,this.connect())}),Ka.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?this.pageHidden=!0:(this.pageHidden=!1,!this.isConnected()&&!this.closeWasClean&&this.teardown(()=>this.connect()))})),this.heartbeatIntervalMs=n.heartbeatIntervalMs||3e4,this.autoSendHeartbeat=n.autoSendHeartbeat??!0,this.heartbeatCallback=n.heartbeatCallback??(()=>{}),this.rejoinAfterMs=s=>n.rejoinAfterMs?n.rejoinAfterMs(s):[1e3,2e3,5e3][s-1]||1e4,this.reconnectAfterMs=s=>n.reconnectAfterMs?n.reconnectAfterMs(s):[10,50,100,150,200,250,500,1e3,2e3][s-1]||5e3,this.logger=n.logger||null,!this.logger&&n.debug&&(this.logger=(s,i,o)=>{console.log(`${s}: ${i}`,o)}),this.longpollerTimeout=n.longpollerTimeout||2e4,this.params=xc(n.params||{}),this.endPoint=`${e}/${ly.websocket}`,this.vsn=n.vsn||iN,this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.heartbeatSentAt=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new m4(()=>{if(this.pageHidden){this.log("Not reconnecting as page is hidden!"),this.teardown();return}this.teardown(async()=>{n.beforeReconnect&&await n.beforeReconnect(),this.connect()})},this.reconnectAfterMs),this.authToken=n.authToken}getLongPollTransport(){return Ra}replaceTransport(e){this.connectClock++,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.conn&&(this.conn.close(),this.conn=null),this.transport=e}protocol(){return location.protocol.match(/^https/)?"wss":"ws"}endPointURL(){let e=Hh.appendParams(Hh.appendParams(this.endPoint,this.params()),{vsn:this.vsn});return e.charAt(0)!=="/"?e:e.charAt(1)==="/"?`${this.protocol()}:${e}`:`${this.protocol()}://${location.host}${e}`}disconnect(e,n,r){this.connectClock++,this.disconnecting=!0,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.teardown(()=>{this.disconnecting=!1,e&&e()},n,r)}connect(e){e&&(console&&console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor"),this.params=xc(e)),!(this.conn&&!this.disconnecting)&&(this.longPollFallbackMs&&this.transport!==Ra?this.connectWithFallback(Ra,this.longPollFallbackMs):this.transportConnect())}log(e,n,r){this.logger&&this.logger(e,n,r)}hasLogger(){return this.logger!==null}onOpen(e){let n=this.makeRef();return this.stateChangeCallbacks.open.push([n,e]),n}onClose(e){let n=this.makeRef();return this.stateChangeCallbacks.close.push([n,e]),n}onError(e){let n=this.makeRef();return this.stateChangeCallbacks.error.push([n,e]),n}onMessage(e){let n=this.makeRef();return this.stateChangeCallbacks.message.push([n,e]),n}onHeartbeat(e){this.heartbeatCallback=e}ping(e){if(!this.isConnected())return!1;let n=this.makeRef(),r=Date.now();this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:n});let s=this.onMessage(i=>{i.ref===n&&(this.off([s]),e(Date.now()-r))});return!0}transportName(e){switch(e){case Ra:return"LongPoll";default:return e.name}}transportConnect(){this.connectClock++,this.closeWasClean=!1;let e;this.authToken&&(e=["phoenix",`${dy}${btoa(this.authToken).replace(/=/g,"")}`]),this.conn=new this.transport(this.endPointURL(),e),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,this.conn.onopen=()=>this.onConnOpen(),this.conn.onerror=n=>this.onConnError(n),this.conn.onmessage=n=>this.onConnMessage(n),this.conn.onclose=n=>this.onConnClose(n)}getSession(e){return this.sessionStore&&this.sessionStore.getItem(e)}storeSession(e,n){this.sessionStore&&this.sessionStore.setItem(e,n)}connectWithFallback(e,n=2500){clearTimeout(this.fallbackTimer);let r=!1,s=!0,i,o,a=this.transportName(e),l=d=>{this.log("transport",`falling back to ${a}...`,d),this.off([i,o]),s=!1,this.replaceTransport(e),this.transportConnect()};if(this.getSession(`phx:fallback:${a}`))return l("memorized");this.fallbackTimer=setTimeout(l,n),o=this.onError(d=>{this.log("transport","error",d),s&&!r&&(clearTimeout(this.fallbackTimer),l(d))}),this.fallbackRef&&this.off([this.fallbackRef]),this.fallbackRef=this.onOpen(()=>{if(r=!0,!s){let d=this.transportName(e);return this.primaryPassedHealthCheck||this.storeSession(`phx:fallback:${d}`,"true"),this.log("transport",`established ${d} fallback`)}clearTimeout(this.fallbackTimer),this.fallbackTimer=setTimeout(l,n),this.ping(d=>{this.log("transport","connected to primary after",d),this.primaryPassedHealthCheck=!0,clearTimeout(this.fallbackTimer)})}),this.transportConnect()}clearHeartbeats(){clearTimeout(this.heartbeatTimer),clearTimeout(this.heartbeatTimeoutTimer)}onConnOpen(){this.hasLogger()&&this.log("transport",`connected to ${this.endPointURL()}`),this.closeWasClean=!1,this.disconnecting=!1,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.autoSendHeartbeat&&this.resetHeartbeat(),this.triggerStateCallbacks("open")}heartbeatTimeout(){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.hasLogger()&&this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(e){this.log("error","error in heartbeat callback",e)}this.triggerChanError(),this.closeWasClean=!1,this.teardown(()=>this.reconnectTimer.scheduleTimeout(),aN,"heartbeat timeout")}}resetHeartbeat(){this.conn&&this.conn.skipHeartbeat||(this.pendingHeartbeatRef=null,this.clearHeartbeats(),this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}teardown(e,n,r){if(!this.conn)return e&&e();const s=this.conn;this.waitForBufferDone(s,()=>{n?s.close(n,r||""):s.close(),this.waitForSocketClosed(s,()=>{this.conn===s&&(this.conn.onopen=function(){},this.conn.onerror=function(){},this.conn.onmessage=function(){},this.conn.onclose=function(){},this.conn=null),e&&e()})})}waitForBufferDone(e,n,r=1){if(r===5||!e.bufferedAmount){n();return}setTimeout(()=>{this.waitForBufferDone(e,n,r+1)},150*r)}waitForSocketClosed(e,n,r=1){if(r===5||e.readyState===bs.closed){n();return}setTimeout(()=>{this.waitForSocketClosed(e,n,r+1)},150*r)}onConnClose(e){this.conn&&(this.conn.onclose=()=>{}),this.hasLogger()&&this.log("transport","close",e),this.triggerChanError(),this.clearHeartbeats(),this.closeWasClean||this.reconnectTimer.scheduleTimeout(),this.triggerStateCallbacks("close",e)}onConnError(e){this.hasLogger()&&this.log("transport",e);let n=this.transport,r=this.establishedConnections;this.triggerStateCallbacks("error",e,n,r),(n===this.transport||r>0)&&this.triggerChanError()}
75triggerChanError(){this.channels.forEach(e=>{e.isErrored()||e.isLeaving()||e.isClosed()||e.trigger(qs.error)})}connectionState(){switch(this.conn&&this.conn.readyState){case bs.connecting:return"connecting";case bs.open:return"open";case bs.closing:return"closing";default:return"closed"}}isConnected(){return this.connectionState()==="open"}remove(e){this.off(e.stateChangeRefs),this.channels=this.channels.filter(n=>n!==e)}off(e){for(let n in this.stateChangeCallbacks)this.stateChangeCallbacks[n]=this.stateChangeCallbacks[n].filter(([r])=>e.indexOf(r)===-1)}channel(e,n={}){let r=new dN(e,n,this);return this.channels.push(r),r}push(e){if(this.hasLogger()){let{topic:n,event:r,payload:s,ref:i,join_ref:o}=e;this.log("push",`${n} ${r} (${o}, ${i})`,s)}this.isConnected()?this.encode(e,n=>this.conn.send(n)):this.sendBuffer.push(()=>this.encode(e,n=>this.conn.send(n)))}makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}sendHeartbeat(){if(!this.isConnected()){try{this.heartbeatCallback("disconnected")}catch(e){this.log("error","error in heartbeat callback",e)}return}if(this.pendingHeartbeatRef){this.heartbeatTimeout();return}this.pendingHeartbeatRef=this.makeRef(),this.heartbeatSentAt=Date.now(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(e){this.log("error","error in heartbeat callback",e)}this.heartbeatTimeoutTimer=setTimeout(()=>this.heartbeatTimeout(),this.heartbeatIntervalMs)}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}onConnMessage(e){this.decode(e.data,n=>{let{topic:r,event:s,payload:i,ref:o,join_ref:a}=n;if(o&&o===this.pendingHeartbeatRef){const l=this.heartbeatSentAt?Date.now()-this.heartbeatSentAt:void 0;this.clearHeartbeats();try{this.heartbeatCallback(i.status==="ok"?"ok":"error",l)}catch(d){this.log("error","error in heartbeat callback",d)}this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.autoSendHeartbeat&&(this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}this.hasLogger()&&this.log("receive",`${i.status||""} ${r} ${s} ${o&&"("+o+")"||""}`.trim(),i);for(let l=0;l<this.channels.length;l++){const d=this.channels[l];d.isMember(r,s,i,a)&&d.trigger(s,i,o,a)}this.triggerStateCallbacks("message",n)})}triggerStateCallbacks(e,...n){try{this.stateChangeCallbacks[e].forEach(([r,s])=>{try{s(...n)}catch(i){this.log("error",`error in ${e} callback`,i)}})}catch(r){this.log("error",`error triggering ${e} callbacks`,r)}}leaveOpenTopic(e){let n=this.channels.find(r=>r.topic===e&&(r.isJoined()||r.isJoining()));n&&(this.hasLogger()&&this.log("transport",`leaving duplicate topic "${e}"`),n.leave())}};class yc{constructor(n,r){const s=fN(r);this.presence=new uN(n.getChannel(),s),this.presence.onJoin((i,o,a)=>{const l=yc.onJoinPayload(i,o,a);n.getChannel().trigger("presence",l)}),this.presence.onLeave((i,o,a)=>{const l=yc.onLeavePayload(i,o,a);n.getChannel().trigger("presence",l)}),this.presence.onSync(()=>{n.getChannel().trigger("presence",{event:"sync"})})}get state(){return yc.transformState(this.presence.state)}static transformState(n){return n=hN(n),Object.getOwnPropertyNames(n).reduce((r,s)=>{const i=n[s];return r[s]=th(i),r},{})}static onJoinPayload(n,r,s){const i=$1(r),o=th(s);return{event:"join",key:n,currentPresences:i,newPresences:o}}static onLeavePayload(n,r,s){const i=$1(r),o=th(s);return{event:"leave",key:n,currentPresences:i,leftPresences:o}}}function th(e){return e.metas.map(n=>(n.presence_ref=n.phx_ref,delete n.phx_ref,delete n.phx_ref_prev,n))}function hN(e){return JSON.parse(JSON.stringify(e))}function fN(e){return(e==null?void 0:e.events)&&{events:e.events}}function $1(e){return e!=null&&e.metas?th(e):[]}var M1;(function(e){e.SYNC="sync",e.JOIN="join",e.LEAVE="leave"})(M1||(M1={}));class gN{get state(){return this.presenceAdapter.state}constructor(n,r){this.channel=n,this.presenceAdapter=new yc(this.channel.channelAdapter,r)}}class mN{constructor(n,r,s){const i=xN(s);this.channel=n.getSocket().channel(r,i),this.socket=n}
75get state(){return this.channel.state}set state(n){this.channel.state=n}get joinedOnce(){return this.channel.joinedOnce}get joinPush(){return this.channel.joinPush}get rejoinTimer(){return this.channel.rejoinTimer}on(n,r){return this.channel.on(n,r)}off(n,r){this.channel.off(n,r)}subscribe(n){return this.channel.join(n)}unsubscribe(n){return this.channel.leave(n)}teardown(){this.channel.teardown()}onClose(n){this.channel.onClose(n)}onError(n){return this.channel.onError(n)}push(n,r,s){let i;try{i=this.channel.push(n,r,s)}catch{throw`tried to push '${n}' to '${this.channel.topic}' before joining. Use channel.subscribe() before pushing events`}if(this.channel.pushBuffer.length>Xz){const o=this.channel.pushBuffer.shift();o.cancelTimeout(),this.socket.log("channel",`discarded push due to buffer overflow: ${o.event}`,o.payload())}return i}updateJoinPayload(n){const r=this.channel.joinPush.payload();this.channel.joinPush.payload=()=>Object.assign(Object.assign({},r),n)}canPush(){return this.socket.isConnected()&&this.state===Ni.joined}isJoined(){return this.state===Ni.joined}isJoining(){return this.state===Ni.joining}isClosed(){return this.state===Ni.closed}isLeaving(){return this.state===Ni.leaving}updateFilterBindings(n){this.channel.filterBindings=n}updatePayloadTransform(n){this.channel.onMessage=n}getChannel(){return this.channel}}function xN(e){return{config:Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},e.config)}}var F1;(function(e){e.ALL="*",e.INSERT="INSERT",e.UPDATE="UPDATE",e.DELETE="DELETE"})(F1||(F1={}));var bc;(function(e){e.BROADCAST="broadcast",e.PRESENCE="presence",e.POSTGRES_CHANGES="postgres_changes",e.SYSTEM="system"})(bc||(bc={}));var Ds;(function(e){e.SUBSCRIBED="SUBSCRIBED",e.TIMED_OUT="TIMED_OUT",e.CLOSED="CLOSED",e.CHANNEL_ERROR="CHANNEL_ERROR"})(Ds||(Ds={}));class Ac{get state(){return this.channelAdapter.state}set state(n){this.channelAdapter.state=n}get joinedOnce(){return this.channelAdapter.joinedOnce}get timeout(){return this.socket.timeout}get joinPush(){return this.channelAdapter.joinPush}get rejoinTimer(){return this.channelAdapter.rejoinTimer}constructor(n,r={config:{}},s){var i,o;if(this.topic=n,this.params=r,this.socket=s,this.bindings={},this.subTopic=n.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},r.config),this.channelAdapter=new mN(this.socket.socketAdapter,n,this.params),this.presence=new gN(this),this._onClose(()=>{this.socket._remove(this)}),this._updateFilterTransform(),this.broadcastEndpointURL=g4(this.socket.socketAdapter.endPointURL()),this.private=this.params.config.private||!1,!this.private&&(!((o=(i=this.params.config)===null||i===void 0?void 0:i.broadcast)===null||o===void 0)&&o.replay))throw`tried to use replay on public channel '${this.topic}'. It must be a private channel.`}subscribe(n,r=this.timeout){var s,i,o;if(this.socket.isConnected()||this.socket.connect(),this.channelAdapter.isClosed()){const{config:{broadcast:a,presence:l,private:d}}=this.params,c=(i=(s=this.bindings.postgres_changes)===null||s===void 0?void 0:s.map(h=>h.filter))!==null&&i!==void 0?i:[],f=!!this.bindings[bc.PRESENCE]&&this.bindings[bc.PRESENCE].length>0||((o=this.params.config.presence)===null||o===void 0?void 0:o.enabled)===!0,p={},u={broadcast:a,presence:Object.assign(Object.assign({},l),{enabled:f}),postgres_changes:c,private:d};this.socket.accessTokenValue&&(p.access_token=this.socket.accessTokenValue),this._onError(h=>{n==null||n(Ds.CHANNEL_ERROR,h)}),this._onClose(()=>n==null?void 0:n(Ds.CLOSED)),this.updateJoinPayload(Object.assign({config:u},p)),this._updateFilterMessage(),this.channelAdapter.subscribe(r).receive("ok",async({postgres_changes:h})=>{if(this.socket._isManualToken()||this.socket.setAuth(),h===void 0){n==null||n(Ds.SUBSCRIBED);return}this._updatePostgresBindings(h,n)}).receive("error",h=>{this.state=Ni.errored,n==null||n(Ds.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(h).join(", ")||"error")))}).receive("timeout",()=>{n==null||n(Ds.TIMED_OUT)})}return this}_updatePostgresBindings(n,r){var s;const i=this.bindings.postgres_changes,o=(s=i==null?void 0:i.length)!==null&&s!==void 0?s:0,a=[];for(let l=0;l<o;l++){const d=i[l],{filter:{event:c,schema:f,table:p,filter:u}}=d,h=n&&n[l];if(h&&h.event===c&&Ac.isFilterValueEqual(h.schema,f)&&Ac.isFilterValueEqual(h.table,p)&&Ac.isFilterValueEqual(h.filter,u))a.push(Object.assign(Object.assign({},d),{id:h.id}));else{this.unsubscribe(),this.state=Ni.errored,r==null||r(Ds.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=a,this.state!=Ni.errored&&r&&r(Ds.SUBSCRIBED)}presenceState(){return this.presence.state}async track(n,r={}){return await this.send({type:"presence",event:"track",payload:n},r.timeout||this.timeout)}async untrack(n={}){return await this.send({type:"presence",event:"untrack"},n)}on(n,r,s){if(this.channelAdapter.isJoined()&&n===bc.PRESENCE)throw this.socket.log("channel",`cannot add presence callbacks for ${this.topic} after joining.`),new Error("cannot add presence callbacks after joining a channel");return this._on(n,r,s)}async httpSend(n,r,s={}){var i;if(r==null)return Promise.reject("Payload is required for httpSend()");const o={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(o.Authorization=`Bearer ${this.socket.accessTokenValue}`);const a={method:"POST",headers:o,body:JSON.stringify({messages:[{topic:this.subTopic,event:n,payload:r,private:this.private}]})},l=await this._fetchWithTimeout(this.broadcastEndpointURL,a,(i=s.timeout)!==null&&i!==void 0?i:this.timeout);if(l.status===202)return{success:!0};let d=l.statusText;
75try{const c=await l.json();d=c.error||c.message||d}catch{}return Promise.reject(new Error(d))}async send(n,r={}){var s,i;if(!this.channelAdapter.canPush()&&n.type==="broadcast"){console.warn("Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery.");const{event:o,payload:a}=n,l={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(l.Authorization=`Bearer ${this.socket.accessTokenValue}`);const d={method:"POST",headers:l,body:JSON.stringify({messages:[{topic:this.subTopic,event:o,payload:a,private:this.private}]})};try{const c=await this._fetchWithTimeout(this.broadcastEndpointURL,d,(s=r.timeout)!==null&&s!==void 0?s:this.timeout);return await((i=c.body)===null||i===void 0?void 0:i.cancel()),c.ok?"ok":"error"}catch(c){return c.name==="AbortError"?"timed out":"error"}}else return new Promise(o=>{var a,l,d;const c=this.channelAdapter.push(n.type,n,r.timeout||this.timeout);n.type==="broadcast"&&!(!((d=(l=(a=this.params)===null||a===void 0?void 0:a.config)===null||l===void 0?void 0:l.broadcast)===null||d===void 0)&&d.ack)&&o("ok"),c.receive("ok",()=>o("ok")),c.receive("error",()=>o("error")),c.receive("timeout",()=>o("timed out"))})}updateJoinPayload(n){this.channelAdapter.updateJoinPayload(n)}async unsubscribe(n=this.timeout){return new Promise(r=>{this.channelAdapter.unsubscribe(n).receive("ok",()=>r("ok")).receive("timeout",()=>r("timed out")).receive("error",()=>r("error"))})}teardown(){this.channelAdapter.teardown()}async _fetchWithTimeout(n,r,s){const i=new AbortController,o=setTimeout(()=>i.abort(),s),a=await this.socket.fetch(n,Object.assign(Object.assign({},r),{signal:i.signal}));return clearTimeout(o),a}_on(n,r,s){const i=n.toLocaleLowerCase(),o=this.channelAdapter.on(n,s),a={type:i,filter:r,callback:s,ref:o};return this.bindings[i]?this.bindings[i].push(a):this.bindings[i]=[a],this._updateFilterMessage(),this}_onClose(n){this.channelAdapter.onClose(n)}_onError(n){this.channelAdapter.onError(n)}_updateFilterMessage(){this.channelAdapter.updateFilterBindings((n,r,s)=>{var i,o,a,l,d,c,f;const p=n.event.toLocaleLowerCase();if(this._notThisChannelEvent(p,s))return!1;const u=(i=this.bindings[p])===null||i===void 0?void 0:i.find(h=>h.ref===n.ref);if(!u)return!0;if(["broadcast","presence","postgres_changes"].includes(p))if("id"in u){const h=u.id,y=(o=u.filter)===null||o===void 0?void 0:o.event;return h&&((a=r.ids)===null||a===void 0?void 0:a.includes(h))&&(y==="*"||(y==null?void 0:y.toLocaleLowerCase())===((l=r.data)===null||l===void 0?void 0:l.type.toLocaleLowerCase()))}else{const h=(c=(d=u==null?void 0:u.filter)===null||d===void 0?void 0:d.event)===null||c===void 0?void 0:c.toLocaleLowerCase();return h==="*"||h===((f=r==null?void 0:r.event)===null||f===void 0?void 0:f.toLocaleLowerCase())}else return u.type.toLocaleLowerCase()===p})}_notThisChannelEvent(n,r){const{close:s,error:i,leave:o,join:a}=h4;return r&&[s,i,o,a].includes(n)&&r!==this.joinPush.ref}_updateFilterTransform(){this.channelAdapter.updatePayloadTransform((n,r,s)=>{if(typeof r=="object"&&"ids"in r){const i=r.data,{schema:o,table:a,commit_timestamp:l,type:d,errors:c}=i;return Object.assign(Object.assign({},{schema:o,table:a,commit_timestamp:l,eventType:d,new:{},old:{},errors:c}),this._getPayloadRecords(i))}return r})}static isFilterValueEqual(n,r){return(n??void 0)===(r??void 0)}_getPayloadRecords(n){const r={new:{},old:{}};return(n.type==="INSERT"||n.type==="UPDATE")&&(r.new=W1(n.columns,n.record)),(n.type==="UPDATE"||n.type==="DELETE")&&(r.old=W1(n.columns,n.old_record)),r}}class yN{constructor(n,r){this.socket=new pN(n,r)}get timeout(){return this.socket.timeout}get endPoint(){return this.socket.endPoint}get transport(){return this.socket.transport}get heartbeatIntervalMs(){return this.socket.heartbeatIntervalMs}get heartbeatCallback(){return this.socket.heartbeatCallback}set heartbeatCallback(n){this.socket.heartbeatCallback=n}get heartbeatTimer(){return this.socket.heartbeatTimer}get pendingHeartbeatRef(){return this.socket.pendingHeartbeatRef}get reconnectTimer(){return this.socket.reconnectTimer}get vsn(){return this.socket.vsn}get encode(){return this.socket.encode}get decode(){return this.socket.decode}get reconnectAfterMs(){return this.socket.reconnectAfterMs}get sendBuffer(){return this.socket.sendBuffer}get stateChangeCallbacks(){return this.socket.stateChangeCallbacks}connect(){this.socket.connect()}disconnect(n,r,s,i=1e4){return new Promise(o=>{setTimeout(()=>
75o("timeout"),i),this.socket.disconnect(()=>{n(),o("ok")},r,s)})}push(n){this.socket.push(n)}log(n,r,s){this.socket.log(n,r,s)}makeRef(){return this.socket.makeRef()}onOpen(n){this.socket.onOpen(n)}onClose(n){this.socket.onClose(n)}onError(n){this.socket.onError(n)}onMessage(n){this.socket.onMessage(n)}isConnected(){return this.socket.isConnected()}isConnecting(){return this.socket.connectionState()==oy.connecting}isDisconnecting(){return this.socket.connectionState()==oy.closing}connectionState(){return this.socket.connectionState()}endPointURL(){return this.socket.endPointURL()}sendHeartbeat(){this.socket.sendHeartbeat()}getSocket(){return this.socket}}const bN={HEARTBEAT_INTERVAL:25e3},AN=[1e3,2e3,5e3,1e4],vN=1e4,_N=` 76 addEventListener("message", (e) => { 77 if (e.data.event === "start") { 78 setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval); 79 } 80 });`;class jN{get endPoint(){return this.socketAdapter.endPoint}get timeout(){return this.socketAdapter.timeout}get transport(){return this.socketAdapter.transport}get heartbeatCallback(){return this.socketAdapter.heartbeatCallback}get heartbeatIntervalMs(){return this.socketAdapter.heartbeatIntervalMs}get heartbeatTimer(){return this.worker?this._workerHeartbeatTimer:this.socketAdapter.heartbeatTimer}get pendingHeartbeatRef(){return this.worker?this._pendingWorkerHeartbeatRef:this.socketAdapter.pendingHeartbeatRef}get reconnectTimer(){return this.socketAdapter.reconnectTimer}get vsn(){return this.socketAdapter.vsn}get encode(){return this.socketAdapter.encode}get decode(){return this.socketAdapter.decode}get reconnectAfterMs(){return this.socketAdapter.reconnectAfterMs}get sendBuffer(){return this.socketAdapter.sendBuffer}get stateChangeCallbacks(){return this.socketAdapter.stateChangeCallbacks}constructor(n,r){var s;if(this.channels=new Array,this.accessTokenValue=null,this.accessToken=null,this.apiKey=null,this.httpEndpoint="",this.headers={},this.params={},this.ref=0,this.serializer=new Gz,this._manuallySetToken=!1,this._authPromise=null,this._workerHeartbeatTimer=void 0,this._pendingWorkerHeartbeatRef=null,this._resolveFetch=o=>o?(...a)=>o(...a):(...a)=>fetch(...a),!(!((s=r==null?void 0:r.params)===null||s===void 0)&&s.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=r.params.apikey;const i=this._initializeOptions(r);this.socketAdapter=new yN(n,i),this.httpEndpoint=g4(n),this.fetch=this._resolveFetch(r==null?void 0:r.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.isConnected())){this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this._setupConnectionHandlers();try{this.socketAdapter.connect()}catch(n){const r=n.message;throw r.includes("Node.js")?new Error(`${r} 81 82To use Realtime in Node.js, you need to provide a WebSocket implementation: 83 84Option 1: Use Node.js 22+ which has native WebSocket support 85Option 2: Install and provide the "ws" package: 86 87 npm install ws 88 89 import ws from "ws" 90 const client = new RealtimeClient(url, { 91 ...options, 92 transport: ws 93 })`):new Error(`WebSocket not available: ${r}`)}this._handleNodeJsRaceCondition()}}endpointURL(){return this.socketAdapter.endPointURL()}async disconnect(n,r){return this.isDisconnecting()?"ok":await this.socketAdapter.disconnect(()=>{clearInterval(this._workerHeartbeatTimer),this._terminateWorker()},n,r)}getChannels(){return this.channels}async removeChannel(n){const r=await n.unsubscribe();return r==="ok"&&n.teardown(),this.channels.length===0&&this.disconnect(),r}async removeAllChannels(){const n=this.channels.map(async s=>{const i=await s.unsubscribe();return s.teardown(),i}),r=await Promise.all(n);return this.disconnect(),r}log(n,r,s){this.socketAdapter.log(n,r,s)}connectionState(){return this.socketAdapter.connectionState()||oy.closed}isConnected(){return this.socketAdapter.isConnected()}isConnecting(){return this.socketAdapter.isConnecting()}isDisconnecting(){return this.socketAdapter.isDisconnecting()}channel(n,r={config:{}}){const s=`realtime:${n}`,i=this.getChannels().find(o=>o.topic===s);if(i)return i;{const o=new Ac(`realtime:${n}`,r,this);return this.channels.push(o),o}}push(n){this.socketAdapter.push(n)}async setAuth(n=null){this._authPromise=this._performAuth(n);try{await this._authPromise}finally{this._authPromise=null}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){this.socketAdapter.sendHeartbeat()}onHeartbeat(n){this.socketAdapter.heartbeatCallback=this._wrapHeartbeatCallback(n)}_makeRef(){return this.socketAdapter.makeRef()}_remove(n){this.channels=this.channels.filter(r=>r.topic!==n.topic)}async _performAuth(n=null){let r,s=!1;if(n)r=n,s=!0;else if(this.accessToken)try{r=await this.accessToken()}catch(i){this.log("error","Error fetching access token from callback",i),r=this.accessTokenValue}else r=this.accessTokenValue;s?this._manuallySetToken=!0:this.accessToken&&(this._manuallySetToken=!1),this.accessTokenValue!=r&&(this.accessTokenValue=r,this.channels.forEac
93h(i=>{const o={access_token:r,version:Vz};r&&i.updateJoinPayload(o),i.joinedOnce&&i.channelAdapter.isJoined()&&i.channelAdapter.push(h4.access_token,{access_token:r})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(n="general"){this._isManualToken()||this.setAuth().catch(r=>{this.log("error",`Error setting auth in ${n}`,r)})}_setupConnectionHandlers(){this.socketAdapter.onOpen(()=>{(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).catch(r=>{this.log("error","error waiting for auth on connect",r)}),this.worker&&!this.workerRef&&this._startWorkerHeartbeat()}),this.socketAdapter.onClose(()=>{this.worker&&this.workerRef&&this._terminateWorker()}),this.socketAdapter.onMessage(n=>{n.ref&&n.ref===this._pendingWorkerHeartbeatRef&&(this._pendingWorkerHeartbeatRef=null)})}_handleNodeJsRaceCondition(){this.socketAdapter.isConnected()&&this.socketAdapter.getSocket().onConnOpen()}_wrapHeartbeatCallback(n){return(r,s)=>{r=="sent"&&this._setAuthSafely(),n&&n(r,s)}}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");const n=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(n),this.workerRef.onerror=r=>{this.log("worker","worker error",r.message),this._terminateWorker(),this.disconnect()},this.workerRef.onmessage=r=>{r.data.event==="keepAlive"&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_terminateWorker(){this.workerRef&&(this.log("worker","terminating worker"),this.workerRef.terminate(),this.workerRef=void 0)}_workerObjectUrl(n){let r;if(n)r=n;else{const s=new Blob([_N],{type:"application/javascript"});r=URL.createObjectURL(s)}return r}_initializeOptions(n){var r,s,i,o,a,l,d,c,f;this.worker=(r=n==null?void 0:n.worker)!==null&&r!==void 0?r:!1,this.accessToken=(s=n==null?void 0:n.accessToken)!==null&&s!==void 0?s:null;const p={};p.timeout=(i=n==null?void 0:n.timeout)!==null&&i!==void 0?i:Yz,p.heartbeatIntervalMs=(o=n==null?void 0:n.heartbeatIntervalMs)!==null&&o!==void 0?o:bN.HEARTBEAT_INTERVAL,p.transport=(a=n==null?void 0:n.transport)!==null&&a!==void 0?a:Uz.getWebSocketConstructor(),p.params=n==null?void 0:n.params,p.logger=n==null?void 0:n.logger,p.heartbeatCallback=this._wrapHeartbeatCallback(n==null?void 0:n.heartbeatCallback),p.reconnectAfterMs=(l=n==null?void 0:n.reconnectAfterMs)!==null&&l!==void 0?l:m=>AN[m-1]||vN;let u,h;const y=(d=n==null?void 0:n.vsn)!==null&&d!==void 0?d:Kz;switch(y){case Zz:u=(m,b)=>b(JSON.stringify(m)),h=(m,b)=>b(JSON.parse(m));break;case p4:u=this.serializer.encode.bind(this.serializer),h=this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${p.vsn}`)}if(p.vsn=y,p.encode=(c=n==null?void 0:n.encode)!==null&&c!==void 0?c:u,p.decode=(f=n==null?void 0:n.decode)!==null&&f!==void 0?f:h,p.beforeReconnect=this._reconnectAuth.bind(this),(n!=null&&n.logLevel||n!=null&&n.log_level)&&(this.logLevel=n.logLevel||n.log_level,p.params=Object.assign(Object.assign({},p.params),{log_level:this.logLevel})),this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=n==null?void 0:n.workerUrl,p.autoSendHeartbeat=!this.worker}return p}async _reconnectAuth(){await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()}}var Uc=class extends Error{constructor(e,n){var r;super(e),this.name="IcebergError",this.status=n.status,this.icebergType=n.icebergType,this.icebergCode=n.icebergCode,this.details=n.details,this.isCommitStateUnknown=n.icebergType==="CommitStateUnknownException"||[500,502,504].includes(n.status)&&((r=n.icebergType)==null?void 0:r.includes("CommitState"))===!0}isNotFound(){return this.status===404}isConflict(){return this.status===409}isAuthenticationTimeout(){return this.status===419}};function wN(e,n,r){const s=new URL(n,e);if(r)for(const[i,o]of Object.entries(r))o!==void 0&&s.searchParams.set(i,o);return s.toString()}async function SN(e){return!e||e.type==="none"?{}:e.type==="bearer"?{Authorization:`Bearer ${e.token}`}:e.type==="header"?{[e.name]:e.value}:e.type==="custom"?await e.getHeaders():{}}function kN(e){const n=e.fetchImpl??globalThis.fetch;return{async request({method:r,path:s,query:i,body:o,headers:a}){const l=wN(e.baseUrl,s,i),d=await SN(e.auth),c=await n(l,{method:r,headers:{...o?{"Content-Type":"application/json"}:{},...d,...a},body:o?JSON.stringify(o):void 0}),f=await c.text(),p=(c.headers.get("content-type")||"").includes("application/json"),u=p&&f?JSON.parse(f):f;if(!c.ok){const h=p?u:void 0,y=h==null?void 0:h.error;throw new Uc((y==null?void 0:y.message)??`Request failed with status ${c.status}`,{status:c.status,icebergType:y==null?void 0:y.type,icebergCode:y==null?void 0:y.code,details:h})}return{status:c.status,headers:c.headers,data:u}}}}function Ju(e){return e.join("�")}var CN=class{constructor(e,n=""){this.client=e,this.prefix=n}async listNamespaces(e){const n=e?{parent:Ju(e.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:n})).data.namespaces.map(s=>({namespace:s}))}async createNamespace(e,n){const r={namespace:e.namespace,properties:n==null?void 0:n.properties};return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:r})).data}async dropNamespace(e){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${Ju(e.namespace)}`})}async loadNamespaceMetadata(e){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Ju(e.namespace)}`})).data.properties}}async namespaceExists(e){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${Ju(e.namespace)}`}),!0}catch(n){if(n instanceof Uc&&n.status===404)return!1;throw n}}
93async createNamespaceIfNotExists(e,n){try{return await this.createNamespace(e,n)}catch(r){if(r instanceof Uc&&r.status===409)return;throw r}}};function Ea(e){return e.join("�")}var TN=class{constructor(e,n="",r){this.client=e,this.prefix=n,this.accessDelegation=r}async listTables(e){return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Ea(e.namespace)}/tables`})).data.identifiers}async createTable(e,n){const r={};return this.accessDelegation&&(r["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${Ea(e.namespace)}/tables`,body:n,headers:r})).data.metadata}async updateTable(e,n){const r=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${Ea(e.namespace)}/tables/${e.name}`,body:n});return{"metadata-location":r.data["metadata-location"],metadata:r.data.metadata}}async dropTable(e,n){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${Ea(e.namespace)}/tables/${e.name}`,query:{purgeRequested:String((n==null?void 0:n.purge)??!1)}})}async loadTable(e){const n={};return this.accessDelegation&&(n["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Ea(e.namespace)}/tables/${e.name}`,headers:n})).data.metadata}async tableExists(e){const n={};this.accessDelegation&&(n["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${Ea(e.namespace)}/tables/${e.name}`,headers:n}),!0}catch(r){if(r instanceof Uc&&r.status===404)return!1;throw r}}async createTableIfNotExists(e,n){try{return await this.createTable(e,n)}catch(r){if(r instanceof Uc&&r.status===409)return await this.loadTable({namespace:e.namespace,name:n.name});throw r}}},zN=class{constructor(e){var s;let n="v1";e.catalogName&&(n+=`/${e.catalogName}`);const r=e.baseUrl.endsWith("/")?e.baseUrl:`${e.baseUrl}/`;this.client=kN({baseUrl:r,auth:e.auth,fetchImpl:e.fetch}),this.accessDelegation=(s=e.accessDelegation)==null?void 0:s.join(","),this.namespaceOps=new CN(this.client,n),this.tableOps=new TN(this.client,n,this.accessDelegation)}async listNamespaces(e){return this.namespaceOps.listNamespaces(e)}async createNamespace(e,n){return this.namespaceOps.createNamespace(e,n)}async dropNamespace(e){await this.namespaceOps.dropNamespace(e)}async loadNamespaceMetadata(e){return this.namespaceOps.loadNamespaceMetadata(e)}async listTables(e){return this.tableOps.listTables(e)}async createTable(e,n){return this.tableOps.createTable(e,n)}async updateTable(e,n){return this.tableOps.updateTable(e,n)}async dropTable(e,n){await this.tableOps.dropTable(e,n)}async loadTable(e){return this.tableOps.loadTable(e)}async namespaceExists(e){return this.namespaceOps.namespaceExists(e)}async tableExists(e){return this.tableOps.tableExists(e)}async createNamespaceIfNotExists(e,n){return this.namespaceOps.createNamespaceIfNotExists(e,n)}async createTableIfNotExists(e,n){return this.tableOps.createTableIfNotExists(e,n)}},Wf=class extends Error{constructor(e,n="storage",r,s){super(e),this.__isStorageError=!0,this.namespace=n,this.name=n==="vectors"?"StorageVectorsError":"StorageError",this.status=r,this.statusCode=s}};function $f(e){return typeof e=="object"&&e!==null&&"__isStorageError"in e}var cy=class extends Wf{constructor(e,n,r,s="storage"){super(e,s,n,r),this.name=s==="vectors"?"StorageVectorsApiError":"StorageApiError",this.status=n,this.statusCode=r}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}},x4=class extends Wf{constructor(e,n,r="storage"){super(e,r),this.name=r==="vectors"?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=n}};const NN=e=>e?(...n)=>e(...n):(...n)=>fetch(...n),RN=e=>{if(typeof e!="object"||e===null)return!1;const n=Object.getPrototypeOf(e);return(n===null||n===Object.prototype||Object.getPrototypeOf(n)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},uy=e=>{if(Array.isArray(e))return e.map(r=>uy(r));if(typeof e=="function"||e!==Object(e))return e;const n={};return Object.entries(e).forEach(([r,s])=>{const i=r.replace(/([-_][a-z])/gi,o=>o.toUpperCase().replace(/[-_]/g,""));n[i]=uy(s)}),n},EN=e=>!e||typeof e!="string"||e.length===0||e.length>100||e.trim()!==e||e.includes("/")||e.includes("\\")?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(e);function Hc(e){"@babel/helpers - typeof";return Hc=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(n){return typeof n}:function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},Hc(e)}function PN(e,n){if(Hc(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var s=r.call(e,n);if(Hc(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(n==="string"?String:Number)(e)}function qN(e){var n=PN(e,"string");return Hc(n)=="symbol"?n:n+""}function DN(e,n,r){return(n=qN(n))in e?Object.defineProperty(e,n,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[n]=r,e}function B1(e,n){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);n&&(s=s.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,s)}return r}function Ue(e){for(var n=1;n<arguments.length;n++){var r=arguments[n]!=null?arguments[n]:{};
93n%2?B1(Object(r),!0).forEach(function(s){DN(e,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):B1(Object(r)).forEach(function(s){Object.defineProperty(e,s,Object.getOwnPropertyDescriptor(r,s))})}return e}const U1=e=>{var n;return e.msg||e.message||e.error_description||(typeof e.error=="string"?e.error:(n=e.error)===null||n===void 0?void 0:n.message)||JSON.stringify(e)},ON=async(e,n,r,s)=>{if(e!==null&&typeof e=="object"&&typeof e.json=="function"){const i=e;let o=parseInt(i.status,10);Number.isFinite(o)||(o=500),i.json().then(a=>{const l=(a==null?void 0:a.statusCode)||(a==null?void 0:a.code)||o+"";n(new cy(U1(a),o,l,s))}).catch(()=>{const a=o+"";n(new cy(i.statusText||`HTTP ${o} error`,o,a,s))})}else n(new x4(U1(e),e,s))},IN=(e,n,r,s)=>{const i={method:e,headers:(n==null?void 0:n.headers)||{}};return e==="GET"||e==="HEAD"||!s?Ue(Ue({},i),r):(RN(s)?(i.headers=Ue({"Content-Type":"application/json"},n==null?void 0:n.headers),i.body=JSON.stringify(s)):i.body=s,n!=null&&n.duplex&&(i.duplex=n.duplex),Ue(Ue({},i),r))};async function Ed(e,n,r,s,i,o,a){return new Promise((l,d)=>{e(r,IN(n,s,i,o)).then(c=>{if(!c.ok)throw c;if(s!=null&&s.noResolveJson)return c;if(a==="vectors"){const f=c.headers.get("content-type");if(c.headers.get("content-length")==="0"||c.status===204)return{};if(!f||!f.includes("application/json"))return{}}return c.json()}).then(c=>l(c)).catch(c=>ON(c,d,s,a))})}function y4(e="storage"){return{get:async(n,r,s,i)=>Ed(n,"GET",r,s,i,void 0,e),post:async(n,r,s,i,o)=>Ed(n,"POST",r,i,o,s,e),put:async(n,r,s,i,o)=>Ed(n,"PUT",r,i,o,s,e),head:async(n,r,s,i)=>Ed(n,"HEAD",r,Ue(Ue({},s),{},{noResolveJson:!0}),i,void 0,e),remove:async(n,r,s,i,o)=>Ed(n,"DELETE",r,i,o,s,e)}}const LN=y4("storage"),{get:Vc,post:Yr,put:py,head:WN,remove:Xb}=LN,yr=y4("vectors");var pd=class{constructor(e,n={},r,s="storage"){this.shouldThrowOnError=!1,this.url=e,this.headers=n,this.fetch=NN(r),this.namespace=s}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(e,n){return this.headers=Ue(Ue({},this.headers),{},{[e]:n}),this}async handleOperation(e){var n=this;try{return{data:await e(),error:null}}catch(r){if(n.shouldThrowOnError)throw r;if($f(r))return{data:null,error:r};throw r}}},$N=class{constructor(e,n){this.downloadFn=e,this.shouldThrowOnError=n}then(e,n){return this.execute().then(e,n)}async execute(){var e=this;try{return{data:(await e.downloadFn()).body,error:null}}catch(n){if(e.shouldThrowOnError)throw n;if($f(n))return{data:null,error:n};throw n}}};let b4;b4=Symbol.toStringTag;var MN=class{constructor(e,n){this.downloadFn=e,this.shouldThrowOnError=n,this[b4]="BlobDownloadBuilder",this.promise=null}asStream(){return new $N(this.downloadFn,this.shouldThrowOnError)}then(e,n){return this.getPromise().then(e,n)}catch(e){return this.getPromise().catch(e)}finally(e){return this.getPromise().finally(e)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){var e=this;try{return{data:await(await e.downloadFn()).blob(),error:null}}catch(n){if(e.shouldThrowOnError)throw n;if($f(n))return{data:null,error:n};throw n}}};const FN={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},H1={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};var BN=class extends pd{constructor(e,n={},r,s){super(e,n,s,"storage"),this.bucketId=r}async uploadOrUpdate(e,n,r,s){var i=this;return i.handleOperation(async()=>{let o;const a=Ue(Ue({},H1),s);let l=Ue(Ue({},i.headers),e==="POST"&&{"x-upsert":String(a.upsert)});const d=a.metadata;typeof Blob<"u"&&r instanceof Blob?(o=new FormData,o.append("cacheControl",a.cacheControl),d&&o.append("metadata",i.encodeMetadata(d)),o.append("",r)):typeof FormData<"u"&&r instanceof FormData?(o=r,o.has("cacheControl")||o.append("cacheControl",a.cacheControl),d&&!o.has("metadata")&&o.append("metadata",i.encodeMetadata(d))):(o=r,l["cache-control"]=`max-age=${a.cacheControl}`,l["content-type"]=a.contentType,d&&(l["x-metadata"]=i.toBase64(i.encodeMetadata(d))),(typeof ReadableStream<"u"&&o instanceof ReadableStream||o&&typeof o=="object"&&"pipe"in o&&typeof o.pipe=="function")&&!a.duplex&&(a.duplex="half")),s!=null&&s.headers&&(l=Ue(Ue({},l),s.headers));const c=i._removeEmptyFolders(n),f=i._getFinalPath(c),p=await(e=="PUT"?py:Yr)(i.fetch,`${i.url}/object/${f}`,o,Ue({headers:l},a!=null&&a.duplex?{duplex:a.duplex}:{}));return{path:c,id:p.Id,fullPath:p.Key}})}async upload(e,n,r){return this.uploadOrUpdate("POST",e,n,r)}async uploadToSignedUrl(e,n,r,s){var i=this;const o=i._removeEmptyFolders(e),a=i._getFinalPath(o),l=new URL(i.url+`/object/upload/sign/${a}`);return l.searchParams.set("token",n),i.handleOperation(async()=>{let d;const c=Ue(Ue({},H1),s),f=Ue(Ue({},i.headers),{"x-upsert":String(c.upsert)});return typeof Blob<"u"&&r instanceof Blob?(d=new FormData,d.append("cacheControl",c.cacheControl),d.append("",r)):typeof FormData<"u"&&r instanceof FormData?(d=r,d.append("cacheControl",c.cacheControl)):(d=r,f["cache-control"]=`max-age=${c.cacheControl}`,f["content-type"]=c.contentType),{path:o,fullPath:(await py(i.fetch,l.toString(),d,{headers:f})).Key}})}async createSignedUploadUrl(e,n){var r=this;return r.handleOperation(async()=>{let s=r._getFinalPath(e);const i=Ue({},r.headers);n!=null&&n.upsert&&(i["x-upsert"]="true");const o=await Yr(r.fetch,`${r.url}/object/upload/sign/${s}`,{},{headers:i}),a=new URL(r.url+o.url),l=a.searchParams.get("token");if(!l)throw new Wf("No token returned by API");return{signedUrl:a.toString(),path:e,token:l}})}async update(e,n,r){return this.uploadOrUpdate("PUT",e,n,r)}async move(e,n,r){var s=this;return s.handleOperation(async()=>await Yr(s.fetch,`${s.url}/object/move`,{bucketId:s.bucketId,sourceKey:e,destinationKey:n,destinationBucket:r==null?void 0:r.destinationBucket},{headers:s.headers}))}async copy(e,n,r){var s=this;return s.handleOperation(async()=>({path:(await Yr(s.fetch,`${s.url}/object/copy`,{bucketId:s.bucketId,sourceKey:e,destinationKey:n,destinationBucket:r==null?void 0:r.destinationBucket},{headers:s.headers})).Key}))}async createSignedUrl(e,n,r){var s=this;return s.handleOperation(async()=>{let i=s._getFinalPath(e);const o=typeof(r==null?void 0:r.transform)=="object"&&r.transform!==null&&Object.keys(r.transform).length>0;let a=await Yr(s.fetch,`${s.url}/object/sign/${i}
93`,Ue({expiresIn:n},o?{transform:r.transform}:{}),{headers:s.headers});const l=r!=null&&r.download?`&download=${r.download===!0?"":r.download}`:"",d=o&&a.signedURL.includes("/object/sign/")?a.signedURL.replace("/object/sign/","/render/image/sign/"):a.signedURL;return{signedUrl:encodeURI(`${s.url}${d}${l}`)}})}async createSignedUrls(e,n,r){var s=this;return s.handleOperation(async()=>{const i=await Yr(s.fetch,`${s.url}/object/sign/${s.bucketId}`,{expiresIn:n,paths:e},{headers:s.headers}),o=r!=null&&r.download?`&download=${r.download===!0?"":r.download}`:"";return i.map(a=>Ue(Ue({},a),{},{signedUrl:a.signedURL?encodeURI(`${s.url}${a.signedURL}${o}`):null}))})}download(e,n,r){const s=typeof(n==null?void 0:n.transform)<"u"?"render/image/authenticated":"object",i=this.transformOptsToQueryString((n==null?void 0:n.transform)||{}),o=i?`?${i}`:"",a=this._getFinalPath(e),l=()=>Vc(this.fetch,`${this.url}/${s}/${a}${o}`,{headers:this.headers,noResolveJson:!0},r);return new MN(l,this.shouldThrowOnError)}async info(e){var n=this;const r=n._getFinalPath(e);return n.handleOperation(async()=>uy(await Vc(n.fetch,`${n.url}/object/info/${r}`,{headers:n.headers})))}async exists(e){var n=this;const r=n._getFinalPath(e);try{return await WN(n.fetch,`${n.url}/object/${r}`,{headers:n.headers}),{data:!0,error:null}}catch(i){if(n.shouldThrowOnError)throw i;if($f(i)){var s;const o=i instanceof cy?i.status:i instanceof x4?(s=i.originalError)===null||s===void 0?void 0:s.status:void 0;if(o!==void 0&&[400,404].includes(o))return{data:!1,error:i}}throw i}}getPublicUrl(e,n){const r=this._getFinalPath(e),s=[],i=n!=null&&n.download?`download=${n.download===!0?"":n.download}`:"";i!==""&&s.push(i);const o=typeof(n==null?void 0:n.transform)<"u"?"render/image":"object",a=this.transformOptsToQueryString((n==null?void 0:n.transform)||{});a!==""&&s.push(a);let l=s.join("&");return l!==""&&(l=`?${l}`),{data:{publicUrl:encodeURI(`${this.url}/${o}/public/${r}${l}`)}}}async remove(e){var n=this;return n.handleOperation(async()=>await Xb(n.fetch,`${n.url}/object/${n.bucketId}`,{prefixes:e},{headers:n.headers}))}async list(e,n,r){var s=this;return s.handleOperation(async()=>{const i=Ue(Ue(Ue({},FN),n),{},{prefix:e||""});return await Yr(s.fetch,`${s.url}/object/list/${s.bucketId}`,i,{headers:s.headers},r)})}async listV2(e,n){var r=this;return r.handleOperation(async()=>{const s=Ue({},e);return await Yr(r.fetch,`${r.url}/object/list-v2/${r.bucketId}`,s,{headers:r.headers},n)})}encodeMetadata(e){return JSON.stringify(e)}toBase64(e){return typeof Buffer<"u"?Buffer.from(e).toString("base64"):btoa(e)}_getFinalPath(e){return`${this.bucketId}/${e.replace(/^\/+/,"")}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){const n=[];return e.width&&n.push(`width=${e.width}`),e.height&&n.push(`height=${e.height}`),e.resize&&n.push(`resize=${e.resize}`),e.format&&n.push(`format=${e.format}`),e.quality&&n.push(`quality=${e.quality}`),n.join("&")}};const UN="2.100.1",gu={"X-Client-Info":`storage-js/${UN}`};var HN=class extends pd{constructor(e,n={},r,s){const i=new URL(e);s!=null&&s.useNewHostname&&/supabase\.(co|in|red)$/.test(i.hostname)&&!i.hostname.includes("storage.supabase.")&&(i.hostname=i.hostname.replace("supabase.","storage.supabase."));const o=i.href.replace(/\/$/,""),a=Ue(Ue({},gu),n);super(o,a,r,"storage")}async listBuckets(e){var n=this;return n.handleOperation(async()=>{const r=n.listBucketOptionsToQueryString(e);return await Vc(n.fetch,`${n.url}/bucket${r}`,{headers:n.headers})})}async getBucket(e){var n=this;return n.handleOperation(async()=>await Vc(n.fetch,`${n.url}/bucket/${e}`,{headers:n.headers}))}async createBucket(e,n={public:!1}){var r=this;return r.handleOperation(async()=>await Yr(r.fetch,`${r.url}/bucket`,{id:e,name:e,type:n.type,public:n.public,file_size_limit:n.fileSizeLimit,allowed_mime_types:n.allowedMimeTypes},{headers:r.headers}))}async updateBucket(e,n){var r=this;return r.handleOperation(async()=>await py(r.fetch,`${r.url}/bucket/${e}`,{id:e,name:e,public:n.public,file_size_limit:n.fileSizeLimit,allowed_mime_types:n.allowedMimeTypes},{headers:r.headers}))}async emptyBucket(e){var n=this;return n.handleOperation(async()=>await Yr(n.fetch,`${n.url}/bucket/${e}/empty`,{},{headers:n.headers}))}async deleteBucket(e){var n=this;return n.handleOperation(async()=>await Xb(n.fetch,`${n.url}/bucket/${e}`,{},{headers:n.headers}))}listBucketOptionsToQueryString(e){const n={};return e&&("limit"in e&&(n.limit=String(e.limit)),"offset"in e&&(n.offset=String(e.offset)),e.search&&(n.search=e.search),e.sortColumn&&(n.sortColumn=e.sortColumn),e.sortOrder&&(n.sortOrder=e.sortOrder)),Object.keys(n).length>0?"?"+new URLSearchParams(n).toString():""}},VN=class extends pd{constructor(e,n={},r){const s=e.replace(/\/$/,""),i=Ue(Ue({},gu),n);super(s,i,r,"storage")}async createBucket(e){var n=this;return n.handleOperation(async()=>await Yr(n.fetch,`${n.url}/bucket`,{name:e},{headers:n.headers}))}async listBuckets(e){var n=this;return n.handleOperation(async()=>
93{const r=new URLSearchParams;(e==null?void 0:e.limit)!==void 0&&r.set("limit",e.limit.toString()),(e==null?void 0:e.offset)!==void 0&&r.set("offset",e.offset.toString()),e!=null&&e.sortColumn&&r.set("sortColumn",e.sortColumn),e!=null&&e.sortOrder&&r.set("sortOrder",e.sortOrder),e!=null&&e.search&&r.set("search",e.search);const s=r.toString(),i=s?`${n.url}/bucket?${s}`:`${n.url}/bucket`;return await Vc(n.fetch,i,{headers:n.headers})})}async deleteBucket(e){var n=this;return n.handleOperation(async()=>await Xb(n.fetch,`${n.url}/bucket/${e}`,{},{headers:n.headers}))}from(e){var n=this;if(!EN(e))throw new Wf("Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines and should avoid the use of any other characters.");const r=new zN({baseUrl:this.url,catalogName:e,auth:{type:"custom",getHeaders:async()=>n.headers},fetch:this.fetch}),s=this.shouldThrowOnError;return new Proxy(r,{get(i,o){const a=i[o];return typeof a!="function"?a:async(...l)=>{try{return{data:await a.apply(i,l),error:null}}catch(d){if(s)throw d;return{data:null,error:d}}}}})}},ZN=class extends pd{constructor(e,n={},r){const s=e.replace(/\/$/,""),i=Ue(Ue({},gu),{},{"Content-Type":"application/json"},n);super(s,i,r,"vectors")}async createIndex(e){var n=this;return n.handleOperation(async()=>await yr.post(n.fetch,`${n.url}/CreateIndex`,e,{headers:n.headers})||{})}async getIndex(e,n){var r=this;return r.handleOperation(async()=>await yr.post(r.fetch,`${r.url}/GetIndex`,{vectorBucketName:e,indexName:n},{headers:r.headers}))}async listIndexes(e){var n=this;return n.handleOperation(async()=>await yr.post(n.fetch,`${n.url}/ListIndexes`,e,{headers:n.headers}))}async deleteIndex(e,n){var r=this;return r.handleOperation(async()=>await yr.post(r.fetch,`${r.url}/DeleteIndex`,{vectorBucketName:e,indexName:n},{headers:r.headers})||{})}},KN=class extends pd{constructor(e,n={},r){const s=e.replace(/\/$/,""),i=Ue(Ue({},gu),{},{"Content-Type":"application/json"},n);super(s,i,r,"vectors")}async putVectors(e){var n=this;if(e.vectors.length<1||e.vectors.length>500)throw new Error("Vector batch size must be between 1 and 500 items");return n.handleOperation(async()=>await yr.post(n.fetch,`${n.url}/PutVectors`,e,{headers:n.headers})||{})}async getVectors(e){var n=this;return n.handleOperation(async()=>await yr.post(n.fetch,`${n.url}/GetVectors`,e,{headers:n.headers}))}async listVectors(e){var n=this;if(e.segmentCount!==void 0){if(e.segmentCount<1||e.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");if(e.segmentIndex!==void 0&&(e.segmentIndex<0||e.segmentIndex>=e.segmentCount))throw new Error(`segmentIndex must be between 0 and ${e.segmentCount-1}`)}return n.handleOperation(async()=>await yr.post(n.fetch,`${n.url}/ListVectors`,e,{headers:n.headers}))}async queryVectors(e){var n=this;return n.handleOperation(async()=>await yr.post(n.fetch,`${n.url}/QueryVectors`,e,{headers:n.headers}))}async deleteVectors(e){var n=this;if(e.keys.length<1||e.keys.length>500)throw new Error("Keys batch size must be between 1 and 500 items");return n.handleOperation(async()=>await yr.post(n.fetch,`${n.url}/DeleteVectors`,e,{headers:n.headers})||{})}},YN=class extends pd{constructor(e,n={},r){const s=e.replace(/\/$/,""),i=Ue(Ue({},gu),{},{"Content-Type":"application/json"},n);super(s,i,r,"vectors")}async createBucket(e){var n=this;return n.handleOperation(async()=>await yr.post(n.fetch,`${n.url}/CreateVectorBucket`,{vectorBucketName:e},{headers:n.headers})||{})}async getBucket(e){var n=this;return n.handleOperation(async()=>await yr.post(n.fetch,`${n.url}/GetVectorBucket`,{vectorBucketName:e},{headers:n.headers}))}async listBuckets(e={}){var n=this;return n.handleOperation(async()=>await yr.post(n.fetch,`${n.url}/ListVectorBuckets`,e,{headers:n.headers}))}async deleteBucket(e){var n=this;return n.handleOperation(async()=>await yr.post(n.fetch,`${n.url}/DeleteVectorBucket`,{vectorBucketName:e},{headers:n.headers})||{})}},XN=class extends YN{constructor(e,n={}){super(e,n.headers||{},n.fetch)}from(e){return new GN(this.url,this.headers,e,this.fetch)}async createBucket(e){var n=()=>super.createBucket,r=this;return n().call(r,e)}async getBucket(e){var n=()=>super.getBucket,r=this;return n().call(r,e)}async listBuckets(e={}){var n=()=>super.listBuckets,r=this;return n().call(r,e)}async deleteBucket(e){var n=()=>super.deleteBucket,r=this;return n().call(r,e)}},GN=class extends ZN{constructor(e,n,r,s){super(e,n,s),this.vectorBucketName=r}async createIndex(e){var n=()=>super.createIndex,r=this;return n().call(r,Ue(Ue({},e),{},{vectorBucketName:r.vectorBucketName}))}
93async listIndexes(e={}){var n=()=>super.listIndexes,r=this;return n().call(r,Ue(Ue({},e),{},{vectorBucketName:r.vectorBucketName}))}async getIndex(e){var n=()=>super.getIndex,r=this;return n().call(r,r.vectorBucketName,e)}async deleteIndex(e){var n=()=>super.deleteIndex,r=this;return n().call(r,r.vectorBucketName,e)}index(e){return new JN(this.url,this.headers,this.vectorBucketName,e,this.fetch)}},JN=class extends KN{constructor(e,n,r,s,i){super(e,n,i),this.vectorBucketName=r,this.indexName=s}async putVectors(e){var n=()=>super.putVectors,r=this;return n().call(r,Ue(Ue({},e),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async getVectors(e){var n=()=>super.getVectors,r=this;return n().call(r,Ue(Ue({},e),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async listVectors(e={}){var n=()=>super.listVectors,r=this;return n().call(r,Ue(Ue({},e),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async queryVectors(e){var n=()=>super.queryVectors,r=this;return n().call(r,Ue(Ue({},e),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async deleteVectors(e){var n=()=>super.deleteVectors,r=this;return n().call(r,Ue(Ue({},e),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}},QN=class extends HN{constructor(e,n={},r,s){super(e,n,r,s)}from(e){return new BN(this.url,this.headers,e,this.fetch)}get vectors(){return new XN(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new VN(this.url+"/iceberg",this.headers,this.fetch)}};const A4="2.100.1",Ya=30*1e3,hy=3,Ug=hy*Ya,e7="http://localhost:9999",t7="supabase.auth.token",n7={"X-Client-Info":`gotrue-js/${A4}`},fy="X-Supabase-Api-Version",v4={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},r7=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,s7=10*60*1e3;
93class Zc extends Error{constructor(n,r,s){super(n),this.__isAuthError=!0,this.name="AuthError",this.status=r,this.code=s}}function De(e){return typeof e=="object"&&e!==null&&"__isAuthError"in e}class i7 extends Zc{constructor(n,r,s){super(n,r,s),this.name="AuthApiError",this.status=r,this.code=s}}function o7(e){return De(e)&&e.name==="AuthApiError"}class Lo extends Zc{constructor(n,r){super(n),this.name="AuthUnknownError",this.originalError=r}}class ci extends Zc{constructor(n,r,s,i){super(n,s,i),this.name=r,this.status=s}}class gr extends ci{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function Hg(e){return De(e)&&e.name==="AuthSessionMissingError"}class Pa extends ci{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class Qu extends ci{constructor(n){super(n,"AuthInvalidCredentialsError",400,void 0)}}class ep extends ci{constructor(n,r=null){super(n,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=r}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}function a7(e){return De(e)&&e.name==="AuthImplicitGrantRedirectError"}class V1 extends ci{constructor(n,r=null){super(n,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=r}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class l7 extends ci{constructor(){super("PKCE code verifier not found in storage. This can happen if the auth flow was initiated in a different browser or device, or if the storage was cleared. For SSR frameworks (Next.js, SvelteKit, etc.), use @supabase/ssr on both the server and client to store the code verifier in cookies.","AuthPKCECodeVerifierMissingError",400,"pkce_code_verifier_not_found")}}class gy extends ci{constructor(n,r){super(n,"AuthRetryableFetchError",r,void 0)}}function Vg(e){return De(e)&&e.name==="AuthRetryableFetchError"}class Z1 extends ci{constructor(n,r,s){super(n,"AuthWeakPasswordError",r,"weak_password"),this.reasons=s}}class my extends ci{constructor(n){super(n,"AuthInvalidJwtError",400,"invalid_jwt")}}const Vh="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),K1=` 94\r=`.split(""),d7=(()=>{const e=new Array(128);for(let n=0;n<e.length;n+=1)e[n]=-1;for(let n=0;n<K1.length;n+=1)e[K1[n].charCodeAt(0)]=-2;for(let n=0;n<Vh.length;n+=1)e[Vh[n].charCodeAt(0)]=n;return e})();function Y1(e,n,r){if(e!==null)for(n.queue=n.queue<<8|e,n.queuedBits+=8;n.queuedBits>=6;){const s=n.queue>>n.queuedBits-6&63;r(Vh[s]),n.queuedBits-=6}else if(n.queuedBits>0)for(n.queue=n.queue<<6-n.queuedBits,n.queuedBits=6;n.queuedBits>=6;){const s=n.queue>>n.queuedBits-6&63;r(Vh[s]),n.queuedBits-=6}}function _4(e,n,r){const s=d7[e];if(s>-1)for(n.queue=n.queue<<6|s,n.queuedBits+=6;n.queuedBits>=8;)r(n.queue>>n.queuedBits-8&255),n.queuedBits-=8;else{if(s===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(e)}"`)}}function X1(e){const n=[],r=a=>{n.push(String.fromCodePoint(a))},s={utf8seq:0,codepoint:0},i={queue:0,queuedBits:0},o=a=>{p7(a,s,r)};for(let a=0;a<e.length;a+=1)_4(e.charCodeAt(a),i,o);return n.join("")}function c7(e,n){if(e<=127){n(e);return}else if(e<=2047){n(192|e>>6),n(128|e&63);return}else if(e<=65535){n(224|e>>12),n(128|e>>6&63),n(128|e&63);return}else if(e<=1114111){n(240|e>>18),n(128|e>>12&63),n(128|e>>6&63),n(128|e&63);return}throw new Error(`Unrecognized Unicode codepoint: ${e.toString(16)}`)}function u7(e,n){for(let r=0;r<e.length;r+=1){let s=e.charCodeAt(r);if(s>55295&&s<=56319){const i=(s-55296)*1024&65535;s=(e.charCodeAt(r+1)-56320&65535|i)+65536,r+=1}c7(s,n)}}function p7(e,n,r){if(n.utf8seq===0){if(e<=127){r(e);return}for(let s=1;s<6;s+=1)if(!(e>>7-s&1)){n.utf8seq=s;break}if(n.utf8seq===2)n.codepoint=e&31;else if(n.utf8seq===3)n.codepoint=e&15;else if(n.utf8seq===4)n.codepoint=e&7;else throw new Error("Invalid UTF-8 sequence");n.utf8seq-=1}else if(n.utf8seq>0){if(e<=127)throw new Error("Invalid UTF-8 sequence");n.codepoint=n.codepoint<<6|e&63,n.utf8seq-=1,n.utf8seq===0&&r(n.codepoint)}}function Sl(e){const n=[],r={queue:0,queuedBits:0},s=i=>{n.push(i)};for(let i=0;i<e.length;i+=1)_4(e.charCodeAt(i),r,s);return new Uint8Array(n)}function h7(e){const n=[];return u7(e,r=>n.push(r)),new Uint8Array(n)}function Ko(e){const n=[],r={queue:0,queuedBits:0},s=i=>{n.push(i)};return e.forEach(i=>
94Y1(i,r,s)),Y1(null,r,s),n.join("")}function f7(e){return Math.round(Date.now()/1e3)+e}function g7(){return Symbol("auth-callback")}const An=()=>typeof window<"u"&&typeof document<"u",yo={tested:!1,writable:!1},j4=()=>{if(!An())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(yo.tested)return yo.writable;const e=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(e,e),globalThis.localStorage.removeItem(e),yo.tested=!0,yo.writable=!0}catch{yo.tested=!0,yo.writable=!1}return yo.writable};function m7(e){const n={},r=new URL(e);if(r.hash&&r.hash[0]==="#")try{new URLSearchParams(r.hash.substring(1)).forEach((i,o)=>{n[o]=i})}catch{}return r.searchParams.forEach((s,i)=>{n[i]=s}),n}const w4=e=>e?(...n)=>e(...n):(...n)=>fetch(...n),x7=e=>typeof e=="object"&&e!==null&&"status"in e&&"ok"in e&&"json"in e&&typeof e.json=="function",Xa=async(e,n,r)=>{await e.setItem(n,JSON.stringify(r))},bo=async(e,n)=>{const r=await e.getItem(n);if(!r)return null;try{return JSON.parse(r)}catch{return r}},bn=async(e,n)=>{await e.removeItem(n)};class Mf{constructor(){this.promise=new Mf.promiseConstructor((n,r)=>{this.resolve=n,this.reject=r})}}Mf.promiseConstructor=Promise;function tp(e){const n=e.split(".");if(n.length!==3)throw new my("Invalid JWT structure");for(let s=0;s<n.length;s++)if(!r7.test(n[s]))throw new my("JWT not in base64url format");return{header:JSON.parse(X1(n[0])),payload:JSON.parse(X1(n[1])),signature:Sl(n[2]),raw:{header:n[0],payload:n[1]}}}async function y7(e){return await new Promise(n=>{setTimeout(()=>n(null),e)})}function b7(e,n){return new Promise((s,i)=>{(async()=>{for(let o=0;o<1/0;o++)try{const a=await e(o);if(!n(o,null,a)){s(a);return}}catch(a){if(!n(o,a)){i(a);return}}})()})}function A7(e){return("0"+e.toString(16)).substr(-2)}function v7(){const n=new Uint32Array(56);if(typeof crypto>"u"){const r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",s=r.length;let i="";for(let o=0;o<56;o++)i+=r.charAt(Math.floor(Math.random()*s));return i}return crypto.getRandomValues(n),Array.from(n,A7).join("")}async function _7(e){const r=new TextEncoder().encode(e),s=await crypto.subtle.digest("SHA-256",r),i=new Uint8Array(s);return Array.from(i).map(o=>String.fromCharCode(o)).join("")}async function j7(e){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."),e;const r=await _7(e);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function qa(e,n,r=!1){const s=v7();let i=s;r&&(i+="/PASSWORD_RECOVERY"),await Xa(e,`${n}-code-verifier`,i);const o=await j7(s);return[o,s===o?"plain":"s256"]}const w7=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function S7(e){const n=e.headers.get(fy);if(!n||!n.match(w7))return null;try{return new Date(`${n}T00:00:00.0Z`)}catch{return null}}function k7(e){if(!e)throw new Error("Missing exp claim");const n=Math.floor(Date.now()/1e3);if(e<=n)throw new Error("JWT has expired")}function C7(e){switch(e){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")}}const T7=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Da(e){if(!T7.test(e))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function Zg(){const e={};return new Proxy(e,{get:(n,r)=>{if(r==="__isUserNotAvailableProxy")return!0;if(typeof r=="symbol"){const s=r.toString();if(s==="Symbol(Symbol.toPrimitive)"||s==="Symbol(Symbol.toStringTag)"||s==="Symbol(util.inspect.custom)")return}throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${r}" property of the session object is not supported. Please use getUser() instead.`)},set:(n,r)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${r}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(n,r)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${r}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function z7(e,n){return new Proxy(e,{get:(r,s,i)=>{if(s==="__isInsecureUserWarningProxy")return!0;
94if(typeof s=="symbol"){const o=s.toString();if(o==="Symbol(Symbol.toPrimitive)"||o==="Symbol(Symbol.toStringTag)"||o==="Symbol(util.inspect.custom)"||o==="Symbol(nodejs.util.inspect.custom)")return Reflect.get(r,s,i)}return!n.value&&typeof s=="string"&&(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."),n.value=!0),Reflect.get(r,s,i)}})}function G1(e){return JSON.parse(JSON.stringify(e))}const Io=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),N7=[502,503,504];async function J1(e){var n;if(!x7(e))throw new gy(Io(e),0);if(N7.includes(e.status))throw new gy(Io(e),e.status);let r;try{r=await e.json()}catch(o){throw new Lo(Io(o),o)}let s;const i=S7(e);if(i&&i.getTime()>=v4["2024-01-01"].timestamp&&typeof r=="object"&&r&&typeof r.code=="string"?s=r.code:typeof r=="object"&&r&&typeof r.error_code=="string"&&(s=r.error_code),s){if(s==="weak_password")throw new Z1(Io(r),e.status,((n=r.weak_password)===null||n===void 0?void 0:n.reasons)||[]);if(s==="session_not_found")throw new gr}else if(typeof r=="object"&&r&&typeof r.weak_password=="object"&&r.weak_password&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.reasons.reduce((o,a)=>o&&typeof a=="string",!0))throw new Z1(Io(r),e.status,r.weak_password.reasons);throw new i7(Io(r),e.status||500,s)}const R7=(e,n,r,s)=>{const i={method:e,headers:(n==null?void 0:n.headers)||{}};return e==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},n==null?void 0:n.headers),i.body=JSON.stringify(s),Object.assign(Object.assign({},i),r))};async function Me(e,n,r,s){var i;const o=Object.assign({},s==null?void 0:s.headers);o[fy]||(o[fy]=v4["2024-01-01"].name),s!=null&&s.jwt&&(o.Authorization=`Bearer ${s.jwt}`);const a=(i=s==null?void 0:s.query)!==null&&i!==void 0?i:{};s!=null&&s.redirectTo&&(a.redirect_to=s.redirectTo);const l=Object.keys(a).length?"?"+new URLSearchParams(a).toString():"",d=await E7(e,n,r+l,{headers:o,noResolveJson:s==null?void 0:s.noResolveJson},{},s==null?void 0:s.body);return s!=null&&s.xform?s==null?void 0:s.xform(d):{data:Object.assign({},d),error:null}}async function E7(e,n,r,s,i,o){const a=R7(n,s,i,o);let l;try{l=await e(r,Object.assign({},a))}catch(d){throw console.error(d),new gy(Io(d),0)}if(l.ok||await J1(l),s!=null&&s.noResolveJson)return l;try{return await l.json()}catch(d){await J1(d)}}function Zr(e){var n;let r=null;D7(e)&&(r=Object.assign({},e),e.expires_at||(r.expires_at=f7(e.expires_in)));const s=(n=e.user)!==null&&n!==void 0?n:e;return{data:{session:r,user:s},error:null}}function Q1(e){const n=Zr(e);return!n.error&&e.weak_password&&typeof e.weak_password=="object"&&Array.isArray(e.weak_password.reasons)&&e.weak_password.reasons.length&&e.weak_password.message&&typeof e.weak_password.message=="string"&&e.weak_password.reasons.reduce((r,s)=>r&&typeof s=="string",!0)&&(n.data.weak_password=e.weak_password),n}function Ri(e){var n;return{data:{user:(n=e.user)!==null&&n!==void 0?n:e},error:null}}function P7(e){return{data:e,error:null}}function q7(e){const{action_link:n,email_otp:r,hashed_token:s,redirect_to:i,verification_type:o}=e,a=Lf(e,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),l={action_link:n,email_otp:r,hashed_token:s,redirect_to:i,verification_type:o},d=Object.assign({},a);return{data:{properties:l,user:d},error:null}}function ev(e){return e}function D7(e){return e.access_token&&e.refresh_token&&e.expires_in}const Kg=["global","local","others"];class O7{constructor({url:n="",headers:r={},fetch:s}){this.url=n,this.headers=r,this.fetch=w4(s),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)},this.customProviders={listProviders:this._listCustomProviders.bind(this),createProvider:this._createCustomProvider.bind(this),getProvider:this._getCustomProvider.bind(this),updateProvider:this._updateCustomProvider.bind(this),deleteProvider:this._deleteCustomProvider.bind(this)}}async signOut(n,r=Kg[0]){if(Kg.indexOf(r)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${Kg.join(", ")}`);try{return await Me(this.fetch,"POST",`${this.url}/logout?scope=${r}`,{headers:this.headers,jwt:n,noResolveJson:!0}),{data:null,error:null}}catch(s){if(De(s))return{data:null,error:s};throw s}}async inviteUserByEmail(n,r={}){try{return await Me(this.fetch,"POST",`${this.url}/invite`,{body:{email:n,data:r.data},headers:this.headers,redirectTo:r.redirectTo,xform:Ri})}catch(s){if(De(s))return{data:{user:null},error:s};throw s}}async generateLink(n){try{const{options:r}=n,s=Lf(n,["options"]),i=Object.assign(Object.assign({},s),r);return"newEmail"in s&&(i.new_email=s==null?void 0:s.newEmail,delete i.newEmail),await Me(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:i,headers:this.headers,xform:q7,redirectTo:r==null?void 0:r.redirectTo})}catch(r){if(De(r))return{data:{properties:null,user:null},error:r};throw r}}async createUser(n){try{return await Me(this.fetch,"POST",`${this.url}/admin/users`,{body:n,headers:this.headers,xform:Ri})}catch(r){if(De(r))return{data:{user:null},error:r};throw r}}async listUsers(n){var r,s,i,o,a,l,d;try{const c={nextPage:null,lastPage:0,total:0},f=await Me(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(s=(r=n==null?void 0:n.page)===null||r===void 0?void 0:r.toString())!==null&&s!==void 0?s:"",per_page:(o=(i=n==null?void 0:n.perPage)===null||i===void 0?void 0:i.toString())!==null&&o!==void 0?o:""},xform:ev});if(f.error)throw f.error;const p=await f.json(),u=(a=f.headers.get("x-total-count"))!==null&&a!==void 0?a:0,h=(d=(l=f.headers.get("link"))===null||l===void 0?void 0:l.split(","))!==null&&d!==void 0?d:[];return h.length>
940&&(h.forEach(y=>{const m=parseInt(y.split(";")[0].split("=")[1].substring(0,1)),b=JSON.parse(y.split(";")[1].split("=")[1]);c[`${b}Page`]=m}),c.total=parseInt(u)),{data:Object.assign(Object.assign({},p),c),error:null}}catch(c){if(De(c))return{data:{users:[]},error:c};throw c}}async getUserById(n){Da(n);try{return await Me(this.fetch,"GET",`${this.url}/admin/users/${n}`,{headers:this.headers,xform:Ri})}catch(r){if(De(r))return{data:{user:null},error:r};throw r}}async updateUserById(n,r){Da(n);try{return await Me(this.fetch,"PUT",`${this.url}/admin/users/${n}`,{body:r,headers:this.headers,xform:Ri})}catch(s){if(De(s))return{data:{user:null},error:s};throw s}}async deleteUser(n,r=!1){Da(n);try{return await Me(this.fetch,"DELETE",`${this.url}/admin/users/${n}`,{headers:this.headers,body:{should_soft_delete:r},xform:Ri})}catch(s){if(De(s))return{data:{user:null},error:s};throw s}}async _listFactors(n){Da(n.userId);try{const{data:r,error:s}=await Me(this.fetch,"GET",`${this.url}/admin/users/${n.userId}/factors`,{headers:this.headers,xform:i=>({data:{factors:i},error:null})});return{data:r,error:s}}catch(r){if(De(r))return{data:null,error:r};throw r}}async _deleteFactor(n){Da(n.userId),Da(n.id);try{return{data:await Me(this.fetch,"DELETE",`${this.url}/admin/users/${n.userId}/factors/${n.id}`,{headers:this.headers}),error:null}}catch(r){if(De(r))return{data:null,error:r};throw r}}async _listOAuthClients(n){var r,s,i,o,a,l,d;try{const c={nextPage:null,lastPage:0,total:0},f=await Me(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(s=(r=n==null?void 0:n.page)===null||r===void 0?void 0:r.toString())!==null&&s!==void 0?s:"",per_page:(o=(i=n==null?void 0:n.perPage)===null||i===void 0?void 0:i.toString())!==null&&o!==void 0?o:""},xform:ev});if(f.error)throw f.error;const p=await f.json(),u=(a=f.headers.get("x-total-count"))!==null&&a!==void 0?a:0,h=(d=(l=f.headers.get("link"))===null||l===void 0?void 0:l.split(","))!==null&&d!==void 0?d:[];return h.length>0&&(h.forEach(y=>{const m=parseInt(y.split(";")[0].split("=")[1].substring(0,1)),b=JSON.parse(y.split(";")[1].split("=")[1]);c[`${b}Page`]=m}),c.total=parseInt(u)),{data:Object.assign(Object.assign({},p),c),error:null}}catch(c){if(De(c))return{data:{clients:[]},error:c};throw c}}async _createOAuthClient(n){try{return await Me(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:n,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(De(r))return{data:null,error:r};throw r}}async _getOAuthClient(n){try{return await Me(this.fetch,"GET",`${this.url}/admin/oauth/clients/${n}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(De(r))return{data:null,error:r};throw r}}async _updateOAuthClient(n,r){try{return await Me(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${n}`,{body:r,headers:this.headers,xform:s=>({data:s,error:null})})}catch(s){if(De(s))return{data:null,error:s};throw s}}async _deleteOAuthClient(n){try{return await Me(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${n}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(De(r))return{data:null,error:r};throw r}}async _regenerateOAuthClientSecret(n){try{return await Me(this.fetch,"POST",`${this.url}/admin/oauth/clients/${n}/regenerate_secret`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(De(r))return{data:null,error:r};throw r}}async _listCustomProviders(n){try{const r={};return n!=null&&n.type&&(r.type=n.type),await Me(this.fetch,"GET",`${this.url}/admin/custom-providers`,{headers:this.headers,query:r,xform:s=>{var i;return{data:{providers:(i=s==null?void 0:s.providers)!==null&&i!==void 0?i:[]},error:null}}})}catch(r){if(De(r))return{data:{providers:[]},error:r};throw r}}async _createCustomProvider(n){try{return await Me(this.fetch,"POST",`${this.url}/admin/custom-providers`,{body:n,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(De(r))return{data:null,error:r};throw r}}async _getCustomProvider(n){try{return await Me(this.fetch,"GET",`${this.url}/admin/custom-providers/${n}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(De(r))return{data:null,error:r};throw r}}async _updateCustomProvider(n,r){try{return await Me(this.fetch,"PUT",`${this.url}/admin/custom-providers/${n}`,{body:r,headers:this.headers,xform:s=>({data:s,error:null})})}catch(s){if(De(s))return{data:null,error:s};throw s}}async _deleteCustomProvider(n){try{return await Me(this.fetch,"DELET
94E",`${this.url}/admin/custom-providers/${n}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(De(r))return{data:null,error:r};throw r}}}function tv(e={}){return{getItem:n=>e[n]||null,setItem:(n,r)=>{e[n]=r},removeItem:n=>{delete e[n]}}}const as={debug:!!(globalThis&&j4()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class S4 extends Error{constructor(n){super(n),this.isAcquireTimeout=!0}}class nv extends S4{}async function I7(e,n,r){as.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",e,n);const s=new globalThis.AbortController;let i;n>0&&(i=setTimeout(()=>{s.abort(),as.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",e)},n)),await Promise.resolve();try{return await globalThis.navigator.locks.request(e,n===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:s.signal},async o=>{if(o){clearTimeout(i),as.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",e,o.name);try{return await r()}finally{as.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",e,o.name)}}else{if(n===0)throw as.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",e),new nv(`Acquiring an exclusive Navigator LockManager lock "${e}" immediately failed`);if(as.debug)try{const a=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(a,null," "))}catch(a){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",a)}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"),clearTimeout(i),await r()}})}catch(o){if(n>0&&clearTimeout(i),(o==null?void 0:o.name)==="AbortError"&&n>0){if(s.signal.aborted)return as.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire timeout, recovering by stealing lock",e),console.warn(`@supabase/gotrue-js: Lock "${e}" was not released within ${n}ms. This may indicate an orphaned lock from a component unmount (e.g., React Strict Mode). Forcefully acquiring the lock to recover.`),await Promise.resolve().then(()=>globalThis.navigator.locks.request(e,{mode:"exclusive",steal:!0},async a=>{if(a){as.debug&&console.log("@supabase/gotrue-js: navigatorLock: recovered (stolen)",e,a.name);try{return await r()}finally{as.debug&&console.log("@supabase/gotrue-js: navigatorLock: released (stolen)",e,a.name)}}else return console.warn("@supabase/gotrue-js: Navigator LockManager returned null lock even with steal: true"),await r()}));throw as.debug&&console.log("@supabase/gotrue-js: navigatorLock: lock was stolen by another request",e),new nv(`Lock "${e}" was released because another request stole it`)}throw o}}function L7(){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)}}function k4(e){if(!/^0x[a-fA-F0-9]{40}$/.test(e))throw new Error(`@supabase/auth-js: Address "${e}" is invalid.`);return e.toLowerCase()}function W7(e){return parseInt(e,16)}function $7(e){const n=new TextEncoder().encode(e);return"0x"+Array.from(n,s=>s.toString(16).padStart(2,"0")).join("")}function M7(e){var n;const{chainId:r,domain:s,expirationTime:i,issuedAt:o=new Date,nonce:a,notBefore:l,requestId:d,resources:c,scheme:f,uri:p,version:u}=e;{if(!Number.isInteger(r))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${r}`);if(!s)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(a&&a.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${a}`);if(!p)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(u!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${u}`);if(!((n=e.statement)===null||n===void 0)&&n.includes(` 95`))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${e.statement}`)}const h=k4(e.address),y=f?`${f}://${s}`:s,m=e.statement?`${e.statement} 96`:"",b=`${y}
96 wants you to sign in with your Ethereum account: 97${h} 98 99${m}`;let A=`URI: ${p} 100Version: ${u} 101Chain ID: ${r}${a?` 102Nonce: ${a}`:""} 103Issued At: ${o.toISOString()}`;if(i&&(A+=` 104Expiration Time: ${i.toISOString()}`),l&&(A+=` 105Not Before: ${l.toISOString()}`),d&&(A+=` 106Request ID: ${d}`),c){let v=` 107Resources:`;for(const x of c){if(!x||typeof x!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${x}`);v+=` 108- ${x}`}A+=v}return`${b} 109${A}`}class en extends Error{constructor({message:n,code:r,cause:s,name:i}){var o;super(n,{cause:s}),this.__isWebAuthnError=!0,this.name=(o=i??(s instanceof Error?s.name:void 0))!==null&&o!==void 0?o:"Unknown Error",this.code=r}}class Zh extends en{constructor(n,r){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r,message:n}),this.name="WebAuthnUnknownError",this.originalError=r}}function F7({error:e,options:n}){var r,s,i;const{publicKey:o}=n;if(!o)throw Error("options was missing required publicKey property");if(e.name==="AbortError"){if(n.signal instanceof AbortSignal)return new en({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else if(e.name==="ConstraintError"){if(((r=o.authenticatorSelection)===null||r===void 0?void 0:r.requireResidentKey)===!0)return new en({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:e});if(n.mediation==="conditional"&&((s=o.authenticatorSelection)===null||s===void 0?void 0:s.userVerification)==="required")return new en({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:e});if(((i=o.authenticatorSelection)===null||i===void 0?void 0:i.userVerification)==="required")return new en({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:e})}else{if(e.name==="InvalidStateError")return new en({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:e});if(e.name==="NotAllowedError")return new en({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if(e.name==="NotSupportedError")return o.pubKeyCredParams.filter(l=>l.type==="public-key").length===0?new en({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:e}):new en({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:e});if(e.name==="SecurityError"){const a=window.location.hostname;if(C4(a)){if(o.rp.id!==a)return new en({message:`The RP ID "${o.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else return new en({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e})}else if(e.name==="TypeError"){if(o.user.id.byteLength<1||o.user.id.byteLength>64)return new en({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:e})}else if(e.name==="UnknownError")return new en({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return new en({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}function B7({error:e,options:n}){const{publicKey:r}=n;if(!r)throw Error("options was missing required publicKey property");if(e.name==="AbortError"){if(n.signal instanceof AbortSignal)return new en({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else{if(e.name==="NotAllowedError")return new en({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if(e.name==="SecurityError"){const s=window.location.hostname;
109if(C4(s)){if(r.rpId!==s)return new en({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else return new en({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e})}else if(e.name==="UnknownError")return new en({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return new en({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}class U7{createNewAbortSignal(){if(this.controller){const r=new Error("Cancelling existing WebAuthn API call for new one");r.name="AbortError",this.controller.abort(r)}const n=new AbortController;return this.controller=n,n.signal}cancelCeremony(){if(this.controller){const n=new Error("Manually cancelling existing WebAuthn API call");n.name="AbortError",this.controller.abort(n),this.controller=void 0}}}const H7=new U7;function V7(e){if(!e)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(e);const{challenge:n,user:r,excludeCredentials:s}=e,i=Lf(e,["challenge","user","excludeCredentials"]),o=Sl(n).buffer,a=Object.assign(Object.assign({},r),{id:Sl(r.id).buffer}),l=Object.assign(Object.assign({},i),{challenge:o,user:a});if(s&&s.length>0){l.excludeCredentials=new Array(s.length);for(let d=0;d<s.length;d++){const c=s[d];l.excludeCredentials[d]=Object.assign(Object.assign({},c),{id:Sl(c.id).buffer,type:c.type||"public-key",transports:c.transports})}}return l}function Z7(e){if(!e)throw new Error("Credential request options are required");if(typeof PublicKeyCredential<"u"&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseRequestOptionsFromJSON=="function")return PublicKeyCredential.parseRequestOptionsFromJSON(e);const{challenge:n,allowCredentials:r}=e,s=Lf(e,["challenge","allowCredentials"]),i=Sl(n).buffer,o=Object.assign(Object.assign({},s),{challenge:i});if(r&&r.length>0){o.allowCredentials=new Array(r.length);for(let a=0;a<r.length;a++){const l=r[a];o.allowCredentials[a]=Object.assign(Object.assign({},l),{id:Sl(l.id).buffer,type:l.type||"public-key",transports:l.transports})}}return o}function K7(e){var n;if("toJSON"in e&&typeof e.toJSON=="function")return e.toJSON();const r=e;return{id:e.id,rawId:e.id,response:{attestationObject:Ko(new Uint8Array(e.response.attestationObject)),clientDataJSON:Ko(new Uint8Array(e.response.clientDataJSON))},type:"public-key",clientExtensionResults:e.getClientExtensionResults(),authenticatorAttachment:(n=r.authenticatorAttachment)!==null&&n!==void 0?n:void 0}}function Y7(e){var n;if("toJSON"in e&&typeof e.toJSON=="function")return e.toJSON();const r=e,s=e.getClientExtensionResults(),i=e.response;return{id:e.id,rawId:e.id,response:{authenticatorData:Ko(new Uint8Array(i.authenticatorData)),clientDataJSON:Ko(new Uint8Array(i.clientDataJSON)),signature:Ko(new Uint8Array(i.signature)),userHandle:i.userHandle?Ko(new Uint8Array(i.userHandle)):void 0},type:"public-key",clientExtensionResults:s,authenticatorAttachment:(n=r.authenticatorAttachment)!==null&&n!==void 0?n:void 0}}function C4(e){return e==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(e)}function rv(){var e,n;return!!(An()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&typeof((e=navigator==null?void 0:navigator.credentials)===null||e===void 0?void 0:e.create)=="function"&&typeof((n=navigator==null?void 0:navigator.credentials)===null||n===void 0?void 0:n.get)=="function")}async function X7(e){try{const n=await navigator.credentials.create(e);return n?n instanceof PublicKeyCredential?{data:n,error:null}:{data:null,error:new Zh("Browser returned unexpected credential type",n)}:{data:null,error:new Zh("Empty credential response",n)}}catch(n){return{data:null,error:F7({error:n,options:e})}}}async function G7(e){try{const n=await navigator.credentials.get(e);return n?n instanceof PublicKeyCredential?{data:n,error:null}:{data:null,error:new Zh("Browser returned unexpected credential type",n)}:{data:null,error:new Zh("Empty credential response",n)}}catch(n){return{data:null,error:B7({error:n,options:e})}}}const J7={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},Q7={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function Kh(...e){const n=i=>i!==null&&typeof i=="object"&&!Array.isArray(i),r=i=>i instanceof ArrayBuffer||ArrayBuffer.isView(i),s={};for(const i of e)if(i)for(const o in i){const a=i[o];if(a!==void 0)if(Array.isArray(a))s[o]=a;
109else if(r(a))s[o]=a;else if(n(a)){const l=s[o];n(l)?s[o]=Kh(l,a):s[o]=Kh(a)}else s[o]=a}return s}function eR(e,n){return Kh(J7,e,n||{})}function tR(e,n){return Kh(Q7,e,n||{})}class nR{constructor(n){this.client=n,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}async _enroll(n){return this.client.mfa.enroll(Object.assign(Object.assign({},n),{factorType:"webauthn"}))}async _challenge({factorId:n,webauthn:r,friendlyName:s,signal:i},o){var a;try{const{data:l,error:d}=await this.client.mfa.challenge({factorId:n,webauthn:r});if(!l)return{data:null,error:d};const c=i??H7.createNewAbortSignal();if(l.webauthn.type==="create"){const{user:f}=l.webauthn.credential_options.publicKey;if(!f.name){const p=s;if(p)f.name=`${f.id}:${p}`;else{const h=(await this.client.getUser()).data.user,y=((a=h==null?void 0:h.user_metadata)===null||a===void 0?void 0:a.name)||(h==null?void 0:h.email)||(h==null?void 0:h.id)||"User";f.name=`${f.id}:${y}`}}f.displayName||(f.displayName=f.name)}switch(l.webauthn.type){case"create":{const f=eR(l.webauthn.credential_options.publicKey,o==null?void 0:o.create),{data:p,error:u}=await X7({publicKey:f,signal:c});return p?{data:{factorId:n,challengeId:l.id,webauthn:{type:l.webauthn.type,credential_response:p}},error:null}:{data:null,error:u}}case"request":{const f=tR(l.webauthn.credential_options.publicKey,o==null?void 0:o.request),{data:p,error:u}=await G7(Object.assign(Object.assign({},l.webauthn.credential_options),{publicKey:f,signal:c}));return p?{data:{factorId:n,challengeId:l.id,webauthn:{type:l.webauthn.type,credential_response:p}},error:null}:{data:null,error:u}}}}catch(l){return De(l)?{data:null,error:l}:{data:null,error:new Lo("Unexpected error in challenge",l)}}}async _verify({challengeId:n,factorId:r,webauthn:s}){return this.client.mfa.verify({factorId:r,challengeId:n,webauthn:s})}async _authenticate({factorId:n,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:s=typeof window<"u"?[window.location.origin]:void 0,signal:i}={}},o){if(!r)return{data:null,error:new Zc("rpId is required for WebAuthn authentication")};try{if(!rv())return{data:null,error:new Lo("Browser does not support WebAuthn",null)};const{data:a,error:l}=await this.challenge({factorId:n,webauthn:{rpId:r,rpOrigins:s},signal:i},{request:o});if(!a)return{data:null,error:l};const{webauthn:d}=a;return this._verify({factorId:n,challengeId:a.challengeId,webauthn:{type:d.type,rpId:r,rpOrigins:s,credential_response:d.credential_response}})}catch(a){return De(a)?{data:null,error:a}:{data:null,error:new Lo("Unexpected error in authenticate",a)}}}async _register({friendlyName:n,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:s=typeof window<"u"?[window.location.origin]:void 0,signal:i}={}},o){if(!r)return{data:null,error:new Zc("rpId is required for WebAuthn registration")};try{if(!rv())return{data:null,error:new Lo("Browser does not support WebAuthn",null)};const{data:a,error:l}=await this._enroll({friendlyName:n});if(!a)return await this.client.mfa.listFactors().then(f=>{var p;return(p=f.data)===null||p===void 0?void 0:p.all.find(u=>u.factor_type==="webauthn"&&u.friendly_name===n&&u.status!=="unverified")}).then(f=>f?this.client.mfa.unenroll({factorId:f==null?void 0:f.id}):void 0),{data:null,error:l};const{data:d,error:c}=await this._challenge({factorId:a.id,friendlyName:a.friendly_name,webauthn:{rpId:r,rpOrigins:s},signal:i},{create:o});return d?this._verify({factorId:a.id,challengeId:d.challengeId,webauthn:{rpId:r,rpOrigins:s,type:d.webauthn.type,credential_response:d.webauthn.credential_response}}):{data:null,error:c}}catch(a){return De(a)?{data:null,error:a}:{data:null,error:new Lo("Unexpected error in register",a)}}}}L7();const rR={url:e7,storageKey:t7,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:n7,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1};async function sv(e,n,r){return await r()}const Oa={};class Kc{get jwks(){var n,r;return(r=(n=Oa[this.storageKey])===null||n===void 0?void 0:n.jwks)!==null&&r!==void 0?r:{keys:[]}}set jwks(n){Oa[this.storageKey]=Object.assign(Object.assign({},Oa[this.storageKey]),{jwks:n})}get jwks_cached_at(){var n,r;return(r=(n=Oa[this.storageKey])===null||n===void 0?void 0:n.cachedAt)!==null&&r!==void 0?r:Number.MIN_SAFE_INTEGER}set jwks_cached_at(n){Oa[this.storageKey]=Object.assign(Object.assign({},Oa[this.storageKey]),{cachedAt:n})}constructor(n){var r,s,i;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=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;const o=Object.assign(Object.assign({},rR),n);if(this.storageKey=o.storageKey,this.instanceID=(r=Kc.nextInstanceID[this.storageKey])!==null&&r!==void 0?r:0,Kc.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!o.debug,typeof o.debug=="function"&&(this.logger=o.debug),this.instanceID>0&&An()){const a=`${this._logPrefix()} 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.`;console.warn(a),this.logDebugMessages&&console.trace(a)}if(this.persistSession=o.persistSession,this.autoRefreshToken=o.autoRefreshToken,this.admin=new O7({url:o.url,headers:o.headers,fetch:o.fetch}),this.url=o.url,this.headers=o.headers,this.fetch=w4(o.fetch),this.lock=o.lock||sv,this.detectSessionInUrl=o.detectSessionInUrl,this.flowType=o.flowType,this.hasCustomAuthorizationHeader=o.hasCustomAuthorizationHeader,this.throwOnError=o.throwOnError,this.lockAcquireTimeout=o.lockAcquireTimeout,o.lock?this.lock=o.lock:this.persistSession&&An()&&(!((s=globalThis==null?void 0:globalThis.navigator)===null||s===void 0)&&s.locks)?this.lock=I7:this.lock=sv,this.jwks||(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),webauthn:new nR(this)}
109,this.oauth={getAuthorizationDetails:this._getAuthorizationDetails.bind(this),approveAuthorization:this._approveAuthorization.bind(this),denyAuthorization:this._denyAuthorization.bind(this),listGrants:this._listOAuthGrants.bind(this),revokeGrant:this._revokeOAuthGrant.bind(this)},this.persistSession?(o.storage?this.storage=o.storage:j4()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=tv(this.memoryStorage)),o.userStorage&&(this.userStorage=o.userStorage)):(this.memoryStorage={},this.storage=tv(this.memoryStorage)),An()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(a){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",a)}(i=this.broadcastChannel)===null||i===void 0||i.addEventListener("message",async a=>{this._debug("received broadcast notification from other tab or client",a);try{await this._notifyAllSubscribers(a.data.event,a.data.session,!1)}catch(l){this._debug("#broadcastChannel","error",l)}})}o.skipAutoInitialize||this.initialize().catch(a=>{this._debug("#initialize()","error",a)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(n){if(this.throwOnError&&n&&n.error)throw n.error;return n}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${A4}) ${new Date().toISOString()}`}_debug(...n){return this.logDebugMessages&&this.logger(this._logPrefix(),...n),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){var n;try{let r={},s="none";if(An()&&(r=m7(window.location.href),this._isImplicitGrantCallback(r)?s="implicit":await this._isPKCECallback(r)&&(s="pkce")),An()&&this.detectSessionInUrl&&s!=="none"){const{data:i,error:o}=await this._getSessionFromURL(r,s);if(o){if(this._debug("#_initialize()","error detecting session from URL",o),a7(o)){const d=(n=o.details)===null||n===void 0?void 0:n.code;if(d==="identity_already_exists"||d==="identity_not_found"||d==="single_identity_not_deletable")return{error:o}}return{error:o}}const{session:a,redirectType:l}=i;return this._debug("#_initialize()","detected session in URL",a,"redirect type",l),await this._saveSession(a),setTimeout(async()=>{l==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",a):await this._notifyAllSubscribers("SIGNED_IN",a)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(r){return De(r)?this._returnResult({error:r}):this._returnResult({error:new Lo("Unexpected error during initialization",r)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(n){var r,s,i;try{const o=await Me(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(s=(r=n==null?void 0:n.options)===null||r===void 0?void 0:r.data)!==null&&s!==void 0?s:{},gotrue_meta_security:{captcha_token:(i=n==null?void 0:n.options)===null||i===void 0?void 0:i.captchaToken}},xform:Zr}),{data:a,error:l}=o;if(l||!a)return this._returnResult({data:{user:null,session:null},error:l});const d=a.session,c=a.user;return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",d)),this._returnResult({data:{user:c,session:d},error:null})}catch(o){if(De(o))return this._returnResult({data:{user:null,session:null},error:o});throw o}}async signUp(n){var r,s,i;try{let o;if("email"in n){const{email:f,password:p,options:u}=n;let h=null,y=null;this.flowType==="pkce"&&([h,y]=await qa(this.storage,this.storageKey)),o=await Me(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:u==null?void 0:u.emailRedirectTo,body:{email:f,password:p,data:(r=u==null?void 0:u.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:u==null?void 0:u.captchaToken},code_challenge:h,code_challenge_method:y},xform:Zr})}else if("phone"in n){const{phone:f,password:p,options:u}=n;o=await Me(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:f,password:p,data:(s=u==null?void 0:u.data)!==null&&s!==void 0?s:{},channel:(i=u==null?void 0:u.channel)!==null&&i!==void 0?i:"sms",gotrue_meta_security:{captcha_token:u==null?void 0:u.captchaToken}},xform:Zr})}else throw new Qu("You must provide either an email or phone number and a password");const{data:a,error:l}=o;if(l||!a)return await bn(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:l});const d=a.session,c=a.user;return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",d)),this._returnResult({data:{user:c,session:d},error:null})}catch(o){if(await bn(this.storage,`${this.storageKey}-code-verifier`),De(o))return this._returnResult({data:{user:null,session:null},error:o});throw o}}async signInWithPassword(n){try{let r;if("email"in n){const{email:o,password:a,options:l}=n;r=await Me(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:o,password:a,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken}},xform:Q1})}else if("phone"in n){const{phone:o,password:a,options:l}=n;r=await Me(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:o,password:a,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken}},xform:Q1})}else throw new Qu("You must provide either an email or phone number and a password");const{data:s,error:i}=r;if(i)return this._returnResult({data:{user:null,session:null},error:i});if(!s||!s.session||!s.user){const o=new Pa;return this._returnResult({data:{user:null,session:null},error:o})}return s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),this._returnResult({data:Object.assign({user:s.user,session:s.session},s.weak_password?{weakPassword:s.weak_password}:null),error:i})}catch(r){if(De(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOAuth(n){var r,s,i,o;return await this._handleProviderSignIn(n.provider,{redirectTo:(r=n.options)===null||r===void 0?void 0:r.redirectTo,scopes:(s=n.options)===null||s===void 0?void 0:s.scopes,queryParams:(i=n.options)===null||i===void 0?void 0:i.queryParams,skipBrowserRedirect:(o=n.options)===null||o===void 0?void 0:o.skipBrowserRedirect})}async exchangeCodeForSession(n){return await this.initializePromise,this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(n))}async signInWithWeb3(n){const{chain:r}=n;switch(r){case"ethereum":return await this.signInWithEthereum(n);case"solana":return await this.signInWithSolana(n);default:throw new Error(`@supabase/auth-js: Unsupported chain "${r}"`)}}async signInWithEthereum(n){var r,s,i,o,a,l,d,c,f,p,u;let h,y;if("message"in n)h=n.message,y=n.signature;else{const{chain:m,wallet:b,statement:A,options:v}=n;let x;if(An())if(typeof b=="object")x=b;else{const L=window;if("ethereum"in L&&typeof L.ethereum=="object"&&"request"in L.ethereum&&typeof L.ethereum.request=="function")x=L.ethereum;else throw new Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.")}else{if(typeof b!="object"||!(v!=null&&v.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");x=b}const _=new URL((r=v==null?void 0:v.url)!==null&&r!==void 0?r:window.location.href),j=await x.request({method:"eth_requestAccounts"}).then(L=>L).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!j||j.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");const C=k4(j[0]);let S=(s=v==null?void 0:v.signInWithEthereum)===null||s===void 0?void 0:s.chainId;if(!S){const L=await x.request({method:"eth_chainId"});S=W7(L)}const T={domain:_.host,address:C,statement:A,uri:_.href,version:"1",chainId:S,nonce:(i=v==null?void 0:v.signInWithEthereum)===null||i===void 0?void 0:i.nonce,issuedAt:(a=(o=v==null?void 0:v.signInWithEthereum)===null||o===void 0?void 0:o.issuedAt)!==null&&a!==void 0?a:new Date,expirationTime:(l=v==null?void 0:v.signInWithEthereum)===null||l===void 0?void 0:l.expirationTime,notBefore:(d=v==null?void 0:v.signInWithEthereum)===null||d===void 0?void 0:d.notBefore,requestId:(c=v==null?void 0:v.signInWithEthereum)===null||c===void 0?void 0:c.requestId,resources:(f=v==null?void 0:v.signInWithEthereum)===null||f===void 0?void 0:f.resources};h=M7(T),y=await x.request({method:"personal_sign",params:[$7(h),C]})}try{const{data:m,error:b}=await Me(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:h,signature:y},!((p=n.options)===null||p===void 0)&&p.captchaToken?{gotrue_meta_security:{captcha_token:(u=n.options)===null||u===void 0?void 0:u.captchaToken}}:null),xform:Zr});if(b)throw b;if(!m||!m.session||!m.user){const A=new Pa;return this._returnResult({data:{user:null,session:null},error:A})}return m.session&&(await this._saveSession(m.session),await this._notifyAllSubscribers("SIGNED_IN",m.session)),this._returnResult({data:Object.assign({},m),error:b})}catch(m){if(De(m))return this._returnResult({data:{user:null,session:null},error:m});throw m}}async signInWithSolana(n){var r,s,i,o,a,l,d,c,f,p,u,h;let y,m;if("message"in n)y=n.message,m=n.signature;else{const{chain:b,wallet:A,statement:v,options:x}=n;let _;if(An())if(typeof A=="object")_=A;else{const C=window;if("solana"in C&&typeof C.solana=="object"&&("signIn"in C.solana&&typeof C.solana.signIn=="function"||"signMessage"in C.solana&&typeof C.solana.signMessage=="function"))_=C.solana;else throw new Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.")}else{if(typeof A!="object"||!(x!=null&&x.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");_=A}const j=new URL((r=x==null?void 0:x.url)!==null&&r!==void 0?r:window.location.href);if("signIn"in _&&_.signIn){const C=await _.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},x==null?void 0:x.signInWithSolana),{version:"1",domain:j.host,uri:j.href}),v?{statement:v}:null));let S;if(Array.isArray(C)&&C[0]&&typeof C[0]=="object")S=C[0];else if(C&&typeof C=="object"&&"signedMessage"in C&&"signature"in C)S=C;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in S&&"signature"in S&&(typeof S.signedMessage=="string"||S.signedMessage instanceof Uint8Array)&&S.signature instanceof Uint8Array)y=typeof S.signedMessage=="string"?S.signedMessage:new TextDecoder().decode(S.signedMessage),m=S.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in _)||typeof _.signMessage!="function"||!("publicKey"in _)||typeof _!="object"||!_.publicKey||!("toBase58"in _.publicKey)||typeof _.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");y=[`${j.host} wants you to sign in with your Solana account:`,_.publicKey.toBase58(),...v?["",v,""]:[""],"Version: 1",`URI: ${j.href}`,`Issued At: ${(i=(s=x==null?void 0:x.signInWithSolana)===null||s===void 0?void 0:s.issuedAt)!==null&&i!==void 0?i:new Date().toISOString()}`,...!((o=x==null?void 0:x.signInWithSolana)===null||o===void 0)&&o.notBefore?[`Not Before: ${x.signInWithSolana.notBefore}`]:[],...!((a=x==null?void 0:x.signInWithSolana)===null||a===void 0)&&a.expirationTime?[`Expiration Time: ${x.signInWithSolana.expirationTime}`]:[],...!((l=x==null?void 0:x.signInWithSolana)===null||l===void 0)&&l.chainId?[`Chain ID: ${x.signInWithSolana.chainId}`]:[],...!((d=x==null?void 0:x.signInWithSolana)===null||d===void 0)&&d.nonce?[`Nonce: ${x.signInWithSolana.nonce}`]:[],...!((c=x==null?void 0:x.signInWithSolana)===null||c===void 0)&&c.requestId?[`Request ID: ${x.signInWithSolana.requestId}`]:[],...!((p=(f=x==null?void 0:x.signInWithSolana)===null||f===void 0?void 0:f.resources)===null||p===void 0)&&p.length?["Resources",...x.signInWithSolana.resources.map(S=>`- ${S}`)]:[]].join(` 110`);const C=await _.signMessage(new TextEncoder().encode(y),"utf8");if(!C||!(C instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");m=C}}try{const{data:b,error:A}=await Me(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:y,signature:Ko(m)},!((u=n.options)===null||u===void 0)&&u.captchaToken?{gotrue_meta_security:{captcha_token:(h=n.options)===null||h===void 0?void 0:h.captchaToken}}:null),xform:Zr});if(A)throw A;if(!b||!b.session||!b.user){const v=new Pa;return this._returnResult({data:{user:null,session:null},error:v})}return b.session&&(await this._saveSession(b.session),await this._notifyAllSubscribers("SIGNED_IN",b.session)),this._returnResult({data:Object.assign({},b),error:A})}catch(b){if(De(b))return this._returnResult({data:{user:null,session:null},error:b});throw b}}async _exchangeCodeForSession(n){const r=await bo(this.storage,`${this.storageKey}-code-verifier`),[s,i]=(r??"").split("/");try{if(!s&&this.flowType==="pkce")throw new l7;const{data:o,error:a}=await Me(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:n,code_verifier:s},xform:Zr});if(await bn(this.storage,`${this.storageKey}-code-verifier`),a)throw a;if(!o||!o.session||!o.user){const l=new Pa;return this._returnResult({data:{user:null,session:null,redirectType:null},error:l})}return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",o.session)),this._returnResult({data:Object.assign(Object.assign({},o),{redirectType:i??null}),error:a})}catch(o){if(await bn(this.storage,`${this.storageKey}-code-verifier`),De(o))return this._returnResult({data:{user:null,session:null,redirectType:null},error:o});throw o}}async signInWithIdToken(n){try{const{options:r,provider:s,token:i,access_token:o,nonce:a}=n,l=await Me(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:s,id_token:i,access_token:o,nonce:a,gotrue_meta_security:{captcha_token:r==null?void 0:r.captchaToken}},xform:Zr}),{data:d,error:c}=l;if(c)return this._returnResult({data:{user:null,session:null},error:c});if(!d||!d.session||!d.user){const f=new Pa;return this._returnResult({data:{user:null,session:null},error:f})}return d.session&&(await this._saveSession(d.session),await this._notifyAllSubscribers("SIGNED_IN",d.session)),this._returnResult({data:d,error:c})}catch(r){if(De(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOtp(n){var r,s,i,o,a;try{if("email"in n){const{email:l,options:d}=n;let c=null,f=null;this.flowType==="pkce"&&([c,f]=await qa(this.storage,this.storageKey));const{error:p}=await Me(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:l,data:(r=d==null?void 0:d.data)!==null&&r!==void 0?r:{},create_user:(s=d==null?void 0:d.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:d==null?void 0:d.captchaToken},code_challenge:c,code_challenge_method:f},redirectTo:d==null?void 0:d.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:p})}if("phone"in n){const{phone:l,options:d}=n,{data:c,error:f}=await Me(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:l,data:(i=d==null?void 0:d.data)!==null&&i!==void 0?i:{},create_user:(o=d==null?void 0:d.shouldCreateUser)!==null&&o!==void 0?o:!0,gotrue_meta_security:{captcha_
110token:d==null?void 0:d.captchaToken},channel:(a=d==null?void 0:d.channel)!==null&&a!==void 0?a:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:c==null?void 0:c.message_id},error:f})}throw new Qu("You must provide either an email or phone number.")}catch(l){if(await bn(this.storage,`${this.storageKey}-code-verifier`),De(l))return this._returnResult({data:{user:null,session:null},error:l});throw l}}async verifyOtp(n){var r,s;try{let i,o;"options"in n&&(i=(r=n.options)===null||r===void 0?void 0:r.redirectTo,o=(s=n.options)===null||s===void 0?void 0:s.captchaToken);const{data:a,error:l}=await Me(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},n),{gotrue_meta_security:{captcha_token:o}}),redirectTo:i,xform:Zr});if(l)throw l;if(!a)throw new Error("An error occurred on token verification.");const d=a.session,c=a.user;return d!=null&&d.access_token&&(await this._saveSession(d),await this._notifyAllSubscribers(n.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",d)),this._returnResult({data:{user:c,session:d},error:null})}catch(i){if(De(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signInWithSSO(n){var r,s,i,o,a;try{let l=null,d=null;this.flowType==="pkce"&&([l,d]=await qa(this.storage,this.storageKey));const c=await Me(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in n?{provider_id:n.providerId}:null),"domain"in n?{domain:n.domain}:null),{redirect_to:(s=(r=n.options)===null||r===void 0?void 0:r.redirectTo)!==null&&s!==void 0?s:void 0}),!((i=n==null?void 0:n.options)===null||i===void 0)&&i.captchaToken?{gotrue_meta_security:{captcha_token:n.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:l,code_challenge_method:d}),headers:this.headers,xform:P7});return!((o=c.data)===null||o===void 0)&&o.url&&An()&&!(!((a=n.options)===null||a===void 0)&&a.skipBrowserRedirect)&&window.location.assign(c.data.url),this._returnResult(c)}catch(l){if(await bn(this.storage,`${this.storageKey}-code-verifier`),De(l))return this._returnResult({data:null,error:l});throw l}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async n=>{const{data:{session:r},error:s}=n;if(s)throw s;if(!r)throw new gr;const{error:i}=await Me(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:r.access_token});return this._returnResult({data:{user:null,session:null},error:i})})}catch(n){if(De(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async resend(n){try{const r=`${this.url}/resend`;if("email"in n){const{email:s,type:i,options:o}=n,{error:a}=await Me(this.fetch,"POST",r,{headers:this.headers,body:{email:s,type:i,gotrue_meta_security:{captcha_token:o==null?void 0:o.captchaToken}},redirectTo:o==null?void 0:o.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:a})}else if("phone"in n){const{phone:s,type:i,options:o}=n,{data:a,error:l}=await Me(this.fetch,"POST",r,{headers:this.headers,body:{phone:s,type:i,gotrue_meta_security:{captcha_token:o==null?void 0:o.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:a==null?void 0:a.message_id},error:l})}throw new Qu("You must provide either an email or phone number and a type")}catch(r){if(De(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async getSession(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async r=>r))}async _acquireLock(n,r){this._debug("#_acquireLock","begin",n);try{if(this.lockAcquired){const s=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),i=(async()=>(await s,await r()))();return this.pendingInLock.push((async()=>{try{await i}catch{}})()),i}return await this.lock(`lock:${this.storageKey}`,n,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const s=r();for(this.pendingInLock.push((async()=>{try{await s}catch{}})()),await s;this.pendingInLock.length;){const i=[...this.pendingInLock];await Promise.all(i),this.pendingInLock.splice(0,i.length)}return await s}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(n){this._debug("#_useSession","begin");try{const r=await this.__loadSession();return await n(r)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let n=null;const r=await bo(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",r),r!==null&&(this._isValidSession(r)?n=r:(this._debug("#getSession()","session from storage is not val
110id"),await this._removeSession())),!n)return{data:{session:null},error:null};const s=n.expires_at?n.expires_at*1e3-Date.now()<Ug:!1;if(this._debug("#__loadSession()",`session has${s?"":" not"} expired`,"expires_at",n.expires_at),!s){if(this.userStorage){const a=await bo(this.userStorage,this.storageKey+"-user");a!=null&&a.user?n.user=a.user:n.user=Zg()}if(this.storage.isServer&&n.user&&!n.user.__isUserNotAvailableProxy){const a={value:this.suppressGetSessionWarning};n.user=z7(n.user,a),a.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:n},error:null}}const{data:i,error:o}=await this._callRefreshToken(n.refresh_token);return o?this._returnResult({data:{session:null},error:o}):this._returnResult({data:{session:i},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(n){if(n)return await this._getUser(n);await this.initializePromise;const r=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser());return r.data.user&&(this.suppressGetSessionWarning=!0),r}async _getUser(n){try{return n?await Me(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:n,xform:Ri}):await this._useSession(async r=>{var s,i,o;const{data:a,error:l}=r;if(l)throw l;return!(!((s=a.session)===null||s===void 0)&&s.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new gr}:await Me(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(o=(i=a.session)===null||i===void 0?void 0:i.access_token)!==null&&o!==void 0?o:void 0,xform:Ri})})}catch(r){if(De(r))return Hg(r)&&(await this._removeSession(),await bn(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:r});throw r}}async updateUser(n,r={}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(n,r))}async _updateUser(n,r={}){try{return await this._useSession(async s=>{const{data:i,error:o}=s;if(o)throw o;if(!i.session)throw new gr;const a=i.session;let l=null,d=null;this.flowType==="pkce"&&n.email!=null&&([l,d]=await qa(this.storage,this.storageKey));const{data:c,error:f}=await Me(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:r==null?void 0:r.emailRedirectTo,body:Object.assign(Object.assign({},n),{code_challenge:l,code_challenge_method:d}),jwt:a.access_token,xform:Ri});if(f)throw f;return a.user=c.user,await this._saveSession(a),await this._notifyAllSubscribers("USER_UPDATED",a),this._returnResult({data:{user:a.user},error:null})})}catch(s){if(await bn(this.storage,`${this.storageKey}-code-verifier`),De(s))return this._returnResult({data:{user:null},error:s});throw s}}async setSession(n){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(n))}async _setSession(n){try{if(!n.access_token||!n.refresh_token)throw new gr;const r=Date.now()/1e3;let s=r,i=!0,o=null;const{payload:a}=tp(n.access_token);if(a.exp&&(s=a.exp,i=s<=r),i){const{data:l,error:d}=await this._callRefreshToken(n.refresh_token);if(d)return this._returnResult({data:{user:null,session:null},error:d});if(!l)return{data:{user:null,session:null},error:null};o=l}else{const{data:l,error:d}=await this._getUser(n.access_token);if(d)return this._returnResult({data:{user:null,session:null},error:d});o={access_token:n.access_token,refresh_token:n.refresh_token,user:l.user,token_type:"bearer",expires_in:s-r,expires_at:s},await this._saveSession(o),await this._notifyAllSubscribers("SIGNED_IN",o)}return this._returnResult({data:{user:o.user,session:o},error:null})}catch(r){if(De(r))return this._returnResult({data:{session:null,user:null},error:r});throw r}}async refreshSession(n){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(n))}async _refreshSession(n){try{return await this._useSession(async r=>{var s;if(!n){const{data:a,error:l}=r;if(l)throw l;n=(s=a.session)!==null&&s!==void 0?s:void 0}if(!(n!=null&&n.refresh_token))throw new gr;const{data:i,error:o}=await this._callRefreshToken(n.refresh_token);return o?this._returnResult({data:{user:null,session:null},error:o}):i?this._returnResult({data:{user:i.user,session:i},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(r){if(De(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async _getSessionFromURL(n,r){try{if(!An())throw new ep("No browser detected.");
110if(n.error||n.error_description||n.error_code)throw new ep(n.error_description||"Error in URL with unspecified error_description",{error:n.error||"unspecified_error",code:n.error_code||"unspecified_code"});switch(r){case"implicit":if(this.flowType==="pkce")throw new V1("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new ep("Not a valid implicit grant flow url.");break;default:}if(r==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!n.code)throw new V1("No code detected.");const{data:v,error:x}=await this._exchangeCodeForSession(n.code);if(x)throw x;const _=new URL(window.location.href);return _.searchParams.delete("code"),window.history.replaceState(window.history.state,"",_.toString()),{data:{session:v.session,redirectType:null},error:null}}const{provider_token:s,provider_refresh_token:i,access_token:o,refresh_token:a,expires_in:l,expires_at:d,token_type:c}=n;if(!o||!l||!a||!c)throw new ep("No session defined in URL");const f=Math.round(Date.now()/1e3),p=parseInt(l);let u=f+p;d&&(u=parseInt(d));const h=u-f;h*1e3<=Ya&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${h}s, should have been closer to ${p}s`);const y=u-p;f-y>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",y,u,f):f-y<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",y,u,f);const{data:m,error:b}=await this._getUser(o);if(b)throw b;const A={provider_token:s,provider_refresh_token:i,access_token:o,expires_in:p,expires_at:u,refresh_token:a,token_type:c,user:m.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:A,redirectType:n.type},error:null})}catch(s){if(De(s))return this._returnResult({data:{session:null,redirectType:null},error:s});throw s}}_isImplicitGrantCallback(n){return typeof this.detectSessionInUrl=="function"?this.detectSessionInUrl(new URL(window.location.href),n):!!(n.access_token||n.error_description)}async _isPKCECallback(n){const r=await bo(this.storage,`${this.storageKey}-code-verifier`);return!!(n.code&&r)}async signOut(n={scope:"global"}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(n))}async _signOut({scope:n}={scope:"global"}){return await this._useSession(async r=>{var s;const{data:i,error:o}=r;if(o&&!Hg(o))return this._returnResult({error:o});const a=(s=i.session)===null||s===void 0?void 0:s.access_token;if(a){const{error:l}=await this.admin.signOut(a,n);if(l&&!(o7(l)&&(l.status===404||l.status===401||l.status===403)||Hg(l)))return this._returnResult({error:l})}return n!=="others"&&(await this._removeSession(),await bn(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(n){const r=g7(),s={id:r,callback:n,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",r),this.stateChangeEmitters.delete(r)}};return this._debug("#onAuthStateChange()","registered callback with id",r),this.stateChangeEmitters.set(r,s),(async()=>(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(r)})))(),{data:{subscription:s}}}async _emitInitialSession(n){return await this._useSession(async r=>{var s,i;try{const{data:{session:o},error:a}=r;if(a)throw a;await((s=this.stateChangeEmitters.get(n))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",o)),this._debug("INITIAL_SESSION","callback id",n,"session",o)}catch(o){await((i=this.stateChangeEmitters.get(n))===null||i===void 0?void 0:i.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",n,"error",o),console.error(o)}})}async resetPasswordForEmail(n,r={}){let s=null,i=null;this.flowType==="pkce"&&([s,i]=await qa(this.storage,this.storageKey,!0));try{return await Me(this.fetch,"POST",`${this.url}/recover`,{body:{email:n,code_challenge:s,code_challenge_method:i,gotrue_meta_security:{captcha_token:r.captchaToken}},headers:this.headers,redirectTo:r.redirectTo})}catch(o){if(await bn(this.storage,`${this.storageKey}-code-verifier`),De(o))return this._returnResult({data:null,error:o});throw o}}async getUserIdentities(){var n;try{const{data:r,error:s}=await this.getUser();if(s)throw s;return this._returnResult({data:{identities:(n=r.user.identities)!==null&&n!==void 0?n:[]},error:null})}catch(r){if(De(r))return this._returnResult({data:null,error:r});throw r}}async linkIdentity(n){return"token"in n?this.linkIdentityIdToken(n):this.linkIdentityOAuth(n)}async linkIdentityOAuth(n){var r;try{const{data:s,error:i}=await this._useSession(async o=>{var a,l,d,c,f;const{data:p,error:u}=o;if(u)throw u;const h=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,n.provider,{redirectTo:(a=n.options)===null||a===void 0?void 0:a.redirectTo,scopes:(l=n.options)===null||l===void 0?void 0:l.scopes,queryParams:(d=n.options)===null||d===void 0?void 0:d.queryParams,skipBrowserRedirect:!0});return await Me(this.fetch,"GET",h,{headers:this.headers,jwt:(f=(c=p.session)===null||c===void 0?void 0:c.access_token)!==null&&f!==void 0?f:void 0})});if(i)throw i;return An()&&!(!((r=n.options)===null||r===void 0)&&r.skipBrowserRedirect)&&window.location.assign(s==null?void 0:s.url),this._returnResult({data:{provider:n.provider,url:s==null?void 0:s.url},error:null})}catch(s){if(De(s))return this._returnResult({data:{provider:n.provider,url:null},error:s});throw s}}async linkIdentityIdToken(n){return await this._useSession(async r=>{var s;try{const{error:i,data:{session:o}}=r;if(i)throw i;const{options:a,provider:l,token:d,access_token:c,nonce:f}=n,p=await Me(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(s=o==null?void 0:o.access_token)!==null&&s!==void 0?s:void 0,body:{provider:l,id_token:d,access_token:c,nonce:f,link_identity:!0,gotrue_meta_security:{captcha_token:a==null?void 0:a.captchaToken}},xform:Zr}),{data:u,error:h}=p;return h?this._returnResult({data:{user:null,session:null},error:h}):!u||!u.session||!u.user?this._returnResult({data:{user:null,session:null},error:new Pa}):(u.session&&(await this._saveSession(u.session),await this._notifyAllSubscribers("USER_UPDATED",u.session)),this._returnResult({data:u,error:h}))}catch(i){if(await bn(this.storage,`${this.storageKey}-code-verifier`),De(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}})}async unlinkIdentity(n){try{return await this._useSession(async r=>{var s,i;const{data:o,error:a}=r;if(a)throw a;
110return await Me(this.fetch,"DELETE",`${this.url}/user/identities/${n.identity_id}`,{headers:this.headers,jwt:(i=(s=o.session)===null||s===void 0?void 0:s.access_token)!==null&&i!==void 0?i:void 0})})}catch(r){if(De(r))return this._returnResult({data:null,error:r});throw r}}async _refreshAccessToken(n){const r=`#_refreshAccessToken(${n.substring(0,5)}...)`;this._debug(r,"begin");try{const s=Date.now();return await b7(async i=>(i>0&&await y7(200*Math.pow(2,i-1)),this._debug(r,"refreshing attempt",i),await Me(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:n},headers:this.headers,xform:Zr})),(i,o)=>{const a=200*Math.pow(2,i);return o&&Vg(o)&&Date.now()+a-s<Ya})}catch(s){if(this._debug(r,"error",s),De(s))return this._returnResult({data:{session:null,user:null},error:s});throw s}finally{this._debug(r,"end")}}_isValidSession(n){return typeof n=="object"&&n!==null&&"access_token"in n&&"refresh_token"in n&&"expires_at"in n}async _handleProviderSignIn(n,r){const s=await this._getUrlForProvider(`${this.url}/authorize`,n,{redirectTo:r.redirectTo,scopes:r.scopes,queryParams:r.queryParams});return this._debug("#_handleProviderSignIn()","provider",n,"options",r,"url",s),An()&&!r.skipBrowserRedirect&&window.location.assign(s),{data:{provider:n,url:s},error:null}}async _recoverAndRefresh(){var n,r;const s="#_recoverAndRefresh()";this._debug(s,"begin");try{const i=await bo(this.storage,this.storageKey);if(i&&this.userStorage){let a=await bo(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!a&&(a={user:i.user},await Xa(this.userStorage,this.storageKey+"-user",a)),i.user=(n=a==null?void 0:a.user)!==null&&n!==void 0?n:Zg()}else if(i&&!i.user&&!i.user){const a=await bo(this.storage,this.storageKey+"-user");a&&(a!=null&&a.user)?(i.user=a.user,await bn(this.storage,this.storageKey+"-user"),await Xa(this.storage,this.storageKey,i)):i.user=Zg()}if(this._debug(s,"session from storage",i),!this._isValidSession(i)){this._debug(s,"session is not valid"),i!==null&&await this._removeSession();return}const o=((r=i.expires_at)!==null&&r!==void 0?r:1/0)*1e3-Date.now()<Ug;if(this._debug(s,`session has${o?"":" not"} expired with margin of ${Ug}s`),o){if(this.autoRefreshToken&&i.refresh_token){const{error:a}=await this._callRefreshToken(i.refresh_token);a&&(console.error(a),Vg(a)||(this._debug(s,"refresh failed with a non-retryable error, removing the session",a),await this._removeSession()))}}else if(i.user&&i.user.__isUserNotAvailableProxy===!0)try{const{data:a,error:l}=await this._getUser(i.access_token);!l&&(a!=null&&a.user)?(i.user=a.user,await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)):this._debug(s,"could not get user data, skipping SIGNED_IN notification")}catch(a){console.error("Error getting user data:",a),this._debug(s,"error getting user data, skipping SIGNED_IN notification",a)}else await this._notifyAllSubscribers("SIGNED_IN",i)}catch(i){this._debug(s,"error",i),console.error(i);return}finally{this._debug(s,"end")}}async _callRefreshToken(n){var r,s;if(!n)throw new gr;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const i=`#_callRefreshToken(${n.substring(0,5)}...)`;this._debug(i,"begin");try{this.refreshingDeferred=new Mf;const{data:o,error:a}=await this._refreshAccessToken(n);if(a)throw a;if(!o.session)throw new gr;await this._saveSession(o.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",o.session);const l={data:o.session,error:null};return this.refreshingDeferred.resolve(l),l}catch(o){if(this._debug(i,"error",o),De(o)){const a={data:null,error:o};return Vg(o)||await this._removeSession(),(r=this.refreshingDeferred)===null||r===void 0||r.resolve(a),a}throw(s=this.refreshingDeferred)===null||s===void 0||s.reject(o),o}finally{this.refreshingDeferred=null,this._debug(i,"end")}}async _notifyAllSubscribers(n,r,s=!0){const i=`#_notifyAllSubscribers(${n})`;this._debug(i,"begin",r,`broadcast = ${s}`);try{this.broadcastChannel&&s&&this.broadcastChannel.postMessage({event:n,session:r});const o=[],a=Array.from(this.stateChangeEmitters.values()).map(async l=>{try{await l.callback(n,r)}catch(d){o.push(d)}});if(await Promise.all(a),o.length>0){for(let l=0;l<o.length;l+=1)console.error(o[l]);throw o[0]}}finally{this._debug(i,"end")}}async _saveSession(n){this._debug("#_saveSession()",n),this.suppressGetSessionWarning=!0,await bn(this.storage,`${this.storageKey}-code-verifier`);const r=Object.assign({},n),s=r.user&&r.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!s&&r.user&&await Xa(this.userStorage,this.storageKey+"-user",{user:r.user});const i=Object.assign({},r);delete i.user;const o=G1(i);await Xa(this.storage,this.storageKey,o)}else{const i=G1(r);await Xa(this.storage,this.storageKey,i)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await bn(this.storage,this.storageKey),await bn(this.storage,this.storageKey+"-code-verifier"),await bn(this.storage,this.storageKey+"-user"),this.userStorage&&await bn(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const n=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{n&&An()&&(window!=null&&window.removeEventListener)&&window.removeEventListener("visibilitychange",n)}
110catch(r){console.error("removing visibilitychange callback failed",r)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const n=setInterval(()=>this._autoRefreshTokenTick(),Ya);this.autoRefreshTicker=n,n&&typeof n=="object"&&typeof n.unref=="function"?n.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(n);const r=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=r,r&&typeof r=="object"&&typeof r.unref=="function"?r.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(r)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const n=this.autoRefreshTicker;this.autoRefreshTicker=null,n&&clearInterval(n);const r=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,r&&clearTimeout(r)}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 n=Date.now();try{return await this._useSession(async r=>{const{data:{session:s}}=r;if(!s||!s.refresh_token||!s.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const i=Math.floor((s.expires_at*1e3-n)/Ya);this._debug("#_autoRefreshTokenTick()",`access token expires in ${i} ticks, a tick lasts ${Ya}ms, refresh threshold is ${hy} ticks`),i<=hy&&await this._callRefreshToken(s.refresh_token)})}catch(r){console.error("Auto refresh tick failed with error. This is likely a transient error.",r)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(n){if(n.isAcquireTimeout||n instanceof S4)this._debug("auto refresh token tick lock not available");else throw n}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!An()||!(window!=null&&window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(n){this._debug("#visibilityChangedCallback","error",n)}},window==null||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(n){console.error("_handleVisibilityChange",n)}}async _onVisibilityChanged(n){const r=`#_onVisibilityChanged(${n})`;this._debug(r,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),n||(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{if(document.visibilityState!=="visible"){this._debug(r,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(n,r,s){const i=[`provider=${encodeURIComponent(r)}`];if(s!=null&&s.redirectTo&&i.push(`redirect_to=${encodeURIComponent(s.redirectTo)}`),s!=null&&s.scopes&&i.push(`scopes=${encodeURIComponent(s.scopes)}`),this.flowType==="pkce"){const[o,a]=await qa(this.storage,this.storageKey),l=new URLSearchParams({code_challenge:`${encodeURIComponent(o)}`,code_challenge_method:`${encodeURIComponent(a)}`});i.push(l.toString())}if(s!=null&&s.queryParams){const o=new URLSearchParams(s.queryParams);i.push(o.toString())}return s!=null&&s.skipBrowserRedirect&&i.push(`skip_http_redirect=${s.skipBrowserRedirect}`),`${n}?${i.join("&")}`}async _unenroll(n){try{return await this._useSession(async r=>{var s;const{data:i,error:o}=r;return o?this._returnResult({data:null,error:o}):await Me(this.fetch,"DELETE",`${this.url}/factors/${n.factorId}`,{headers:this.headers,jwt:(s=i==null?void 0:i.session)===null||s===void 0?void 0:s.access_token})})}catch(r){if(De(r))return this._returnResult({data:null,error:r});throw r}}async _enroll(n){try{return await this._useSession(async r=>{var s,i;const{data:o,error:a}=r;if(a)return this._returnResult({data:null,error:a});const l=Object.assign({friendly_name:n.friendlyName,factor_type:n.factorType},n.factorType==="phone"?{phone:n.phone}:n.factorType==="totp"?{issuer:n.issuer}:{}),{data:d,error:c}=await Me(this.fetch,"POST",`${this.url}/factors`,{body:l,headers:this.headers,jwt:(s=o==null?void 0:o.session)===null||s===void 0?void 0:s.access_token});return c?this._returnResult({data:null,error:c}):(n.factorType==="totp"&&d.type==="totp"&&(!((i=d==null?void 0:d.totp)===null||i===void 0)&&i.qr_code)&&(d.totp.qr_code=`data:image/svg+xml;utf-8,${d.totp.qr_code}`),this._returnResult({data:d,error:null}))})}catch(r){if(De(r))return this._returnResult({data:null,error:r});throw r}}async _verify(n){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async r=>{var s;const{data:i,error:o}=r;if(o)return this._returnResult({data:null,error:o});const a=Object.assign({challenge_id:n.challengeId},"webauthn"in n?{webauthn:Object.assign(Object.assign({},n.webauthn),{credential_response:n.webauthn.type==="create"?K7(n.webauthn.credential_response):Y7(n.webauthn.credential_response)})}:{code:n.code}),{data:l,error:d}=await Me(this.fetch,"POST",`${this.url}/factors/${n.factorId}/verify`,{body:a,headers:this.headers,jwt:(s=i==null?void 0:i.session)===null||s===void 0?void 0:s.access_token});return d?this._returnResult({data:null,error:d}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+l.expires_in},l)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",l),this._returnResult({data:l,error:d}))})}catch(r){if(De(r))return this._returnResult({data:null,error:r});throw r}})}async _challenge(n){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async r=>{var s;const{data:i,error:o}=r;if(o)return this._returnResult({data:null,error:o});const a=await Me(this.fetch,"POST",`${this.url}/factors/${n.factorId}/challenge`,{body:n,headers:this.headers,jwt:(s=i==null?void 0:i.session)===null||s===void 0?void 0:s.access_token});if(a.error)return a;const{data:l}=a;if(l.type!=="webauthn")return{data:l,error:null};switch(l.webauthn.type){case"create":return{data:Object.assign(Object.assign({},l),{webauthn:Object.assign(Object.assign({},l.webauthn),{credential_options:Object.assign(Object.assign({},l.webauthn.credential_options),{publicKey:V7(l.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},l),{webauthn:Object.assign(Object.assign({},l.webauthn),{credential_options:Object.assign(Object.assign({},l.webauthn.credential_options),{publicKey:Z7(l.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(r){if(De(r))return this._returnResult({data:null,error:r});throw r}})}async _challengeAndVerify(n){const{data:r,error:s}=await this._challenge({factorId:n.factorId});return s?this._returnResult({data:null,error:s}):await this._verify({factorId:n.factorId,challengeId:r.id,code:n.code})}async _listFactors(){var n;const{data:{user:r},error:s}=await this.getUser();if(s)return{data:null,error:s};const i={all:[],phone:[],totp:[],webauthn:[]};for(const o of(n=r==null?void 0:r.factors)!==null&&n!==void 0?n:[])i.all.push(o),o.status==="verified"&&i[o.factor_type].push(o);return{data:i,error:null}}async _getAuthenticatorAssuranceLevel(n){var r,s,i,o;if(n)try{const{payload:h}=tp(n);let y=null;h.aal&&(y=h.aal);let m=y;const{data:{user:b},error:A}=await this.getUser(n);if(A)return this._returnResult({data:null,error:A});((s=(r=b==null?void 0:b.factors)===null||r===void 0?void 0:r.filter(_=>_.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(m="aal2");const x=h.amr||[];return{data:{currentLevel:y,nextLevel:m,currentAuthenticationMethods:x},error:null}}catch(h){if(De(h))return this._returnResult({data:null,error:h});throw h}const{data:{session:a},error:l}
110=await this.getSession();if(l)return this._returnResult({data:null,error:l});if(!a)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:d}=tp(a.access_token);let c=null;d.aal&&(c=d.aal);let f=c;((o=(i=a.user.factors)===null||i===void 0?void 0:i.filter(h=>h.status==="verified"))!==null&&o!==void 0?o:[]).length>0&&(f="aal2");const u=d.amr||[];return{data:{currentLevel:c,nextLevel:f,currentAuthenticationMethods:u},error:null}}async _getAuthorizationDetails(n){try{return await this._useSession(async r=>{const{data:{session:s},error:i}=r;return i?this._returnResult({data:null,error:i}):s?await Me(this.fetch,"GET",`${this.url}/oauth/authorizations/${n}`,{headers:this.headers,jwt:s.access_token,xform:o=>({data:o,error:null})}):this._returnResult({data:null,error:new gr})})}catch(r){if(De(r))return this._returnResult({data:null,error:r});throw r}}async _approveAuthorization(n,r){try{return await this._useSession(async s=>{const{data:{session:i},error:o}=s;if(o)return this._returnResult({data:null,error:o});if(!i)return this._returnResult({data:null,error:new gr});const a=await Me(this.fetch,"POST",`${this.url}/oauth/authorizations/${n}/consent`,{headers:this.headers,jwt:i.access_token,body:{action:"approve"},xform:l=>({data:l,error:null})});return a.data&&a.data.redirect_url&&An()&&!(r!=null&&r.skipBrowserRedirect)&&window.location.assign(a.data.redirect_url),a})}catch(s){if(De(s))return this._returnResult({data:null,error:s});throw s}}async _denyAuthorization(n,r){try{return await this._useSession(async s=>{const{data:{session:i},error:o}=s;if(o)return this._returnResult({data:null,error:o});if(!i)return this._returnResult({data:null,error:new gr});const a=await Me(this.fetch,"POST",`${this.url}/oauth/authorizations/${n}/consent`,{headers:this.headers,jwt:i.access_token,body:{action:"deny"},xform:l=>({data:l,error:null})});return a.data&&a.data.redirect_url&&An()&&!(r!=null&&r.skipBrowserRedirect)&&window.location.assign(a.data.redirect_url),a})}catch(s){if(De(s))return this._returnResult({data:null,error:s});throw s}}async _listOAuthGrants(){try{return await this._useSession(async n=>{const{data:{session:r},error:s}=n;return s?this._returnResult({data:null,error:s}):r?await Me(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,xform:i=>({data:i,error:null})}):this._returnResult({data:null,error:new gr})})}catch(n){if(De(n))return this._returnResult({data:null,error:n});throw n}}async _revokeOAuthGrant(n){try{return await this._useSession(async r=>{const{data:{session:s},error:i}=r;return i?this._returnResult({data:null,error:i}):s?(await Me(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:s.access_token,query:{client_id:n.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new gr})})}catch(r){if(De(r))return this._returnResult({data:null,error:r});throw r}}async fetchJwk(n,r={keys:[]}){let s=r.keys.find(l=>l.kid===n);if(s)return s;const i=Date.now();if(s=this.jwks.keys.find(l=>l.kid===n),s&&this.jwks_cached_at+s7>i)return s;const{data:o,error:a}=await Me(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(a)throw a;return!o.keys||o.keys.length===0||(this.jwks=o,this.jwks_cached_at=i,s=o.keys.find(l=>l.kid===n),!s)?null:s}async getClaims(n,r={}){try{let s=n;if(!s){const{data:h,error:y}
110=await this.getSession();if(y||!h.session)return this._returnResult({data:null,error:y});s=h.session.access_token}const{header:i,payload:o,signature:a,raw:{header:l,payload:d}}=tp(s);r!=null&&r.allowExpired||k7(o.exp);const c=!i.alg||i.alg.startsWith("HS")||!i.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(i.kid,r!=null&&r.keys?{keys:r.keys}:r==null?void 0:r.jwks);if(!c){const{error:h}=await this.getUser(s);if(h)throw h;return{data:{claims:o,header:i,signature:a},error:null}}const f=C7(i.alg),p=await crypto.subtle.importKey("jwk",c,f,!0,["verify"]);if(!await crypto.subtle.verify(f,p,a,h7(`${l}.${d}`)))throw new my("Invalid JWT signature");return{data:{claims:o,header:i,signature:a},error:null}}catch(s){if(De(s))return this._returnResult({data:null,error:s});throw s}}}Kc.nextInstanceID={};const sR=Kc,iR="2.100.1";let ic="";typeof Deno<"u"?ic="deno":typeof document<"u"?ic="web":typeof navigator<"u"&&navigator.product==="ReactNative"?ic="react-native":ic="node";const oR={"X-Client-Info":`supabase-js-${ic}/${iR}`},aR={headers:oR},lR={schema:"public"},dR={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},cR={};function Yc(e){"@babel/helpers - typeof";return Yc=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(n){return typeof n}:function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},Yc(e)}function uR(e,n){if(Yc(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var s=r.call(e,n);if(Yc(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(n==="string"?String:Number)(e)}function pR(e){var n=uR(e,"string");return Yc(n)=="symbol"?n:n+""}function hR(e,n,r){return(n=pR(n))in e?Object.defineProperty(e,n,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[n]=r,e}function iv(e,n){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);n&&(s=s.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,s)}return r}function Ht(e){for(var n=1;n<arguments.length;n++){var r=arguments[n]!=null?arguments[n]:{};n%2?iv(Object(r),!0).forEach(function(s){hR(e,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):iv(Object(r)).forEach(function(s){Object.defineProperty(e,s,Object.getOwnPropertyDescriptor(r,s))})}return e}const fR=e=>e?(...n)=>e(...n):(...n)=>fetch(...n),gR=()=>Headers,mR=(e,n,r)=>{const s=fR(r),i=gR();return async(o,a)=>{var l;const d=(l=await n())!==null&&l!==void 0?l:e;let c=new i(a==null?void 0:a.headers);return c.has("apikey")||c.set("apikey",e),c.has("Authorization")||c.set("Authorization",`Bearer ${d}`),s(o,Ht(Ht({},a),{},{headers:c}))}};function xR(e){return e.endsWith("/")?e:e+"/"}function yR(e,n){var r,s;const{db:i,auth:o,realtime:a,global:l}=e,{db:d,auth:c,realtime:f,global:p}=n,u={db:Ht(Ht({},d),i),auth:Ht(Ht({},c),o),realtime:Ht(Ht({},f),a),storage:{},global:Ht(Ht(Ht({},p),l),{},{headers:Ht(Ht({},(r=p==null?void 0:p.headers)!==null&&r!==void 0?r:{}),(s=l==null?void 0:l.headers)!==null&&s!==void 0?s:{})}),accessToken:async()=>""};return e.accessToken?u.accessToken=e.accessToken:delete u.accessToken,u}function bR(e){const n=e==null?void 0:e.trim();if(!n)throw new Error("supabaseUrl is required.");if(!n.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(xR(n))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var AR=class extends sR{constructor(e){super(e)}},vR=class{constructor(e,n,r){var s,i;this.supabaseUrl=e,this.supabaseKey=n;const o=bR(e);if(!n)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",o),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",o),this.storageUrl=new URL("storage/v1",o),this.functionsUrl=new URL("functions/v1",o);const a=`sb-${o.hostname.split(".")[0]}-auth-token`,l={db:lR,realtime:cR,auth:Ht(Ht({},dR),{},{storageKey:a}
110),global:aR},d=yR(r??{},l);if(this.storageKey=(s=d.auth.storageKey)!==null&&s!==void 0?s:"",this.headers=(i=d.global.headers)!==null&&i!==void 0?i:{},d.accessToken)this.accessToken=d.accessToken,this.auth=new Proxy({},{get:(f,p)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(p)} is not possible`)}});else{var c;this.auth=this._initSupabaseAuthClient((c=d.auth)!==null&&c!==void 0?c:{},this.headers,d.global.fetch)}this.fetch=mR(n,this._getAccessToken.bind(this),d.global.fetch),this.realtime=this._initRealtimeClient(Ht({headers:this.headers,accessToken:this._getAccessToken.bind(this)},d.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(f=>this.realtime.setAuth(f)).catch(f=>console.warn("Failed to set initial Realtime auth token:",f)),this.rest=new Bz(new URL("rest/v1",o).href,{headers:this.headers,schema:d.db.schema,fetch:this.fetch,timeout:d.db.timeout,urlLengthLimit:d.db.urlLengthLimit}),this.storage=new QN(this.storageUrl.href,this.headers,this.fetch,r==null?void 0:r.storage),d.accessToken||this._listenForAuthEvents()}get functions(){return new Dz(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,n={},r={head:!1,get:!1,count:void 0}){return this.rest.rpc(e,n,r)}channel(e,n={config:{}}){return this.realtime.channel(e,n)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var e=this,n,r;if(e.accessToken)return await e.accessToken();const{data:s}=await e.auth.getSession();return(n=(r=s.session)===null||r===void 0?void 0:r.access_token)!==null&&n!==void 0?n:e.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:n,detectSessionInUrl:r,storage:s,userStorage:i,storageKey:o,flowType:a,lock:l,debug:d,throwOnError:c},f,p){const u={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new AR({url:this.authUrl.href,headers:Ht(Ht({},u),f),storageKey:o,autoRefreshToken:e,persistSession:n,detectSessionInUrl:r,storage:s,userStorage:i,flowType:a,lock:l,debug:d,throwOnError:c,fetch:p,hasCustomAuthorizationHeader:Object.keys(this.headers).some(h=>h.toLowerCase()==="authorization")})}_initRealtimeClient(e){return new jN(this.realtimeUrl.href,Ht(Ht({},e),{},{params:Ht(Ht({},{apikey:this.supabaseKey}),e==null?void 0:e.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((e,n)=>{this._handleTokenChanged(e,"CLIENT",n==null?void 0:n.access_token)})}_handleTokenChanged(e,n,r){(e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==r?(this.changedAccessToken=r,this.realtime.setAuth(r)):e==="SIGNED_OUT"&&(this.realtime.setAuth(),n=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};const _R=(e,n,r)=>new vR(e,n,r);
110function jR(){if(typeof window<"u")return!1;const e=globalThis.process;if(!e)return!1;const n=e.version;if(n==null)return!1;const r=n.match(/^v(\d+)\./);return r?parseInt(r[1],10)<=18:!1}jR()&&console.warn("â ï¸ Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217");const wR="https://yktemdaxnvraobkjfvnn.supabase.co",SR="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InlrdGVtZGF4bnZyYW9ia2pmdm5uIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzQ1NTU3NTUsImV4cCI6MjA5MDEzMTc1NX0.P28ZkVvihtA2vtUY8LnmtJhpXjRvaMCnBOSt_i0AehA",w=_R(wR,SR,{auth:{persistSession:!0,autoRefreshToken:!0}});let Xc=null,Gb=null;function kR(e){return e&&e.length>10?e:null}function CR(e,n){Xc=e,Gb=kR(n)}function ov(){Xc=null,Gb=null}function Yt(){return Xc}function Kt(){return Gb}function cn(){if(!Xc)throw new Error("tenantContext: not authenticated");return Xc}const T4=g.createContext({user:null,profile:null,tenant:null,role:null,tenantId:null,loading:!0,signOut:async()=>{}});function TR({children:e}){const[n,r]=g.useState(null),[s,i]=g.useState(null),[o,a]=g.useState(null),[l,d]=g.useState(!0);async function c(p){try{const{data:u,error:h}=await w.from("profiles").select("*").eq("id",p).single();if(h||!u){console.error("Profile fetch error:",h),d(!1);return}i(u),CR(u.tenant_id,u.branch_id??null);const{data:y}=await w.from("tenants").select("*").eq("id",u.tenant_id).single();y&&a(y)}catch(u){console.error("loadProfileAndTenant error:",u)}finally{d(!1)}}g.useEffect(()=>{w.auth.getSession().then(({data:{session:u}})=>{r((u==null?void 0:u.user)??null),u!=null&&u.user?c(u.user.id):d(!1)});const{data:{subscription:p}}=w.auth.onAuthStateChange((u,h)=>{r((h==null?void 0:h.user)??null),h!=null&&h.user?c(h.user.id):(i(null),a(null),ov(),d(!1))});return()=>p.unsubscribe()},[]);async function f(){await w.auth.signOut(),r(null),i(null),a(null),ov()}return t.jsx(T4.Provider,{value:{user:n,profile:s,tenant:o,role:(s==null?void 0:s.role)??null,tenantId:(s==null?void 0:s.tenant_id)??null,loading:l,signOut:f},children:e})}function Jb(){return g.useContext(T4)}function Ee(){const{user:e,profile:n,tenant:r,role:s,loading:i}=Jb(),[o,a]=g.useState(null);return g.useEffect(()=>{w.auth.getSession().then(({data:{session:d}})=>{a(d)});const{data:{subscription:l}}=w.auth.onAuthStateChange((d,c)=>{a(c)});return()=>l.unsubscribe()},[]),{session:o,user:e,profile:n,tenant:r,role:s,loading:i}}const nh=[{path:"/dashboard",group:"Core",label:"Dashboard",icon:"ð "},{path:"/leads",group:"Core",label:"Leads",icon:"ð¯"},{path:"/customers",group:"Core",label:"Customers",icon:"ð¥"},{path:"/schedule",group:"Core",label:"Schedule",icon:"ðï¸"},{path:"/follow-ups",group:"Core",label:"Follow-Ups",icon:"ð"},{path:"/quotes",group:"Sales",label:"Quotes",icon:"ð"},{path:"/offers",group:"Sales",label:"Final Offers",icon:"ð"},{path:"/products",group:"Sales",label:"Products",icon:"ð¦"},{path:"/communications",group:"Sales",label:"Communications",icon:"ð¬"},{path:"/dispatch",group:"Operations",label:"Dispatch",icon:"ð"},{path:"/installations",group:"Operations",label:"Installations",icon:"ð§"},{path:"/services",group:"Operations",label:"Services",icon:"ð ï¸"},{path:"/fulfillment",group:"Operations",label:"Fulfillment",icon:"ð"},{path:"/service-due",group:"Operations",label:"Service Due",icon:"ðï¸"},{path:"/service-board",group:"Operations",label:"Service Board",icon:"ð«"},{path:"/shipping",group:"Operations",label:"Shipping",icon:"ð®"},{path:"/inventory",group:"Operations",label:"Inventory",icon:"ð·ï¸"},{path:"/invoices",group:"Finance",label:"Invoices",icon:"ð§¾"},{path:"/invoice/new",group:"Finance",label:"New Invoice",icon:"â"},{path:"/accounting",group:"Finance",label:"Accounting",icon:"ð°"},{path:"/reports",group:"Analytics",label:"Reports",icon:"ð"},{path:"/heatmap",group:"Analytics",label:"Heatmap",icon:"ðºï¸"},{path:"/admin/users",group:"Admin",label:"Users",icon:"âï¸"},{path:"/admin/terms",group:"Admin",label:"Terms",icon:"ð"}],av=nh.map(e=>e.path),rh={admin:av,super_admin:av,frontdesk:["/dashboard","/leads","/customers","/quotes","/offers","/invoices","/dispatch","/communications","/follow-ups","/schedule","/fulfillment","/shipping","/service-due","/service-board"],salesrep:["/dashboard","/leads","/customers","/quotes","/offers","/schedule","/follow-ups","/service-board"],technician:["/dashboard","/installations","/schedule"]};function rs(e){var d,c;const{user:n,profile:r}=Ee(),s=e??(r==null?void 0:r.role)??((d=n==null?void 0:n.user_metadata)==null?void 0:d.role)??null,o=((c=n==null?void 0:n.user_metadata)==null?void 0:c.pages)??null??(s?rh[s]??null:null);function a(f){return s==="admin"||s==="super_admin"?!0:o?f==="/dashboard"?!0:o.some(p=>f.startsWith(p)):!1}function l(f,p){return!0}return{canAccess:a,can:l,allowedPages:o,role:s}}const z4=g.createContext({userBranch:null,allBranches:[],selectedBranchId:null,
110setSelectedBranchId:()=>{},userBranchActive:null,loading:!0});function zR({children:e}){const{profile:n}=Jb(),[r,s]=g.useState(null),[i,o]=g.useState([]),[a,l]=g.useState(null),[d,c]=g.useState(null),[f,p]=g.useState(!0);g.useEffect(()=>{if(!(n!=null&&n.tenant_id)){p(!1);return}u()},[n==null?void 0:n.tenant_id,n==null?void 0:n.branch_id]);async function u(){try{if(n!=null&&n.branch_id){const{data:b}=await w.from("branches").select("is_active").eq("id",n.branch_id).single();c(b?b.is_active!==!1:null)}else c(null);const{data:h,error:y}=await w.from("branches").select("id, name, code, city, state, is_default, tenant_id").eq("tenant_id",n.tenant_id).eq("is_active",!0).order("is_default",{ascending:!1});if(y)throw y;const m=h??[];if(o(m),n!=null&&n.branch_id&&m.length>0){const b=m.find(A=>A.id===n.branch_id)??null;s(b),l((b==null?void 0:b.id)??null)}else if(m.length>0){const b=m.find(A=>A.is_default)??m[0];s(b),l(b.id)}}catch(h){console.error("BranchContext: loadBranches error",h)}finally{p(!1)}}return t.jsx(z4.Provider,{value:{userBranch:r,allBranches:i,selectedBranchId:a,setSelectedBranchId:l,userBranchActive:d,loading:f},children:e})}function mu(){return g.useContext(z4)}async function NR(){const{data:{user:e}}=await w.auth.getUser();if(!e)return null;const{data:n,error:r}=await w.from("profiles").select("ui_prefs").eq("id",e.id).single();if(r)return null;const s=(n==null?void 0:n.ui_prefs)||{};return typeof s.clock_color=="string"?s.clock_color:null}async function RR(e){const{data:{user:n}}=await w.auth.getUser();if(!n)return;const{data:r}=await w.from("profiles").select("ui_prefs").eq("id",n.id).single(),s={...(r==null?void 0:r.ui_prefs)||{},clock_color:e};await w.from("profiles").update({ui_prefs:s}).eq("id",n.id)}const xy="America/Indiana/Indianapolis",yy=[{name:"neon",hex:"#39ff14"},{name:"lime",hex:"#a3e635"},{name:"cyan",hex:"#22d3ee"},{name:"sky",hex:"#38bdf8"},{name:"amber",hex:"#fbbf24"},{name:"orange",hex:"#fb923c"},{name:"rose",hex:"#fb7185"},{name:"magenta",hex:"#e879f9"},{name:"violet",hex:"#a78bfa"},{name:"ice",hex:"#e2e8f0"}],ER="neon";function PR(e){return(yy.find(n=>n.name===e)||yy[0]).hex}function qR(e){var i,o;const n=new Intl.DateTimeFormat("en-US",{timeZone:xy,weekday:"short",hour:"2-digit",hour12:!1}).formatToParts(e),r=((i=n.find(a=>a.type==="weekday"))==null?void 0:i.value)||"";let s=parseInt(((o=n.find(a=>a.type==="hour"))==null?void 0:o.value)||"0",10);return s===24&&(s=0),!["Sat","Sun"].includes(r)&&s>=9&&s<17}function DR(){const[e,n]=g.useState(()=>new Date),[r,s]=g.useState(ER),[i,o]=g.useState(!1),[a,l]=g.useState(!1),d=g.useRef(void 0),c=g.useRef(null);g.useEffect(()=>(d.current=window.setInterval(()=>n(new Date),1e3),()=>window.clearInterval(d.current)),[]),g.useEffect(()=>{let b=!0;return NR().then(A=>{b&&A&&s(A)}),()=>{b=!1}},[]),g.useEffect(()=>{if(!i)return;const b=A=>{c.current&&!c.current.contains(A.target)&&o(!1)};return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[i]);const f=PR(r),p=f+"66",u=qR(e),h=e.toLocaleTimeString("en-US",{timeZone:xy,hour:"numeric",minute:"2-digit",second:"2-digit",hour12:!0}),y=e.toLocaleDateString("en-US",{timeZone:xy,weekday:"short",month:"short",day:"numeric"});function m(b){s(b),o(!1),RR(b).then(()=>{l(!0),window.setTimeout(()=>l(!1),900)}).catch(()=>{})}return t.jsxs("div",{ref:c,style:{position:"relative"},children:[t.jsx("style",{children:"@keyframes clkSaved { 0%,100% { box-shadow: 0 0 12px var(--g) } 50% { box-shadow: 0 0 22px var(--g), 0 0 4px #fff8 } }"}),t.jsxs("div",{onClick:()=>o(b=>!b),title:`${u?"Business hours â open":"After hours â closed"} · click to change color`,style:{"--g":p,display:"flex",alignItems:"center",gap:10,padding:"6px 16px",borderRadius:10,cursor:"pointer",userSelect:"none",background:"#0b1622",border:`1px solid ${f}44`,boxShadow:`0 0 12px ${p}, inset 0 0 8px ${f}11`,transition:"border-color 0.2s, box-shadow 0.2s",fontVariantNumeric:"tabular-nums",animation:a?"clkSaved 0.9s ease-in-out":void 0},children:[t.jsx("span",{style:{width:7,height:7,borderRadius:"50%",flexShrink:0,background:u?"#22c55e":"#475569",boxShadow:u?"0 0 6px #22c55e88":"none"}}),t.jsxs("div",{style:{lineHeight:1.1,textAlign:"center"},children:[t.jsx("div",{style:{fontSize:16,fontWeight:700,letterSpacing:"0.06em",color:f,textShadow:r==="ice"?"none":`0 0 8px ${p}`,fontFamily:'ui-monospace, "SF Mono", Menlo, monospace'},children:h}),t.jsxs("div",{style:{fontSize:9,color:"#64748b",marginTop:1,letterSpacing:"0.08em",textTransform:"uppercase"},children:[y," · Indiana"]})]})]}),i&&t.jsx("div",{style:{position:"absolute",top:"calc(100% + 8px)",left:"50%",transform:"translateX(-50%)",background:"#0b1622",border:"1px solid #1e3a4f",borderRadius:12,padding:12,boxShadow:"0 10px 30px rgba(0,0,0,0.5)",zIndex:50,display:"grid",gridTemplateColumns:"repeat(5, 1fr)",gap:10,width:190},children:yy.map(b=>{const A=b.name===r;return t.jsx("button",{onClick:()=>m(b.name),title:b.name,style:{width:26,height:26,borderRadius:"50%",cursor:"pointer",background:b.hex,border:A?"2px solid #fff":"2px s
110olid transparent",boxShadow:`0 0 10px ${b.hex}88`,outline:A?`2px solid ${b.hex}`:"none",outlineOffset:2,transition:"transform 0.1s"},onMouseEnter:v=>{v.currentTarget.style.transform="scale(1.15)"},onMouseLeave:v=>{v.currentTarget.style.transform="scale(1)"}},b.name)})})]})}const kt={bg:"#0d1117",topbar:"#162232",border:"#1e3a4f",textPri:"#e2e8f0",textSec:"#64748b",accent:"#0d7ea3"},OR=[{label:"CORE",items:[{path:"/dashboard",label:"Dashboard",icon:"â",hex:"#60a5fa",soon:!1,roles:["admin","frontdesk","salesrep","technician"]},{path:"/schedule",label:"My Schedule",icon:"ðï¸",hex:"#34d399",soon:!1,roles:["admin","frontdesk","salesrep","technician"]},{path:"/calendar",label:"Calendar",icon:"ð",hex:"#378add",soon:!1,roles:["admin","frontdesk"]},{path:"/customers",label:"Customers",icon:"ð¥",hex:"#4ade80",soon:!1,roles:["admin","frontdesk","salesrep"]},{path:"/follow-ups",label:"Tasks",icon:"ð",hex:"#f472b6",soon:!1,roles:["admin","frontdesk","salesrep"]}]},{label:"SALES",items:[{path:"/leads",label:"Pipeline",icon:"⬡",hex:"#22d3ee",soon:!1,roles:["admin","frontdesk","salesrep"]},{path:"/quotes",label:"Quotes",icon:"ð",hex:"#22d3ee",soon:!1,roles:["admin","frontdesk","salesrep"]},{path:"/offers",label:"Final Offers",icon:"ð",hex:"#fbbf24",soon:!1,roles:["admin","frontdesk","salesrep"]},{path:"/services",label:"Contracts",icon:"ð",hex:"#818cf8",soon:!1,roles:["admin","frontdesk"]},{path:"/invoices",label:"Invoices",icon:"ð§¾",hex:"#34d399",soon:!1,roles:["admin","frontdesk"]},{path:"/failed-payments",label:"Failed Payments",icon:"ð¨",hex:"#f87171",soon:!1,roles:["admin","frontdesk"]},{path:"/communications",label:"Communications",icon:"ð¬",hex:"#22d3ee",soon:!1,roles:["admin","frontdesk","salesrep"]}]},{label:"OPERATIONS",items:[{path:"/dispatch",label:"Dispatch",icon:"ð
",hex:"#a78bfa",soon:!1,roles:["admin","frontdesk"]},{path:"/installations",label:"Installs",icon:"ð§",hex:"#fb923c",soon:!1,roles:["admin","technician"]},{path:"/shipping",label:"Shipping",icon:"ð",hex:"#06b6d4",soon:!1,roles:["admin","frontdesk"]},{path:"/fulfillment",label:"Fulfillment",icon:"ð",hex:"#fbbf24",soon:!1,roles:["admin","frontdesk"]},{path:"/service-due",label:"Service Due",icon:"ðï¸",hex:"#4ade80",soon:!1,roles:["admin","frontdesk"]},{path:"/service-board",label:"Service Board",icon:"ð«",hex:"#f59e0b",soon:!1,roles:["admin","frontdesk","salesrep"]}]},{label:"ADMIN",items:[{path:"/products",label:"Products",icon:"ð·ï¸",hex:"#fbbf24",soon:!1,roles:["admin"]},{path:"/inventory",label:"Inventory",icon:"ð¦",hex:"#2dd4bf",soon:!1,roles:["admin"]},{path:"/accounting",label:"Accounting",icon:"ð°",hex:"#facc15",soon:!1,roles:["admin"]},{path:"/admin/users",label:"Team & Users",icon:"ð¤",hex:"#f87171",soon:!1,roles:["admin"]},{path:"/admin/terms",label:"Admin Settings",icon:"âï¸",hex:"#8b5cf6",soon:!1,roles:["admin"]},{path:"/admin/account",label:"Account Settings",icon:"ð¦",hex:"#0d7ea3",soon:!1,roles:["admin"]},{path:"/campaigns",label:"Campaigns",icon:"ð£",hex:"#fb7185",soon:!1,roles:["admin"]},{path:"/reports",label:"Reports",icon:"ð",hex:"#38bdf8",soon:!1,roles:["admin"]},{path:"/heatmap",label:"Location Map",icon:"ðºï¸",hex:"#22c55e",soon:!1,roles:["admin"]}]},{label:"PLATFORM",items:[{path:"/super-admin/tenants",label:"Tenants",icon:"ð¢",hex:"#f472b6",soon:!1,roles:["super_admin"]}]}],IR={super_admin:"Super Admin",admin:"Admin",frontdesk:"Front Desk",salesrep:"Sales Rep",technician:"Technician"},lv={super_admin:"#f472b6",admin:"#60a5fa",frontdesk:"#a78bfa",salesrep:"#4ade80",technician:"#fb923c"};function LR({name:e,size:n=32}){const r=(e??"").trim()||"?",s=r.split(" ").map(a=>a[0]).join("").slice(0,2).toUpperCase(),i=["#3b82f6","#22c55e","#8b5cf6","#f97316","#14b8a6","#06b6d4"],o=i[r.charCodeAt(0)%i.length];return t.jsx("div",{style:{width:n,height:n,borderRadius:"50%",background:o,color:"#fff",display:"flex",alignItems:"center",justifyContent:"center",fontWeight:800,fontSize:n*.38,flexShrink:0},children:s})}function dv({sections:e,profile:n,role:r,open:s,onClose:i,onSignOut:o,unreadCount:a,tenant:l}){return t.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",background:kt.bg},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"16px 14px",borderBottom:`1px solid ${kt.border}`,flexShrink:0},children:[t.jsx("div",{style:{width:32,height:32,borderRadius:8,background:"#3b82f6",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,boxShadow:"0 0 14px #3b82f650"},children:t.jsx("span",{style:{color:"#fff",fontWeight:900,fontSize:14},children:((l==null?void 0:l.company_name)||(l==null?void 0:l.name)||"C")[0].toUpperCase()})}),s&&t.jsxs("div",{children:[t.jsx("div",{style:{color:"#f1f5f9",fontWeight:700,fontSize:13,lineHeight:1.2},children:(l==null?void 0:l.company_name)||(l==null?void 0:l.name)||"CRM"}),t.jsx("div",{style:{color:kt.textSec,fontSize:11},children:"CRM"})]})]}),t.jsx("nav",{style:{flex:1,overflowY:"auto",padding:"10px 0"},children:e.map(d=>t.jsxs("div",{children:[s&&t.jsx("div",{style:{fontSize:9,fontWeight:800,color:kt.textSec,letterSpacing:"0.1em",padding:"10px 16px 4px",textTransform:"uppercase"},children:d.label}),!s&&t.jsx("div",{style:{height:8}}),d.items.map(c=>c.soon?t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"8px 10px",margin:"0 6px 2px",borderRadius:8,opacity:.38,cursor:"not-allowed",color:kt.textSec},children:[t.jsx("span",{style:{width:6,height:6,borderRadius:"50%",background:"transparent",flexShrink:0}}),t.jsx("span",{style:{fontSize:16,flexShrink:0},children:c.icon}),s&&t.jsxs(t.Fragment,{children:[t.jsx("span",{style:{fontSize:13,flex:1},children:c.label}),t.jsx("span",{style:{fontSize:9,fontWeight:800,letterSpacing:"0.06em",background:"#1e293b",color:"#475569",padding:"2px 6px",borderRadius:20},children:"SOON"})]})]},c.path):t.jsx(Tz,{to:c.path,style:{textDecoration:"none",display:"block"},onClick:i,children:({isActive:f})=>t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"8px 10px",margin:"0 6px 2px",borderRadius:8,cursor:"pointer",transition:"all 0.12s",background:f?`${c.hex}1a`:"transparent",color:f?c.hex:kt.textSec,fontWeight:f?600:400},onMouseEnter:p=>
110{if(!f){const u=p.currentTarget;u.style.background="rgba(255,255,255,0.05)",u.style.color=kt.textPri}},onMouseLeave:p=>{if(!f){const u=p.currentTarget;u.style.background="transparent",u.style.color=kt.textSec}},children:[t.jsx("span",{style:{width:6,height:6,borderRadius:"50%",background:f?c.hex:"transparent",flexShrink:0}}),t.jsx("span",{style:{fontSize:16,flexShrink:0,lineHeight:1},children:c.icon}),s&&t.jsx("span",{style:{fontSize:13,flex:1,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:c.label}),c.path==="/communications"&&a>0&&t.jsx("span",{style:{fontSize:10,fontWeight:800,minWidth:18,textAlign:"center",background:"#ef4444",color:"#fff",padding:"1px 6px",borderRadius:20,flexShrink:0,lineHeight:1.6},children:a>99?"99+":a})]})},c.path))]},d.label))}),n&&t.jsxs("div",{style:{padding:12,borderTop:`1px solid ${kt.border}`,flexShrink:0},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[t.jsx(LR,{name:n.full_name,size:32}),s&&t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsx("div",{style:{color:"#cbd5e1",fontWeight:600,fontSize:13,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:n.full_name}),r&&t.jsx("span",{style:{fontSize:10,fontWeight:700,padding:"2px 8px",borderRadius:20,background:`${lv[r]||"#64748b"}20`,color:lv[r]||"#64748b",display:"inline-block",marginTop:2},children:IR[r]||r})]})]}),s&&t.jsx("button",{onClick:o,style:{marginTop:10,fontSize:12,color:kt.textSec,background:"none",border:"none",cursor:"pointer",padding:0},onMouseEnter:d=>d.currentTarget.style.color="#f87171",onMouseLeave:d=>d.currentTarget.style.color=kt.textSec,children:"Sign out"})]})]})}function WR({children:e}){var T;const{profile:n,role:r,tenant:s}=Ee(),{canAccess:i,allowedPages:o}=rs(),{userBranch:a,selectedBranchId:l,allBranches:d}=mu(),c=gt(),[f,p]=g.useState(!0),[u,h]=g.useState(!1),[y,m]=g.useState(0),b=g.useRef(0),A=g.useRef(!1);g.useEffect(()=>{if(!(n!=null&&n.tenant_id))return;let L=!1;typeof Notification<"u"&&Notification.permission==="default"?Notification.requestPermission().then(O=>{A.current=O==="granted"}).catch(()=>{}):typeof Notification<"u"&&(A.current=Notification.permission==="granted");async function E(){const{count:O,error:z}=await w.from("communications_log").select("id",{count:"exact",head:!0}).eq("direction","inbound").eq("channel","sms").is("read_at",null).not("from_number","is",null);if(L||z)return;const P=O||0;if(P>b.current&&A.current)try{const D=new Notification("New message",{body:`You have ${P} unread message${P===1?"":"s"}.`,tag:"cevora-sms-unread"});D.onclick=()=>{window.focus(),c("/communications"),D.close()}}catch{}b.current=P,m(P)}E();const R=w.channel("comms-unread").on("postgres_changes",{event:"INSERT",schema:"public",table:"communications_log"},()=>E()).on("postgres_changes",{event:"UPDATE",schema:"public",table:"communications_log"},()=>E()).subscribe(),N=setInterval(E,6e4);return()=>{L=!0,clearInterval(N),w.removeChannel(R)}},[n==null?void 0:n.tenant_id,c]);const v=g.useRef(null),x=g.useRef(!1);g.useEffect(()=>{if(!(n!=null&&n.tenant_id)||r!=="frontdesk"&&r!=="admin")return;let L=!1;const E=()=>{x.current=!0};window.addEventListener("pointerdown",E,{once:!0}),window.addEventListener("keydown",E,{once:!0});function R(){if(x.current)try{const M=window.AudioContext||window.webkitAudioContext;if(!M)return;const k=new M;[880,1174.7].forEach(($,I)=>{const B=k.createOscillator(),J=k.createGain();
110B.type="sine",B.frequency.value=$;const ae=k.currentTime+I*.18;J.gain.setValueAtTime(1e-4,ae),J.gain.exponentialRampToValueAtTime(.35,ae+.02),J.gain.exponentialRampToValueAtTime(1e-4,ae+.45),B.connect(J),J.connect(k.destination),B.start(ae),B.stop(ae+.5)}),setTimeout(()=>{try{k.close()}catch{}},1500)}catch{}}function N(){if(x.current)try{if(typeof speechSynthesis>"u")return;const M=new SpeechSynthesisUtterance("New lead");setTimeout(()=>{try{speechSynthesis.speak(M)}catch{}},520)}catch{}}async function O(){const{data:M}=await w.from("leads").select("first_name, last_name").is("opened_at",null).order("created_at",{ascending:!1}).limit(1).maybeSingle(),k=M?[M.first_name,M.last_name].filter(Boolean).join(" "):"";if(R(),N(),A.current)try{const q=new Notification("New lead",{body:k||"A new lead just came in.",tag:"cevora-new-lead"});q.onclick=()=>{window.focus(),c("/leads"),q.close()}}catch{}}async function z(){const{count:M,error:k}=await w.from("leads").select("id",{count:"exact",head:!0}).is("opened_at",null);if(L||k)return;const q=M||0,$=v.current;$!==null&&q>$&&await O(),v.current=q}z();const P=w.channel("new-lead-alert").on("postgres_changes",{event:"INSERT",schema:"public",table:"leads"},()=>z()).subscribe(),D=setInterval(z,6e4);return()=>{L=!0,clearInterval(D),w.removeChannel(P),window.removeEventListener("pointerdown",E),window.removeEventListener("keydown",E)}},[n==null?void 0:n.tenant_id,r,c]);const _=OR.map(L=>({...L,items:L.items.filter(E=>r?r==="super_admin"?!0:r==="admin"?E.roles.includes("admin"):o?i(E.path):E.roles.includes(r):!1)})).filter(L=>L.items.length>0);async function j(){await w.auth.signOut(),c("/")}const C=(()=>{const L=(s==null?void 0:s.name)??"";return a!=null&&a.city&&(a!=null&&a.state)?`${L} â ${a.city}, ${a.state}`:L||"Solutions CRM"})(),S=l?(T=d==null?void 0:d.find(L=>L.id===l))==null?void 0:T.name:a==null?void 0:a.name;return t.jsxs("div",{style:{display:"flex",height:"100vh",background:kt.bg,overflow:"hidden"},children:[u&&t.jsx("div",{style:{position:"fixed",inset:0,zIndex:40,background:"rgba(0,0,0,0.6)"},onClick:()=>h(!1),className:"md:hidden"}),t.jsxs("div",{className:"md:hidden",style:{position:"fixed",inset:"0 auto 0 0",zIndex:50,width:240,background:kt.bg,borderRight:`1px solid ${kt.border}`,transform:u?"translateX(0)":"translateX(-100%)",transition:"transform 0.25s ease"},children:[t.jsx("button",{onClick:()=>h(!1),style:{position:"absolute",top:10,right:10,width:32,height:32,borderRadius:8,background:"rgba(255,255,255,0.05)",border:"none",color:"#94a3b8",fontSize:18,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},children:"â"}),t.jsx(dv,{sections:_,profile:n,role:r,tenant:s,open:!0,onClose:()=>h(!1),onSignOut:j,unreadCount:y})]}),t.jsxs("aside",{className:"hidden md:flex flex-col",style:{width:f?224:60,flexShrink:0,background:kt.bg,borderRight:`1px solid ${kt.border}`,transition:"width 0.2s ease",overflow:"hidden"},children:[t.jsx(dv,{sections:_,profile:n,role:r,tenant:s,open:f,onClose:()=>{},onSignOut:j,unreadCount:y}),t.jsx("button",{onClick:()=>p(!f),style:{padding:"10px 14px",borderTop:`1px solid ${kt.border}`,fontSize:11,color:kt.textSec,background:"none",border:"none",cursor:"pointer",textAlign:"left",flexShrink:0},onMouseEnter:L=>L.currentTarget.style.color=kt.textPri,onMouseLeave:L=>L.currentTarget.style.color=kt.textSec,children:f?"â Collapse":"â¶"})]}),t.jsxs("main",{style:{flex:1,overflow:"hidden",display:"flex",flexDirection:"column",minWidth:0},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"0 20px",height:52,flexShrink:0,background:kt.topbar,borderBottom:`1px solid ${kt.border}`},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,flex:1,minWidth:0},children:[t.jsx("button",{className:"md:hidden",onClick:()=>h(!0),style:{background:"none",border:"none",cursor:"pointer",display:"flex",flexDirection:"column",gap:5,padding:4},children:[0,1,2].map(L=>t.jsx("span",{style:{display:"block",width:20,height:2,borderRadius:2,background:"#94a3b8"}},L))}),t.jsx("span",{style:{fontSize:13,color:kt.textSec},children:C})]}),t.jsx("div",{className:"hidden md:block",children:t.jsx(DR,{})}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,flex:1,justifyContent:"flex-end"},children:[S&&t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"5px 12px",borderRadius:8,fontSize:12,fontWeight:600,background:"rgba(13,126,163,0.12)",border:"1px solid rgba(13,126,163,0.3)",color:kt.accent},children:[t.jsx("span",{children:"ð¢"}),t.jsx("span",{children:S})]}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[t.jsx("span",{style:{width:8,height:8,borderRadius:"50%",background:"#4ade80",display:"inline-block",boxShadow:"0 0 6px #4ade8060"}}),t.jsx("span",{style:{fontSize:12,color:kt.textSec},children:"Live"})]})]})]}),t.jsx("div",{style:{flex:1,overflowY:"auto",display:"flex",flexDirection:"column",minHeight:0,padding:"20px 24px"},children:e})]})]})}const cv="getcevora.com",$R=new Set(["localhost","127.0.0.1","getcevora.com","www.getcevora.com"]);function Qb(e=typeof window<"u"?window.location.hostname:""){const n=e.toLowerCase().trim();return n==="localhost"||n==="127.0.0.1"?"zenith":$R.has(n)?null:n.endsWith(`.${cv}`)?n.slice(0,-(cv.length+1)).split(".")[0]||null:(n.endsWith(".vercel.app"),null)}function Ff(e){const[n,r]=g.useState(null),[s,i]=g.useState(!0),[o,a]=g.useState(null);return g.useEffect(()=>{if(!e){i(!1),a("No provider specified");return}i(!0),a(null),w.from("public_tenant_info").select("*").eq("slug",e).maybeSingle().then(({data:l,error:d})=>{d?a(d.message):l?r(l):a("Provider not found"),i(!1)})},[e]),{tenant:n,loading:s,error:o}}function MR(e){if(!e)return"";const n=e.replace(/\D/g,"");return n.length===10?"("+n.slice(0,3)+") "+n.slice(3,6)+"-"+n.slice(6):n.length===11&&n[0]==="1"?"("+n.slice(1,4)+") "+n.slice(4,7)+"-"+n.slice(7):e}function FR(e){const n=[e.address_line1,e.address_line2].filter(
110Boolean).join(", "),s=[[e.city,e.state].filter(Boolean).join(", "),e.zip].filter(Boolean).join(" ");return[n,s].filter(Boolean).join(", ")}function BR(){const e=gt(),[n]=If(),r=n.get("signup")==="success",s=Qb(),{tenant:i}=Ff(s??void 0),o=(i==null?void 0:i.primary_color)||"#0d7ea3",a=(i==null?void 0:i.name)||"Cevora",l=(i==null?void 0:i.tagline)||"Sign in to your account",d=a.charAt(0).toUpperCase(),[c,f]=g.useState(""),[p,u]=g.useState(""),[h,y]=g.useState(!1),[m,b]=g.useState(null);async function A(v){v.preventDefault(),y(!0),b(null);const{error:x}=await w.auth.signInWithPassword({email:c,password:p});x&&(b(x.message),y(!1))}return t.jsx("div",{style:{minHeight:"100vh",backgroundColor:"#0f1923",display:"flex",alignItems:"center",justifyContent:"center",fontFamily:"system-ui, -apple-system, sans-serif",padding:"16px"},children:t.jsxs("div",{style:{width:"100%",maxWidth:"400px"},children:[t.jsxs("div",{style:{textAlign:"center",marginBottom:"32px"},children:[i!=null&&i.logo_url?t.jsx("img",{src:i.logo_url,alt:a,style:{height:"56px",margin:"0 auto 16px",display:"block",objectFit:"contain"}}):t.jsx("div",{style:{width:"56px",height:"56px",borderRadius:"14px",background:`linear-gradient(135deg, ${o}, ${o}cc)`,display:"flex",alignItems:"center",justifyContent:"center",margin:"0 auto 16px",fontSize:"24px",fontWeight:"800",color:"#ffffff",letterSpacing:"-0.5px"},children:d}),t.jsx("h1",{style:{fontSize:"24px",fontWeight:"700",color:"#e2e8f0",margin:"0 0 4px 0"},children:i?a:"Welcome to Cevora"}),t.jsx("p",{style:{color:"#64748b",fontSize:"14px",margin:"0"},children:l})]}),t.jsxs("div",{style:{backgroundColor:"#162232",border:"1px solid #1e3a4f",borderRadius:"12px",padding:"28px"},children:[r&&t.jsx("div",{style:{backgroundColor:"#22c55e18",border:"1px solid #22c55e40",borderRadius:"8px",padding:"12px 16px",marginBottom:"20px",color:"#22c55e",fontSize:"13px",lineHeight:"1.5"},children:"Account created successfully! Sign in to access your dashboard."}),m&&t.jsx("div",{style:{backgroundColor:"#ef444418",border:"1px solid #ef444440",borderRadius:"8px",padding:"12px 16px",marginBottom:"16px",color:"#ef4444",fontSize:"13px",lineHeight:"1.5"},children:m}),t.jsxs("form",{onSubmit:A,children:[t.jsxs("div",{style:{marginBottom:"16px"},children:[t.jsx("label",{style:{display:"block",fontSize:"11px",fontWeight:"600",color:"#64748b",textTransform:"uppercase",letterSpacing:"0.05em",marginBottom:"6px"},children:"Email"}),t.jsx("input",{type:"email",value:c,onChange:v=>f(v.target.value),placeholder:"[email protected]",required:!0,style:{width:"100%",backgroundColor:"#0f1923",border:"1px solid #1e3a4f",borderRadius:"8px",padding:"10px 14px",color:"#e2e8f0",fontSize:"14px",outline:"none",boxSizing:"border-box",transition:"border-color 0.15s"},onFocus:v=>v.currentTarget.style.borderColor="#0d7ea3",onBlur:v=>v.currentTarget.style.borderColor="#1e3a4f"})]}),t.jsxs("div",{style:{marginBottom:"20px"},children:[t.jsx("label",{style:{display:"block",fontSize:"11px",fontWeight:"600",color:"#64748b",textTransform:"uppercase",letterSpacing:"0.05em",marginBottom:"6px"},children:"Password"}),t.jsx("input",{type:"password",value:p,onChange:v=>u(v.target.value),placeholder:"â¢â¢â¢â¢â¢â¢â¢â¢",required:!0,style:{width:"100%",backgroundColor:"#0f1923",border:"1px solid #1e3a4f",borderRadius:"8px",padding:"10px 14px",color:"#e2e8f0",fontSize:"14px",outline:"none",boxSizing:"border-box",transition:"border-color 0.15s"},onFocus:v=>v.currentTarget.style.borderColor="#0d7ea3",onBlur:v=>v.currentTarget.style.borderColor="#1e3a4f"})]}),t.jsx("div",{style:{marginBottom:"16px",textAlign:"right",marginTop:"-8px"},children:t.jsx("button",{type:"button",onClick:()=>e("/forgot-password"),style:{background:"none",border:"none",color:"#0d7ea3",fontSize:"12px",fontWeight:"600",cursor:"pointer",padding:"0"},children:"Forgot password?"})}),t.jsx("button",{type:"submit",disabled:h,style:{width:"100%",backgroundColor:h?"#0a5f7a":"#0d7ea3",color:"#ffffff",border:"none",borderRadius:"8px",padding:"11px",fontSize:"14px",fontWeight:"600",cursor:h?"not-allowed":"pointer",opacity:h?.7:1,transition:"background-color 0.15s, opacity 0.15s"},onMouseEnter:v=>{h||(v.currentTarget.style.backgroundColor="#0b8db5")},onMouseLeave:v=>{h||(v.currentTarget.style.backgroundColor="#0d7ea3")},children:h?"Signing in...":"Sign In"})]}),t.jsx("div",{style:{marginTop:"20px",paddingTop:"20px",borderTop:"1px solid #1e3a4f",textAlign:"center"},children:t.jsxs("p",{style:{color:"#64748b",fontSize:"13px",margin:"0"},children:["Don't have an account?"," ",t.jsx("button",{onClick:()=>e("/signup"),style:{background:"none",border:"none",color:"#0d7ea3",fontSize:"13px",fontWeight:"600",cursor:"pointer",padding:"0"},children:"Start free trial â"})]})})]}),t.jsx("p",{style:{textAlign:"center",color:"#475569",fontSize:"12px",marginTop:"24px"},children:"Cevora â CRM for Water Treatment Companies"})]})})}function UR(){return t.jsx("div",{className:"min-h-screen bg-navy flex items-center justify-center",children:t.jsxs("div",{className:"text-center",children:[t.jsx("div",{className:"w-12 h-12 bg-accent rounded-xl flex items-center justify-center mx-auto mb-4 animate-pulse",children:t.jsx("span",{className:"text-white font-black text-xl",children:"Z"})}),t.jsx("div",{className:"text-muted text-sm",children:"Loading..."})]})})}const Xt=(e,n)=>!!e&&n.includes(e),Kn=["super_admin","admin"],Pd=["super_admin","admin","frontdesk"],HR=["super_admin","admin","frontdesk","salesrep","technician"],yt={completeJobs:e=>Xt(e,HR),viewAllInstallJobs:e=>Xt(e,Kn),addServicePlans:e=>Xt(e,["super_admin","admin","frontdesk","salesrep"]),pauseServicePlans:e=>Xt(e,Pd),cancelServicePlans:e=>Xt(e,Kn),overridePlanPrice:e=>Xt(e,Kn),editReminders:e=>Xt(e,Pd),editSaltReminders:e=>Xt(e,Pd),editMonthlyBilling:e=>Xt(e,Pd),recoverPayments:e=>Xt(e,Pd),reviewDocuments:e=>Xt(e,Kn),manageContracts:e=>Xt(e,Kn),manageTerms:e=>Xt(e,Kn),manageFollowUps:e=>Xt(e,Kn),managePhotos:e=>Xt(e,Kn),manageInventory:e=>Xt(e,Kn),manageInvoices:e=>Xt(e,Kn),manageQuotes:e=>Xt(e,Kn),viewAdminReports:e=>Xt(e,Kn),viewFullSchedule:e=>Xt(e,Kn),manageProducts:e=>Xt(e,Kn)},VR={retail_minus_payments:"Retail Minus Payments",fixed_schedule:"Fixed Schedule",custom:"Custom"};function ZR(e){return e==="admin"||e==="super_admin"}function KR(e){return e==="admin"||e==="super_admin"}
110const YR=["id","name","sku","category","description","retail_price","rental_price_monthly","install_fee","maintenance_price_monthly","filter_interval_months","buyout_formula","warranty_months","requires_survey_type","is_active","track_inventory","created_at","updated_at"].join(", "),XR="*";function GR(e){return e?w.from("product_catalog").select(XR):w.from("product_catalog").select(YR)}async function JR(e,n=!1){let r=GR(n).order("category").order("name");e!=null&&e.activeOnly&&(r=r.eq("is_active",!0)),e!=null&&e.category&&(r=r.eq("category",e.category));const{data:s,error:i}=await r;if(i)throw i;return s||[]}async function QR(e){const{data:n,error:r}=await w.from("product_catalog").insert(e).select().single();if(r)throw r;return n}async function eE(e,n){const{data:r,error:s}=await w.from("product_catalog").update(n).eq("id",e).select().single();if(s)throw s;return r}async function tE(e){const{error:n}=await w.from("product_catalog").update({is_active:!1}).eq("id",e);if(n)throw n}async function nE(e){const{error:n}=await w.from("product_catalog").update({is_active:!0}).eq("id",e);if(n)throw n}const Yg="landing-assets",rE=["image/jpeg","image/png","image/webp"],sE=5*1024*1024;async function iE(){const{data:{user:e}}=await w.auth.getUser();if(!e)throw new Error("Not authenticated");const{data:n,error:r}=await w.from("profiles").select("tenant_id").eq("id",e.id).single();if(r||!(n!=null&&n.tenant_id))throw new Error("No tenant for user");return n.tenant_id}function oE(e){const n=e.lastIndexOf("."),r=(n>0?e.slice(0,n):e).toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40)||"asset",s=(n>0?e.slice(n+1):"").toLowerCase().replace(/[^a-z0-9]/g,"");return s?`${r}.${s}`:r}async function aE(e){try{const n=URL.createObjectURL(e),r=await new Promise((s,i)=>{const o=new Image;o.onload=()=>s({width:o.naturalWidth,height:o.naturalHeight}),o.onerror=()=>i(new Error("dimension read failed")),o.src=n});return URL.revokeObjectURL(n),r}catch{return{width:null,height:null}}}async function e0(e,n){var u;if(!rE.includes(e.type))throw new Error(`Unsupported type ${e.type||"(unknown)"} â JPG, PNG, or WebP only`);if(e.size>sE)throw new Error(`File too large (${Math.round(e.size/1024/1024)}MB) â max 5MB`);if(!n||!n.trim())throw new Error("Alt text is required");const r=await iE(),s=((u=crypto==null?void 0:crypto.randomUUID)==null?void 0:u.call(crypto))||`${Date.now()}-${Math.random().toString(36).slice(2)}`,i=`${r}/${s}-${oE(e.name)}`,{error:o}=await w.storage.from(Yg).upload(i,e,{cacheControl:"3600",upsert:!1,contentType:e.type});if(o)throw new Error(`Upload failed: ${o.message}`);const{data:a}=w.storage.from(Yg).getPublicUrl(i),l=a.publicUrl,{width:d,height:c}=await aE(e),{data:f,error:p}=await w.from("landing_assets").insert({storage_path:i,original_filename:e.name,mime_type:e.type,width:d,height:c,file_size:e.size,alt_text:n.trim(),processing_status:"ready"}).select("*").single();if(p)throw await w.storage.from(Yg).remove([i]).catch(()=>{}),new Error(`Asset record failed: ${p.message}`);return{assetRef:`asset:${i}`,row:f,publicUrl:l}}class sh extends Error{constructor(n){super(n),this.name="FamilyValidationError"}}const uv=8;async function lE(){const{data:e,error:n}=await w.from("product_families").select("*").order("sort_order").order("name");if(n)throw new Error(`Failed to load product families: ${n.message}`);const r=e||[];if(!r.length)return[];const{data:s,error:i}=await w.from("product_catalog").select("family_id").not("family_id","is",null);if(i)return console.error("[productFamilies] count lookup failed:",i.message),r.map(a=>({...a,product_count:0}));const o=new Map;for(const a of s||[]){const l=a.family_id;o.set(l,(o.get(l)||0)+1)}return r.map(a=>({...a,product_count:o.get(a.id)||0}))}async function dE(e){const{data:n,error:r}=await w.from("product_catalog").select("id, name").eq("family_id",e).eq("is_active",!0).order("name");if(r)throw new Error(`Failed to load the family's products: ${r.message}`);return n||[]}function N4(e){if(!e.name.trim())throw new sh("A family needs a name.");if(e.highlights.length>uv)throw new sh(`${uv} bullets is the most a card can carry without burying the price.`);if(e.marketing_url&&!/^https?:\/\//i.test(e.marketing_url))throw new sh("The product page link needs to start with http:// or https://")}async function cE(e,n){var i,o,a;N4(e);const{data:r,error:s}=await w.from("product_families").insert({name:e.name.trim(),eyebrow:((i=e.eyebrow)==null?void 0:i.trim())||null,tagline:((o=e.tagline)==null?void 0:o.trim())||null,highlights:e.highlights.filter(l=>l.trim()).map(l=>l.trim()),image_url:e.image_url,marketing_url:((a=e.marketing_url)==null?void 0:a.trim())||null,sort_order:n}).select().single();if(s||!r)throw new Error(`Failed to create the family: ${s==null?void 0:s.message}`);return r}async function uE(e,n){var i,o,a;N4(n);const{data:r,error:s}=await w.from("product_families").update({name:n.name.trim(),eyebrow:((i=n.eyebrow)==null?void 0:i.trim())||null,tagline:((o=n.tagline)==null?void 0:o.trim())||null,highlights:n.highlights.filter(l=>l.trim()).map(l=>l.trim()),image_url:n.image_url,marketing_url:((a=n.marketing_url)==null?void 0:a.trim())||null,updated_at:new Date().toISOString()}).eq("id",e).select().single();if(s||!r)throw new Error(`Failed to save the family: ${s==null?void 0:s.message}`);return r}async function pE(e,n){const{publicUrl:r}=await e0(e,`${n} product photo`);return r}async function hE(){const{data:e,error:n}=await w.from("product_families").select("*").eq("is_active",!0);if(n)return console.error("[productFamilies] map load failed:",n.message),new Map;const r=new Map;for(const s of e||[])r.set(s.id,s);return r}
110const pv={name:"",eyebrow:"",tagline:"",highlights:[""],image_url:null,marketing_url:""};function fE(){const[e,n]=g.useState([]),[r,s]=g.useState(!0),[i,o]=g.useState(null),[a,l]=g.useState(pv),[d,c]=g.useState([]),[f,p]=g.useState(!1),[u,h]=g.useState(!1),[y,m]=g.useState(""),[b,A]=g.useState(""),v=g.useRef(null),x=g.useCallback(async()=>{s(!0);try{n(await lE()),m("")}catch(T){m(T.message)}finally{s(!1)}},[]);g.useEffect(()=>{x()},[x]);async function _(T){var L;o(T.id),m(""),A(""),l({name:T.name,eyebrow:T.eyebrow||"",tagline:T.tagline||"",highlights:(L=T.highlights)!=null&&L.length?[...T.highlights]:[""],image_url:T.image_url,marketing_url:T.marketing_url||""});try{c(await dE(T.id))}catch{c([])}}function j(){o("new"),l({...pv,highlights:[""]}),c([]),m(""),A("")}async function C(T){var E;const L=(E=T.target.files)==null?void 0:E[0];if(L){h(!0),m("");try{const R=await pE(L,a.name||"Product");l(N=>({...N,image_url:R})),A("Photo uploaded. Save to keep it.")}catch(R){m(`Photo not uploaded: ${R.message}`)}finally{h(!1),v.current&&(v.current.value="")}}}async function S(){p(!0),m(""),A("");try{i==="new"?await cE(a,e.length):i&&await uE(i,a),o(null),await x()}catch(T){m(T instanceof sh?T.message:`Could not save: ${T.message}`)}finally{p(!1)}}return i?t.jsxs("div",{style:{border:"1px solid #1e3a4f",borderRadius:12,padding:18},children:[t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"baseline",marginBottom:16},children:[t.jsx("div",{style:{fontSize:16,fontWeight:700,color:"#e2e8f0"},children:i==="new"?"New product family":a.name}),t.jsx("button",{onClick:()=>o(null),style:gE,children:"Cancel"})]}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"minmax(0,1fr) 240px",gap:20,alignItems:"start"},children:[t.jsxs("div",{children:[t.jsx(rp,{label:"Name",hint:"Internal â what you call this product",children:t.jsx("input",{value:a.name,onChange:T=>l(L=>({...L,name:T.target.value})),style:qd})}),t.jsx(rp,{label:"Eyebrow",hint:"Small line above the name, e.g. DEPENDABLE WHOLE-HOME SOFTENING",children:t.jsx("input",{value:a.eyebrow||"",onChange:T=>l(L=>({...L,eyebrow:T.target.value})),style:qd})}),t.jsx(rp,{label:"One-line promise",hint:"The sentence under the name",children:t.jsx("input",{value:a.tagline||"",onChange:T=>l(L=>({...L,tagline:T.target.value})),style:qd})}),t.jsx(rp,{label:"Product page link",hint:"Optional â your own site",children:t.jsx("input",{value:a.marketing_url||"",onChange:T=>l(L=>({...L,marketing_url:T.target.value})),style:qd})}),t.jsxs("div",{style:{marginTop:14},children:[t.jsx("div",{style:{fontSize:11,color:"#64748b",marginBottom:6},children:"Benefit bullets â up to 8, in the order they appear"}),a.highlights.map((T,L)=>t.jsxs("div",{style:{display:"flex",gap:6,marginBottom:6},children:[t.jsx("input",{value:T,onChange:E=>l(R=>{const N=[...R.highlights];return N[L]=E.target.value,{...R,highlights:N}}),style:{...qd,flex:1,marginBottom:0}}),t.jsx("button",{onClick:()=>l(E=>({...E,highlights:E.highlights.filter((R,N)=>N!==L).length?E.highlights.filter((R,N)=>N!==L):[""]})),"aria-label":"Remove this bullet",style:{...np,width:34},children:"Ã"})]},L)),a.highlights.length<8&&t.jsx("button",{onClick:()=>l(T=>({...T,highlights:[...T.highlights,""]})),style:np,children:"Add a bullet"})]})]}),t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:11,color:"#64748b",marginBottom:6},children:"Product photo"}),t.jsx("div",{style:{width:"100%",height:180,borderRadius:10,marginBottom:8,border:a.image_url?"1px solid #1e3a4f":"1px dashed #1e3a4f",background:"#162232",display:"flex",alignItems:"center",justifyContent:"center",overflow:"hidden"},children:a.image_url?t.jsx("img",{src:a.image_url,alt:"",style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain"}}):t.jsx("span",{style:{fontSize:12,color:"#475569"},children:"No photo yet"})}),t.jsx("input",{ref:v,type:"file",accept:"image/jpeg,image/png,image/webp",onChange:C,style:{display:"none"},id:"family-photo"}),t.jsx("label",{htmlFor:"family-photo",style:{...np,display:"block",textAlign:"center",cursor:"pointer"},children:u?"Uploadingâ¦":a.image_url?"Replace photo":"Upload a photo"}),t.jsx("p",{style:{fontSize:11,color:"#475569",marginTop:8,lineHeight:1.5},children:"JPG, PNG or WebP, up to 5 MB. A plain product shot on white works best."}),d.length>0&&t.jsxs("div",{style:{marginTop:18},children:[t.jsxs("div",{style:{fontSize:11,color:"#64748b",marginBottom:6},children:["Used by ",d.length," ",d.length===1?"product":"products"]}),d.map(T=>t.jsx("div",{style:{fontSize:12,color:"#94a3b8",lineHeight:1.5,marginBottom:3},children:T.name},T.id))]})]})]}),b&&t.jsx("p",{style:{fontSize:12,color:"#4ade80",marginTop:14},children:b}),y&&t.jsx("p",{style:{fontSize:12,color:"#f87171",marginTop:14,lineHeight:1.5},children:y}),t.jsxs("div",{style:{display:"flex",gap:8,marginTop:18},children:[t.jsx("button",{onClick:S,disabled:f||u,style:hv(f||u),
110children:f?"Savingâ¦":"Save family"}),t.jsx("button",{onClick:()=>o(null),style:np,children:"Cancel"})]})]}):t.jsxs("div",{style:{border:"1px solid #1e3a4f",borderRadius:12,padding:18},children:[t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"baseline",marginBottom:6},children:[t.jsx("div",{style:{fontSize:16,fontWeight:700,color:"#e2e8f0"},children:"Product families"}),t.jsx("button",{onClick:j,style:hv(!1),children:"New family"})]}),t.jsx("p",{style:{fontSize:13,color:"#64748b",lineHeight:1.55,marginBottom:16,maxWidth:"70ch"},children:"What a customer sees on a final offer: the photo, the one-line promise and the benefit bullets. Written once per product, so every size of the same system shares it."}),r?t.jsx("p",{style:{fontSize:13,color:"#64748b"},children:"Loadingâ¦"}):e.length?t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:e.map(T=>{var L;return t.jsxs("button",{onClick:()=>_(T),style:{display:"flex",gap:14,alignItems:"center",textAlign:"left",padding:12,background:"#162232",border:"1px solid #1e3a4f",borderRadius:10,cursor:"pointer",width:"100%"},children:[t.jsx("div",{style:{width:56,height:56,borderRadius:8,flexShrink:0,background:"#0f1c2b",border:T.image_url?"1px solid #1e3a4f":"1px dashed #1e3a4f",display:"flex",alignItems:"center",justifyContent:"center",overflow:"hidden"},children:T.image_url?t.jsx("img",{src:T.image_url,alt:"",style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain"}}):t.jsx("span",{style:{fontSize:9,color:"#475569"},children:"no photo"})}),t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsx("div",{style:{fontSize:14,fontWeight:600,color:"#e2e8f0"},children:T.name}),t.jsxs("div",{style:{fontSize:12,color:"#64748b",marginTop:2},children:[T.product_count," ",T.product_count===1?"product":"products"," · ",((L=T.highlights)==null?void 0:L.length)||0," bullets",!T.image_url&&" · needs a photo"]})]}),t.jsx("span",{style:{fontSize:12,color:"#64748b"},children:"Edit"})]},T.id)})}):t.jsx("p",{style:{fontSize:13,color:"#64748b"},children:"No families yet. Add one and point your catalog products at it."}),y&&t.jsx("p",{style:{fontSize:12,color:"#f87171",marginTop:14},children:y})]})}const qd={width:"100%",padding:"8px 10px",fontSize:13,color:"#e2e8f0",background:"#162232",border:"1px solid #1e3a4f",borderRadius:8,marginBottom:12,boxSizing:"border-box"},np={padding:"7px 12px",fontSize:12,fontWeight:600,borderRadius:7,color:"#94a3b8",background:"none",border:"1px solid #1e3a4f",cursor:"pointer"},gE={fontSize:13,color:"#64748b",background:"none",border:"none",cursor:"pointer"};function hv(e){return{padding:"8px 14px",fontSize:13,fontWeight:700,borderRadius:8,border:"none",color:e?"#475569":"#0f1c2b",background:e?"#1e3a4f":"#38bdf8",cursor:e?"not-allowed":"pointer"}}function rp({label:e,hint:n,children:r}){return t.jsxs("label",{style:{display:"block"},children:[t.jsx("div",{style:{fontSize:11,color:"#64748b",marginBottom:4},children:e}),r,n&&t.jsx("div",{style:{fontSize:10,color:"#475569",marginTop:-8,marginBottom:12},children:n})]})}function mE(){const[e,n]=g.useState(window.innerWidth<768);return g.useEffect(()=>{const r=()=>n(window.innerWidth<768);return window.addEventListener("resize",r),()=>window.removeEventListener("resize",r)},[]),e}const fv={name:"",sku:"",category:"ro",description:"",retail_price:null,rental_price_monthly:null,install_fee:0,maintenance_price_monthly:null,filter_interval_months:null,buyout_formula:"retail_minus_payments",warranty_months:12,requires_survey_type:null,is_active:!0,vendor_sku:null,vendor_cost:null,vendor_id:null,subcategory:null,min_sell_price:null,vendor_name:null,vendor_description:null,parts_warranty:null,parts_warranty_unit:"months",labour_warranty:null,labour_warranty_unit:"months",max_discount_pct:0,is_open_item:!1},gv={ro:{bg:"rgba(6,182,212,0.15)",text:"#22d3ee",border:"rgba(6,182,212,0.3)"},softener:{bg:"rgba(59,130,246,0.15)",text:"#60a5fa",border:"rgba(59,130,246,0.3)"},whole_home_filter:{bg:"rgba(167,139,250,0.15)",text:"#a78bfa",border:"rgba(167,139,250,0.3)"},replacement_filter:{bg:"rgba(251,191,36,0.15)",text:"#fbbf24",border:"rgba(251,191,36,0.3)"},accessory:{bg:"rgba(148,163,184,0.15)",text:"#cbd5e1",border:"rgba(148,163,184,0.3)"},uv:{bg:"rgba(52,211,153,0.15)",text:"#34d399",border:"rgba(52,211,153,0.3)"},iron_filter:{bg:"rgba(251,146,60,0.15)",text:"#fb923c",border:"rgba(251,146,60,0.3)"},pfas:{bg:"rgba(244,114,182,0.15)",text:"#f472b6",border:"rgba(244,114,182,0.3)"},salt_free:{bg:"rgba(34,197,94,0.15)",text:"#4ade80",border:"rgba(34,197,94,0.3)"},lead_filter:{bg:"rgba(239,68,68,0.15)",text:"#f87171",border:"rgba(239,68,68,0.3)"},well_water:{bg:"rgba(217,119,6,0.15)",text:"#fbbf24",border:"rgba(217,119,6,0.3)"},miscellaneous:{bg:"rgba(148,163,184,0.15)",text:"#cbd5e1",border:"rgba(148,163,184,0.3)"}},mv={bg:"rgba(148,163,184,0.15)",text:"#cbd5e1",border:"rgba(148,163,184,0.3)"},Xg={ro:"Reverse Osmosis",softener:"Water Softener",whole_home_filter:"Whole Home Filter",replacement_filter:"Replacement Filter",accessory:"Accessory",uv:"UV Sterilization",iron_filter:"Iron Filter",pfas:"PFAS Filter",salt_free:"Salt-Free",lead_f
110ilter:"Lead Filter",well_water:"Well Water",miscellaneous:"Miscellaneous"},xE=[{key:"all",label:"All",icon:"â",color:"#e2e8f0",bg:"rgba(226,232,240,0.1)",border:"rgba(226,232,240,0.2)"},{key:"ro",label:"RO",icon:"ð§",color:"#22d3ee",bg:"rgba(6,182,212,0.1)",border:"rgba(6,182,212,0.25)"},{key:"softener",label:"Softener",icon:"ðµ",color:"#60a5fa",bg:"rgba(59,130,246,0.1)",border:"rgba(59,130,246,0.25)"},{key:"whole_home_filter",label:"Whole Home",icon:"ð ",color:"#a78bfa",bg:"rgba(167,139,250,0.1)",border:"rgba(167,139,250,0.25)"},{key:"salt_free",label:"Salt-Free",icon:"ð",color:"#4ade80",bg:"rgba(34,197,94,0.1)",border:"rgba(34,197,94,0.25)"},{key:"well_water",label:"Well Water",icon:"ð",color:"#fbbf24",bg:"rgba(217,119,6,0.1)",border:"rgba(217,119,6,0.25)"},{key:"uv",label:"UV",icon:"âï¸",color:"#34d399",bg:"rgba(52,211,153,0.1)",border:"rgba(52,211,153,0.25)"},{key:"pfas",label:"PFAS",icon:"ð¡ï¸",color:"#f472b6",bg:"rgba(244,114,182,0.1)",border:"rgba(244,114,182,0.25)"},{key:"lead_filter",label:"Lead",icon:"â ï¸",color:"#f87171",bg:"rgba(239,68,68,0.1)",border:"rgba(239,68,68,0.25)"},{key:"replacement_filter",label:"Filters",icon:"ð",color:"#fbbf24",bg:"rgba(251,191,36,0.1)",border:"rgba(251,191,36,0.25)"},{key:"accessory",label:"Accessory",icon:"ð§",color:"#94a3b8",bg:"rgba(148,163,184,0.1)",border:"rgba(148,163,184,0.25)"},{key:"miscellaneous",label:"Misc",icon:"ð§¾",color:"#94a3b8",bg:"rgba(148,163,184,0.1)",border:"rgba(148,163,184,0.25)"}];function pi(e){return e==null?"â":`$${Number(e).toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}`}function sp({value:e,unit:n,icon:r}){if(!e)return t.jsx("span",{style:{color:"#334155"},children:"â"});const s="#38bdf8",i=n==="years"?e===1?"year":"years":e===1?"month":"months";return t.jsxs("span",{style:{fontSize:10,padding:"2px 7px",borderRadius:20,fontWeight:700,background:`${s}15`,border:`1px solid ${s}35`,color:s,whiteSpace:"nowrap"},children:[r," ",e," ",i]})}function yE(){const{profile:e}=Ee(),n=mE(),r=(e==null?void 0:e.role)??null,s=ZR(r),i=KR(r),[o,a]=g.useState([]),[l,d]=g.useState(!0),[c,f]=g.useState(!1),[p,u]=g.useState(null),[h,y]=g.useState(fv),[m,b]=g.useState(!1),[A,v]=g.useState(null),[x,_]=g.useState("all"),[j,C]=g.useState(!1),[S,T]=g.useState("");g.useEffect(()=>{L()},[x,j,r]);async function L(){d(!0);try{const k=await JR({activeOnly:!j,category:x==="all"?void 0:x},yt.manageProducts(r));a(k)}catch(k){v(k.message)}finally{d(!1)}}function E(){y(fv),u(null),f(!0),v(null)}function R(k){y({name:k.name,sku:k.sku||"",category:k.category,description:k.description||"",retail_price:k.retail_price,rental_price_monthly:k.rental_price_monthly,install_fee:k.install_fee,maintenance_price_monthly:k.maintenance_price_monthly,filter_interval_months:k.filter_interval_months,buyout_formula:k.buyout_formula,warranty_months:k.warranty_months,requires_survey_type:k.requires_survey_type,is_active:k.is_active,vendor_sku:k.vendor_sku??null,vendor_cost:k.vendor_cost??null,vendor_id:k.vendor_id??null,subcategory:k.subcategory??null,min_sell_price:k.min_sell_price??null,vendor_name:k.vendor_name??null,vendor_description:k.vendor_description??null,parts_warranty:k.parts_warranty??null,parts_warranty_unit:k.parts_warranty_unit??"months",labour_warranty:k.labour_warranty??null,labour_warranty_unit:k.labour_warranty_unit??"months",max_discount_pct:k.max_discount_pct??0,is_open_item:k.is_open_item??!1}),u(k.id),f(!0),v(null)}async function N(){if(!h.name.trim()){v("Product name is required");return}b(!0),v(null);try{const k={...h};i||(delete k.vendor_sku,delete k.vendor_cost,delete k.vendor_id,delete k.vendor_name,delete k.vendor_description,delete k.min_sell_price),p?await eE(p,k):await QR(k),f(!1),u(null),await L()}catch(k){v(k.message)}finally{b(!1)}}async function O(k){try{k.is_active?await tE(k.id):await nE(k.id),await L()}catch(q){v(q.message)}}function z(k,q){y($=>({...$,[k]:q}))}const P=o.filter(k=>k.is_active).length,D=[...new Set(o.map(k=>k.category))].length,M=o.filter(k=>{if(!S.trim())return!0;const q=S.toLowerCase();return k.name.toLowerCase().includes(q)||k.sku&&k.sku.toLowerCase().includes(q)||s&&k.vendor_sku&&k.vendor_sku.toLowerCase().includes(q)||k.description&&k.description.toLowerCase().includes(q)||k.subcategory&&k.subcategory.toLowerCase().includes(q)});return t.jsxs("div",{style:{background:"#0f1923",minHeight:"100vh",color:"#e2e8f0",display:"flex",flexDirection:"column"},children:[t.jsxs("div",{style:{background:"#162232",borderBottom:"1px solid #1e3a4f",padding:"16px 20px",display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsx("div",{style:{fontWeight:800,fontSize:20,color:"#e2e8f0",lineHeight:1.2},children:"Product Catalog"}),t.jsxs("div",{style:{color:"#64748b",fontSize:12,marginTop:2},children:[o.length," product",o.length!==1?"s":""," · Prices feed quotes, contracts, and billing."]})]}),!n&&t.jsx("input",{placeholder:"Search name, SKU, subcategoryâ¦",value:S,onChange:k=>T(k.target.value),style:{background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:8,color:"#e2e8f0",padding:"9px 14px",fontSize:13,outline:"none",width:240}}),t.jsxs("label",{style:{display:"flex",alignItems:"center",gap:6,cursor:"pointer"},children:[t.jsx("input",{type:"checkbox",checked:j,onChange:k=>C(k.target.checked),style:{accentColor:"#0d7ea3"}}),t.jsx("span",{style:{fontSize:13,color:"#94a3b8"},children:"Inactive"})]}),yt.manageProducts(r)&&t.jsx("button",{onClick:E,style:{padding:"10px 18px",borderRadius:8,border:"none",cursor:"pointer",background:"#0d7ea3",color:"#fff",fontWeight:700,fontSize:14,whiteSpace:"nowrap"},children:"+ Add Product"})]}),n&&t.jsx("div",{style:{padding:"10px 16px",background:"#0f1923",borderBottom:"1px solid #1e3a4f"},children:t.jsx("input",{placeholder:"Searchâ¦",value:S,onChange:k=>T(k.target.value),style:{background:"#162232",border:"1px solid #1e3a4f",borderRadius:8,color:"#e2e8f0",padding:"10px 14px",fontSize:14,outline:"none",width:"100%",boxSizing:"border-box"}})}),yt.manageProducts(r)&&t.jsx("div",{style:{padding:"12px 16px",background:"#0f1923",borderBottom:"1px solid #1e3a4f"},children:t.jsxs("details",{children:[t.jsx("summary",{style:{cursor:"pointer",fontSize:13,fontWeight:600,color:"#94a3b8",listStyle:"none",padding:"4px 0"},children:"Product families â photos and copy for final offers"}),t.jsx("div",{style:{marginTop:12},children:t.jsx(fE,{})})]})}),t.jsx("div",{style:{background:"#0c1a26",borderBottom:"1px solid #1e3a4f",padding:"10px 16px",display:"flex",gap:6,overflowX:"auto"},children:xE.map(k=>{const q=k.key==="all"?o.length:o.filter(I=>I.category===k.key).length,$=x===k.key;return k.key!=="all"&&q===0?null:t.jsxs("button",{onClick:()=>_(k.key),style:{flexShrink:0,display:"flex",alignItems:"center",gap:5,padding:n?"8px 10px":"9px 12px",borderRadius:10,border:`1px solid ${$?k.color+"60":k.border}`,background:$?k.bg:"rgba(255,255,255,0.02)",color:$?k.color:"#475569",cursor:"pointer",fontSize:12,fontWeight:$?700:500,boxShadow:$?`0 0 14px ${k.color}20`:"none",whiteSpace:"nowrap"},children:[t.jsx("span",{children:k.icon}),!n&&t.jsx("span",{children:k.label}),t.jsx("span",{style:{background:$?k.color+"30":"rgba(255,255,255,0.06)",color:$?k.color:"#64748b",borderRadius:20,padding:"1px 6px",fontSize:11,fontWeight:700},children:q})]},k.key)})}),t.jsx("div",{style:{display:"flex",gap:10,padding:"12px 16px",borderBottom:"1px solid #1e3a4f",background:"#0f1923",overflowX:"auto"},children:[{label:"Showing",val:String(M.length),color:"#94a3b8"},{label:"Active",val:String(P),color:"#4ade80"},{label:"Categories",val:String(D),color:"#a78bfa"}].map(k=>t.jsxs("div",{style:{background:"#162232",border:"1px solid #1e3a4f",borderRadius:10,padding:"8px 14px",flexShrink:0,minWidth:90},children:[t.jsx("div",{style:{color:"#64748b",fontSize:10,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.08em"},children:k.label}),t.jsx("div",{style:{color:k.color,fontWeight:800,fontSize:18,marginTop:2},children:k.val})]},k.label))}),A&&!c&&t.jsxs("div",{style:{margin:"12px 16px 0",padding:"10px 14px",borderRadius:8,background:"rgba(239,68,68,0.12)",border:"1px solid rgba(239,68,68,0.3)",color:"#f87171",fontSize:13,display:"flex",alignItems:"center",justifyContent:"space-between"},children:[t.jsx("span",{children:A}),t.jsx("button",{onClick:()=>v(null),style:{background:"none",border:"none",color:"#f87171",cursor:"pointer",fontSize:16},children:"Ã"})]}),t.jsx("div",{style:{flex:1,overflowY:"auto",padding:n?"12px":"16px 24px"},children:l?t.jsx("div",{style:{textAlign:"center",padding:60,color:"#64748b"},children:"Loading productsâ¦"}):M.length===0?t.jsxs("div",{style:{textAlign:"center",padding:60},children:[t.jsx("div",{style:{fontSize:40,marginBottom:12},children:"ð¦"}),t.jsx("div",{style:{color:"#64748b",fontSize:15},children:S?"No products matching your search":"No products found"}),!S&&yt.manageProducts(r)&&t.jsx("button",{onClick:E,style:{marginTop:16,padding:"10px 24px",borderRadius:8,border:"none",cursor:"pointer",background:"#0d7ea3",color:"#fff",fontWeight:700},children:"Add First Product"})]}):n?t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:10},children:M.map(k=>{const q=gv[k.category]||mv,$=k;return t.jsxs("div",{style:{background:"#162232",border:"1px solid #1e3a4f",borderRadius:12,padding:"14px 16px",opacity:k.is_active?1:.5},children:[t.jsxs("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:8,marginBottom:6},children:[t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsx("div",{style:{fontSize:15,fontWeight:700,color:"#e2e8f0"},children:k.name}),k.sku&&t.jsx("div",{style:{fontSize:11,color:"#64748b",fontFamily:"monospace",marginTop:2},children:k.sku}),$.subcategory&&t.jsx("div",{style:{fontSize:11,color:"#475569",marginTop:2},children:$.subcategory})]}),t.jsx("span",{style:{fontSize:11,fontWeight:700,color:k.is_active?"#4ade80":"#f87171",background:k.is_active?"rgba(74,222,128,0.12)":"rgba(248,113,113,0.12)",border:`1px solid ${k.is_active?"rgba(74,222,128,0.3)":"rgba(248,113,113,0.3)"}`,padding:"3px 8px",borderRadius:6},children:k.is_active?"Active":"Inactive"})]}),t.jsx("div",{style:{marginBottom:8,display:"flex",gap:6,flexWrap:"wrap"},children:t.jsx("span",{style:{fontSize:11,fontWeight:700,padding:"3px 8px",borderRadius:6,color:q.text,background:q.bg,border:`1px solid ${q.border}`},children:Xg[k.category]||k.category})}),t.jsx("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8,marginBottom:8},children:[{label:"Retail",val:pi(k.retail_price),color:"#e2e8f0"},{label:"Rental/mo",val:pi(k.rental_price_monthly),color:k.rental_price_monthly?"#22d3ee":"#475569"}
110,{label:"Install Fee",val:pi(k.install_fee),color:"#e2e8f0"},{label:"Warranty",val:k.warranty_months?`${k.warranty_months}mo`:"â",color:"#94a3b8"}].map(I=>t.jsxs("div",{style:{background:"#0f1923",borderRadius:8,padding:"8px 10px",border:"1px solid #1a2a3a"},children:[t.jsx("div",{style:{fontSize:10,color:"#64748b",textTransform:"uppercase",fontWeight:600},children:I.label}),t.jsx("div",{style:{fontSize:14,fontWeight:700,color:I.color,marginTop:2},children:I.val})]},I.label))}),($.parts_warranty||$.labour_warranty)&&t.jsxs("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginBottom:8},children:[$.parts_warranty&&t.jsx(sp,{value:$.parts_warranty,unit:$.parts_warranty_unit,icon:"ð©"}),$.labour_warranty&&t.jsx(sp,{value:$.labour_warranty,unit:$.labour_warranty_unit,icon:"ð·"})]}),yt.manageProducts(r)&&t.jsxs("div",{style:{display:"flex",gap:8,paddingTop:10,borderTop:"1px solid #1e3a4f"},children:[t.jsx("button",{onClick:()=>R(k),style:{flex:1,padding:"8px 0",borderRadius:8,border:"1px solid rgba(13,126,163,0.3)",background:"transparent",color:"#22d3ee",cursor:"pointer",fontSize:13,fontWeight:600},children:"Edit"}),t.jsx("button",{onClick:()=>O(k),style:{flex:1,padding:"8px 0",borderRadius:8,border:`1px solid ${k.is_active?"rgba(248,113,113,0.25)":"rgba(74,222,128,0.25)"}`,background:"transparent",color:k.is_active?"#f87171":"#4ade80",cursor:"pointer",fontSize:13,fontWeight:600},children:k.is_active?"Deactivate":"Reactivate"})]})]},k.id)})}):t.jsx("div",{style:{background:"#162232",border:"1px solid #1e3a4f",borderRadius:12,overflowX:"auto"},children:t.jsxs("table",{style:{width:"100%",borderCollapse:"collapse"},children:[t.jsx("thead",{children:t.jsx("tr",{style:{background:"#0f1923",borderBottom:"1px solid #1e3a4f"},children:[{label:"Product",align:"left"},{label:"SKU",align:"left"},...s?[{label:"Vendor SKU",align:"left"}]:[],{label:"Category",align:"left"},{label:"Retail",align:"right"},...s?[{label:"Cost",align:"right"},{label:"Min Sell",align:"right"}]:[],{label:"Rental/mo",align:"right"},{label:"Install",align:"right"},{label:"Parts Warranty",align:"left"},{label:"Labour Warranty",align:"left"},{label:"Status",align:"center"},{label:"Actions",align:"right"}].map(k=>t.jsx("th",{style:{padding:"10px 12px",fontSize:10,fontWeight:700,color:"#64748b",textTransform:"uppercase",letterSpacing:"0.08em",textAlign:k.align,whiteSpace:"nowrap",...k.label==="Actions"?{position:"sticky",right:0,background:"#0f1923"}:{}},children:k.label},k.label))})}),t.jsx("tbody",{children:M.map(k=>{const q=gv[k.category]||mv,$=k;return t.jsxs("tr",{style:{borderBottom:"1px solid #1a2a3a",opacity:k.is_active?1:.45},onMouseEnter:I=>{I.currentTarget.style.background="#1a2e42"},onMouseLeave:I=>{I.currentTarget.style.background="transparent"},children:[t.jsxs("td",{style:{padding:"10px 12px",maxWidth:220},children:[t.jsx("div",{style:{fontSize:13,fontWeight:600,color:"#e2e8f0",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:k.name}),$.subcategory&&t.jsx("div",{style:{fontSize:10,color:"#475569",marginTop:1},children:$.subcategory})]}),t.jsx("td",{style:{padding:"10px 12px",fontSize:11,color:"#94a3b8",fontFamily:"monospace",whiteSpace:"nowrap"},children:k.sku||"â"}),s&&t.jsx("td",{style:{padding:"10px 12px",fontSize:11,fontFamily:"monospace"},children:k.vendor_sku?t.jsx("span",{style:{color:"#fbbf24",background:"rgba(251,191,36,0.08)",border:"1px solid rgba(251,191,36,0.2)",borderRadius:4,padding:"2px 6px"},children:k.vendor_sku}):t.jsx("span",{style:{color:"#334155"},children:"â"})}),t.jsx("td",{style:{padding:"10px 12px"},children:t.jsx("span",{style:{fontSize:11,fontWeight:700,padding:"3px 9px",borderRadius:6,color:q.text,background:q.bg,border:`1px solid ${q.border}`,whiteSpace:"nowrap"},children:Xg[k.category]||k.category})}),t.jsx("td",{style:{padding:"10px 12px",textAlign:"right",fontSize:13,fontWeight:700,color:"#e2e8f0",whiteSpace:"nowrap"},children:pi(k.retail_price)}),s&&t.jsxs(t.Fragment,{children:[t.jsx("td",{style:{padding:"10px 12px",textAlign:"right",fontSize:12,color:k.vendor_cost?"#4ade80":"#334155",whiteSpace:"nowrap"},children:k.vendor_cost!=null?pi(k.vendor_cost):"â"}),t.jsx("td",{style:{padding:"10px 12px",textAlign:"right",fontSize:12,color:$.min_sell_price?"#fbbf24":"#334155",whiteSpace:"nowrap"},children:$.min_sell_price?pi($.min_sell_price):"â"})]}),t.jsx("td",{style:{padding:"10px 12px",textAlign:"right",fontSize:12,fontWeight:600,color:k.rental_price_monthly?"#22d3ee":"#475569",whiteSpace:"nowrap"},children:pi(k.rental_price_monthly)}),t.jsx("td",{style:{padding:"10px 12px",textAlign:"right",fontSize:12,color:"#e2e8f0",whiteSpace:"nowrap"},children:pi(k.install_fee)}),t.jsx("td",{style:{padding:"10px 12px"},children:t.jsx(sp,{value:$.parts_warranty,unit:$.parts_warranty_unit,icon:"ð©"})}),t.jsx("td",{style:{padding:"10px 12px"},children:t.jsx(sp,{value:$.labour_warranty,unit:$.labour_warranty_unit,icon:"ð·"})}),t.jsx("td",{style:{padding:"10px 12px",textAlign:"center"},children:t.jsx("span",{style:{fontSize:11,fontWeight:700,padding:"3px 9px",borderRadius:6,color:k.is_active?"#4ade80":"#f87171",background:k.is_active?"rgba(74,222,128,0.12)":"rgba(248,113,113,0.12)",border:`1px solid ${k.is_active?"rgba(74,222,128,0.3)":"rgba(248,113,113,0.3)"}`},children:k.is_active?"Active":"Inactive"})}),t.jsx("td",{style:{padding:"10px 12px",textAlign:"right",position:"sticky",right:0,background:"#162232"},children:yt.manageProducts(r)&&t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",gap:6},children:[t.jsx("button",{onClick:()=>R(k),style:{padding:"4px 10px",borderRadius:6,border:"1px solid rgba(13,126,163,0.3)",background:"transparent",color:"#22d3ee",cursor:"pointer",fontSize:11,fontWeight:600},onMouseEnter:I=>{I.currentTarget.style.background="rgba(13,126,163,0.15)"},onMouseLeave:I=>
110{I.currentTarget.style.background="transparent"},children:"Edit"}),t.jsx("button",{onClick:()=>O(k),style:{padding:"4px 10px",borderRadius:6,border:`1px solid ${k.is_active?"rgba(248,113,113,0.25)":"rgba(74,222,128,0.25)"}`,background:"transparent",color:k.is_active?"#f87171":"#4ade80",cursor:"pointer",fontSize:11,fontWeight:600},onMouseEnter:I=>{I.currentTarget.style.background=k.is_active?"rgba(248,113,113,0.12)":"rgba(74,222,128,0.12)"},onMouseLeave:I=>{I.currentTarget.style.background="transparent"},children:k.is_active?"Deactivate":"Reactivate"})]})})]},k.id)})})]})})}),c&&yt.manageProducts(r)&&t.jsx("div",{style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.65)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:50,padding:16},children:t.jsxs("div",{style:{background:"#162232",border:"1px solid #1e3a4f",borderRadius:12,width:"100%",maxWidth:720,maxHeight:"92vh",overflowY:"auto"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"20px 24px",borderBottom:"1px solid #1e3a4f"},children:[t.jsxs("div",{children:[t.jsx("div",{style:{color:"#e2e8f0",fontWeight:700,fontSize:18},children:p?"Edit Product":"Add New Product"}),t.jsx("div",{style:{color:"#64748b",fontSize:13,marginTop:2},children:p?"Update product details":"Fill in product information"})]}),t.jsx("button",{onClick:()=>{f(!1),u(null)},style:{background:"none",border:"none",color:"#64748b",fontSize:20,cursor:"pointer"},children:"Ã"})]}),t.jsxs("div",{style:{padding:24,display:"flex",flexDirection:"column",gap:16},children:[t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:16},children:[t.jsx(Bt,{label:"Product Name",required:!0,children:t.jsx(Yn,{value:h.name,onChange:k=>z("name",k),placeholder:"Zenith RO System"})}),t.jsx(Bt,{label:"Internal SKU",children:t.jsx(Yn,{value:h.sku||"",onChange:k=>z("sku",k||null),placeholder:"ZPS-RO-100"})})]}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:16},children:[t.jsx(Bt,{label:"Category",children:t.jsx(Gg,{value:h.category,onChange:k=>z("category",k),options:Object.entries(Xg).map(([k,q])=>({value:k,label:q}))})}),t.jsx(Bt,{label:"Subcategory",children:t.jsx(Yn,{value:h.subcategory||"",onChange:k=>z("subcategory",k||null),placeholder:"e.g. Essential Series"})})]}),t.jsx("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:16},children:t.jsx(Bt,{label:"Requires Survey Type",children:t.jsx(Gg,{value:h.requires_survey_type||"",onChange:k=>z("requires_survey_type",k||null),options:[{value:"",label:"None"},{value:"ro",label:"RO Survey"},{value:"softener",label:"Softener Survey"},{value:"whole_home_filter",label:"Whole Home Filter Survey"}]})})}),t.jsx(Bt,{label:"Description",children:t.jsx("textarea",{value:h.description||"",onChange:k=>z("description",k.target.value||null),rows:2,placeholder:"Customer-facing product description â appears on quotes and invoices",style:{width:"100%",background:"#0f1923",border:"1px solid #1e3a4f",color:"#e2e8f0",fontSize:14,borderRadius:8,padding:"10px 14px",outline:"none",boxSizing:"border-box",resize:"none"}})}),i&&t.jsxs("div",{style:{borderTop:"1px solid #1e3a4f",paddingTop:16},children:[t.jsxs("div",{style:{fontSize:13,fontWeight:700,color:"#fbbf24",marginBottom:12,display:"flex",alignItems:"center",gap:8},children:["ð VENDOR / ORDERING",t.jsx("span",{style:{fontSize:10,fontWeight:600,color:"#92400e",background:"rgba(251,191,36,0.1)",border:"1px solid rgba(251,191,36,0.2)",borderRadius:4,padding:"2px 6px"},children:"ADMIN ONLY"})]}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:16,marginBottom:12},children:[t.jsx(Bt,{label:"Vendor Name",children:t.jsx(Yn,{value:h.vendor_name||"",onChange:k=>z("vendor_name",k||null),placeholder:"e.g. NWS"})}),t.jsx(Bt,{label:"Vendor SKU / Part Number",children:t.jsx(Yn,{value:h.vendor_sku||"",onChange:k=>z("vendor_sku",k||null),placeholder:"e.g. NWS-32MB-C1517"})})]}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:16,marginBottom:12},children:[t.jsx(Bt,{label:"Vendor Cost ($/unit)",children:t.jsx(Yn,{type:"number",value:h.vendor_cost??"",onChange:k=>z("vendor_cost",k?parseFloat(k):null),placeholder:"0.00"})}),t.jsx(Bt,{label:"Min Sell Price ($)",children:t.jsx(Yn,{type:"number",value:h.min_sell_price??"",onChange:k=>z("min_sell_price",k?parseFloat(k):null),placeholder:"0.00"})})]}),t.jsx(Bt,{label:"Vendor Description",children:t.jsx("textarea",{value:h.vendor_description||"",onChange:k=>z("vendor_description",k.target.value||null),rows:2,placeholder:"Supplier's product description",style:{width:"100%",background:"#0f1923",border:"1px solid #1e3a4f",color:"#e2e8f0",fontSize:14,borderRadius:8,padding:"10px 14px",outline:"none",boxSizing:"border-box",resize:"none"}})})]}),t.jsxs("div",{style:{borderTop:"1px solid #1e3a4f",paddingTop:16},children:[t.jsx("div",{style:{fontSize:13,fontWeight:700,color:"#94a3b8",marginBottom:12},children:"PRICING"}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:16},children:[t.jsx(Bt,{label:"Retail Price ($)",children:t.jsx(Yn,{type:"number",value:h.retail_price??"",onChange:k=>z("retail_price",k?parseFloat(k):null),placeholder:"899.00"})}),t.jsx(Bt,{label:"Rental ($/month)",children:t.jsx(Yn,{type:"number",value:h.rental_price_monthly??"",onChange:k=>z("rental_price_monthly",k?parseFloat(k):null),placeholder:"29.99"})}),t.jsx(Bt,{label:"Install Fee ($)",children:t.jsx(Yn,{type:"number",value:h.install_fee??"",onChange:k=>z("install_fee",k?parseFloat(k):0),placeholder:"150.00"})}),t.jsx(Bt,{label:"Maintenance ($/month)",children:t.jsx(Yn,{type:"number",value:h.maintenance_price_monthly??"",onChange:k=>z("maintenance_price_monthly",k?parseFloat(k):null),placeholder:"9.99"})})]})]}),t.jsxs("div",{style:{borderTop:"1px solid #1e3a4f",paddingTop:16},children:[t.jsx("div",{style:{fontSize:13,fontWeight:700,color:"#94a3b8",marginBottom:12},children:"DISCOUNTS & CUSTOM LINES"}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:16,alignItems:"start"},children:[t.jsx(Bt,{label:"Max rep discount (%)",tooltip:"The most a sales rep can discount this product on a quote. 0 = no discount. Admins are not limited.",children:t.jsx(Yn,{type:"number",value:h.max_discount_pct??0,onChange:k=>{const q=k===""?0:parseFloat(k);z("max_discount_pct",Number.isFinite(q)?Math.min(100,Math.max(0,q)):0)},placeholder:"0"})}),t.jsx(Bt,{label:"Open SKU (custom line)",tooltip:"Reps pick this for custom lines. They can change the wording and price; the SKU stays the same for reporting. Never discounted.",children:t.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,padding:"10px 0",cursor:"pointer"},children:[t.jsx("input",{type:"checkbox",checked:!!h.is_open_item,onChange:k=>z("is_open_item",k.target.checked),style:{accentColor:"#0d7ea3"}}),t.jsx("span",{style:{fontSize:13,color:"#94a3b8"},children:"Use as an open SKU"})]})})]})]}),t.jsxs("div",{style:{borderTop:"1px solid #1e3a4f",paddingTop:16},children:[t.jsx("div",{style:{fontSize:13,fontWeight:700,color:"#94a3b8",marginBottom:12},children:"WARRANTY & FILTERS"}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:16,marginBottom:12},children:[t.jsx(Bt,{label:"Parts Warranty",tooltip:"Parts coverage duration. Shown on customer Systems tab with remaining time.",children:t.jsxs("div",{style:{display:"flex",gap:8},children:[t.jsx("input",{type:"number",min:"0",value:h.parts_warranty??"",onChange:k=>z("parts_warranty",k.target.value?parseInt(k.target.value):null),placeholder:"e.g. 5",style:{flex:1,background:"#0f1923",border:"1px solid #1e3a4f",color:"#e2e8f0",fontSize:14,borderRadius:8,padding:"10px 14px",outline:"none",boxSizing:"border-box"}}),t.jsxs("select",{value:h.parts_warranty_unit||"months",onChange:k=>z("parts_warranty_unit",k.target.value),style:{background:"#0f1923",border:"1px solid #1e3a4f",color:"#e2e8f0",fontSize:14,borderRadius:8,padding:"10px 14px",outline:"none",cursor:"pointer"},children:[t.jsx("option",{value:"months",children:"Months"}),t.jsx("option",{value:"years",children:"Years"})]})]})}),t.jsx(Bt,{label:"Labour Warranty",tooltip:"Labour coverage duration. Shown on customer Systems tab with remaining time.",children:t.jsxs("div",{style:{display:"flex",gap:8},children:[t.jsx("input",{type:"number",min:"0",value:h.labour_warranty??"",onChange:k=>z("labour_warranty",k.target.value?parseInt(k.target.value):null),placeholder:"e.g. 1",style:{flex:1,background:"#0f1923",border:"1px solid #1e3a4f",color:"#e2e8f0",fontSize:14,borderRadius:8,padding:"10px 14px",outline:"none",boxSizing:"border-box"}}),t.jsxs("select",{value:h.labour_warranty_unit||"months",onChange:k=>z("labour_warranty_unit",k.target.value),style:{background:"#0f1923",border:"1px solid #1e3a4f",color:"#e2e8f0",fontSize:14,borderRadius:8,padding:"10px 14px",outline:"none",cursor:"pointer"},children:[t.jsx("option",{value:"months",children:"Months"}),t.jsx("option",{value:"years",children:"Years"})]})]})})]}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:16},children:[t.jsx(Bt,{label:"Warranty (months)",children:t.jsx(Yn,{type:"number",value:h.warranty_months??"",onChange:k=>z("warranty_months",k?parseInt(k):0),placeholder:"12"})}),t.jsx(Bt,{label:"Filter Interval (months)",children:t.jsx(Yn,{type:"number",value:h.filter_interval_months??"",onChange:k=>z("filter_interval_months",k?parseInt(k):null),placeholder:"12"})}),t.jsx(Bt,{label:"Buyout Formula",children:t.jsx(Gg,{value:h.buyout_formula||"",onChange:k=>z("buyout_formula",k||null),options:[{value:"",label:"N/A"},...Object.entries(VR).map(([k,q])=>({value:k,label:q}))]})})]})]}),A&&t.jsx("div",{style:{padding:"10px 14px",borderRadius:8,background:"rgba(239,68,68,0.12)",border:"1px solid rgba(239,68,68,0.3)",color:"#f87171",fontSize:13},children:A})]}),t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",gap:12,padding:"16px 24px",borderTop:"1px solid #1e3a4f"},children:[t.jsx("button",{onClick:()=>{f(!1),u(null)},style:{padding:"8px 16px",fontSize:13,color:"#64748b",background:"none",border:"none",cursor:"pointer"},children:"Cancel"}),t.jsx("button",{onClick:N,disabled:m,style:{padding:"10px 22px",borderRadius:8,border:"none",cursor:"pointer",background:m?"#0d7ea350":"#0d7ea3",color:"#fff",fontWeight:700,fontSize:14,opacity:m?.5:1},children:m?"Savingâ¦":p?"Update Product":"Create Product"})]})]})})]})}function Bt({label:e,required:n,tooltip:r,children:s}){return t.jsxs("div",{children:[t.jsxs("label",{style:{display:"block",fontSize:12,color:"#64748b",marginBottom:6},children:[e," ",n&&t.jsx("span",{style:{color:"#f87171"},children:"*"}),r&&t.jsx("span",{title:r,style:{cursor:"help",marginLeft:4,color:"#334155"},children:"â"})]}),s]})}
110function Yn({value:e,onChange:n,placeholder:r,type:s="text"}){return t.jsx("input",{type:s,step:s==="number"?"0.01":void 0,value:e,onChange:i=>n(i.target.value),placeholder:r,style:{width:"100%",background:"#0f1923",border:"1px solid #1e3a4f",color:"#e2e8f0",fontSize:14,borderRadius:8,padding:"10px 14px",outline:"none",boxSizing:"border-box"}})}function Gg({value:e,onChange:n,options:r}){return t.jsx("select",{value:e,onChange:s=>n(s.target.value),style:{width:"100%",background:"#0f1923",border:"1px solid #1e3a4f",color:"#e2e8f0",fontSize:14,borderRadius:8,padding:"10px 14px",outline:"none",boxSizing:"border-box"},children:r.map(s=>t.jsx("option",{value:s.value,children:s.label},s.value))})}const Vi={general:"General",call_back:"Call Back",google_review:"Google Review",service_due:"Service Due",filter_replacement:"Filter Replacement",renewal:"Renewal",re_engage:"Re-engage"},Xl={general:"ð",call_back:"ð",google_review:"â",service_due:"ð§",filter_replacement:"ð",renewal:"ð
",re_engage:"ð"},hd="*";async function bE(){const{data:e,error:n}=await w.from("follow_up_tasks").select(hd).is("completed_at",null).order("due_date",{ascending:!0});if(n)throw n;return e||[]}async function AE(){const e=new Date().toISOString().split("T")[0],{data:n,error:r}=await w.from("follow_up_tasks").select(hd).is("completed_at",null).lt("due_date",e).order("due_date",{ascending:!0});if(r)throw r;return n||[]}async function vE(){const e=new Date().toISOString().split("T")[0],{data:n,error:r}=await w.from("follow_up_tasks").select(hd).is("completed_at",null).eq("due_date",e).order("due_date",{ascending:!0});if(r)throw r;return n||[]}async function _E(e){const{data:n,error:r}=await w.from("follow_up_tasks").select(hd).eq("lead_id",e).order("due_date",{ascending:!0});if(r)throw r;return n||[]}async function jE(e){const{data:n,error:r}=await w.from("follow_up_tasks").select(hd).eq("customer_id",e).order("due_date",{ascending:!0});if(r)throw r;return n||[]}async function wE(e=20){const{data:n,error:r}=await w.from("follow_up_tasks").select(hd).not("completed_at","is",null).order("completed_at",{ascending:!1}).limit(e);if(r)throw r;return n||[]}async function Bf(e){const{data:n,error:r}=await w.from("follow_up_tasks").insert({task_type:e.task_type,lead_id:e.lead_id||null,customer_id:e.customer_id||null,job_id:e.job_id||null,assigned_to:e.assigned_to||null,title:e.title,notes:e.notes||null,due_date:e.due_date,due_time:e.due_time||null,ticket_id:e.ticket_id||null}).select().single();if(r)throw new Error(`Failed to create follow-up: ${r.message}`);return n}async function fd(e){const{data:n,error:r}=await w.from("follow_up_tasks").update({completed_at:new Date().toISOString()}).eq("id",e).select().single();if(r)throw new Error(`Failed to complete follow-up: ${r.message}`);return n}async function SE(e){const{data:n,error:r}=await w.from("follow_up_tasks").update({completed_at:null}).eq("id",e).select().single();if(r)throw new Error(`Failed to reopen follow-up: ${r.message}`);return n}async function kE(e){const{error:n}=await w.from("follow_up_tasks").delete().eq("id",e);if(n)throw new Error(`Failed to delete follow-up: ${n.message}`)}function t0({onClose:e,onCreate:n,userId:r}){const[s,i]=g.useState("call_back"),[o,a]=g.useState(""),[l,d]=g.useState(""),[c,f]=g.useState(new Date().toISOString().split("T")[0]),[p,u]=g.useState("none"),[h,y]=g.useState(""),[m,b]=g.useState([]),[A,v]=g.useState(null),[x,_]=g.useState(!1),[j,C]=g.useState(!1);function S(R){i(R),(!o||Object.values(Vi).some(N=>o.startsWith(N)))&&a(`${Vi[R]} follow-up`)}async function T(R){if(R.length<2){b([]);return}_(!0);try{if(p==="lead"){const{data:N}=await w.from("leads").select("id, full_name, phone, stage").or(`full_name.ilike.%${R}%,phone.ilike.%${R}%`).not("stage","in","(won,lost,dnd)").limit(5);b(N||[])}else if(p==="customer"){const{data:N}=await w.from("customers").select("id, full_name, phone, lifecycle_status").or(`full_name.ilike.%${R}%,phone.ilike.%${R}%`).limit(5);b(N||[])}}catch{b([])}finally{_(!1)}}function L(){!o.trim()||!c||(C(!0),n({task_type:s,title:o.trim(),notes:l.trim()||null,due_date:c,lead_id:p==="lead"&&A?A.id:null,customer_id:p==="customer"&&A?A.id:null,assigned_to:r}))}const E={width:"100%",background:"#0f1923",border:"1px solid #1e3a4f",color:"#e2e8f0",fontSize:14,borderRadius:8,padding:"10px 14px",outline:"none",boxSizing:"border-box"};return t.jsx("div",{style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.6)",display:"flex",alignItems:"center",justifyContent:"center",padding:16,zIndex:50},children:t.jsxs("div",{style:{background:"#162232",border:"1px solid #1e3a4f",borderRadius:12,width:"100%",maxWidth:440,maxHeight:"90vh",overflowY:"auto"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"20px 24px",borderBottom:"1px solid #1e3a4f",position:"sticky",top:0,background:"#162232",zIndex:1},children:[t.jsxs("div",{children:[t.jsx("div",{style:{color:"#e2e8f0",fontWeight:700,fontSize:18},children:"New Follow-Up"}),t.jsx("div",{style:{color:"#64748b",fontSize:13,marginTop:2},children:"Create a task"})]}),t.jsx("button",{onClick:e,style:{background:"none",border:"none",color:"#64748b",fontSize:20,cursor:"pointer"},children:"Ã"})]}),t.jsxs("div",{style:{padding:24,display:"flex",flexDirection:"column",gap:16},children:[t.jsxs("div",{children:[t.jsx("label",{style:{display:"block",fontSize:12,color:"#64748b",marginBottom:6},children:"Type"}),t.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:Object.keys(Vi).map(R=>t.jsxs("button",{onClick:()=>S(R),style:{fontSize:12,padding:"6px 12px",borderRadius:8,fontWeight:600,cursor:"pointer",border:s===R?"1px solid #0d7ea3":"1px solid #1e3a4f",background:s===R?"rgba(13,126,163,0.15)":"transparent",color:s===R?"#22d3ee":"#64748b",transition:"all 0.15s"},children:[Xl[R]," ",Vi[R]]},R))})]}),t.jsxs("div",{children:[t.jsxs("label",{style:{display:"block",fontSize:12,color:"#64748b",marginBottom:6},children:["Title ",t.jsx("span",{style:{color:"#f87171"},children:"*"})]}),t.jsx("input",{type:"text",value:o,onChange:R=>
110a(R.target.value),placeholder:"Call back about softener quote",style:E})]}),t.jsxs("div",{children:[t.jsxs("label",{style:{display:"block",fontSize:12,color:"#64748b",marginBottom:6},children:["Due Date ",t.jsx("span",{style:{color:"#f87171"},children:"*"})]}),t.jsx("input",{type:"date",value:c,onChange:R=>f(R.target.value),style:E})]}),t.jsxs("div",{children:[t.jsx("label",{style:{display:"block",fontSize:12,color:"#64748b",marginBottom:6},children:"Link to"}),t.jsx("div",{style:{display:"flex",gap:6,marginBottom:8},children:["none","lead","customer"].map(R=>t.jsx("button",{onClick:()=>{u(R),v(null),y(""),b([])},style:{fontSize:12,padding:"6px 12px",borderRadius:8,fontWeight:600,cursor:"pointer",border:"1px solid #1e3a4f",background:p===R?"rgba(255,255,255,0.06)":"transparent",color:p===R?"#e2e8f0":"#64748b"},children:R==="none"?"No link":R==="lead"?"⬡ Lead":"ð¤ Customer"},R))}),p!=="none"&&!A&&t.jsxs("div",{style:{position:"relative"},children:[t.jsx("input",{type:"text",value:h,onChange:R=>{y(R.target.value),T(R.target.value)},placeholder:`Search ${p}s by name or phoneâ¦`,style:E}),m.length>0&&t.jsx("div",{style:{position:"absolute",zIndex:10,width:"100%",marginTop:4,background:"#162232",border:"1px solid #1e3a4f",borderRadius:8,overflow:"hidden"},children:m.map(R=>t.jsxs("button",{onClick:()=>{v(R),b([])},style:{display:"flex",flexDirection:"column",width:"100%",padding:"12px 14px",background:"none",border:"none",cursor:"pointer",textAlign:"left",borderBottom:"1px solid #1a2a3a"},onMouseEnter:N=>N.currentTarget.style.background="#1e3a5f",onMouseLeave:N=>N.currentTarget.style.background="none",children:[t.jsx("span",{style:{color:"#e2e8f0",fontWeight:600,fontSize:14},children:R.full_name}),t.jsxs("span",{style:{color:"#64748b",fontSize:12},children:[R.phone," · ",R.stage||R.lifecycle_status]})]},R.id))})]}),A&&t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:8,padding:"10px 14px"},children:[t.jsx("span",{style:{fontSize:14},children:p==="lead"?"⬡":"ð¤"}),t.jsx("span",{style:{fontSize:14,color:"#e2e8f0",flex:1},children:A.full_name}),t.jsx("button",{onClick:()=>v(null),style:{background:"none",border:"none",color:"#64748b",cursor:"pointer",fontSize:14},children:"Ã"})]})]}),t.jsxs("div",{children:[t.jsx("label",{style:{display:"block",fontSize:12,color:"#64748b",marginBottom:6},children:"Notes"}),t.jsx("textarea",{value:l,onChange:R=>d(R.target.value),placeholder:"Additional detailsâ¦",rows:2,style:{...E,resize:"none"}})]})]}),t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",gap:12,padding:"16px 24px",borderTop:"1px solid #1e3a4f",position:"sticky",bottom:0,background:"#162232"},children:[t.jsx("button",{onClick:e,style:{padding:"8px 16px",fontSize:13,color:"#64748b",background:"none",border:"none",cursor:"pointer"},children:"Cancel"}),t.jsx("button",{onClick:L,disabled:!o.trim()||!c||j,style:{padding:"10px 22px",borderRadius:8,border:"none",cursor:"pointer",background:!o.trim()||!c||j?"#0d7ea350":"#0d7ea3",color:"#fff",fontWeight:700,fontSize:14,opacity:!o.trim()||!c||j?.5:1},children:j?"Creatingâ¦":"Create Follow-Up"})]})]})})}function xv(e){const n=new Date;n.setHours(0,0,0,0);const r=new Date(e+"T00:00:00");return Math.floor((r.getTime()-n.getTime())/864e5)}function ip(e){return new Date(e+"T00:00:00").toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}function yv(e){return new Date(e).toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function CE(){const[e,n]=g.useState(window.innerWidth<768);return g.useEffect(()=>{const r=()=>n(window.innerWidth<768);return window.addEventListener("resize",r),()=>window.removeEventListener("resize",r)},[]),e}const bv=[{key:"all",label:"All Open",icon:"â",color:"#e2e8f0",bg:"rgba(226,232,240,0.1)",border:"rgba(226,232,240,0.2)"},{key:"overdue",label:"Overdue",icon:"ð´",color:"#f87171",bg:"rgba(248,113,113,0.1)",border:"rgba(248,113,113,0.25)"},{key:"today",label:"Today",icon:"â",color:"#fbbf24",bg:"rgba(251,191,36,0.1)",border:"rgba(251,191,36,0.25)"},{key:"upcoming",label:"Upcoming",icon:"â·",color:"#a78bfa",bg:"rgba(167,139,250,0.1)",border:"rgba(167,139,250,0.25)"},{key:"completed",label:"Completed",icon:"â",color:"#4ade80",bg:"rgba(74,222,128,0.1)",border:"rgba(74,222,128,0.25)"}];function TE(){const{user:e,role:n}=Ee(),r=gt(),s=CE(),[i,o]=g.useState([]),[a,l]=g.useState([]),[d,c]=g.useState(!0),[f,p]=g.useState(null),[u,h]=g.useState("all"),[y,m]=g.useState(""),[b,A]=g.useState(!1),[v,x]=g.useState({});async function _(){c(!0);try{const[q,$]=await Promise.all([bE(),wE(20)]);o(q),l($);const I=[...new Set([...q,...$].map(ae=>
110ae.lead_id).filter(Boolean))],B=[...new Set([...q,...$].map(ae=>ae.customer_id).filter(Boolean))],J={};if(I.length>0){const{data:ae}=await w.from("leads").select("id, full_name").in("id",I);(ae||[]).forEach(te=>{J[`lead:${te.id}`]=te.full_name})}if(B.length>0){const{data:ae}=await w.from("customers").select("id, full_name").in("id",B);(ae||[]).forEach(te=>{J[`customer:${te.id}`]=te.full_name})}x(J)}catch(q){p(q.message)}finally{c(!1)}}g.useEffect(()=>{_()},[]);const j=new Date().toISOString().split("T")[0],C=i.filter(q=>q.due_date<j),S=i.filter(q=>q.due_date===j),T=i.filter(q=>q.due_date>j),L=q=>q==="all"?i.length:q==="overdue"?C.length:q==="today"?S.length:q==="upcoming"?T.length:a.length,E=u==="all"?i:u==="overdue"?C:u==="today"?S:u==="upcoming"?T:a,R=g.useMemo(()=>{if(!y.trim())return E;const q=y.toLowerCase();return E.filter($=>{const I=N($);return $.title.toLowerCase().includes(q)||$.notes&&$.notes.toLowerCase().includes(q)||I&&I.toLowerCase().includes(q)})},[E,y,v]);function N(q){return q.lead_id?v[`lead:${q.lead_id}`]||null:q.customer_id&&v[`customer:${q.customer_id}`]||null}function O(q){return q.lead_id?"lead":q.customer_id?"customer":null}function z(q){q.lead_id?r("/leads"):q.customer_id&&r(`/customers/${q.customer_id}`)}async function P(q){try{await fd(q),await _()}catch($){p($.message)}}async function D(q){try{await SE(q),await _()}catch($){p($.message)}}async function M(q){if(confirm("Delete this follow-up?"))try{await kE(q),await _()}catch($){p($.message)}}async function k(q){try{await Bf(q),A(!1),await _()}catch($){p($.message)}}return t.jsxs("div",{style:{background:"#0f1923",minHeight:"100vh",color:"#e2e8f0",display:"flex",flexDirection:"column"},children:[t.jsxs("div",{style:{background:"#162232",borderBottom:"1px solid #1e3a4f",padding:"16px 24px",display:"flex",alignItems:"center",gap:12,flexWrap:"wrap"},children:[t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsx("div",{style:{fontWeight:800,fontSize:20,color:"#e2e8f0",lineHeight:1.2},children:"Tasks"}),t.jsx("div",{style:{color:"#64748b",fontSize:12,marginTop:2},children:C.length>0?t.jsxs(t.Fragment,{children:[t.jsxs("span",{style:{color:"#f87171"},children:[C.length," overdue"]})," · ",S.length," today · ",T.length," upcoming"]}):t.jsxs(t.Fragment,{children:["All caught up · ",S.length," today · ",T.length," upcoming"]})})]}),!s&&t.jsx("input",{placeholder:"Search title or nameâ¦",value:y,onChange:q=>m(q.target.value),style:{background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:8,color:"#e2e8f0",padding:"9px 14px",fontSize:13,outline:"none",width:220,flexShrink:0}}),t.jsx("button",{onClick:()=>A(!0),style:{padding:"10px 22px",borderRadius:8,border:"none",cursor:"pointer",background:"#0d7ea3",color:"#fff",fontWeight:700,fontSize:14,flexShrink:0,whiteSpace:"nowrap"},children:"+ New Task"})]}),s&&t.jsx("div",{style:{padding:"10px 16px",background:"#0f1923",borderBottom:"1px solid #1e3a4f"},children:t.jsx("input",{placeholder:"Search title or nameâ¦",value:y,onChange:q=>m(q.target.value),style:{background:"#162232",border:"1px solid #1e3a4f",borderRadius:8,color:"#e2e8f0",padding:"10px 14px",fontSize:14,outline:"none",width:"100%",boxSizing:"border-box"}})}),s?t.jsx("div",{style:{background:"#0c1a26",borderBottom:"1px solid #1e3a4f",padding:"10px 16px",display:"flex",gap:6,flexShrink:0,overflowX:"auto"},children:bv.map(q=>{const $=L(q.key),I=u===q.key;return t.jsxs("button",{onClick:()=>h(q.key),style:{flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:"8px 10px",borderRadius:10,border:`1px solid ${I?q.color+"60":q.border}`,background:I?q.bg:"rgba(255,255,255,0.02)",color:I?q.color:"#475569",cursor:"pointer",fontSize:12,fontWeight:I?700:500,boxShadow:I?`0 0 14px ${q.color}20`:"none"},children:[t.jsx("span",{children:q.icon}),$>0&&t.jsx("span",{style:{background:I?q.color+"30":"rgba(255,255,255,0.06)",color:I?q.color:"#64748b",borderRadius:20,padding:"1px 6px",fontSize:11,fontWeight:700},children:$})]},q.key)})}):t.jsx("div",{style:{background:"#0c1a26",borderBottom:"1px solid #1e3a4f",padding:"12px 24px",display:"flex",gap:8,flexShrink:0},children:bv.map(q=>{const $=L(q.key),I=u===q.key;return t.jsxs("button",{onClick:()=>h(q.key),style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",gap:7,padding:"11px 8px",borderRadius:10,border:`1px solid ${I?q.color+"60":q.border}`,background:I?q.bg:"rgba(255,255,255,0.02)",color:I?q.color:"#475569",cursor:"pointer",fontSize:13,fontWeight:
110I?700:500,transition:"all 0.12s",boxShadow:I?`0 0 14px ${q.color}20`:"none"},onMouseEnter:B=>{I||(B.currentTarget.style.background=q.bg,B.currentTarget.style.color=q.color,B.currentTarget.style.borderColor=q.border)},onMouseLeave:B=>{I||(B.currentTarget.style.background="transparent",B.currentTarget.style.color="#475569",B.currentTarget.style.borderColor=q.border)},children:[t.jsx("span",{style:{fontSize:14},children:q.icon}),t.jsx("span",{children:q.label}),$>0&&t.jsx("span",{style:{background:I?q.color+"30":"rgba(255,255,255,0.06)",color:I?q.color:"#64748b",borderRadius:20,padding:"1px 7px",fontSize:11,fontWeight:700,minWidth:20,textAlign:"center"},children:$})]},q.key)})}),t.jsx("div",{style:{display:"flex",gap:12,padding:s?"12px 16px":"14px 24px",borderBottom:"1px solid #1e3a4f",background:"#0f1923",flexShrink:0,overflowX:"auto"},children:[{label:"Open",val:String(i.length),color:"#94a3b8"},{label:"Overdue",val:String(C.length),color:"#f87171"},{label:"Due Today",val:String(S.length),color:"#fbbf24"},{label:"Completed",val:String(a.length),color:"#4ade80"}].map(q=>t.jsxs("div",{style:{background:"#162232",border:"1px solid #1e3a4f",borderRadius:10,padding:s?"8px 14px":"10px 18px",flexShrink:0,minWidth:s?85:110},children:[t.jsx("div",{style:{color:"#64748b",fontSize:10,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.08em"},children:q.label}),t.jsx("div",{style:{color:q.color,fontWeight:800,fontSize:s?18:20,marginTop:3},children:q.val})]},q.label))}),f&&t.jsxs("div",{style:{margin:"12px 24px 0",padding:"10px 14px",borderRadius:8,background:"rgba(239,68,68,0.12)",border:"1px solid rgba(239,68,68,0.3)",color:"#f87171",fontSize:13,display:"flex",alignItems:"center",justifyContent:"space-between"},children:[t.jsx("span",{children:f}),t.jsx("button",{onClick:()=>p(null),style:{background:"none",border:"none",color:"#f87171",cursor:"pointer",fontSize:16},children:"Ã"})]}),t.jsx("div",{style:{flex:1,overflowY:"auto",padding:s?"12px 12px":"16px 24px"},children:d?t.jsx("div",{style:{textAlign:"center",padding:60,color:"#64748b"},children:"Loading follow-upsâ¦"}):R.length===0?t.jsxs("div",{style:{textAlign:"center",padding:60},children:[t.jsx("div",{style:{fontSize:40,marginBottom:12},children:u==="completed"?"â
":"ð"}),t.jsx("div",{style:{color:"#64748b",fontSize:15},children:y?"No matching follow-ups":u==="overdue"?"No overdue tasks â nice!":u==="today"?"Nothing due today":u==="upcoming"?"No upcoming tasks":u==="completed"?"No completed tasks yet":"No open follow-ups"}),u==="all"&&!y&&t.jsx("button",{onClick:()=>A(!0),style:{marginTop:16,padding:"10px 24px",borderRadius:8,border:"none",cursor:"pointer",background:"#0d7ea3",color:"#fff",fontWeight:700},children:"Create First Task"})]}):s?t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:10},children:R.map(q=>{const $=xv(q.due_date),I=$<0&&!q.completed_at,B=$===0&&!q.completed_at,J=!!q.completed_at,ae=N(q),te=O(q),U=J?ip(q.due_date):I?`${Math.abs($)}d overdue`:B?"Due today":$===1?"Tomorrow":`In ${$}d`,W=J?"#475569":I?"#f87171":B?"#fbbf24":$<=3?"#fb923c":"#94a3b8",G=q.task_type==="call_back"?"#60a5fa":q.task_type==="google_review"?"#fbbf24":q.task_type==="service_due"?"#22d3ee":q.task_type==="re_engage"?"#a78bfa":"#94a3b8";return t.jsxs("div",{style:{background:"#162232",border:"1px solid #1e3a4f",borderRadius:12,padding:"14px 16px",opacity:J?.55:1},children:[t.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:10},children:[t.jsx("div",{style:{paddingTop:2,flexShrink:0},children:J?t.jsx("button",{onClick:()=>D(q.id),style:{width:22,height:22,borderRadius:5,border:"none",background:"#16a34a",cursor:"pointer",color:"#fff",fontSize:12,fontWeight:700,display:"flex",alignItems:"center",justifyContent:"center"},children:"â"}):t.jsx("button",{onClick:()=>P(q.id),style:{width:22,height:22,borderRadius:5,border:"2px solid #475569",background:"transparent",cursor:"pointer"},onMouseEnter:V=>{V.currentTarget.style.borderColor="#4ade80",V.currentTarget.style.background="rgba(74,222,128,0.15)"},onMouseLeave:V=>{V.currentTarget.style.borderColor="#475569",V.currentTarget.style.background="transparent"}})}),t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,marginBottom:5},children:[t.jsxs("span",{style:{fontSize:14,fontWeight:700,color:J?"#64748b":"#e2e8f0",textDecoration:J?"line-through":"none",flex:1,minWidth:0},children:[Xl[q.task_type]," ",q.title]}),t.jsx("span",{style:{fontSize:12,fontWeight:700,color:W,flexShrink:0},children:U})]}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[t.jsx("span",{style:{fontSize:11,fontWeight:700,color:G,background:G+"22",padding:"2px 7px",borderRadius:6},children:Vi[q.task_type]}),!J&&t.jsx("span",{style:{fontSize:11,color:"#475569"},children:ip(q.due_date)})]})]})]}),ae&&t.jsxs("button",{onClick:()=>z(q),style:{fontSize:13,marginTop:10,background:"none",border:"none",cursor:"pointer",padding:0,color:te==="lead"?"#38bdf8":"#4ade80",display:"block"},children:[te==="lead"?"⬡":"ð¤"," ",ae]}),q.notes&&t.jsx("div",{style:{fontSize:12,color:"#64748b",marginTop:6},children:q.notes}),J&&q.completed_at&&t.jsxs("div",{style:{fontSize:11,color:"#475569",marginTop:6},children:["Completed ",yv(q.completed_at)]}),yt.manageFollowUps(n)&&t.jsx("div",{style:{marginTop:10,paddingTop:10,borderTop:"1px solid #1e3a4f"},children:t.jsx("button",{onClick:()=>M(q.id),style:{background:"none",border:"1px solid #3f1a1a",borderRadius:6,cursor:"pointer",color:"#ef4444",fontSize:12,fontWeight:600,padding:"6px 12px"},children:"ð Delete"})})]},q.id)})}):t.jsx("div",{style:{background:"#162232",border:"1px solid #1e3a4f",borderRadius:12,overflow:"hidden"},children:R.map((q,$)=>{const I=xv(q.due_date),B=I<0&&!q.completed_at,J=I===0&&!q.completed_at,ae=!!q.completed_at,te=N(q),U=O(q),W=ae?ip(q.due_date):B?`${Math.abs(I)}d overdue`:J?"Due today":I===1?"Tomorrow":`In ${I}d`,G=ae?"#475569":B?"#f87171":J?"#fbbf24":I<=3?"#fb923c":"#94a3b8",V=q.task_type==="call_back"?"#60a5fa":q.task_type==="google_review"?"#fbbf24":q.task_type==="service_due"?"#22d3ee":q.task_type==="re_engage"?"#a78bfa":"#94a3b8";return t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"12px 14px",borderBottom:$<R.length-1?"1px solid #1a2a3a":"none",opacity:ae?.5:1,transition:"background 0.1s",cursor:"default"},onMouseEnter:ee=>{ee.currentTarget.style.background="#1a2e42"},onMouseLeave:ee=>{ee.currentTarget.style.background="transparent"},children:[ae?t.jsx("button",{onClick:()=>D(q.id),title:"Reopen",style:{width:20,height:20,borderRadius:4,flexShrink:0,border:"none",background:"#16a34a",cursor:"pointer",color:"#fff",fontSize:11,fontWeight:700,display:"flex",alignItems:"center",justifyContent:"center"},children:"â"}):t.jsx("button",{onClick:()=>P(q.id),title:"Mark complete",style:{width:20,height:20,borderRadius:4,flexShrink:0,border:"2px s
110olid #475569",background:"transparent",cursor:"pointer"},onMouseEnter:ee=>{ee.currentTarget.style.borderColor="#4ade80",ee.currentTarget.style.background="rgba(74,222,128,0.15)"},onMouseLeave:ee=>{ee.currentTarget.style.borderColor="#475569",ee.currentTarget.style.background="transparent"}}),t.jsx("span",{style:{fontSize:14,flexShrink:0},children:Xl[q.task_type]}),t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[t.jsx("span",{style:{fontSize:13,fontWeight:600,color:ae?"#64748b":"#e2e8f0",textDecoration:ae?"line-through":"none"},children:q.title}),t.jsx("span",{style:{fontSize:11,fontWeight:700,color:V,background:V+"22",padding:"3px 8px",borderRadius:6},children:Vi[q.task_type]})]}),te&&t.jsxs("button",{onClick:()=>z(q),style:{fontSize:12,marginTop:2,background:"none",border:"none",cursor:"pointer",padding:0,color:U==="lead"?"#38bdf8":"#4ade80"},onMouseEnter:ee=>{ee.currentTarget.style.textDecoration="underline"},onMouseLeave:ee=>{ee.currentTarget.style.textDecoration="none"},children:[U==="lead"?"⬡":"ð¤"," ",te]}),q.notes&&t.jsx("div",{style:{fontSize:11,color:"#64748b",marginTop:2,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:400},children:q.notes}),ae&&q.completed_at&&t.jsxs("div",{style:{fontSize:11,color:"#475569",marginTop:2},children:["Completed ",yv(q.completed_at)]})]}),t.jsxs("div",{style:{textAlign:"right",flexShrink:0},children:[t.jsx("div",{style:{fontSize:12,fontWeight:600,color:G},children:W}),!ae&&t.jsx("div",{style:{fontSize:10,color:"#475569",marginTop:2},children:ip(q.due_date)})]}),yt.manageFollowUps(n)&&t.jsx("button",{onClick:()=>M(q.id),title:"Delete",style:{background:"none",border:"none",cursor:"pointer",color:"#475569",fontSize:14,padding:"4px 8px",lineHeight:1,borderRadius:6},onMouseEnter:ee=>{ee.currentTarget.style.color="#ef4444",ee.currentTarget.style.background="#3f1a1a"},onMouseLeave:ee=>{ee.currentTarget.style.color="#475569",ee.currentTarget.style.background="none"},children:"ð"})]},q.id)})})}),b&&t.jsx(t0,{onClose:()=>A(!1),onCreate:k,userId:(e==null?void 0:e.id)||null})]})}const ih={slug:"",company_name:"Water Treatment Solutions",phone:"",email:"",address_line1:"",city:"",state:"",zip:"",logo_url:"",tagline:"",website:"",bank_name:"",bank_routing:"",bank_account:"",bank_account_name:"",accounts_email:"",owner_name:"",hearth_apply_url:"",tax_rate:.07};function zE(e){return e?{slug:e.slug||"",company_name:(e.company_name||ih.company_name).trim()||ih.company_name,phone:e.phone||"",email:e.email||"",address_line1:e.address_line1||e.address||"",city:e.city||"",state:e.state||"",zip:e.zip||"",logo_url:e.logo_url||"",tagline:e.tagline||"",website:e.website||"",bank_name:e.bank_name||"",bank_routing:e.bank_routing||"",bank_account:e.bank_account||"",bank_account_name:e.bank_account_name||"",accounts_email:e.accounts_email||e.email||"",owner_name:e.owner_name||"",hearth_apply_url:e.hearth_apply_url||e.hearth_application_url||"",tax_rate:typeof e.tax_rate=="number"?e.tax_rate:.07}:ih}function Yh(e){const n=[e.address_line1];return(e.city||e.state||e.zip)&&n.push([e.city,e.state].filter(Boolean).join(", ")+(e.zip?` ${e.zip}`:"")),n.filter(Boolean).join(", ")}function ma(e){return e.address_line1||""}function xa(e){return[e.city,e.state].filter(Boolean).join(", ")+(e.zip?` ${e.zip}`:"")}function Av(e,n,r){const s=e.hearth_apply_url;if(!s)return"";if(!n)return s;const i=(n.full_name||"").trim().split(" "),o=i[0]||"",a=i.slice(1).join(" ")||"",l=new URLSearchParams;return o&&l.set("firstName",o),a&&l.set("lastName",a),n.email&&l.set("email",n.email),n.phone&&l.set("phone",n.phone.replace(/\D/g,"")),r>0&&l.set("amount",String(Math.round(r))),`${s}?${l.toString()}`}function He(e){return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}).format(e||0)}function $n(){return new Date().toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric"})}function NE(e){return e?{full_name:e.full_name&&e.full_name.trim()||[e.first_name,e.last_name].filter(Boolean).join(" ").trim()||"",first_name:e.first_name,last_name:e.last_name,email:e.email||"",phone:e.phone||"",address:e.address||"",city:e.city||"",state:e.state||"",zip:e.zip||""}:void 0}function op(e){return e?{...e,total:e.total_amount??e.total??0}:null}function RE(e,n,r,s,i){const o=r.map(a=>` 111 <div class="section"> 112 <h3>${a.title||""}</h3> 113 <p>${(a.content||"").replace(/\[INSTALL_FEE\]/g,He(e.install_fee)).replace(/\[MONTHLY_AMOUNT\]/g,He(e.monthly_amount)).replace(/\n/g,"<br/>")}</p> 114 </div> 115 `).join("");return`<!DOCTYPE html> 116<html> 117<head> 118 <meta charset="UTF-8" /> 119 <title>${e.agreement_number} â ${s.company_name}</title> 120 <style> 121 * { box-sizing: border-box; margin: 0; padding: 0; } 122 body { font-family: Georgia, serif; color: #1a1a2e; background: white; padding: 40px; max-width: 800px; margin: 0 auto; } 123 .header { background: #0a2540; color: white; padding: 32px; text-align: center; border-radius: 8px 8px 0 0; } 124 .header h1 { font-size: 20px; font-weight: bold; letter-spacing: 1px; } 125 .header p { font-size: 12px; color: #93c5fd; margin-top: 4px; } 126 .subheader { background: #f8fafc; border: 1px solid #e2e8f0; border-top: none; padding: 20px; text-align: center; } 127 .subheader h2 { font-size: 22px; font-weight: bold; } 128 .subheader .agnum { color: #0a2540; font-size: 14px; font-weight: 600; margin-top: 6px; } 129 .parties { display: grid; grid-template-columns: 1fr 1fr; gap: 32px; padding: 20px; border: 1px solid #e2e8f0; border-top: none; } 130 .party-label { font-size: 10px; font-weight: bold; color: #94a3b8; text-transform: uppercase; letter-spacing: 1px; margin-bottom: 4px; } 131 .party-name { font-weight: bold; font-size: 14px; } 132 .party-address { font-size: 12px; color: #64748b; margin-top: 2px; } 133 .financials { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 8px; background: #eff6ff; border: 1px solid #bfdbfe; border-top: none; padding: 20px; text-align: center; } 134 .fin-label { font-size: 10px; color: #3b82f6; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px; } 135 .fin-value { font-size: 18px; font-weight: bold; color: #1e3a8a; margin-top: 4px; } 136 .notice { background: #fffbeb; border: 1px solid #fcd34d; border-top: none; padding: 12px 20px; text-align: center; font-size: 11px; font-weight: bold; color: #92400e; text-transform: uppercase; letter-spacing: 0.5px; } 137 .intro { padding: 20px; border: 1px solid #e2e8f0; border-top: none; font-size: 13px; line-height: 1.6; } 138 .section { border: 1px solid #e2e8f0; margin-top: 16px; border-radius: 8px; overflow: hidden; } 139 .section h3 { background: #f8fafc; padding: 10px 20px; font-size: 13px; font-weight: bold; border-bottom: 1px solid #e2e8f0; } 140 .section p { padding: 16px 20px; font-size: 12px; line-height: 1.8; color: #374151; } 141 .signatures { border: 2px solid #e2e8f0; border-radius: 8px; padding: 32px; margin-top: 24px; } 142 .sig-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 24px; } 143 .sig-box { background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 8px; padding: 16px; } 144 .sig-party-label { font-size: 10px; color: #94a3b8; font-weight: 600; text-transform: uppercase; letter-spacing: 1px; margin-bottom: 8px; } 145 .sig-name { font-size: 22px; font-style: italic; font-family: Georgia, serif; color: #0a2540; border-bottom: 1px solid #334155; padding-bottom: 6px; margin-bottom: 8px; min-height: 36px; } 146 .sig-meta { font-size: 11px; color: #64748b; } 147 .footer { margin-top: 32px; text-align: center; font-size: 10px; color: #94a3b8; } 148 @media print { body { padding: 20px; } .no-print { display: none !important; } } 149 </style> 150</head> 151<body> 152 <div class="no-print" style="margin-bottom:20px; text-align:center;"> 153 <button onclick="window.print()" style="background:#0a2540;color:white;border:none;padding:10px 28px;border-radius:6px;font-size:14px;font-weight:600;cursor:pointer;"> 154 ð¨ï¸ Print / Save as PDF 155 </button> 156 <p style="margin-top:8px;font-size:11px;color:#64748b;">Use your browser's "Save as PDF" option when printing</p> 157 </div> 158 <div class="header"> 159 <h1>${s.company_name.toUpperCase()}</h1> 160 <p>${ma(s)}${s.city?` · ${xa(s)}`:""}</p> 161 <p>${s.phone}${s.website?` · ${s.website}`:""}</p> 162 </div> 163 <div class="subheader"> 164 <div style="font-size:10px;font-weight:bold;color:#94a3b8;text-transform:uppercase;letter-spacing:2px;margin-bottom:4px;">Legal Agreement</div> 165 <h2>Residential Equipment Rental Agreement</h2> 166 <div class="agnum">${e.agreement_number}</div> 167 </div> 168 <div class="parties"> 169 <div> 170 <div class="party-label">Company</div> 171 <div class="party-name">${s.company_name}</div> 172 <div class="party-address">${ma(s)}<br/>
172${xa(s)}</div> 173 </div> 174 <div> 175 <div class="party-label">Customer</div> 176 <div class="party-name">${(n==null?void 0:n.full_name)||""}</div> 177 <div class="party-address">${(n==null?void 0:n.address)||""}<br/>${(n==null?void 0:n.city)||""}, ${(n==null?void 0:n.state)||""} ${(n==null?void 0:n.zip)||""}</div> 178 </div> 179 </div> 180 <div class="financials"> 181 <div><div class="fin-label">Monthly Payment</div><div class="fin-value">${He(e.monthly_amount)}/mo</div></div> 182 <div><div class="fin-label">Setup Fee (one-time)</div><div class="fin-value">${He(e.install_fee)}</div></div> 183 <div><div class="fin-label">Initial Term</div><div class="fin-value">36 months</div></div> 184 </div> 185 <div class="notice">By signing, you agree to all terms including the binding arbitration clause in Article IX.</div> 186 <div class="intro"> 187 This Agreement is entered into as of <strong>${$n()}</strong> between 188 <strong>${s.company_name}</strong> ("Company") and <strong>${(n==null?void 0:n.full_name)||""}</strong> ("Customer").
189 </div> 190 ${o} 191 <div class="signatures"> 192 <div style="font-weight:bold;font-size:13px;margin-bottom:4px;">IN WITNESS WHEREOF</div> 193 <p style="font-size:11px;color:#64748b;margin-bottom:24px;">Executed as of ${$n()}.</p> 194 <div class="sig-grid"> 195 <div class="sig-box"> 196 <div class="sig-party-label">${s.company_name.toUpperCase()}</div> 197 <div class="sig-name">${s.owner_name||"Authorized Representative"}</div> 198 <div class="sig-meta">Authorized Representative · ${$n()}</div> 199 </div> 200 <div class="sig-box"> 201 <div class="sig-party-label">CUSTOMER</div> 202 ${i?`<img src="${i}" style="height:36px;max-width:200px;object-fit:contain;margin-bottom:4px;" />`:`<div class="sig-name">${e.signed_name||(n==null?void 0:n.full_name)||""}</div>`} 203 <div class="sig-meta">${(n==null?void 0:n.full_name)||""} · Signed ${e.signed_at?new Date(e.signed_at).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric"}):$n()}</div> 204 </div> 205 </div> 206 </div> 207 <div class="footer"> 208 <p>${s.company_name} · ${Yh(s)}</p> 209 <p>${s.phone}${s.email?` · ${s.email}`:""}${s.website?` · ${s.website}`:""}</p> 210 <p style="margin-top:6px;">Agreement ${e.agreement_number} · Generated ${$n()}</p> 211 </div> 212</body> 213</html>`}function Gl(e){return parseFloat(e==null?void 0:e.discount_amount)||0}function Zs(e){return Math.round((e||[]).reduce((n,r)=>n+Gl(r),0)*100)/100}function EE(e){const n=Gl(e);return n>0?`<div style="font-size:12px;color:#16a34a;margin-top:2px;">${parseFloat(e.discount_pct)||0}% off: â${He(n)}</div>`:""}function PE(e,n,r,s,i){const o=parseFloat(e.total_amount??e.total??0),a=parseFloat(e.tax_amount||0),l=parseFloat(e.subtotal||o-a||0),d=e.line_items_snapshot||[],c=[],f=c.reduce((m,b)=>m+parseFloat(b.total_price??b.unit_price??0),0),p=o+f,u=d.map(m=>` 214 <tr style="border-bottom:1px solid #f1f5f9;"> 215 <td style="padding:12px 24px;font-size:13px;color:#1e293b;">${m.description}${EE(m)}</td> 216 <td style="padding:12px 16px;font-size:13px;color:#64748b;text-align:center;">${m.quantity}</td> 217 <td style="padding:12px 16px;font-size:13px;color:#64748b;text-align:right;">${He(m.unit_price)}</td> 218 <td style="padding:12px 24px;font-size:13px;font-weight:600;color:#0f172a;text-align:right;">${He(m.total_price)}</td> 219 </tr> 220 `).join(""),h=c.map(m=>{const b=parseFloat(m.total_price??m.unit_price??0);return` 221 <tr style="border-bottom:1px solid #f1f5f9;background:#fffbeb;"> 222 <td style="padding:12px 24px;font-size:13px;color:#1e293b;"> 223 First Month â ${m.description||"Service Plan"} 224 <div style="font-size:10px;color:#92400e;margin-top:2px;font-style:italic;">Recurring ${He(b)}/month begins next billing cycle</div> 225 </td> 226 <td style="padding:12px 16px;font-size:13px;color:#64748b;text-align:center;">1</td> 227 <td style="padding:12px 16px;font-size:13px;color:#64748b;text-align:right;">${He(b)}</td> 228 <td style="padding:12px 24px;font-size:13px;font-weight:600;color:#0f172a;text-align:right;">${He(b)}</td> 229 </tr> 230 `}).join(""),y=r.map(m=>`<p style="font-size:11px;color:#64748b;line-height:1.7;margin-bottom:8px;">${m.content}</p>`).join("");return`<!DOCTYPE html> 231<html> 232<head> 233 <meta charset="UTF-8" /> 234 <title>${e.invoice_number} â ${s.company_name}</title> 235 <style> 236 * { box-sizing: border-box; margin: 0; padding: 0; } 237 body { font-family: Georgia, serif; color: #1a1a2e; background: white; padding: 40px; max-width: 800px; margin: 0 auto; } 238 @media print { body { padding: 20px; } .no-print { display: none !important; } } 239 </style> 240</head> 241<body> 242 <div class="no-print" style="margin-bottom:20px;text-align:center;"> 243 <button onclick="window.print()" style="background:#0a2540;color:white;border:none;padding:10px 28px;border-radius:6px;font-size:14px;font-weight:600;cursor:pointer;"> 244 ð¨ï¸ Print / Save as PDF 245 </button> 246 <p style="margin-top:8px;font-size:11px;color:#64748b;">Use your browser's "Save as PDF" option when printing</p> 247 </div> 248 249 <div style="background:#0a2540;color:white;padding:32px;border-radius:8px 8px 0 0;"> 250 <div style="display:flex;align-items:flex-start;justify-content:space-between;"> 251 <div> 252 <div style="font-size:28px;font-weight:900;letter-spacing:1px;">INVOICE</div> 253 <div style="color:#93c5fd;font-size:13px;margin-top:4px;">${e.invoice_number}</div> 254 <div style="color:#93c5fd;font-size:12px;margin-top:2px;">${s.company_name}</div> 255 </div> 256 <div style="text-align:right;"> 257 <div style="font-size:36px;font-weight:900;">${He(o)}</div> 258 <div style="color:#93c5fd;font-size:11px;margin-top:2px;">Total Amount Due</div> 259 </div> 260 </div> 261 </div> 262 263 <div style="display:grid;grid-template-columns:1fr 1fr;gap:32px;padding:20px 24px;border:1px solid #e2e8f0;border-top:none;"> 264 <div> 265 <div style="font-size:10px;font-weight:bold;color:#94a3b8;text-transform:uppercase;letter-spacing:1px;margin-bottom:4px;">Bill To</div> 266 <div style="font-weight:bold;font-size:14px;">${(n==null?void 0:n.full_name)||""}</div> 267 <div style="font-size:12px;color:#64748b;margin-top:2px;">${(n==null?void 0:n.address)||""}</div> 268 <div style="font-size:12px;color:#64748b;">${(n==null?void 0:n.city)||""}, ${(n==null?void 0:n.state)||""} ${(n==null?void 0:n.zip)||""}</div> 269 <div style="font-size:12px;color:#64748b;">${(n==null?void 0:n.phone)||""}</div> 270 </div> 271 <div style="text-align:right;"> 272 <div style="font-size:10px;font-weight:bold;color:#94a3b8;text-transform:uppercase;letter-spacing:1px;margin-bottom:4px;">From</div> 273 <div style="font-weight:bold;font-size:14px;">${s.company_name}</div> 274 <div style="font-size:12px;color:#64748b;">${ma(s)}</div> 275 <div style="font-size:12px;color:#64748b;">${xa(s)}</div> 276 <div style="font-size:12px;color:#64748b;margin-top:8px;">Invoice Date: ${$n()}</div> 277 </div> 278 </div> 279 280 <table style="width:100%;border-collapse:collapse;border:1px solid #e2e8f0;border-top:none;"> 281 <thead> 282 <tr style="background:#f8fafc;border-bottom:1px solid #e2e8f0;"> 283 <th style="padding:10px 24px;text-align:left;font-size:11px;font-weight:700;color:#94a3b8;text-transform:uppercase;letter-spacing:0.5px;">Description</th> 284 <th style="padding:10px 16px;text-align:center;font-size:11px;font-weight:700;color:#94a3b8;text-transform:uppercase;letter-spacing:0.5px;">Qty</th> 285 <th style="padding:10px 16px;text-align:right;font-size:11px;font-weight:700;color:#94a3b8;text-transform:uppercase;letter-spacing:0.5px;">Unit Price</th> 286 <th style="padding:10px 24px;text-align:right;font-size:11px;font-weight:700;color:#94a3b8;text-transform:uppercase;letter-spacing:0.5px;">Amount</th> 287 </tr> 288 </thead> 289 <tbody>${u}${h}</tbody> 290 </table> 291 292 <div style="background:#f8fafc;border:1px solid #e2e8f0;border-top:none;padding:16px 24px;"> 293 <div style="max-width:280px;margin-left:auto;"> 294 <div style="display:flex;justify-content:space-between;font-size:13px;color:#64748b;margin-bottom:6px;"><span>Subtotal</span><span>${He(l+Zs(d))}</span></div> 295 ${Zs(d)>0?`<div style="display:flex;justify-content:space-between;font-size:13px;color:#16a34a;margin-bottom:6px;"><span>Discount</span><span>â${He(Zs(d))}</span></div>`:""} 296 <div style="display:flex;justify-content:space-between;font-size:13px;color:#64748b;margin-bottom:8px;"><span>Tax</span><span>${He(a)}</span></div> 297 <div style="display:flex;justify-content:space-between;font-size:16px;font-weight:bold;color:#0f172a;border-top:1px solid #cbd5e1;padding-top:8px;"><span>Invoice Total</span><span>${He(o)}</span></div> 298 ${f>0?` 299 <div style="display:flex;justify-content:space-between;font-size:13px;color:#64748b;margin-top:8px;"><span>+ First month service plan</span><span>${He(f)}</span></div> 300 <div style="display:flex;justify-content:space-between;font-size:15px;font-weight:bold;color:#0a2540;border-top:1px solid #cbd5e1;padding-top:8px;margin-top:6px;"><span>Total Charged Today</span><span>${He(p)}</span></div> 301 `:""} 302 </div> 303 </div> 304 305 <div style="border:1px solid #e2e8f0;border-top:none;padding:20px 24px;"> 306 <div style="font-size:11px;font-weight:700;color:#94a3b8;text-transform:uppercase;letter-spacing:1px;margin-bottom:8px;">Terms & Conditions</div> 307 ${y} 308 </div> 309 310 <div style="border:2px solid #e2e8f0;border-radius:8px;padding:28px 24px;margin-top:20px;"> 311 <div style="font-weight:bold;font-size:13px;margin-bottom:4px;">Customer Authorization</div> 312 <p style="font-size:11px;color:#64748b;margin-bottom:20px;">By signing, I authorize ${s.company_name} to proceed and agree to the payment terms above.</p> 313 <div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;"> 314 <div style="background:#f8fafc;border:1px solid #e2e8f0;border-radius:8px;padding:16px;"> 315 <div style="font-size:10px;color:#94a3b8;font-weight:600;text-transform:uppercase;letter-spacing:1px;margin-bottom:8px;">${s.company_name.toUpperCase()}</div> 316 <div style="font-size:22px;font-style:italic;font-family:Georgia,serif;color:#0a2540;border-bottom:1px solid #334155;padding-bottom:6px;margin-bottom:8px;">${s.owner_name||"Authorized Representative"}</div> 317 <div style="font-size:11px;color:#64748b;">Authorized Representative · ${$n()}</div> 318 </div> 319 <div style="background:#f8fafc;border:1px solid #e2e8f0;border-radius:8px;padding:16px;"> 320 <div style="font-size:10px;color:#94a3b8;font-weight:600;text-transform:uppercase;letter-spacing:1px;margin-bottom:8px;">CUSTOMER</div> 321 ${i?`<img src="${i}" style="height:36px;
321max-width:200px;object-fit:contain;display:block;margin-bottom:8px;" />`:`<div style="font-size:22px;font-style:italic;font-family:Georgia,serif;color:#0a2540;border-bottom:1px solid #334155;padding-bottom:6px;margin-bottom:8px;">${(e==null?void 0:e.signed_name)||(n==null?void 0:n.full_name)||""}</div>`} 322 <div style="font-size:11px;color:#64748b;">${(n==null?void 0:n.full_name)||""} · Signed ${e!=null&&e.signed_at?new Date(e.signed_at).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric"}):$n()}</div> 323 </div> 324 </div> 325 </div> 326 327 <div style="margin-top:28px;text-align:center;font-size:10px;color:#94a3b8;"> 328 <p>${s.company_name} · ${Yh(s)}</p> 329 <p>${s.phone}${s.email?` · ${s.email}`:""}${s.website?` · ${s.website}`:""}</p> 330 <p style="margin-top:4px;">Invoice ${e.invoice_number} · Generated ${$n()}</p> 331 </div> 332</body> 333</html>`}async function vv(e){if(e)try{const r=await(await fetch("/api/jobs/auto-create-from-lead",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({lead_id:e})})).json();r.success?console.log("[QuoteReview] Job auto-created:",r.job_id,r.already_existed?"(already existed)":""):console.error("[QuoteReview] Auto-create job failed:",r.error)}catch(n){console.error("[QuoteReview] Auto-create job error:",n)}}function qE({brand:e}){const n=e.company_name.split(" ").map(r=>r[0]).join("").slice(0,2).toUpperCase();return t.jsxs("div",{className:"flex items-center gap-3",children:[e.logo_url?t.jsx("img",{src:e.logo_url,alt:e.company_name,style:{height:40,objectFit:"contain"}}):t.jsx("div",{className:"w-10 h-10 rounded-xl flex items-center justify-center flex-shrink-0",style:{backgroundColor:"#0a2540"},children:t.jsx("span",{className:"text-white font-black text-base",children:n})}),t.jsxs("div",{children:[t.jsx("div",{className:"font-bold text-gray-900 text-sm",children:e.company_name}),t.jsxs("div",{className:"text-xs text-gray-400",children:[e.city?`${e.city}, ${e.state}`:"",e.phone?` · ${e.phone}`:""]})]})]})}function DE({steps:e,current:n}){return t.jsx("div",{className:"flex items-center gap-1 mb-8 overflow-x-auto pb-1",children:e.map((r,s)=>t.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx("div",{className:`w-6 h-6 rounded-full flex items-center justify-center text-xs font-bold ${s<n?"bg-green-500 text-white":s===n?"text-white":"bg-gray-200 text-gray-400"}`,style:s===n?{backgroundColor:"#0a2540"}:{},children:s<n?"â":s+1}),t.jsx("span",{className:`text-xs font-medium hidden sm:block whitespace-nowrap ${s===n?"text-gray-800 font-semibold":s<n?"text-green-600":"text-gray-400"}`,children:r})]}),s<e.length-1&&t.jsx("div",{className:`h-px w-6 flex-shrink-0 ${s<n?"bg-green-400":"bg-gray-200"}`})]},s))})}function n0({onSign:e,label:n="Sign Document",loading:r=!1}){const[s,i]=g.useState("type"),[o,a]=g.useState(""),[l,d]=g.useState(!1),c=g.useRef(null),[f,p]=g.useState(!1),[u,h]=g.useState(!1),y=g.useRef(null);function m(C,S){const T=S.getBoundingClientRect(),L=S.width/T.width,E=S.height/T.height;return"touches"in C?{x:(C.touches[0].clientX-T.left)*L,y:(C.touches[0].clientY-T.top)*E}:{x:(C.clientX-T.left)*L,y:(C.clientY-T.top)*E}}function b(C){const S=c.current;S&&(C.preventDefault(),p(!0),y.current=m(C,S))}function A(C){if(!f)return;const S=c.current;if(!S)return;C.preventDefault();const T=S.getContext("2d");if(!T||!y.current)return;const L=m(C,S);T.beginPath(),T.moveTo(y.current.x,y.current.y),T.lineTo(L.x,L.y),T.strokeStyle="#0a2540",T.lineWidth=2.5,T.lineCap="round",T.lineJoin="round",T.stroke(),y.current=L,h(!0)}function v(){p(!1),y.current=null}function x(){var S;const C=c.current;C&&((S=C.getContext("2d"))==null||S.clearRect(0,0,C.width,C.height),h(!1))}function _(){var C;if(l)if(s==="type"){if(o.trim().length<2)return;e(o.trim(),void 0)}else{if(!u)return;e("Drawn signature",(C=c.current)==null?void 0:C.toDataURL("image/png"))}}const j=l&&(s==="type"?o.trim().length>=2:u);return t.jsxs("div",{className:"border border-gray-200 rounded-xl p-5 bg-gray-50",children:[t.jsx("div",{className:"text-sm font-semibold text-gray-700 mb-4",children:"Sign this document"}),t.jsx("div",{className:"flex gap-1 mb-4 bg-white border border-gray-200 rounded-lg p-1
333w-fit",children:["type","draw"].map(C=>t.jsx("button",{onClick:()=>i(C),className:"px-4 py-1.5 rounded-md text-xs font-semibold transition-colors",style:s===C?{backgroundColor:"#0a2540",color:"white"}:{color:"#64748b"},children:C==="type"?"â¨ï¸ Type":"âï¸ Draw"},C))}),s==="type"?t.jsxs("div",{className:"mb-4",children:[t.jsx("label",{className:"block text-xs font-medium text-gray-600 mb-1",children:"Full Legal Name"}),t.jsx("input",{type:"text",value:o,onChange:C=>a(C.target.value),placeholder:"Type your full name to sign",className:"w-full px-3 py-2.5 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"}),o.trim().length>=2&&t.jsxs("div",{className:"mt-3 p-3 bg-white border border-gray-200 rounded-lg",children:[t.jsx("div",{className:"text-xs text-gray-400 mb-1",children:"Signature preview"}),t.jsx("div",{className:"text-2xl text-gray-800",style:{fontFamily:"Georgia, serif",fontStyle:"italic"},children:o})]})]}):t.jsxs("div",{className:"mb-4",children:[t.jsx("label",{className:"block text-xs font-medium text-gray-600 mb-1",children:"Draw your signature"}),t.jsxs("div",{className:"relative bg-white border-2 border-dashed border-gray-300 rounded-lg overflow-hidden",style:{height:120},children:[t.jsx("canvas",{ref:c,width:600,height:120,className:"w-full h-full cursor-crosshair touch-none",onMouseDown:b,onMouseMove:A,onMouseUp:v,onMouseLeave:v,onTouchStart:b,onTouchMove:A,onTouchEnd:v}),!u&&t.jsx("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:t.jsx("span",{className:"text-gray-300 text-sm",children:"Sign here"})}),t.jsx("div",{className:"absolute bottom-3 left-4 right-4 border-b border-gray-300 pointer-events-none"})]}),u&&t.jsx("button",{onClick:x,className:"mt-1.5 text-xs text-red-400 hover:text-red-600",children:"â Clear"})]}),t.jsxs("label",{className:"flex items-start gap-3 mb-4 cursor-pointer",children:[t.jsx("input",{type:"checkbox",checked:l,onChange:C=>d(C.target.checked),className:"mt-0.5 w-4 h-4 rounded border-gray-300 flex-shrink-0"}),t.jsx("span",{className:"text-xs text-gray-600",children:"By signing, I agree this constitutes my legal electronic signature with the same effect as a handwritten signature."})]}),t.jsx("button",{onClick:_,disabled:!j||r,className:"w-full py-3 rounded-lg text-white font-semibold text-sm transition-all disabled:opacity-40 disabled:cursor-not-allowed flex items-center justify-center gap-2",style:{backgroundColor:"#0a2540"},children:r?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"})," Processing..."]}):n})]})}function OE({agreement:e,customer:n,terms:r,brand:s,onSign:i,signing:o,error:a}){return t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{className:"bg-white border border-gray-200 rounded-2xl overflow-hidden shadow-sm",children:[t.jsxs("div",{className:"px-8 py-6 text-white text-center",style:{backgroundColor:"#0a2540"},children:[t.jsx("div",{className:"text-xl font-bold tracking-wide",children:s.company_name.toUpperCase()}),t.jsxs("div",{className:"text-sm text-blue-200 mt-1",children:[ma(s),s.city?` · ${xa(s)}`:""]}),t.jsxs("div",{className:"text-sm text-blue-200",children:[s.phone,s.website?` · ${s.website}`:""]})]}),t.jsxs("div",{className:"px-8 py-5 text-center bg-gray-50 border-b border-gray-200",children:[t.jsx("div",{className:"text-xs font-bold text-gray-400 uppercase tracking-widest mb-1",children:"Legal Agreement"}),t.jsx("div",{className:"text-2xl font-bold text-gray-900",children:"Residential Equipment Rental Agreement"}),t.jsx("div",{className:"text-sm font-semibold mt-2",style:{color:"#0a2540"},children:e.agreement_number})]}),t.jsxs("div",{className:"px-8 py-5 grid grid-cols-2 gap-8 border-b border-gray-100",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-xs font-bold text-gray-400 uppercase tracking-wide mb-1",children:"Company"}),t.jsx("div",{className:"font-bold text-gray-900",children:s.company_name}),t.jsx("div",{className:"text-sm text-gray-500",children:ma(s)}),t.jsx("div",{className:"text-sm text-gray-500",children:xa(s)})]}),t.jsxs("div",{children:[t.jsx("div",{className:"text-xs font-bold text-gray-400 uppercase tracking-wide mb-1",children:"Customer"}),t.jsx("div",{className:"font-bold text-gray-900",children:n==null?void 0:n.full_name}),t.jsx("div",{className:"text-sm text-gray-500",children:n==null?void 0:n.address}),t.jsxs("div",{className:"text-sm text-gray-500",children:[n==null?void 0:n.city,", ",n==null?void 0:n.state," ",n==null?void 0:n.zip]})]})]}),t.jsx("div",{className:"grid grid-cols-3 gap-4 px-8 py-5 bg-blue-50 border-b border-blue-100 text-center",children:[{label:"Monthly Payment",value:`${He(e.monthly_amount)}/mo`},{label:"Setup Fee (one-time)",value:He(e.install_fee)},{label:"Initial Term",value:"36 months"}].map(l=>t.jsxs("div",{children:[t.jsx("div",{className:"text-xs text-blue-500 font-semibold uppercase tracking-wide",children:l.label}),t.jsx("div",{className:"text-lg font-bold text-blue-900 mt-1",children:l.value})]},l.label))}),t.jsx("div",{className:"px-8 py-4 bg-amber-50 border-b border-amber-100",children:t.jsx("p",{className:"text-xs font-bold text-amber-700 text-center uppercase tracking-wide",children:"By
333signing, you agree to all terms including the binding arbitration clause in Article IX."})}),t.jsx("div",{className:"px-8 py-5",children:t.jsxs("p",{className:"text-sm text-gray-700 leading-relaxed",children:["This Agreement is entered into as of ",t.jsx("strong",{children:$n()})," between"," ",t.jsx("strong",{children:s.company_name}),' ("Company") and ',t.jsx("strong",{children:n==null?void 0:n.full_name}),' ("Customer").']})})]}),r.map((l,d)=>t.jsxs("div",{className:"bg-white border border-gray-200 rounded-xl overflow-hidden shadow-sm",children:[t.jsx("div",{className:"px-6 py-3 bg-gray-50 border-b border-gray-100",children:t.jsx("h3",{className:"text-sm font-bold text-gray-800",children:l.title})}),t.jsx("div",{className:"px-6 py-5",children:t.jsx("p",{className:"text-sm text-gray-700 leading-relaxed whitespace-pre-wrap",children:l.content.replace(/\[INSTALL_FEE\]/g,He(e.install_fee)).replace(/\[MONTHLY_AMOUNT\]/g,He(e.monthly_amount))})})]},l.title+d)),t.jsxs("div",{className:"bg-white border-2 border-gray-200 rounded-2xl p-8 shadow-sm",children:[t.jsx("div",{className:"font-bold text-gray-700 text-sm mb-1",children:"IN WITNESS WHEREOF"}),t.jsxs("p",{className:"text-xs text-gray-500 mb-6",children:["Executed as of ",$n(),"."]}),t.jsxs("div",{className:"grid grid-cols-2 gap-6 mb-8",children:[t.jsxs("div",{className:"p-4 bg-gray-50 rounded-xl border border-gray-200",children:[t.jsx("div",{className:"text-xs text-gray-400 font-semibold mb-2",children:s.company_name.toUpperCase()}),t.jsx("div",{className:"h-10 border-b border-gray-400 mb-2 flex items-end",children:t.jsx("span",{className:"text-xl pb-1",style:{fontFamily:"Georgia, serif",fontStyle:"italic",color:"#0a2540"},children:s.owner_name||"Authorized Representative"})}),t.jsxs("div",{className:"text-xs text-gray-500",children:["Authorized Representative · ",$n()]})]}),t.jsxs("div",{className:"p-4 bg-gray-50 rounded-xl border border-gray-200",children:[t.jsx("div",{className:"text-xs text-gray-400 font-semibold mb-2",children:"CUSTOMER"}),t.jsx("div",{className:"h-10 border-b border-gray-300 mb-2"}),t.jsx("div",{className:"text-xs text-gray-500",children:n==null?void 0:n.full_name})]})]}),a&&t.jsx("p",{className:"text-red-500 text-xs mb-4",children:a}),t.jsx(n0,{onSign:i,label:"Sign Rental Agreement",loading:o})]})]})}function IE({invoice:e,customer:n,terms:r,brand:s,onSign:i,signing:o,error:a}){const l=e.line_items_snapshot||[];return t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{className:"bg-white border border-gray-200 rounded-2xl overflow-hidden shadow-sm",children:[t.jsx("div",{className:"px-8 py-6 text-white",style:{backgroundColor:"#0a2540"},children:t.jsxs("div",{className:"flex items-start justify-between",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-2xl font-bold",children:"INVOICE"}),t.jsx("div",{className:"text-blue-200 text-sm",children:e.invoice_number})]}),t.jsxs("div",{className:"text-right",children:[t.jsx("div",{className:"text-3xl font-black",children:He(e.total)}),t.jsx("div",{className:"text-blue-200 text-xs mt-1",children:"Total Amount"})]})]})}),t.jsxs("div",{className:"px-8 py-5 grid grid-cols-2 gap-8 border-b border-gray-100",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-xs font-bold text-gray-400 uppercase tracking-wide mb-1",children:"Bill To"}),t.jsx("div",{className:"font-bold text-gray-900",children:n==null?void 0:n.full_name}),t.jsx("div",{className:"text-sm text-gray-500",children:n==null?void 0:n.address}),t.jsxs("div",{className:"text-sm text-gray-500",children:[n==null?void 0:n.city,", ",n==null?void 0:n.state," ",n==null?void 0:n.zip]}),t.jsx("div",{className:"text-sm text-gray-500",children:n==null?void 0:n.phone})]}),t.jsxs("div",{className:"text-right",children:[t.jsx("div",{className:"text-xs font-bold text-gray-400 uppercase tracking-wide mb-1",children:"From"}),t.jsx("div",{className:"font-bold text-gray-900",children:s.company_name}),t.jsx("div",{className:"text-sm text-gray-500",children:ma(s)}),t.jsx("div",{className:"text-sm text-gray-500",children:xa(s)}),t.jsx("div",{className:"mt-3 text-xs text-gray-400",children:"Invoice Date"}),t.jsx("div",{className:"font-semibold text-gray-700 text-sm",children:$n()})]})]}),l.length>0&&t.jsxs(t.Fragment,{children:[t.jsxs("table",{className:"w-full",children:[t.jsx("thead",{children:t.jsxs("tr",{className:"bg-gray-50 border-b border-gray-200 text-xs text-gray-400 font-bold uppercase tracking-wide",children:[t.jsx("th",{className:"px-8 py-3 text-left",children:"Description"}),t.jsx("th",{className:"px-4 py-3 text-center",children:"Qty"}),t.jsx("th",{className:"px-4 py-3 text-right",children:"Unit Price"}),t.jsx("th",{className:"px-8 py-3 text-right",children:"Amount"})]})}
333),t.jsx("tbody",{children:l.map((d,c)=>t.jsxs("tr",{className:"border-b border-gray-50",children:[t.jsxs("td",{className:"px-8 py-4 text-sm text-gray-800",children:[d.description,Gl(d)>0&&t.jsxs("div",{style:{fontSize:12,color:"#16a34a",marginTop:2},children:[parseFloat(d.discount_pct)||0,"% off: â",He(Gl(d))]})]}),t.jsx("td",{className:"px-4 py-4 text-sm text-gray-600 text-center",children:d.quantity}),t.jsx("td",{className:"px-4 py-4 text-sm text-gray-600 text-right",children:He(d.unit_price)}),t.jsx("td",{className:"px-8 py-4 text-sm font-semibold text-gray-900 text-right",children:He(d.total_price)})]},c))})]}),t.jsx("div",{className:"px-8 py-5 bg-gray-50",children:t.jsxs("div",{className:"max-w-xs ml-auto space-y-2",children:[t.jsxs("div",{className:"flex justify-between text-sm text-gray-600",children:[t.jsx("span",{children:"Subtotal"}),t.jsx("span",{children:He(e.total-(e.tax_amount||0)+Zs(l))})]}),Zs(l)>0&&t.jsxs("div",{className:"flex justify-between text-sm",style:{color:"#16a34a"},children:[t.jsx("span",{children:"Discount"}),t.jsxs("span",{children:["â",He(Zs(l))]})]}),t.jsxs("div",{className:"flex justify-between text-sm text-gray-600",children:[t.jsx("span",{children:"Tax"}),t.jsx("span",{children:He(e.tax_amount||0)})]}),t.jsxs("div",{className:"flex justify-between text-base font-bold text-gray-900 pt-2 border-t border-gray-300",children:[t.jsx("span",{children:"Total"}),t.jsx("span",{children:He(e.total)})]})]})})]})]}),t.jsxs("div",{className:"bg-white border border-gray-200 rounded-xl p-6",children:[t.jsx("div",{className:"text-xs font-bold text-gray-400 uppercase tracking-wide mb-2",children:"Terms & Conditions"}),t.jsx("a",{href:s.slug?`/t/${s.slug}/terms`:"/terms",target:"_blank",rel:"noopener noreferrer",className:"text-xs text-blue-600 hover:underline block mb-3",children:"View full Terms & Conditions â"}),r.map((d,c)=>t.jsx("p",{className:"text-xs text-gray-600 leading-relaxed mb-2",children:d.content},d.title+c))]}),t.jsxs("div",{className:"bg-white border-2 border-gray-200 rounded-2xl p-8 shadow-sm",children:[t.jsx("div",{className:"font-bold text-gray-700 text-sm mb-1",children:"Customer Authorization"}),t.jsxs("p",{className:"text-xs text-gray-500 mb-6",children:["By signing, I authorize ",s.company_name," to proceed and agree to the payment terms above."]}),t.jsxs("div",{className:"grid grid-cols-2 gap-6 mb-8",children:[t.jsxs("div",{className:"p-4 bg-gray-50 rounded-xl border border-gray-200",children:[t.jsx("div",{className:"text-xs text-gray-400 font-semibold mb-2",children:s.company_name.toUpperCase()}),t.jsx("div",{className:"h-10 border-b border-gray-400 mb-2 flex items-end",children:t.jsx("span",{className:"text-xl pb-1",style:{fontFamily:"Georgia, serif",fontStyle:"italic",color:"#0a2540"},children:s.owner_name||"Authorized Representative"})}),t.jsxs("div",{className:"text-xs text-gray-500",children:["Authorized Representative · ",$n()]})]}),t.jsxs("div",{className:"p-4 bg-gray-50 rounded-xl border border-gray-200",children:[t.jsx("div",{className:"text-xs text-gray-400 font-semibold mb-2",children:"CUSTOMER"}),t.jsx("div",{className:"h-10 border-b border-gray-300 mb-2"}),t.jsx("div",{className:"text-xs text-gray-500",children:n==null?void 0:n.full_name})]})]}),a&&t.jsx("p",{className:"text-red-500 text-xs mb-4",children:a}),t.jsx(n0,{onSign:i,label:"Sign Invoice",loading:o})]})]})}function LE(){var V,ee,re,Q,oe,ne,ge,be,we,F,K,Z,ie;const{token:e}=di(),[n]=If(),[r,s]=g.useState("loading"),[i,o]=g.useState(null),[a,l]=g.useState([]),[d,c]=g.useState([]),[f,p]=g.useState([]),[u,h]=g.useState(null),[y,m]=g.useState(null),[b,A]=g.useState(""),[v,x]=g.useState(!1),[_,j]=g.useState(!1),[C,S]=g.useState(!1),[T,L]=g.useState(""),[E,R]=g.useState(ih),[N,O]=g.useState([]),z=g.useRef(null),P=(i==null?void 0:i.commercial_type)==="rental"?"rental":(i==null?void 0:i.commercial_type)==="financed"?"finance":"purchase",D=["Review Quote","Sign Quote","Sign Agreement","Save Card"],M=["Review Quote","Sign Quote","Sign Invoice","Payment"],k=["Review Quote","Sign Quote","Apply for Financing"],q=r==="view_quote"?1:r==="view_agreement"||r==="view_invoice"?2:r==="payment_choice"||r==="stripe_card_save"||r==="stripe_purchase_payment"?3:r==="hearth_redirect"?2:r==="complete"?P==="finance"?3:4:0;function $(Y){if(!Y)return null;const X=zE(Y.tenant_branding);R(X);const H={...Y.quote};return H.customer=NE(Y.customer),H.created_by_name=Y.rep_name||null,H.total==null&&H.total_amount!=null&&(H.total=H.total_amount),o(H),l(Y.line_items||[]),c(Y.rental_terms||[]),p(Y.purchase_terms||[]),Y.agreement&&h(Y.agreement),Y.invoice&&m(op(Y.invoice)),H}async function I(Y){if(!i)return;const X=i.customer;j(!0);try{const H=window.location.origin,pe=await(await fetch("/api/stripe/create-checkout-session",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({customer_name:X==null?void 0:X.full_name,customer_email:X==null?void 0:X.email,amount_cents:Y.amount_cents,description:Y.description,quote_type:Y.flow,agreement_id:Y.agreement_id,invoice_id:Y.invoice_id,quote_id:i.id,customer_id:i.customer_id,tenant_id:i.tenant_id,service_plan_lines:Y.service_plan_lines||[],tax_rate:Y.tax_rate??E.tax_rate??.07,success_url:`${H}/q/${e}?paid=1&session_id={CHECKOUT_SESSION_ID}`,cancel_url:`${H}/q/${e}?cancelled=1`})})).json();if(pe.error)throw new Error(pe.error);window.location.href=pe.url}catch(H){A(H.message||`Failed to start payment. Please call ${E.phone||"us"}.`),j(!1)}}async function B(){var Y;S(!0),A("");try{const X=u;if(!X){A(`Agreement not found. Please contact ${E.phone||"us"}.`),S(!1);return}const H=((Y=X.terms_snapshot)==null?void 0:Y.blocks)||d,de=T||X.signature_data||void 0,pe
333=RE(X,i==null?void 0:i.customer,H,E,de),Ne=new Blob([pe],{type:"text/html"}),Ie=URL.createObjectURL(Ne),Ze=document.createElement("a");Ze.href=Ie,Ze.target="_blank",Ze.rel="noopener noreferrer",Ze.click(),setTimeout(()=>URL.revokeObjectURL(Ie),1e4)}catch(X){A(X.message||"Could not generate PDF. Please try again.")}S(!1)}async function J(){var Y;S(!0),A("");try{const X=y;if(!X){A(`Invoice not found. Please contact ${E.phone||"us"}.`),S(!1);return}const H=((Y=X.terms_snapshot)==null?void 0:Y.blocks)||f,de=T||X.signature_data||void 0,pe=PE(X,i==null?void 0:i.customer,H,E,de),Ne=new Blob([pe],{type:"text/html"}),Ie=URL.createObjectURL(Ne),Ze=document.createElement("a");Ze.href=Ie,Ze.target="_blank",Ze.rel="noopener noreferrer",Ze.click(),setTimeout(()=>URL.revokeObjectURL(Ie),1e4)}catch(X){A(X.message||"Could not generate PDF. Please try again.")}S(!1)}g.useEffect(()=>{if(!e){s("error"),A("No quote token provided.");return}const Y=n.get("paid")==="1",X=n.get("financing_approved")==="1";(async()=>{try{const{data:H,error:de}=await w.rpc("public_get_quote_bundle",{p_token:e});if(de||!H){s("error"),A("Quote not found.");return}const pe=$(H);if(!pe){s("error"),A("Quote not found.");return}if(Y){s("complete");return}if(pe.expires_at&&new Date(pe.expires_at)<new Date){s("expired");return}if(["accepted","declined","void"].includes(pe.status)){s("already_complete");return}if(w.rpc("public_mark_quote_viewed",{p_token:e}).then(()=>{}),pe.signed_at){const Ne=pe.commercial_type;if(Ne==="rental"&&H.agreement){s(H.agreement.signed_at?"stripe_card_save":"view_agreement");return}if(Ne==="financed"&&!X){s("hearth_redirect");return}if(H.invoice){s(H.invoice.signed_at?"payment_choice":"view_invoice");return}}s("view_quote")}catch(H){console.error("[QuoteReview] load error:",H),s("error"),A((H==null?void 0:H.message)||"Something went wrong.")}})()},[e]);function ae(){setTimeout(()=>{var Y;return(Y=z.current)==null?void 0:Y.scrollIntoView({behavior:"smooth"})},100)}async function te(Y,X){var H,de,pe,Ne,Ie,Ze,ht;if(X&&L(X),!(!i||!e)){x(!0),A("");try{const{error:ke}=await w.rpc("public_sign_quote",{p_token:e,p_signed_name:Y,p_signature_data:X||null});if(ke)throw ke;if(o(Pe=>Pe&&{...Pe,status:"signed",signed_at:new Date().toISOString()}),P==="rental"){const{data:Pe,error:nt}=await w.rpc("public_create_agreement",{p_token:e,p_monthly_amount:Number(i.monthly_rental_price),p_install_fee:Number(i.install_fee)||0,p_term_months:36,p_terms_snapshot:{blocks:d,captured_at:new Date().toISOString()},p_line_items_snapshot:a});if(nt)throw nt;h(Pe),w.rpc("public_convert_lead_customer",{p_token:e}).then(()=>{}),s("view_agreement"),ae()}else if(P==="purchase"){const Pe=a.reduce((_e,je)=>_e+(je.total_price??je.total??0),0),nt=parseFloat((Pe*(E.tax_rate||.07)).toFixed(2)),ue=parseFloat((Pe+nt).toFixed(2)),fe=Math.round(ue*.5*100)/100,le=[(H=i.customer)==null?void 0:H.address,(de=i.customer)==null?void 0:de.city,(pe=i.customer)==null?void 0:pe.state,(Ne=i.customer)==null?void 0:Ne.zip].filter(Boolean).join(", "),{data:ce,error:xe}=await w.rpc("public_create_invoice",{p_token:e,p_subtotal:Pe,p_tax_amount:nt,p_total_amount:ue,p_deposit_percent:50,p_deposit_amount:fe,p_terms_snapshot:{blocks:f,captured_at:new Date().toISOString()},p_line_items_snapshot:a,p_customer_name:((Ie=i.customer)==null?void 0:Ie.full_name)||null,p_customer_email:((Ze=i.customer)==null?void 0:Ze.email)||null,p_customer_phone:((ht=i.customer)==null?void 0:ht.phone)||null,p_customer_address:le||null});if(xe)throw xe;m(op(ce));const ve=a.filter(_e=>_e.item_type==="service_plan");for(const _e of ve){const je=_e.product_id||_e.product_catalog_id;if(!je){console.warn("No plan_id on service plan line item");continue}const Be=_e.unit_price??_e.total_price??0;try{await w.rpc("public_create_customer_service_plan",{p_token:e,p_plan_id:je,p_price_monthly:Be,p_billing_interval:"monthly"})}catch(Je){console.error("Failed to create pending service plan:",Je)}}w.rpc("public_convert_lead_customer",{p_token:e}).then(()=>{}),s("view_invoice"),ae()}else{w.rpc("public_convert_lead_customer",{p_token:e}).then(()=>{});const Pe=Av(E,i.customer,i.total);s("hearth_redirect"),setTimeout(()=>{window.location.href=Pe},1800)}}catch(ke){console.error("[QuoteReview] handleSignQuote error:",ke),A(ke.message||"Signing failed. Please try again.")}x(!1)}}async function U(Y,X){if(X&&L(X),!(!u||!e)){x(!0),A("");try{const{data:H,error:de}=await w.rpc("public_sign_agreement",{p_token:e,p_agreement_id:u.id,p_signed_name:Y,p_signature_data:X||null});if(de)throw de;h(H);const{error:pe}=await w.rpc("public_create_contract_on_signing",{p_token:e,p_agreement_id:u.id});if(pe)throw pe;i!=null&&i.lead_id&&await vv(i.lead_id),s("stripe_card_save"),ae()}catch(H){console.error("[QuoteReview] handleSignAgreement error:",H),A(H.message||"Signing failed. Please try again.")}x(!1)}}
333async function W(Y,X){if(X&&L(X),!(!y||!e)){x(!0),A("");try{const{data:H,error:de}=await w.rpc("public_sign_invoice",{p_token:e,p_invoice_id:y.id,p_signed_name:Y,p_signature_data:X||null});if(de)throw de;m(op(H)),i!=null&&i.lead_id&&await vv(i.lead_id);try{}catch{}s("payment_choice"),ae()}catch(H){console.error("[QuoteReview] handleSignInvoice error:",H),A(H.message||"Signing failed. Please try again.")}x(!1)}}async function G(Y){if(!y||!i||!e)return;const X=Math.round(Y==="full"?y.total*100:y.total*.5*100),H=Y==="full"?`Full Payment â ${y.invoice_number}`:`Purchase Deposit (50%) â ${y.invoice_number}`;if(Y==="full")try{const{data:pe}=await w.rpc("public_update_invoice_to_full_payment",{p_token:e,p_invoice_id:y.id});pe&&m(op(pe))}catch(pe){console.error("[QuoteReview] update invoice to full payment error:",pe)}const de=N;s("stripe_purchase_payment"),await I({amount_cents:X,description:H,flow:"purchase",invoice_id:y.id,service_plan_lines:de,tax_rate:E.tax_rate})}return r==="loading"?t.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center",children:t.jsxs("div",{className:"text-center",children:[t.jsx("div",{className:"w-10 h-10 border-2 border-t-transparent rounded-full animate-spin mx-auto mb-3",style:{borderColor:"#0a2540",borderTopColor:"transparent"}}),t.jsx("p",{className:"text-gray-500 text-sm",children:"Loading your document..."})]})}):r==="error"?t.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center p-4",children:t.jsxs("div",{className:"bg-white rounded-2xl shadow p-8 max-w-md w-full text-center",children:[t.jsx("div",{className:"text-4xl mb-3",children:"â ï¸"}),t.jsx("h2",{className:"text-lg font-bold mb-2",children:"Document Not Found"}),t.jsx("p",{className:"text-sm text-gray-500",children:b}),E.phone&&t.jsx("p",{className:"text-xs text-gray-400 mt-4",children:E.phone})]})}):r==="expired"?t.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center p-4",children:t.jsxs("div",{className:"bg-white rounded-2xl shadow p-8 max-w-md w-full text-center",children:[t.jsx("div",{className:"text-4xl mb-3",children:"â°"}),t.jsx("h2",{className:"text-lg font-bold mb-2",children:"Quote Expired"}),t.jsx("p",{className:"text-sm text-gray-500",children:"Please contact your sales rep for a new quote."}),E.phone&&t.jsx("p",{className:"text-xs text-gray-400 mt-4",children:E.phone})]})}):r==="already_complete"?t.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center p-4",children:t.jsxs("div",{className:"bg-white rounded-2xl shadow p-8 max-w-md w-full text-center",children:[t.jsx("div",{className:"text-4xl mb-3",children:"â
"}),t.jsx("h2",{className:"text-lg font-bold mb-2",children:"Already Processed"}),t.jsx("p",{className:"text-sm text-gray-500",children:"This document has already been signed."}),E.phone&&t.jsx("p",{className:"text-xs text-gray-400 mt-4",children:E.phone})]})}):r==="hearth_redirect"?t.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center p-4",children:t.jsxs("div",{className:"bg-white rounded-2xl shadow p-8 max-w-md w-full text-center",children:[t.jsx("div",{className:"w-16 h-16 rounded-full flex items-center justify-center mx-auto mb-4 text-3xl",style:{backgroundColor:"#f0fdf4"},children:"ð¦"}),t.jsx("h2",{className:"text-xl font-bold mb-2",children:"Quote Signed!"}),t.jsx("p",{className:"text-sm text-gray-500 mb-5",children:"You're being redirected to complete your financing application. Your information has been pre-filled to save you time."}),t.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-xl p-4 mb-5 text-left space-y-1.5 text-sm",children:[((V=i==null?void 0:i.customer)==null?void 0:V.full_name)&&t.jsxs("div",{className:"flex justify-between",children:[t.jsx("span",{className:"text-gray-500",children:"Name"}),t.jsx("span",{className:"font-medium text-gray-800",children:i.customer.full_name})]}),((ee=i==null?void 0:i.customer)==null?void 0:ee.email)&&t.jsxs("div",{className:"flex justify-between",children:[t.jsx("span",{className:"text-gray-500",children:"Email"}),t.jsx("span",{className:"font-medium text-gray-800",children:i.customer.email})]}),(i==null?void 0:i.total)&&i.total>0&&t.jsxs("div",{className:"flex justify-between",children:[t.jsx("span",{className:"text-gray-500",children:"Amount"}),t.jsx("span",{className:"font-medium text-gray-800",children:He(i.total)})]})]}),t.jsxs("div",{className:"flex items-center justify-center gap-2 mb-4",children:[t.jsx("div",{className:"w-5 h-5 border-2 border-t-transparent roun
333ded-full animate-spin",style:{borderColor:"#0a2540",borderTopColor:"transparent"}}),t.jsx("span",{className:"text-sm text-gray-500",children:"Redirecting to financing application..."})]}),t.jsx("button",{onClick:()=>{const Y=Av(E,i==null?void 0:i.customer,(i==null?void 0:i.total)||0);Y&&(window.location.href=Y)},className:"w-full py-3 rounded-xl text-white font-semibold text-sm",style:{backgroundColor:"#0a2540"},children:"Continue to Hearth â"}),E.phone&&t.jsx("p",{className:"text-xs text-gray-400 mt-4",children:E.phone})]})}):r==="stripe_card_save"?t.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center p-4",children:t.jsx("div",{className:"bg-white rounded-2xl shadow p-8 max-w-md w-full text-center",children:_?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"w-14 h-14 rounded-full flex items-center justify-center mx-auto mb-4",style:{backgroundColor:"#eff6ff"},children:t.jsx("div",{className:"w-7 h-7 border-2 border-t-transparent rounded-full animate-spin",style:{borderColor:"#0a2540",borderTopColor:"transparent"}})}),t.jsx("h2",{className:"text-xl font-bold mb-2",children:"Redirecting to secure card save..."})]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"w-16 h-16 rounded-full bg-green-50 flex items-center justify-center mx-auto mb-4 text-3xl",children:"â
"}),t.jsx("h2",{className:"text-xl font-bold mb-2",children:"Agreement Signed!"}),t.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-xl p-4 mb-5 text-left",children:[t.jsx("div",{className:"text-sm font-semibold text-blue-800 mb-1",children:"ð³ No charge today"}),t.jsxs("p",{className:"text-sm text-blue-700",children:["We just need to save your payment method securely.",t.jsx("strong",{children:" Autopay will begin after your installation is completed."})]})]}),t.jsxs("div",{className:"bg-gray-50 rounded-xl p-4 mb-5 text-left space-y-2",children:[t.jsxs("div",{className:"flex justify-between text-sm text-gray-600",children:[t.jsx("span",{children:"Monthly rental"}),t.jsxs("span",{className:"font-semibold",children:[He((u==null?void 0:u.monthly_amount)||0),"/mo"]})]}),t.jsxs("div",{className:"flex justify-between text-sm text-gray-600",children:[t.jsx("span",{children:"First charge"}),t.jsx("span",{className:"font-semibold text-green-600",children:"After installation"})]}),t.jsxs("div",{className:"flex justify-between text-sm text-gray-600",children:[t.jsx("span",{children:"Agreement"}),t.jsx("span",{className:"font-semibold",children:u==null?void 0:u.agreement_number})]})]}),b&&t.jsx("p",{className:"text-red-500 text-xs mb-4",children:b}),t.jsx("button",{onClick:()=>I({amount_cents:0,description:`Card save for rental â ${u==null?void 0:u.agreement_number}`,flow:"rental",agreement_id:u==null?void 0:u.id}),className:"w-full py-3 rounded-xl text-white font-semibold text-sm",style:{backgroundColor:"#0a2540"},children:"Save Card Securely â"}),E.phone&&t.jsx("p",{className:"text-xs text-gray-400 mt-4",children:E.phone})]})})}):r==="payment_choice"?t.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center p-4",children:t.jsxs("div",{className:"bg-white rounded-2xl shadow p-8 max-w-md w-full",children:[t.jsxs("div",{className:"text-center mb-6",children:[t.jsx("div",{className:"w-16 h-16 rounded-full bg-green-50 flex items-center justify-center mx-auto mb-4 text-3xl",children:"â
"}),t.jsx("h2",{className:"text-xl font-bold",children:"Invoice Signed!"}),t.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"Choose your payment option below."})]}),t.jsx("div",{className:"space-y-3 mb-6",children:(()=>{const Y=(y==null?void 0:y.total)||0,X=N.reduce((Ie,Ze)=>Ie+Ze.amount_cents/100,0),H=Math.round(Y*.5*100)/100,de=H+X,pe=Y+X,Ne=N.length>0;return t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:()=>G("50_percent"),className:"w-full border-2 border-gray-200 hover:border-blue-400 rounded-xl p-4 text-left transition-colors group",children:t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsxs("div",{children:[t.jsx("div",{className:"font-bold text-gray-900 group-hover:text-blue-700",children:"Pay 50% Deposit Today"}),t.jsxs("div",{className:"text-xs text-gray-500 mt-0.5",children:[He(H)," deposit",Ne?` + ${He(X)} first month plan`:""]}),t.jsxs("div",{className:"text-xs text-gray-500",children:["Balance of ",He(H)," due on installation day"]})]}),t.jsx("div",{className:"text-xl font-black",style:{color:"#0a2540"},children:He(de)})]})}),t.jsx("button",{onClick:()=>G("full"),className:"w-full border-2 border-gray-200 hover:border-green-400 rounded-xl p-4 text-left transition-colors group",children:t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsxs("div",{children:[t.jsx("div",{className:"font-bold text-gray-900 group-hover:text-green-700",children:"Pay Full Amount"}),t.jsxs("div",{className:"text-xs text-gray-500 mt-0.5",children:[He(Y)," invoice",Ne?` + ${He(X)} first month plan`:""]}),t.jsx("div",{className:"text-xs text-gray-500",children:"No balance due at installation"})]}),t.jsx("div",{className:"text-xl font-black text-green-600",children:He(pe)})]})})]})})()}),b&&t.jsx("p",{className:"text-red-500 text-xs mb-4 text-center",children:b}),E.phone&&t.jsx("p",{className:"text-xs text-gray-400 text-center",children:E.phone})]})}):r==="stripe_purchase_payment"?t.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center p-4",children:t.jsxs("div",{className:"bg-white rounded-2xl shadow p-8 max-w-md w-full text-center",children:[t.jsx("div",{className:"w-14 h-14 roun
333ded-full flex items-center justify-center mx-auto mb-4",style:{backgroundColor:"#eff6ff"},children:t.jsx("div",{className:"w-7 h-7 border-2 border-t-transparent rounded-full animate-spin",style:{borderColor:"#0a2540",borderTopColor:"transparent"}})}),t.jsx("h2",{className:"text-xl font-bold mb-2",children:"Redirecting to secure payment..."}),t.jsx("p",{className:"text-sm text-gray-400",children:"Please wait"})]})}):r==="complete"?t.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center p-4",children:t.jsxs("div",{className:"bg-white rounded-2xl shadow p-8 max-w-md w-full text-center",children:[t.jsx("div",{className:"text-5xl mb-4",children:"ð"}),t.jsx("h2",{className:"text-xl font-bold mb-2",children:P==="rental"?"Card Saved Successfully!":"All Done!"}),t.jsx("p",{className:"text-sm text-gray-500 mb-6",children:P==="rental"?"Your payment method has been saved. Autopay will begin after your installation is completed. We'll be in touch to schedule.":`Documents signed and payment received. ${E.company_name} will be in touch soon.`}),P==="rental"&&t.jsxs("div",{className:"mb-5",children:[t.jsx("button",{onClick:B,disabled:C,className:"w-full py-3 rounded-xl font-semibold text-sm flex items-center justify-center gap-2 disabled:opacity-50",style:{backgroundColor:"#f0f9ff",border:"1.5px solid #bae6fd",color:"#0369a1"},children:C?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"w-4 h-4 border-2 border-t-transparent rounded-full animate-spin",style:{borderColor:"#0369a1",borderTopColor:"transparent"}}),"Generating PDF..."]}):t.jsx(t.Fragment,{children:"ð Download Your Signed Agreement"})}),t.jsx("p",{className:"text-xs text-gray-400 mt-2",children:"Downloads as a PDF file directly to your device"})]}),P==="purchase"&&t.jsxs("div",{className:"mb-5",children:[t.jsx("button",{onClick:J,disabled:C,className:"w-full py-3 rounded-xl font-semibold text-sm flex items-center justify-center gap-2 disabled:opacity-50",style:{backgroundColor:"#f0fdf4",border:"1.5px solid #bbf7d0",color:"#15803d"},children:C?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"w-4 h-4 border-2 border-t-transparent rounded-full animate-spin",style:{borderColor:"#15803d",borderTopColor:"transparent"}}),"Generating PDF..."]}):t.jsx(t.Fragment,{children:"ð Download Your Signed Invoice"})}),t.jsx("p",{className:"text-xs text-gray-400 mt-2",children:"Downloads as a PDF file directly to your device"})]}),b&&t.jsx("p",{className:"text-red-500 text-xs mb-4",children:b}),E.phone&&t.jsx("p",{className:"text-xs text-gray-400",children:E.phone})]})}):t.jsxs("div",{className:"min-h-screen bg-gray-50",ref:z,children:[t.jsx("div",{className:"bg-white border-b border-gray-200 sticky top-0 z-10 shadow-sm",children:t.jsxs("div",{className:"max-w-3xl mx-auto px-4 py-4 flex items-center justify-between",children:[t.jsx(qE,{brand:E}),t.jsx("div",{className:"text-xs text-gray-400 font-mono",children:i==null?void 0:i.quote_number})]})}),t.jsxs("div",{className:"max-w-3xl mx-auto px-4 py-8",children:[t.jsx(DE,{steps:P==="rental"?D:P==="finance"?k:M,current:q}),r==="view_quote"&&i&&t.jsxs("div",{className:"space-y-5",children:[t.jsxs("div",{className:"bg-white rounded-2xl border border-gray-200 shadow-sm overflow-hidden",children:[t.jsxs("div",{className:"px-6 py-5 text-white",style:{backgroundColor:"#0a2540"},children:[t.jsxs("div",{className:"flex items-start justify-between",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-xl font-bold",children:P==="rental"?"Rental Quote":P==="purchase"?"Purchase Order":"Finance Quote"}),t.jsx("div",{className:"text-blue-200 text-sm",children:i.quote_number})]}),t.jsxs("div",{className:"text-right",children:[t.jsx("div",{className:"text-xs text-blue-300",children:"Expires"}),t.jsx("div",{className:"text-white font-medium text-sm",children:i.expires_at?new Date(i.expires_at).toLocaleDateString():"â"})]})]}),t.jsxs("div",{className:"flex gap-8 mt-4 pt-4 border-t border-blue-800",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-xs text-blue-300 uppercase tracking-wide",children:"Quotation Date"}),t.jsx("div",{className:"text-white text-sm font-medium",children:i.created_at?new Date(i.created_at).toLocaleDateString():$n()})]}),t.jsxs("div",{children:[t.jsx("div",{className:"text-xs text-blue-300 uppercase tracking-wide",children:"Expiration"}),t.jsx("div",{className:"text-white text-sm font-medium",children:i.expires_at?new Date(i.expires_at).toLocaleDateString():"â"})]}),t.jsxs("div",{children:[t.jsx("div",{className:"text-xs text-blue-300 uppercase tracking-wide",children:"Sales Consultant"}),t.jsx("div",{className:"text-white text-sm font-medium",children:i.created_by_name||E.company_name})]})]})]}),t.jsxs("div",{className:"px-6 py-5 grid grid-cols-3 gap-4 text-sm border-b border-gray-100",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-xs font-bold text-gray-400 uppercase tracking-wide mb-1",children:"Bill To"}),t.jsx("div",{className:"font-semibold text-gray-800",children:((re=i.customer)==null?void 0:re.full_name)||"â"}),t.jsx("div",{className:"text-gray-500 text-xs",children:(Q=i.customer)==null?void 0:Q.address}),t.jsxs("div",{className:"text-gray-500 text-xs",children:[(oe=i.customer)==null?void 0:oe.city,", ",(ne=i.customer)==null?void 0:ne.state," ",(ge=i.customer)==null?void 0:ge.zip]}),t.jsx("div",{className:"text-gray-500 text-xs",children:(be=i.customer)==null?void 0:be.phone})]}),t.jsxs("div",{children:[t.jsx("div",{className:"text-xs font-bold text-gray-400 uppercase tracking-wide mb-1",children:"Installation Address"}),t.jsx("div",{className:"font-semibold text-gray-800",children:((we=i.customer)==null?void 0:we.full_name)||"â"}),t.jsx("div",{className:"text-gray-500 text-xs",children:(F=i.customer)==null?void 0:F.address}),t.jsxs("div",{className:"text-gray-500 text-xs",children:[(K=i.customer)==null?void 0:K.city,", ",(Z=i.customer)==null?void 0:Z.state," ",(ie=i.customer)==null?void 0:ie.zip]})]}),t.jsxs("div",{className:"text-right",children:[t.jsx("div",{className:"text-xs font-bold text-gray-400 uppercase tracking-wide mb-1",children:"From"}),t.jsx("div",{className:"font-semibold text-gray-800",children:E.company_name}),t.jsx("div",{className:"text-gray-500 text-xs",children:ma(E)}),t.jsx("div",{className:"text-gray-500 text-xs",children:xa(E)})]})]})]}),t.jsxs("div",{className:"bg-white rounded-2xl border border-gray-200 shadow-sm p-6",children:[t.jsx("div",{className:"text-xs font-bold text-gray-400 uppercase tracking-wide mb-2",children:"Estimation Details"}),t.jsx("p",{className:"text-sm text-gray-600 leading-relaxed",children:"This system has been recommended based on your home size, water usage, and water quality needs. It is designed to improve overall water quality, enhance efficiency, and protect your plumbing, appli
333ances, and fixtures."}),i.notes&&t.jsx("p",{className:"text-sm text-gray-600 mt-2",children:i.notes})]}),P==="finance"&&t.jsxs("div",{className:"rounded-xl p-4 border",style:{backgroundColor:"#f0fdf4",borderColor:"#bbf7d0"},children:[t.jsx("div",{className:"text-xs font-bold mb-1",style:{color:"#15803d"},children:"ð Financing Available via Hearth"}),t.jsx("p",{className:"text-xs",style:{color:"#166534"},children:"After signing this quote you'll be redirected to Hearth to complete a 60-second pre-qualification. Does not affect your credit score."})]}),a.length>0&&t.jsxs("div",{className:"bg-white rounded-2xl border border-gray-200 shadow-sm overflow-hidden",children:[t.jsx("div",{className:"px-6 py-3 bg-gray-50 border-b border-gray-100 text-xs font-bold text-gray-400 uppercase tracking-wide",children:"Equipment & Services"}),t.jsxs("table",{className:"w-full",children:[t.jsx("thead",{children:t.jsxs("tr",{className:"text-xs text-gray-400 border-b border-gray-100",children:[t.jsx("th",{className:"px-6 py-3 text-left font-semibold",children:"Description"}),t.jsx("th",{className:"px-4 py-3 text-center font-semibold",children:"Qty"}),t.jsx("th",{className:"px-4 py-3 text-right font-semibold",children:"Price"}),t.jsx("th",{className:"px-6 py-3 text-right font-semibold",children:"Total"})]})}),t.jsx("tbody",{children:a.filter(Y=>Y.item_type!=="service_plan").map(Y=>t.jsxs("tr",{className:"border-b border-gray-50",children:[t.jsxs("td",{className:"px-6 py-4 text-sm text-gray-800",children:[Y.description,Gl(Y)>0&&t.jsxs("div",{style:{fontSize:12,color:"#16a34a",marginTop:2},children:[parseFloat(Y.discount_pct)||0,"% off: â",He(Gl(Y))]})]}),t.jsx("td",{className:"px-4 py-4 text-sm text-gray-600 text-center",children:Y.quantity}),t.jsx("td",{className:"px-4 py-4 text-sm text-gray-600 text-right",children:P==="rental"?`${He(Y.unit_price)}/mo`:He(Y.unit_price)}),t.jsx("td",{className:"px-6 py-4 text-sm font-semibold text-gray-900 text-right",children:P==="rental"?`${He(Y.total_price)}/mo`:He(Y.total_price)})]},Y.id))})]}),t.jsx("div",{className:"px-6 py-4 bg-gray-50",children:P==="rental"?t.jsxs("div",{className:"space-y-2",children:[t.jsxs("div",{className:"flex justify-between text-sm text-gray-600",children:[t.jsx("span",{children:"Installation Fee (one-time)"}),t.jsx("span",{className:"font-medium",children:He(Number(i.install_fee)||0)})]}),t.jsxs("div",{className:"flex justify-between text-base font-bold text-gray-900 pt-2 border-t border-gray-200",children:[t.jsx("span",{children:"Monthly Total"}),t.jsxs("span",{style:{color:"#0a2540"},children:[He(Number(i.monthly_rental_price)),"/mo"]})]})]}):t.jsxs("div",{className:"max-w-xs ml-auto space-y-1.5",children:[t.jsxs("div",{className:"flex justify-between text-sm text-gray-600",children:[t.jsx("span",{children:"Subtotal"}),t.jsx("span",{children:He(Number(i.subtotal)+Zs(a))})]}),Zs(a)>0&&t.jsxs("div",{className:"flex justify-between text-sm",style:{color:"#16a34a"},children:[t.jsx("span",{children:"Discount"}),t.jsxs("span",{children:["â",He(Zs(a))]})]}),t.jsxs("div",{className:"flex justify-between text-sm text-gray-600",children:[t.jsx("span",{children:"Tax"}),t.jsx("span",{children:He(i.tax_amount)})]}),t.jsxs("div",{className:"flex justify-between text-base font-bold text-gray-900 pt-2 border-t border-gray-200",children:[t.jsx("span",{children:"Total"}),t.jsx("span",{children:He(i.total)})]}),P==="purchase"&&t.jsxs("div",{className:"flex justify-between text-sm font-semibold pt-1",style:{color:"#0a2540"},children:[t.jsx("span",{children:"50% Deposit Option"}),t.jsx("span",{children:He(i.total*.5)})]})]})})]}),a.some(Y=>Y.item_type==="service_plan")&&t.jsxs("div",{className:"bg-white rounded-2xl border border-gray-200 shadow-sm overflow-hidden",children:[t.jsx("div",{className:"px-6 py-3 bg-amber-50 border-b border-amber-100 text-xs font-bold text-amber-700 uppercase tracking-wide",children:"Included Service Plans"}),t.jsx("div",{className:"px-6 py-3 text-xs text-gray-500 border-b border-gray-100",children:"The following service plans are included with this quote. Plans activate after your installation is complete."}),t.jsxs("table",{className:"w-full",children:[t.jsx("thead",{children:t.jsxs("tr",{className:"text-xs text-gray-400 border-b border-gray-100",children:[t.jsx("th",{className:"px-6 py-2 text-left font-semibold",children:"Service Plan"}),t.jsx("th",{className:"px-6 py-2 text-right font-semibold",children:"Price"})]})}),t.jsx("tbody",{children:a.filter(Y=>Y.item_type==="service_plan").map(Y=>t.jsxs("tr",{className:"border-b border-gray-50 bg-amber-50/30",children:[t.jsx("td",{className:"px-6 py-3 text-sm text-gray-800 font-medium",children:Y.description}),t.jsx("td",{className:"px-6 py-3 text-sm font-semibold text-amber-700 text-right",children:He(Y.unit_price)})]},Y.id))})]})]}),P==="rental"&&t.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-xl p-4",children:[t.jsx("div",{className:"text-xs font-bold text-blue-700 mb-1",children:"Rental Agreement Notice"}),t.jsxs("p",{className:"text-xs text-blue-600",children:["Accepting this quote initiates a 36-month Residential Equipment Rental Agreement. Equipment remains property of ",E.company_name,". 50% of payments apply toward buyout."]})]}),P==="purchase"&&E.bank_name&&t.jsxs("div",{className:"bg-white rounded-2xl border border-gray-200 shadow-sm overflow-hidden",children:[t.jsx("div",{className:"px-6 py-3 bg-gray-50 border-b border-gray-100",children:t.jsx("div",{className:"text-xs font-bold text-gray-400 uppercase tracking-wide",children:"Direct Transfer / ACH Details"})}),t.jsx("table",{className:"w-full text-sm",children:t.jsx("tbody",{children:[["Bank Name",E.bank_name],["ACH ABA Number",E.bank_routing],["Account Number",E.bank_account],["Account Name",E.bank_account_name],["Email",E.accounts_email],["Phone Number",E.phone]].filter(([,Y])=>Y).map(([Y,X])=>t.jsxs("tr",{className:"border-b border-gray-50",children:[t.jsx("td",{className:"px-6 py-3 font-semibold text-gray-700 w-48",children:Y}),t.jsx("td",{className:"px-6 py-3 text-gray-600",children:X})]},Y))})})]}),t.jsx("div",{className:"text-center",children:t.jsx("a",{href:E.slug?`/t/${E.slug}/terms`:"/terms",target:"_blank",rel:"noopener noreferrer",className:"text-xs text-blue-600 hover:underline",children:"Click here to view Terms & Conditions â"})}),t.jsxs("div",{className:"bg-white rounded-2xl border border-gray-200 shadow-sm p-6",children:[t.jsx("div",{className:"text-xs font-bold text-gray-400 uppercase tracking-wide mb-2",children:"Customer Authorization"}),t.jsx("p",{className:"text-xs text-gray-600 leading-relaxed mb-5",children:P==="finance"?`By
333signing, I authorize ${E.company_name} to proceed as outlined and agree to complete a Hearth financing application for the amount shown.`:`This is a good-faith estimate. By signing, I authorize ${E.company_name} to proceed as outlined and agree to pay for all services rendered.`}),t.jsx(n0,{onSign:te,label:P==="finance"?"Sign & Continue to Hearth â":"Sign & Accept Quote",loading:v}),b&&t.jsx("p",{className:"text-red-500 text-xs mt-3",children:b})]})]}),r==="view_agreement"&&i&&u&&t.jsx(OE,{agreement:u,customer:i.customer,terms:d,brand:E,onSign:U,signing:v,error:b}),r==="view_invoice"&&i&&y&&t.jsx(IE,{invoice:y,customer:i.customer,terms:f,brand:E,onSign:W,signing:v,error:b}),t.jsxs("div",{className:"mt-10 text-center text-xs text-gray-400 pb-8 space-y-1",children:[t.jsxs("p",{children:[E.company_name,Yh(E)?` · ${Yh(E)}`:""]}),t.jsxs("p",{children:[E.phone,E.email?` · ${E.email}`:"",E.website?` · ${E.website}`:""]})]})]})]})}const r0="America/Indiana/Indianapolis";function R4(e){return new Intl.DateTimeFormat("en-US",{timeZone:r0,weekday:"long",month:"long",day:"numeric"}).format(new Date(e))}function WE(e){return new Intl.DateTimeFormat("en-CA",{timeZone:r0,year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date(e))}function E4(e){return new Intl.DateTimeFormat("en-US",{timeZone:r0,hour:"numeric",minute:"2-digit",hour12:!0}).format(new Date(e))}function $E(e){return`${R4(e)} at ${E4(e)}`}function ME(e){const n=new Map;for(const r of e){const s=WE(r);n.has(s)||n.set(s,{key:s,label:R4(r),slots:[]}),n.get(s).slots.push(r)}return Array.from(n.values())}const sn={bg:"#0b1220",card:"#111c2e",border:"#1e3a4f",text:"#e2e8f0",sub:"#94a3b8",accent:"#0ea5e9",accentText:"#ffffff",good:"#22c55e"};function FE(){const{token:e}=di(),[n,r]=g.useState(!0),[s,i]=g.useState(null),[o,a]=g.useState(""),[l,d]=g.useState([]),[c,f]=g.useState(null),[p,u]=g.useState(!1),[h,y]=g.useState(null);g.useEffect(()=>{let x=!1;async function _(){if(!e){i("This booking link is invalid."),r(!1);return}try{const j=await fetch(`/api/booking/slots?token=${encodeURIComponent(e)}`),C=await j.json();if(x)return;if(!j.ok){i(C.error||"Could not load available times."),r(!1);return}a(C.first_name||""),C.already_booked&&C.booked_slot?f(C.booked_slot):d(Array.isArray(C.slots)?C.slots:[])}catch{x||i("Could not load available times. Please try again.")}finally{x||r(!1)}}return _(),()=>{x=!0}},[e]);async function m(x){if(!(!e||p)){y(x),u(!0),i(null);try{const _=await fetch("/api/booking/slots",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:e,slot:x})}),j=await _.json();if(!_.ok){i(j.error||"Could not save your time. Please pick another."),_.status===409&&d(C=>C.filter(S=>S!==x)),y(null),u(!1);return}f(j.booked_slot||x)}catch{i("Could not save your time. Please try again."),y(null),u(!1)}}}const b={minHeight:"100vh",background:sn.bg,color:sn.text,fontFamily:"system-ui, -apple-system, Segoe UI, Roboto, sans-serif",display:"flex",justifyContent:"center",padding:"24px 16px"},A={width:"100%",maxWidth:560};if(n)return t.jsx("div",{style:b,children:t.jsx("div",{style:A,children:t.jsx("p",{style:{color:sn.sub},children:"Loading available timesâ¦"})})});if(c)return t.jsx("div",{style:b,children:t.jsx("div",{style:A,children:t.jsxs("div",{style:{background:sn.card,border:`1px solid ${sn.border}`,borderRadius:16,padding:28,textAlign:"center"},children:[t.jsx("div",{style:{fontSize:40,marginBottom:10},children:"â"}),t.jsxs("h1",{style:{fontSize:22,fontWeight:800,margin:"0 0 8px"},children:["You're all set",o?`, ${o}`:"","!"]}),t.jsx("p",{style:{color:sn.text,fontSize:16,margin:"0 0 4px"},children:"We'll call you"}),t.jsx("p",{style:{color:sn.good,fontSize:18,fontWeight:700,margin:0},children:$E(c)}),t.jsx("p",{style:{color:sn.sub,fontSize:13,marginTop:16},children:"Need to change it? Just reply to our text and we'll help."})]})})});const v=ME(l);return t.jsx("div",{style:b,children:t.jsxs("div",{style:A,children:[t.jsxs("div",{style:{marginBottom:20},children:[t.jsx("h1",{style:{fontSize:24,fontWeight:800,margin:"0 0 6px"},children:o?`Hi ${o}, pick a time`:"Pick a time"}),t.jsx("p",{style:{color:sn.sub,fontSize:15,margin:0},children:"Choose when you'd like us to call you. It only takes a second."})]}),s&&t.jsx("div",{style:{background:"rgba(239,68,68,0.1)",border:"1px solid rgba(239,68,68,0.4)",color:"#fca5a5",borderRadius:10,padding:"10px 14px",marginBottom:16,fontSize:14},children:s}),v.length===0?t.jsx("div",{style:{background:sn.card,border:`1px solid ${sn.border}`,borderRadius:12,padding:20,color:sn.sub},children:"No open times right now. We'll reach out to you directly â no action needed."}):v.map(x=>t.jsxs("div",{style:{marginBottom:22},children:[t.jsx("div",{style:{fontSize:13,fontWeight:700,color:sn.sub,textTransform:"uppercase",letterSpacing:.5,marginBottom:10},children:x.label}),t.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(96px, 1fr))",gap:10},children:x.slots.map(_=>{const j=h===_;return t.jsx("button",{onClick:()=>m(_),disabled:p,style:{padding:"12px 8px",borderRadius:10,border:`1px solid ${j?sn.accent:sn.border}`,background:j?sn.accent:sn.card,color:j?sn.accentText:sn.text,fontSize:15,fontWeight:600,cursor:p?"default":"pointer",opacity:p&&!j?.5:1,transition:"all 0.12s"},children:j&&p?"â¦":E4(_)},_)})})]},x.key))]})})}const Dd="#0a2540",ps="#4a5561",Dn="#6b7a87",Ga="#e3e8ec",Jn="#ffffff",BE="#f5f7f9",UE="#15803d",HE="#fdf0e3",VE="#a3540a",ZE="#e1f5ee",KE="#1d9e75",Jg="#0f6e56",YE=` 334@keyframes offerSweep { 335 0% { transform: translateX(-140%) skewX(-18deg); } 336 100% { transform: translateX(320%) skewX(-18deg); } 337} 338.offerShimmer { 339 position: absolute; top: 0; bottom: 0; left: 0; width: 42%; 340 background: rgba(255,255,255,0.55); 341 animation: offerSweep 4.5s ease-in-out infinite; 342 pointer-events: none; z-index: 0; 343} 344@media (prefers-reduced-motion: reduce) { 345 .offerShimmer { animation: none; opacity: 0; } 346}`,XE='"Plus Jakarta Sans", "Segoe UI", system-ui, -apple-system, Roboto, Helvetica, Arial, sans-serif',ls=e=>e==null?"":"$"+Number(e).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g,",").replace(/\.00$/,"");function GE(e){const n=new Date(e).getTime()-Date.now();return n<=0?null:{days:Math.floor(n/864e5),hours:Math.floor(n%864e5/36e5),mins:Math.floor(n%36e5/6e4),secs:Math.floor(n%6e4/1e3)}}const _v=e=>new Intl.DateTimeFormat("en-US",{weekday:"long",month:"long",day:"numeric"}).format(new Date(e));function JE(){const{token:e}=di(),[n,r]=g.useState("loading"),[s,i]=g.useState({}),[o,a]=g.useState(""),[l,d]=g.useState(null),[c,f]=g.useState(null),[p,u]=g.useState(null),[h,y]=g.useState(null),[m,b]=g.useState(null),[A,v]=g.useState(null),[x,_]=g.useState([]),[j,C]=g.useState(null),[S,T]=g.useState("buy"),[L,E]=g.useState(null),[R,N]=g.useState(""),[O,z]=g.useState(null),P=g.useCallback(async()=>{var re,Q,oe,ne,ge,be;if(!e)return r("gone");try{const we=await fetch(`/api/final-offers/offer?token=${encodeURIComponent(e)}`);
346if(we.status===404)return r("gone");if(!we.ok)return r("error");const F=await we.json();if(i(F.business||{}),F.state==="claimed")return z(F.claimed_option||null),r("claimed");if(F.state==="expired")return u(F.expires_at||null),r("expired");a(F.first_name||""),d(((re=F.offer)==null?void 0:re.headline)||null),f(((Q=F.offer)==null?void 0:Q.message)||null),u(((oe=F.offer)==null?void 0:oe.expires_at)||null),y(((ne=F.offer)==null?void 0:ne.bundle_note)||null),b(((ge=F.offer)==null?void 0:ge.bundle_headline)||null),v(((be=F.offer)==null?void 0:be.bundle_sub)||null);const K=F.items||[];_(K),!K.some(Z=>Z.purchase_total!=null)&&K.some(Z=>Z.rental_monthly!=null)&&T("rent"),r("live")}catch{r("error")}},[e]);g.useEffect(()=>{P()},[P]),g.useEffect(()=>{if(n!=="live"||!p)return;const re=()=>{const oe=GE(p);C(oe),oe||P()};re();const Q=setInterval(re,1e3);return()=>clearInterval(Q)},[n,p,P]);const D=s.primary_color||"#0d7ea3",M=s.company_name||s.name||"";async function k(re){if(e){E(re),N("");try{const Q=await fetch("/api/final-offers/offer",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:e,option:re==="buy"?"purchase":"rental"})});if(Q.status===410)return N(""),P();if(!Q.ok){const oe=await Q.json().catch(()=>({}));N(oe.error||"That did not go through. Try again, or give us a call.");return}z(re==="buy"?"purchase":"rental"),r("claimed")}catch{N("That did not go through. Check your connection, or give us a call.")}finally{E(null)}}}const q=(re,Q=!0)=>t.jsxs("div",{style:{minHeight:"100vh",background:BE,color:Dd,fontFamily:XE},children:[t.jsx("div",{style:{background:Dd,color:Jn,padding:"10px 20px"},children:t.jsxs("div",{style:{maxWidth:1040,margin:"0 auto",display:"flex",justifyContent:"space-between",alignItems:"center",gap:12,fontSize:13,fontWeight:500,flexWrap:"wrap"},children:[t.jsx("span",{children:"Serving Indianapolis & surrounding areas"}),s.phone&&t.jsx("a",{href:`tel:${s.phone}`,style:{color:Jn,textDecoration:"none",fontWeight:700},children:s.phone})]})}),t.jsx("div",{style:{background:Jn,borderBottom:`1px solid ${Ga}`,padding:"16px 20px"},children:t.jsx("div",{style:{maxWidth:1040,margin:"0 auto",display:"flex",alignItems:"center",gap:12},children:s.logo_url?t.jsx("img",{src:s.logo_url,alt:M,style:{height:34,maxWidth:"70%"}}):M?t.jsx("span",{style:{fontSize:18,fontWeight:800,letterSpacing:"-0.02em"},children:M}):null})}),t.jsx("div",{style:{maxWidth:Q?1040:640,margin:"0 auto",padding:"32px 20px 56px"},children:re}),t.jsx("div",{style:{borderTop:`1px solid ${Ga}`,padding:"26px 20px 40px"},children:t.jsxs("div",{style:{maxWidth:1040,margin:"0 auto",display:"flex",flexWrap:"wrap",gap:20,justifyContent:"space-between",fontSize:14,lineHeight:1.7,color:Dn},children:[t.jsxs("div",{children:[M&&t.jsx("div",{style:{fontWeight:700,color:Dd},children:M}),t.jsx("div",{children:"6951 E 30th St, Suite B · Indianapolis, IN 46219"}),t.jsx("div",{children:"Serving Indianapolis, Avon, Brownsburg, Greenwood, Plainfield, Lawrence and nearby"})]}),t.jsxs("div",{style:{color:ps},children:[s.phone&&t.jsxs("div",{children:["Questions? ",t.jsx("a",{href:`tel:${s.phone}`,style:{color:D,fontWeight:700},children:s.phone})]}),s.email&&t.jsx("div",{children:t.jsx("a",{href:`mailto:${s.email}`,style:{color:D,fontWeight:700},children:s.email})}),t.jsx("div",{style:{color:Dn},children:"Free in-home water test · No pressure to buy"})]})]})})]});if(n==="loading")return q(t.jsx("p",{style:{fontSize:15,color:Dn,padding:"40px 0"},children:"Loading your offerâ¦"}),!1);if(n==="gone")return q(t.jsx(Qg,{title:"This link isn't valid",children:"It may have been cancelled, or the address may be mistyped. Give us a call and we'll sort it out."}),!1);if(n==="error")return q(t.jsx(Qg,{title:"We couldn't load your offer",children:"Something went wrong at our end. Refresh the page, or call us and we'll read it to you."}),!1);if(n==="expired")return q(t.jsxs(Qg,{title:"This offer has ended",accent:D,children:[p?`It ran until ${_v(p)}. `:"","The pricing on it is no longer available, but we'd still like to help with your water. Call us and we'll talk through what makes sense now."]}),!1);if(n==="claimed")return q(t.jsxs("div",{style:{background:Jn,border:`1px solid ${Ga}`,borderRadius:16,padding:"34px 28px"},children:[t.jsx("h1",{style:{margin:"0 0 12px",fontSize:26,fontWeight:800,letterSpacing:"-0.025em"},children:"We've got it"}),t.jsx("p",{style:{margin:0,fontSize:16,lineHeight:1.65,color:ps,maxWidth:"58ch"},children:O==="rental"?`Someone from ${M||"our team"} will call you shortly to set up the rental, book a free water test and arrange the install. Your monthly price is held.`:`Someone from ${M||"our team"} will call you shortly to go over it, book a free water test and confirm the right size for your home. Your price is held.`})]}),!1);const $=x.some(re=>re.purchase_total!=null),I=x.some(re=>re.rental_monthly!=null),B=S==="buy",J=x.reduce((re,Q)=>re+(Q.purchase_total||0),0),te=x.reduce((re,Q)=>re+(Q.list_total||0),0)-J,U=x.reduce((re,Q)=>re+(Q.line_total??Q.purchase_total??0),0),W=U-J,G=x.reduce((re,Q)=>re+(Q.rental_monthly||0),0),V=x.reduce((re,Q)=>re+(Q.install_fee||0)*(Q.quantity||1),0),ee=re=>({padding:"11px 26px",fontSize:15,fontWeight:700,borderRadius:9,border:"none",cursor:"pointer",fontFamily:"inherit",background:re?Jn:"transparent",color:re?Dd:"#5c6d7a",boxShadow:re?"0 1px 3px rgba(10,37,64,0.14)":"none"});return q(t.jsxs(t.Fragment,{children:[t.jsx("style",{children:YE}),t.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:32,alignItems:"flex-start",marginBottom:32},children:[t.jsxs("div",{style:{flex:"1 1 460px",minWidth:0},children:[t.jsx("div",{style:{fontSize:12,fontWeight:800,letterSpacing:"0.14em",color:D,marginBottom:12},children:"SPECIAL PRICING FOR YOUR HOME"}),t.jsx("h1",{style:{margin:"0 0 14px",fontSize:"clamp(28px, 4vw, 44px)",lineHeight:1.12,fontWeight:800,letterSpacing:"-0.03em"},children:l||(o?`${o}, here is our best price on better water at home`:"Here is our best price on better water at home")}),t.jsx("p",{style:{margin:0,fontSize:17,lineHeight:1.65,color:ps,maxWidth:"62ch"},children:c||"Hard water, chlorine taste and spotted glassware are normal in Indianapolis â and all three are fixable. These are our starting systems at a price we can hold for a few days. If your free water test calls for something larger, we will show you the difference before anything is signed."})]}),p&&j&&t.jsxs("div",{style:{flex:"0 1 320px",background:Jn,border:`2px solid ${D}`,borderRadius:16,padding:"22px 24px"},children:[t.jsx("div",{style:{fontSize:12,fontWeight:800,letterSpacing:"0.12em",color:Dn,marginBottom:8},children:"THIS PRICING ENDS"}),t.jsxs("div",{style:{display:"flex",gap:8},children:[t.jsx(ap,{value:j.days,label:j.days===1?"day":"days",accent:D}),t.jsx(ap,{value:j.hours,label:"hrs",accent:D,pad:!0}),t.jsx(ap,{value:j.mins,label:"min",accent:D,pad:!0}),t.jsx(ap,{value:j.secs,label:"sec",accent:D,pad:!0})]}),t.jsx("div",{style:{fontSize:15,color:ps,marginTop:12},children:_v(p)})]})]}),$&&I&&t.jsxs("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:14,marginBottom:18},children:[t.jsxs("div",{style:{display:"flex",background:"#e3e8ec",borderRadius:12,padding:4,gap:4},children:[t.jsx("button",{type:"button",onClick:()=>T("buy"),style:ee(B),children:"Buy it"}),t.jsx("button",{type:"button",onClick:()=>T("rent"),style:ee(!B),children:"Rent it"})]}),t.jsx("span",{style:{fontSize:14,color:Dn},children:B?"Installation by our own team is included in every purchase price.":"Installation is charged once, at the start of the rental."})]}),h&&B&&x.length>1&&t.jsxs("div",{style:{position:"relative",overflow:"hidden",background:ZE,border:`1.5px solid ${KE}`,borderRadius:12,padding:"18px 22px",marginBottom:14,display:"flex",gap:16,alignItems:"center"},children:[t.jsx("span",{"aria-hidden":"true",className:"offerShimmer"}),t.jsxs("svg",{width:"30",height:"30",viewBox:"0 0 24 24",fill:"none",stroke:Jg,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,position:"relative",zIndex:1},"aria-hidden":"true",children:[t.jsx("rect",{x:"3",y:"8",width:"18",height:"13",rx:"2"}),t.jsx("path",{d:"M12 8v13M3 12h18M7.5 8a2.5 2.5 0 0 1 0-5C10 3 12 8 12 8s2-5 4.5-5a2.5 2.5 0 0 1 0 5"})]}),t.jsxs("div",{style:{position:"relative",zIndex:1},children:[t.jsx("div",{style:{fontSize:27,fontWeight:800,color:Jg,letterSpacing:"-0.02em",lineHeight:1.1},children:m||h}),A&&t.jsx("div",{style:{fontSize:14,color:Jg,marginTop:3},children:A})]})]}),t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:14},children:x.map((re,Q)=>{const oe=re.purchase_total!=null,ne=re.rental_monthly!=null,ge=B?oe:ne;return t.jsxs("article",{style:{background:Jn,border:`1px solid ${Ga}`,borderRadius:16,padding:22,display:"flex",flexWrap:"wrap",gap:24,opacity:ge?1:.55},children:[re.image_url&&t.jsx("div",{style:{flex:"0 0 240px",maxWidth:"100%",aspectRatio:"1 / 1",background:Jn,borderRadius:12,overflow:"hidden",display:"flex",alignItems:"center",justifyContent:"center"},children:t.jsx("img",{src:re.image_url,alt:re.name,style:{width:"100%",height:"100%",objectFit:"contain",display:"block"}})}),t.jsxs("div",{style:{flex:"1 1 320px",minWidth:0},children:[re.eyebrow&&t.jsx("div",{style:{fontSize:11,fontWeight:800,letterSpacing:"0.12em",color:D,marginBottom:8},children:re.eyebrow}),t.jsxs("h2",{style:{margin:"0 0 6px",fontSize:21,fontWeight:700,lineHeight:1.3,letterSpacing:"-0.015em"},children:[re.quantity>1?`${re.quantity} à `:"",re.name]}),(re.tagline||re.description)&&t.jsx("p",{style:{margin:"0 0 14px",fontSize:15,lineHeight:1.55,color:ps},children:re.tagline||re.description}),re.highlights.length>0&&t.jsx("ul",{style:{margin:0,padding:0,listStyle:"none",display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(240px, 1fr))",gap:"7px 20px"},children:re.highlights.map((be,we)=>t.jsxs("li",{style:{display:"flex",gap:9,alignItems:"flex-start"},children:[t.jsx("svg",{width:"17",height:"17",viewBox:"0 0 24 24",fill:"none",stroke:UE,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,marginTop:2},"aria-hidden":"true",children:t.jsx("polyline",{points:"20 6 9 17 4 12"})}),t.jsx("span",{style:{fontSize:14,lineHeight:1.45,color:"#3d4a55"},children:be})]},we))}),re.warranty_text&&t.jsx("p",{style:{margin:"12px 0 0",fontSize:14,color:Dn},children:re.warranty_text})]}),t.jsx("div",{style:{flex:"0 0 200px",display:"flex",flexDirection:"column",justifyContent:"center"},children:B?oe?t.jsxs(t.Fragment,{children:[re.discount_label&&t.jsx("span",{style:{alignSelf:"flex-start",background:HE,color:VE,fontSize:12,fontWeight:800,letterSpacing:"0.04em",padding:"5px 10px",borderRadius:6,marginBottom:10},children:re.discount_label}),re.list_total!=null&&re.list_total>(re.line_total??re.purchase_total??0)&&t.jsx("div",{style:{fontSize:15,color:Dn,textDecoration:"line-through"},children:ls(re.list_total)}),t.jsx("div",{style:{fontSize:32,fontWeight:800,letterSpacing:"-0.03em",lineHeight:1.1},children:ls(re.line_total??re.purchase_total)}),t.jsx("div",{style:{fontSize:14,color:ps,marginTop:6},children:"Installation included"})]}):t.jsx("div",{style:{fontSize:14,color:Dn,lineHeight:1.5},children:"Available to rent only"}):ne?t.jsxs(t.Fragment,{children:[t.jsxs("div",{style:{fontSize:32,fontWeight:800,letterSpacing:"-0.03em",lineHeight:1.1},children:[ls(re.rental_monthly),t.jsx("span",{style:{fontSize:16,fontWeight:500,color:Dn},children:"/month"})]}),re.install_fee!=null&&t.jsxs("div",{style:{fontSize:14,color:ps,marginTop:6},children:["plus ",ls(re.install_fee)," installation, once"]})]}):t.jsx("div",{style:{fontSize:14,color:Dn,lineHeight:1.5},children:"Available to buy only"})})]},Q)})}),x.length>1&&t.jsxs("div",{style:{background:Dd,borderRadius:16,padding:"26px 30px",marginTop:18,display:"flex",flexWrap:"wrap",gap:20,justifyContent:"space-between",alignItems:"flex-end"},children:[B&&W>.005&&t.jsxs("div",{style:{flex:"1 1 100%",display:"flex",flexDirection:"column",gap:9,paddingBottom:18,borderBottom:"1px solid #2c4256"},children:[t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:16,fontSize:15,color:"#b9c9d6"},children:[t.jsxs("span",{children:["Subtotal â ",x.length," systems"]}),t.jsx("span",{children:ls(U)})]}),t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:16,fontSize:15,fontWeight:700,color:"#6fd3a8"}
346,children:[t.jsx("span",{children:"Bundle discount â 2 or more systems"}),t.jsxs("span",{children:["â",ls(W)]})]})]}),t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:13,fontWeight:700,letterSpacing:"0.1em",color:"#8fa8bd",marginBottom:10},children:B?"TO BUY, ALL TOGETHER":"TO RENT, ALL TOGETHER"}),t.jsx("div",{style:{fontSize:42,fontWeight:800,color:Jn,letterSpacing:"-0.035em",lineHeight:1},children:B?ls(J):`${ls(G)}/month`}),t.jsx("div",{style:{fontSize:15,color:"#b9c9d6",marginTop:10},children:B?"Installation included. Nothing due today.":V>0?`${ls(V)} one-time installation, then the monthly price.`:"Nothing due today."})]}),B&&te>.005&&t.jsxs("div",{style:{textAlign:"right"},children:[t.jsx("div",{style:{fontSize:13,fontWeight:700,letterSpacing:"0.1em",color:"#8fa8bd",marginBottom:10},children:"YOU SAVE"}),t.jsx("div",{style:{fontSize:30,fontWeight:800,color:"#6fd3a8",letterSpacing:"-0.03em",lineHeight:1},children:ls(te)})]})]}),B&&W>.005&&t.jsxs("div",{style:{display:"flex",gap:8,alignItems:"flex-start",padding:"12px 4px 0"},children:[t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:ps,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,marginTop:2},"aria-hidden":"true",children:[t.jsx("circle",{cx:"12",cy:"12",r:"10"}),t.jsx("path",{d:"M12 16v-4M12 8h.01"})]}),t.jsx("span",{style:{fontSize:13,color:ps,lineHeight:1.5},children:"The bundle discount applies when you take 2 or more systems. On a single system you pay the price shown on its line â that discount is already in it."})]}),t.jsxs("div",{style:{display:"flex",gap:8,alignItems:"flex-start",padding:"12px 4px 0"},children:[t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:Dn,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,marginTop:2},"aria-hidden":"true",children:[t.jsx("circle",{cx:"12",cy:"12",r:"10"}),t.jsx("path",{d:"M12 16v-4M12 8h.01"})]}),t.jsx("span",{style:{fontSize:13,color:Dn,lineHeight:1.5},children:"Applies to pre-plumb and replacement connections; establishing new connections requires additional quoting."})]}),t.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:12,marginTop:24},children:[$&&t.jsx("button",{type:"button",onClick:()=>k("buy"),disabled:L!==null,style:{flex:"1 1 240px",padding:"19px 0",fontSize:17,fontWeight:800,color:Jn,background:D,border:"none",borderRadius:12,cursor:L?"wait":"pointer",fontFamily:"inherit"},children:L==="buy"?"One momentâ¦":I?"I'll buy it":"I'll take it"}),I&&t.jsx("button",{type:"button",onClick:()=>k("rent"),disabled:L!==null,style:{flex:"1 1 240px",padding:"19px 0",fontSize:17,fontWeight:800,color:$?D:Jn,background:$?Jn:D,border:$?`2px solid ${D}`:"none",borderRadius:12,cursor:L?"wait":"pointer",fontFamily:"inherit"},children:L==="rent"?"One momentâ¦":$?"I'll rent it":"I'll take it"})]}),t.jsxs("p",{style:{margin:"14px 0 0",textAlign:"center",fontSize:14,lineHeight:1.6,color:Dn},children:["Nothing is charged and nothing is signed here. We'll call you to go through it, book a free water test and confirm the right size for your home.",$&&I?" Either way, you can still change your mind when we talk.":""]}),R&&t.jsx("p",{style:{margin:"12px 0 0",textAlign:"center",fontSize:15,color:"#b42318"},children:R}),t.jsxs("div",{style:{background:Jn,border:`1px solid ${Ga}`,borderRadius:16,padding:"20px 26px",marginTop:30,display:"flex",flexWrap:"wrap",gap:16,alignItems:"center",justifyContent:"space-between"},children:[t.jsx("div",{style:{fontSize:15,fontWeight:700},children:"5-Star on Google · BBB Accredited"}),t.jsxs("div",{style:{fontSize:14,color:Dn},children:["Certified performance · Locally installed by ",M||"our own team"]})]})]}))}function ap({value:e,label:n,accent:r,pad:s}){return t.jsxs("div",{style:{textAlign:"center",minWidth:52},children:[t.jsx("div",{style:{fontSize:30,fontWeight:800,color:r,letterSpacing:"-0.03em",lineHeight:1.1,fontVariantNumeric:"tabular-nums"},children:s?String(e).padStart(2,"0"):e}),t.jsx("div",{style:{fontSize:11,fontWeight:700,letterSpacing:"0.08em",color:Dn,marginTop:3},children:n.toUpperCase()})]})}function Qg({title:e,children:n,accent:r}){return t.jsxs("div",{style:{background:Jn,border:`1px solid ${Ga}`,borderRadius:16,padding:"34px 28px",borderTop:r?`3px solid ${r}`:void 0},children:[t.jsx("h1",{style:{margin:"0 0 12px",fontSize:26,fontWeight:800,letterSpacing:"-0.025em"},children:e}),t.jsx("p",{style:{margin:0,fontSize:16,lineHeight:1.65,color:ps,maxWidth:"58ch"},children:n})]})}const ro=e=>Math.round((e+Number.EPSILON)*100)/100;function s0(e,n,r){return e==null?null:!n||r==null||r<=0?ro(e):ro(n==="percent"?Math.max(0,e*(1-Math.min(r,100)/100)):Math.max(0,e-r))}function QE(e,n){return!e||n==null||n<=0?"":e==="percent"?`${ro(n)}% OFF`:Ja(ro(n))+" OFF"}const Cs=e=>ro(e/100),Ao=e=>Math.round(e*100);function eP(e,n){if(!e.length)return{ok:!1,error:"An offer needs at least one product.",breaches:[]};e=e.map(h=>({...h,offered_price:s0(h.list_price,h.discount_type,h.discount_value)}));for(const h of e){if(!Number.isInteger(h.quantity)||h.quantity<1)return{ok:!1,error:`"${h.name}
346" has an invalid quantity (${h.quantity}).`,breaches:[]};const y=h.display_mode==="purchase"||h.display_mode==="both",m=h.display_mode==="rental"||h.display_mode==="both";if(y&&(h.offered_price==null||h.offered_price<0))return{ok:!1,error:`"${h.name}" is shown as a purchase but has no purchase price.`,breaches:[]};if(m&&(h.offered_rental_monthly==null||h.offered_rental_monthly<0))return{ok:!1,error:`"${h.name}" is shown as a rental but has no monthly price.`,breaches:[]}}const r=new Set(e.filter(h=>h.display_mode==="purchase"||h.display_mode==="both").map(h=>h.key)),s=new Map;for(const h of e)r.has(h.key)&&s.set(h.key,Ao(h.offered_price)*h.quantity);const i=[...s.values()].reduce((h,y)=>h+y,0),o=e.reduce((h,y)=>r.has(y.key)?h+Ao(y.list_price??y.offered_price??0)*y.quantity:h,0);if(n!=null&&!r.size)return{ok:!1,error:"A bundle price needs at least one product shown as a purchase.",breaches:[]};if(n!=null&&n<0)return{ok:!1,error:"Bundle price cannot be negative.",breaches:[]};if(n!=null&&Ao(n)>i)return{ok:!1,error:`The bundle price (${Ja(n)}) is higher than the prices on the lines (${Ja(Cs(i))}). A bundle is a discount, not a markup.`,breaches:[]};const a=new Map;if(n==null||i===0)for(const[h,y]of s)a.set(h,y);else{const h=Ao(n),y=h/i;let m=0;for(const[A,v]of s){const x=Math.round(v*y);a.set(A,x),m+=x}const b=h-m;if(b!==0){let A="",v=-1;for(const[x,_]of s)_>v&&(v=_,A=x);a.set(A,a.get(A)+b)}}const l=[];for(const h of e){if(!r.has(h.key)||h.min_sell_price==null)continue;const y=a.get(h.key),m=Ao(h.min_sell_price)*h.quantity;y<m&&l.push({key:h.key,name:h.name,quantity:h.quantity,allocated_total:Cs(y),floor_total:Cs(m),shortfall:Cs(m-y)})}if(l.length){const h=l.reduce((m,b)=>b.shortfall>m.shortfall?b:m),y=l.length>1?` (and ${l.length-1} other line${l.length>2?"s":""})`:"";return{ok:!1,breaches:l,error:`This price falls below the minimum on "${h.name}"${y}. That line comes out at ${Ja(h.allocated_total)} against a minimum of ${Ja(h.floor_total)} â ${Ja(h.shortfall)} short. Raise the bundle price or take the product off the offer.`}}const d=e.map(h=>{const y=QE(h.discount_type,h.discount_value);if(!r.has(h.key))return{...h,discount_label:y,allocated_total:null,allocated_price:null};const m=Cs(a.get(h.key));return{...h,discount_label:y,allocated_total:m,allocated_price:ro(m/h.quantity)}}),c=Cs([...a.values()].reduce((h,y)=>h+y,0)),f=Cs(o),p=Cs(e.reduce((h,y)=>y.display_mode==="rental"||y.display_mode==="both"?h+Ao(y.install_fee??0)*y.quantity:h,0)),u=Cs(e.reduce((h,y)=>y.display_mode==="rental"||y.display_mode==="both"?h+Ao(y.offered_rental_monthly??0)*y.quantity:h,0));return{ok:!0,items:d,purchase_total:c,install_total:p,rental_monthly_total:u,list_total:f,savings:ro(f-c)}}function Ja(e){return"$"+e.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g,",")}class Pr extends Error{constructor(n){super(n),this.name="OfferValidationError"}}const jv=30,oh=2;function i0(e,n,r){if(!n||r==null||r<=0)return null;const s=e.filter(a=>a.display_mode==="purchase"||a.display_mode==="both");if(s.length<oh)return null;const i=s.reduce((a,l)=>{const d=s0(l.list_price,l.discount_type,l.discount_value);return a+(d??0)*(l.quantity||1)},0);if(i<=0)return null;const o=n==="percent"?i*(1-Math.min(r,100)/100):i-r;return Math.round(Math.max(0,o)*100)/100}async function tP(){const{data:e,error:n}=await w.from("product_catalog").select("id, name, sku, category, description, retail_price, rental_price_monthly, install_fee, min_sell_price, family_id, warranty_months, parts_warranty, parts_warranty_unit, labour_warranty, labour_warranty_unit").eq("is_active",!0).order("name");if(n)throw new Error(`Failed to load products: ${n.message}`);return e||[]}async function P4(e){const{data:n,error:r}=await w.from("final_offers").select("*").eq("lead_id",e).in("status",["draft","active"]).limit(2);if(r)throw new Error(`Failed to load offer: ${r.message}`);if(!(n!=null&&n.length))return null;if(n.length>1)throw new Error(`Lead ${e} has ${n.length} open offers. The unique index should prevent this â do not proceed, this needs looking at.`);return o0(n[0])}async function nP(e=200){const{data:n,error:r}=await w.from("final_offers").select("*, leads(first_name, last_name)").order("created_at",{ascending:!1}).limit(e);
346if(r)throw new Error(`Failed to load offers: ${r.message}`);const s=n||[];if(!s.length)return[];const{data:i,error:o}=await w.from("final_offer_items").select("offer_id, name, quantity, display_mode, allocated_total, offered_price, offered_rental_monthly").in("offer_id",s.map(d=>d.id)).order("sort_order");o&&console.error("[finalOffers] list items failed:",o.message);const a=i||[],l=new Map;for(const d of a){const c=l.get(d.offer_id)||[];c.push(d),l.set(d.offer_id,c)}return s.map(d=>{const c=l.get(d.id)||[],f=c.reduce((y,m)=>m.display_mode!=="purchase"&&m.display_mode!=="both"?y:y+(m.allocated_total??(m.offered_price??0)*(m.quantity||1)),0),p=c.reduce((y,m)=>m.display_mode!=="rental"&&m.display_mode!=="both"?y:y+(m.offered_rental_monthly??0)*(m.quantity||1),0),{leads:u,...h}=d;return{...h,lead_name:`${(u==null?void 0:u.first_name)||""} ${(u==null?void 0:u.last_name)||""}`.trim()||"Unknown lead",item_count:c.length,item_names:c.map(y=>y.name),buy_total:f>0?Math.round(f*100)/100:null,rental_monthly_total:p>0?Math.round(p*100)/100:null}})}async function by(e){const{data:n,error:r}=await w.from("final_offers").select("*").eq("id",e).maybeSingle();if(r)throw new Error(`Failed to load offer: ${r.message}`);return n?o0(n):null}async function o0(e){const{data:n,error:r}=await w.from("final_offer_items").select("*").eq("offer_id",e.id).order("sort_order");if(r)throw new Error(`Failed to load offer items: ${r.message}`);return{...e,items:n||[]}}function rP(e,n="purchase",r){var s;return{key:`${e.id}-${Math.random().toString(36).slice(2,8)}`,product_catalog_id:e.id,name:e.name,description:(r==null?void 0:r.tagline)||e.description,eyebrow:(r==null?void 0:r.eyebrow)||null,tagline:(r==null?void 0:r.tagline)||null,image_url:(r==null?void 0:r.image_url)||null,specs:(s=r==null?void 0:r.highlights)!=null&&s.length?{highlights:r.highlights}:null,warranty_text:sP(e),quantity:1,display_mode:n,list_price:e.retail_price,list_rental_monthly:e.rental_price_monthly,install_fee:e.install_fee,min_sell_price:e.min_sell_price,discount_type:null,discount_value:null,offered_price:e.retail_price,offered_rental_monthly:e.rental_price_monthly}}function sP(e){const n=[],r=Number(e.parts_warranty)||0,s=Number(e.labour_warranty)||0;return r>0&&n.push(`${r} ${e.parts_warranty_unit||"months"} parts`),s>0&&n.push(`${s} ${e.labour_warranty_unit||"months"} labour`),!n.length&&e.warranty_months&&n.push(`${e.warranty_months} months`),n.length?n.join(" · ")+" warranty":null}function a0(e){const n=oP(e.expires_on),r=i0(e.items,e.bundle_discount_type,e.bundle_discount_value),s=eP(iP(e.items),r);return{expiry:n,alloc:s,bundlePrice:r}}function iP(e){return e.map(n=>({key:n.key,name:n.name,quantity:n.quantity,display_mode:n.display_mode,list_price:n.list_price,discount_type:n.discount_type,discount_value:n.discount_value,offered_price:n.offered_price,offered_rental_monthly:n.offered_rental_monthly,min_sell_price:n.min_sell_price,install_fee:n.install_fee}))}function oP(e){if(!/^\d{4}-\d{2}-\d{2}$/.test(e))return{ok:!1,error:"Pick an expiry date."};const n=new Date(`${e}T23:59:59`);if(Number.isNaN(n.getTime()))return{ok:!1,error:"That expiry date is not valid."};const r=Date.now();return n.getTime()<=r?{ok:!1,error:"The expiry date has already passed."}:(n.getTime()-r)/864e5>jv?{ok:!1,error:`An offer can run at most ${jv} days. A deadline further out than that stops reading as a deadline.`}:{ok:!0,iso:n.toISOString()}}async function aP(e){var l;const{expiry:n,alloc:r}=a0(e);if(!n.ok)throw new Pr(n.error);if(!r.ok)throw new Pr(r.error);if(await P4(e.lead_id))throw new Pr("This lead already has an open offer. Cancel it before sending another.");const{data:i}=await w.auth.getUser(),{data:o,error:a}=await w.from("final_offers").insert({lead_id:e.lead_id,status:"draft",headline:e.headline,message:e.message,bundle_discount_type:e.bundle_discount_type,bundle_discount_value:e.bundle_discount_value,bundle_price:i0(e.items,e.bundle_discount_type,e.bundle_discount_value),expires_at:n.iso,created_by:((l=i==null?void 0:i.user)==null?void 0:l.id)||null}).select().single();if(a||!o)throw(a==null?void 0:a.code)==="23505"?new Pr("An offer for this lead was just created somewhere else. Reload the lead."):new Error(`Failed to create offer: ${a==null?void 0:a.message}`);return await q4(o.id,e.items,r.items),o0(o)}async function lP(e,n){const r=await by(e);if(!r)throw new Pr("That offer no longer exists.");if(r.status!=="draft")throw new Pr(`This offer has already been ${r.status==="active"?"sent":r.status}. Cancel it and build a new one rather than changing what a customer may have seen.`);const{expiry:s,alloc:i}=a0(n);if(!s.ok)throw new Pr(s.error);if(!i.ok)throw new Pr(i.error);const{error:o}=await w.from("final_offers").update({headline:n.headline,message:n.message,bundle_discount_type:n.bundle_discount_type,bundle_discount_value:n.bundle_discount_value,bundle_price:i0(n.items,n.bundle_discount_type,n.bundle_discount_value),expires_at:s.iso,updated_at:new Date().toISOString()}).eq("id",e).eq("status","draft");if(o)throw new Error(`Failed to update offer: ${o.message}`);const{error:a}=await w.from("final_offer_items").delete().eq("offer_id",e);if(a)throw new Error(`Failed to replace offer items: ${a.message}`);await q4(e,n.items,i.items);const l=await by(e);if(!l)throw new Error("Offer vanished mid-update.");return l}async function q4(e,n,r){const s=new Map(r.map(a=>[a.key,a])),i=n.map((a,l)=>
346{const d=s.get(a.key);return{offer_id:e,product_catalog_id:a.product_catalog_id,sort_order:l,quantity:a.quantity,name:a.name,description:a.description,eyebrow:a.eyebrow,tagline:a.tagline,image_url:a.image_url,specs:a.specs,warranty_text:a.warranty_text,list_price:a.list_price,list_rental_monthly:a.list_rental_monthly,install_fee:a.install_fee,min_sell_price:a.min_sell_price,discount_type:a.discount_type,discount_value:a.discount_value,offered_price:s0(a.list_price,a.discount_type,a.discount_value),allocated_price:(d==null?void 0:d.allocated_price)??null,allocated_total:(d==null?void 0:d.allocated_total)??null,offered_rental_monthly:a.offered_rental_monthly,display_mode:a.display_mode}}),{error:o}=await w.from("final_offer_items").insert(i);if(o)throw o.code==="23514"?new Error("A line came out below its minimum price and was rejected by the database. The allocator should have caught this first â do not retry, this needs looking at."):new Error(`Failed to save offer items: ${o.message}`)}async function dP(e){const{data:n,error:r}=await w.from("final_offers").update({status:"active",sent_at:new Date().toISOString(),updated_at:new Date().toISOString()}).eq("id",e).eq("status","draft").select().maybeSingle();if(r)throw new Error(`Failed to mark offer sent: ${r.message}`);if(!n)throw new Pr("That offer is no longer a draft â it may already have been sent or cancelled.");return n}async function cP(e){const{data:n,error:r}=await w.from("final_offers").update({status:"cancelled",updated_at:new Date().toISOString()}).eq("id",e).in("status",["draft","active"]).select().maybeSingle();if(r)throw new Error(`Failed to cancel offer: ${r.message}`);if(!n)throw new Pr("That offer is not open, so there is nothing to cancel.");return n}function Ay(e){return`${window.location.origin}/o/${e}`}const fs=e=>e==null?"â":"$"+Number(e).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g,",").replace(/\.00$/,""),em=e=>e?new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric"}).format(new Date(e)):"â";function uP(e){const n=new Date(e.expires_at).getTime()<=Date.now();return e.status==="claimed"?{label:"Claimed",fg:"#4ade80",bg:"rgba(74,222,128,0.12)"}:e.status==="cancelled"?{label:"Cancelled",fg:"#64748b",bg:"rgba(100,116,139,0.12)"}:e.status==="expired"||n?{label:"Expired",fg:"#fbbf24",bg:"rgba(251,191,36,0.12)"}:e.status==="draft"?{label:"Draft",fg:"#94a3b8",bg:"rgba(148,163,184,0.12)"}:{label:"Live",fg:"#38bdf8",bg:"rgba(56,189,248,0.12)"}}function pP(e){const n=new Date(e).getTime()-Date.now();if(n<=0)return"ended";const r=Math.floor(n/864e5);if(r>=1)return`${r}d left`;const s=Math.floor(n/36e5);return s>=1?`${s}h left`:"under an hour"}function hP(){const e=gt(),[n,r]=g.useState([]),[s,i]=g.useState(!0),[o,a]=g.useState(""),[l,d]=g.useState("all"),[c,f]=g.useState(""),[p,u]=g.useState(null),[h,y]=g.useState(!1),[m,b]=g.useState(""),A=g.useCallback(async()=>{i(!0);try{r(await nP()),a("")}catch(C){a(C.message)}finally{i(!1)}},[]);g.useEffect(()=>{A()},[A]);async function v(C){y(!0),b(""),u(null);try{const S=await by(C);S?u(S):b("That offer no longer exists.")}catch(S){b(S.message)}finally{y(!1)}}const x=g.useMemo(()=>{const C=Date.now(),S=n.filter(R=>R.status==="active"&&new Date(R.expires_at).getTime()>C).length,T=n.filter(R=>R.status==="claimed").length,L=n.filter(R=>R.status==="expired"||R.status==="active"&&new Date(R.expires_at).getTime()<=C).length,E=T+L;return{sent:n.filter(R=>R.sent_at).length,live:S,claimed:T,expired:L,rate:E?Math.round(T/E*100):null}},[n]),_=g.useMemo(()=>{const C=Date.now(),S=c.trim().toLowerCase();return n.filter(T=>{const L=new Date(T.expires_at).getTime()<=C;return!(l==="active"&&!(T.status==="active"&&!L)||l==="claimed"&&T.status!=="claimed"||l==="expired"&&!(T.status==="expired"||T.status==="active"&&L)||S&&!T.lead_name.toLowerCase().includes(S)&&!T.item_names.some(E=>E.toLowerCase().includes(S)))})},[n,l,c]),j=[{key:"all",label:"All",n:n.length},{key:"active",label:"Live",n:x.live},{key:"claimed",label:"Claimed",n:x.claimed},{key:"expired",label:"Expired",n:x.expired}];return t.jsxs("div",{style:{background:"#0f1923",minHeight:"100vh",color:"#e2e8f0"},children:[t.jsxs("div",{style:{background:"#162232",borderBottom:"1px solid #1e3a4f",padding:"16px 20px",display:"flex",alignItems:"center",gap:12,flexWrap:"wrap"},children:[t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsx("div",{style:{fontWeight:800,fontSize:20,lineHeight:1.2},children:"Final Offers"}),t.jsx("div",{style:{color:"#64748b",fontSize:12,marginTop:2},children:"Every offer sent, and what came of it"})]}),t.jsx("input",{value:c,onChange:C=>f(C.target.value),placeholder:"Search a name or productâ¦",style:{background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:8,color:"#e2e8f0",padding:"9px 12px",fontSize:13,minWidth:240,outline:"none"}})]}),t.jsx("div",{style:{background:"#0c1a26",borderBottom:"1px solid #1e3a4f",padding:"10px 16px",display:"flex",gap:6,overflowX:"auto"},children:j.map(C=>t.jsxs("button",{onClick:()=>d(C.key),style:{padding:"7px 14px",fontSize:13,fontWeight:600,borderRadius:8,whiteSpace:"nowrap",cursor:"pointer",color:l===C.key?"#0f1c2b":"#94a3b8",background:l===C.key?"#38bdf8":"#162232",border:"1px solid #1e3a4f"},children:[C.label," ",t.jsx("span",{style:{opacity:.75},children:C.n})]},C.key))}),t.jsxs("div",{style:{display:"flex",gap:10,padding:"12px 16px",borderBottom:"1px solid #1e3a4f",overflowX:"auto"},children:[t.jsx(Od,{label:"Sent",value:String(x.sent),color:"#94a3b8"}),t.jsx(Od,{label:"Live now",value:String(x.live),color:"#38bdf8"}),t.jsx(Od,{label:"Claimed",value:String(x.claimed),color:"#4ade80"}),t.jsx(Od,{label:"Expired",value:String(x.expired),color:"#fbbf24"}),t.jsx(Od,{label:"Taken",value:x.rate==null?"â":`${x.rate}%`,color:"#e2e8f0",hint:x.rate==null?"none finished yet":"of those that finished"})]}),t.jsx("div",{style:{padding:16},children:s?t.jsx("p",{style:{fontSize:13,color:"#64748b"},children:"Loadingâ¦"}):o?t.jsx("p",{style:{fontSize:13,color:"#f87171"},children:o}):_.length?t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:_.map(C=>{const S=uP(C),T=S.label==="Live";return t.jsxs("button",{onClick:()=>v(C.id),style:{display:"flex",gap:14,alignItems:"center",width:"100%",textAlign:"left",background:"#162232",border:"1px solid #1e3a4f",borderRadius:10,padding:"12px 14px",cursor:"pointer",color:"#e2e8f0"},children:[t.jsxs("div",{style:{flex:"1 1 220px",minWidth:0},children:[t.jsx("div",{style:{fontSize:14,fontWeight:700},children:C.lead_name}),t.jsx("div",{style:{fontSize:12,color:"#64748b",marginTop:3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:C.item_names.join(" · ")||"No products"})]}),t.jsxs("div",{style:{flex:"0 0 130px",fontSize:13,color:"#94a3b8"},children:[C.buy_total!=null&&t.jsx("div",{children:fs(C.buy_total)}),C.rental_monthly_total!=null&&t.jsxs("div",{style:{fontSize:12,color:"#64748b"},children:[fs(C.rental_monthly_total),"/mo"]})]}),t.jsxs("div",{style:{flex:"0 0 120px",fontSize:12,color:"#64748b"},children:[t.jsxs("div",{children:["Sent ",em(C.sent_at)]}),t.jsx("div",{children:T?pP(C.expires_at):`Ends ${em(C.expires_at)}`})]}),t.jsxs("div",{style:{flex:"0 0 150px"},children:[t.jsx("span",{style:{display:"inline-block",padding:"4px 10px",borderRadius:6,fontSize:11,fontWeight:800,letterSpacing:"0.04em",color:S.fg,background:S.bg},children:S.label}),C.status==="claimed"&&t.jsxs("div",{style:{fontSize:12,color:"#94a3b8",marginTop:5},children:[C.claimed_option==="rental"?"wants to rent":"wants to buy",C.claimed_at?` · ${em(C.claimed_at)}`:""]})]})]},C.id)})}):t.jsx("p",{style:{fontSize:13,color:"#64748b",textAlign:"center",padding:"40px 0"},children:n.length?"Nothing here. Try another tab or clear the search.":"No offers yet. Build one from a lead that has gone quiet."})}),(p||h||m)&&t.jsx(fP,{offer:p,loading:h,error:m,onClose:()=>{u(null),b("")},onOpenLead:C=>e(`/leads?lead=${C}`)})]})}function fP({offer:e,loading:n,error:r,onClose:s,onOpenLead:i}){const o=e==null?void 0:e.claimed_option,a=!o||o==="purchase",l=!o||o==="rental",d=((e==null?void 0:e.items)||[]).reduce((p,u)=>p+(u.allocated_total??0),0),c=((e==null?void 0:e.items)||[]).reduce((p,u)=>p+(u.display_mode==="rental"||u.display_mode==="both"?(u.offered_rental_monthly??0)*(u.quantity||1):0),0),f=((e==null?void 0:e.items)||[]).reduce((p,u)=>p+(u.display_mode==="rental"||u.display_mode==="both"?(u.install_fee??0)*(u.quantity||1):0),0);return t.jsx("div",{onClick:s,style:{position:"fixed",inset:0,background:"rgba(8,15,23,0.72)",display:"flex",justifyContent:"center",alignItems:"flex-start",padding:"40px 16px",overflowY:"auto",zIndex:50},children:t.jsx("div",{onClick:p=>p.stopPropagation(),style:{background:"#162232",border:"1px solid #1e3a4f",borderRadius:14,width:"100%",maxWidth:640,padding:22},children:n?t.jsx("p",{style:{fontSize:13,color:"#64748b"},children:"Loadingâ¦"}):r?t.jsx("p",{style:{fontSize:13,color:"#f87171"},children:r}):e?t.jsxs(t.Fragment,{children:[t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"baseline",marginBottom:4},children:[t.jsx("div",{style:{fontSize:17,fontWeight:800,color:"#e2e8f0"},children:o?o==="rental"?"They want to rent":"They want to buy":"What was sent"}),t.jsx("button",{onClick:s,style:{fontSize:13,color:"#64748b",background:"none",border:"none",cursor:"pointer"},children:"Close"})]}),t.jsx("p",{style:{fontSize:12,color:"#64748b",marginBottom:16},children:o?"Build the quote at these numbers â this is what the customer agreed to.":"Not claimed yet. The
346se are the numbers on the offer."}),e.items.map(p=>{const u=p.allocated_total??null,h=p.offered_rental_monthly??null;return t.jsxs("div",{style:{border:"1px solid #1e3a4f",borderRadius:10,padding:"12px 14px",marginBottom:8},children:[t.jsxs("div",{style:{fontSize:14,fontWeight:600,color:"#e2e8f0",marginBottom:6},children:[p.quantity>1?`${p.quantity} Ã `:"",p.name]}),t.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:20,fontSize:13},children:[a&&u!=null&&t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:11,color:"#64748b"},children:"Buy"}),t.jsx("div",{style:{fontWeight:700,color:"#e2e8f0"},children:fs(u)}),p.list_price!=null&&p.list_price*(p.quantity||1)>u&&t.jsxs("div",{style:{fontSize:11,color:"#64748b"},children:["was ",fs(p.list_price*(p.quantity||1))]})]}),l&&h!=null&&t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:11,color:"#64748b"},children:"Rent"}),t.jsxs("div",{style:{fontWeight:700,color:"#e2e8f0"},children:[fs(h),"/mo"]})]}),l&&p.install_fee!=null&&(p.display_mode==="rental"||p.display_mode==="both")&&t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:11,color:"#64748b"},children:"Install"}),t.jsx("div",{style:{fontWeight:700,color:"#e2e8f0"},children:fs(p.install_fee)})]})]})]},p.id)}),t.jsxs("div",{style:{borderTop:"1px solid #1e3a4f",marginTop:12,paddingTop:12},children:[a&&d>0&&t.jsx(lp,{label:"Total to buy",value:fs(d),strong:!0}),l&&c>0&&t.jsx(lp,{label:"Total to rent",value:`${fs(c)}/mo`,strong:!0}),l&&f>0&&t.jsx(lp,{label:"Installation, one time",value:fs(f)}),e.bundle_discount_value!=null&&a&&t.jsx(lp,{label:"Includes bundle discount",value:e.bundle_discount_type==="percent"?`${e.bundle_discount_value}%`:fs(e.bundle_discount_value)})]}),o==="purchase"&&t.jsxs("div",{style:{background:"rgba(251,191,36,0.08)",border:"1px solid rgba(251,191,36,0.3)",borderRadius:10,padding:"10px 12px",marginTop:14},children:[t.jsx("div",{style:{fontSize:12,fontWeight:700,color:"#fbbf24",marginBottom:4},children:"Before you send the quote"}),t.jsx("p",{style:{fontSize:12,color:"#e2e8f0",lineHeight:1.5},children:"The offer showed no installation fee â a purchase price is all-in. QuoteBuilder adds an install-fee line automatically, so remove it."})]}),t.jsx("button",{onClick:()=>i(e.lead_id),style:{width:"100%",marginTop:16,padding:"11px 0",fontSize:13,fontWeight:700,color:"#0f1c2b",background:"#38bdf8",border:"none",borderRadius:8,cursor:"pointer"},children:"Open the lead and build the quote"})]}):null})})}function lp({label:e,value:n,strong:r}){return t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",padding:"4px 0"},children:[t.jsx("span",{style:{fontSize:13,color:"#94a3b8"},children:e}),t.jsx("span",{style:{fontSize:r?15:13,fontWeight:r?700:500,color:"#e2e8f0"},children:n})]})}function Od({label:e,value:n,color:r,hint:s}){return t.jsxs("div",{style:{background:"#162232",border:"1px solid #1e3a4f",borderRadius:10,padding:"10px 16px",minWidth:110},children:[t.jsx("div",{style:{fontSize:10,fontWeight:700,letterSpacing:"0.08em",color:"#64748b"},children:e.toUpperCase()}),t.jsx("div",{style:{fontSize:22,fontWeight:800,color:r,marginTop:4},children:n}),s&&t.jsx("div",{style:{fontSize:10,color:"#475569",marginTop:2},children:s})]})}const D4="America/Indiana/Indianapolis";function O4(e){const[n,r]=e.split(":").map(Number),s=n>=12?"PM":"AM";return`${n>12?n-12:n===0?12:n}:${String(r).padStart(2,"0")} ${s}`}function I4(e,n){const r=new Intl.DateTimeFormat("en-US",{timeZone:n,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(e),s=i=>{var o;return((o=r.find(a=>a.type===i))==null?void 0:o.value)||""};return`${s("year")}-${s("month")}-${s("day")}`}function gP(e,n){const r=new Intl.DateTimeFormat("en-US",{timeZone:n,hour:"2-digit",minute:"2-digit",hour12:!1}).formatToParts(e),s=o=>{var a;return((a=r.find(l=>l.type===o))==null?void 0:a.value)||"0"};let i=parseInt(s("hour"),10);return i===24&&(i=0),i*60+parseInt(s("minute"),10)}function mP(e){const[n,r]=e.split(":").map(Number);return n*60+r}function l0(e,n){const[r,s]=(e.start||"09:30").split(":").map(Number),[i,o]=(e.end||"16:30").split(":").map(Number),a=r*60+s,l=i*60+o,d=e.slot_minutes||30,c=[];for(let h=a;h+d<=l+1;h+=d){const y=Math.floor(h/60),m=h%60,b=`${String(y).padStart(2,"0")}
346:${String(m).padStart(2,"0")}`;c.push({value:b,display:O4(b)})}if(!n)return c;const f=e.tz||D4,p=new Date;if(n!==I4(p,f))return c;const u=gP(p,f)+(e.min_notice_minutes??0);return c.filter(h=>mP(h.value)>=u)}function L4(e){const n=e.tz||D4,r=[],s=e.min_notice_days??1,i=e.horizon_days??14,o=new Set(e.days||[1,2,3,4,5]),a=new Date,l=I4(a,n);for(let d=0;d<=i&&r.length<30;d++){const c=new Date(a.getTime()+d*864e5),f=new Intl.DateTimeFormat("en-US",{timeZone:n,weekday:"short",year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(c),p=_=>{var j;return((j=f.find(C=>C.type===_))==null?void 0:j.value)||""},u=p("weekday"),h=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"].indexOf(u)+1;if(!o.has(h))continue;const y=p("year"),m=p("month"),b=p("day"),A=`${y}-${m}-${b}`;let v=d<s,x=v?"Too soon":void 0;!v&&A===l&&l0(e,A).length===0&&(v=!0,x="No times left"),r.push({iso:A,dow:u,md:`${m}/${b}`,tooSoon:v,unavailableLabel:x})}return r}const W4="cev_attr",xP=512,$4=["gclid","fbclid","utm_source","utm_medium","utm_campaign"];function yP(){try{const e=window.sessionStorage.getItem(W4);if(!e)return{};const n=JSON.parse(e);return n&&typeof n=="object"&&!Array.isArray(n)?n:{}}catch{return{}}}function bP(e){try{window.sessionStorage.setItem(W4,JSON.stringify(e))}catch{}}function M4(){if(typeof window>"u")return{};const e=yP();let n=!1;try{const r=new URLSearchParams(window.location.search);for(const s of $4){const i=(r.get(s)||"").trim();i&&!e[s]&&(e[s]=i.slice(0,xP),n=!0)}}catch{}return n&&bP(e),e}function d0(){const e=M4(),n={};for(const r of $4)e[r]&&(n[r]=e[r]);return n}typeof window<"u"&&M4();const wv="company_website",AP="/api/leads/capture",vP="/api/forms/availability";function _P(){const{slug:e}=di(),[n,r]=g.useState(null),[s,i]=g.useState(!1),[o,a]=g.useState(1),[l,d]=g.useState({}),[c,f]=g.useState(""),[p,u]=g.useState(!1),[h,y]=g.useState(!1),[m,b]=g.useState(null),[A,v]=g.useState(null),[x,_]=g.useState({}),[j,C]=g.useState(!1),[S,T]=g.useState("");g.useEffect(()=>{(async()=>{const{data:ne}=await w.from("public_lead_forms").select("*").eq("slug",e).maybeSingle();if(!ne){i(!0);return}r(ne)})()},[e]),g.useEffect(()=>{function ne(){const be=document.documentElement.scrollHeight;try{window.parent.postMessage({cevoraFormHeight:be,slug:e},"*")}catch{}}ne();const ge=setInterval(ne,500);return window.addEventListener("resize",ne),()=>{clearInterval(ge),window.removeEventListener("resize",ne)}},[e,o,n,m,A]);const L=g.useMemo(()=>n?L4(n.schedule_rules):[],[n]),E=g.useMemo(()=>n?l0(n.schedule_rules,m):[],[n,m]);async function R(ne){if(b(ne),v(null),!!n&&!x[ne])try{const be=await(await fetch(`${vP}?slug=${encodeURIComponent(n.slug)}&date=${ne}`)).json();_(we=>({...we,[ne]:Array.isArray(be.taken)?be.taken:[]}))}catch{_(ge=>({...ge,[ne]:[]}))}}const N=(n==null?void 0:n.accent_color)||"#0f6e56",O=(n==null?void 0:n.bg_color)||"#ffffff",z=(n==null?void 0:n.text_color)||"#111111",P=(n==null?void 0:n.button_color)||N,D=(n==null?void 0:n.placeholder_color)||"#9aa0a8",M=(n==null?void 0:n.input_border_color)||"#cccccc",k=(n==null?void 0:n.input_bg_color)||"#ffffff",q=(n==null?void 0:n.input_text_color)||void 0,$=(n==null?void 0:n.link_color)||"#2563eb",I=(n==null?void 0:n.terms_url)||"https://app.termly.io/policy-viewer/policy.html?policyUUID=e9899f57-2949-4c56-af3a-cad0fb55e72c",B=(n==null?void 0:n.privacy_url)||"https://app.termly.io/policy-viewer/policy.html?policyUUID=c2402a15-5a4a-4761-b3c7-dd05d35181b9";function J(ne,ge){d(be=>({...be,[ne]:ge}))}function ae(){if(!n)return"Loadingâ¦";for(const ne of n.fields)if(ne.show&&ne.required&&!(l[ne.key]||"").trim())return`${ne.label} is required`;return null}async function te(){if(!n)return;T("");const ne=ae();if(ne){T(ne),a(n.booking_first&&n.schedule_enabled?2:1);return}if(n.schedule_enabled&&(!m||!A)){T("Please choose a date and time");return}C(!0);const ge=m&&A?`${m} ${A}`:void 0,be={form_slug:n.slug,first_name:l.first_name||"",last_name:l.last_name||"",phone:l.phone||"",email:l.email||"",address:l.address||"",city:l.city||"",state:l.state||"",zip:l.zip||"",water_concern:l.water_concern||"",notes:l.notes||"",sms_opt_in:p,email_opt_in:h,consent_text_version:"zenith_v1_2026-07",[wv]:c,...d0()};ge&&(be.preferred_slot_at=ge);try{const we=await fetch(AP,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(be)}),F=await we.json().catch(()=>({}));if(!we.ok&&we.status!==201){T(F.error||"Something went wrong. Please try again."),C(!1);return}a(3)}catch{T("Network error. Please try again.")}C(!1)}if(s)return t.jsx(Cv,{children:t.jsx("div",{style:{color:"#64748b",fontSize:15},children:"This form is not available."})});if(!n)return t.jsx(Cv,{children:t.jsx("div",{style:{color:"#64748b",fontSize:15},children:"Loadingâ¦"})});const U=n.fields.filter(ne=>ne.show),W=m?x[m]||[]:[],G=!!n.booking_first&&n.schedule_enabled,V=G?2:1,ee=G?1:2,re=n.schedule_enabled?2:1,Q=G?["Pick a time","Your info","Confirm"]:["Your info","Pick a time","Confirm"],oe=t.jsxs("div",{style:{marginTop:20,display:"flex",flexDirection:"column",gap:10},children:[t.jsxs("label",{style:{display:"flex",alignItems:"flex-start",ga
346p:8,cursor:"pointer"},children:[t.jsx("input",{type:"checkbox",checked:p,onChange:ne=>u(ne.target.checked),style:{marginTop:3}}),t.jsxs("span",{style:{fontSize:12,color:z,opacity:.85,lineHeight:1.5},children:["Opt in to receive text updates from Zenith Pure Solutions (optional). You agree to receive appointment reminders and occasional offers by automated text at the number provided, up to 4 msgs/month. Consent is not a condition of purchase. Msg & data rates may apply. Reply HELP for help or call (317) 690-4172. Reply STOP to opt out anytime. View our"," ",t.jsx("a",{href:I,target:"_blank",rel:"noopener noreferrer",style:{color:$},children:"Company Terms"})," ","and"," ",t.jsx("a",{href:B,target:"_blank",rel:"noopener noreferrer",style:{color:$},children:"Privacy Policy"}),"."]})]}),t.jsxs("label",{style:{display:"flex",alignItems:"flex-start",gap:8,cursor:"pointer"},children:[t.jsx("input",{type:"checkbox",checked:h,onChange:ne=>y(ne.target.checked),style:{marginTop:3}}),t.jsx("span",{style:{fontSize:12,color:z,opacity:.85,lineHeight:1.5},children:"Send me water tips and offers by email. Unsubscribe anytime."})]})]});return t.jsxs("div",{style:{minHeight:"100vh",background:"#eef1f4",padding:20,boxSizing:"border-box"},children:[t.jsx("style",{children:`.cev-form-input::placeholder { color: ${D}; opacity: 1; }`}),t.jsxs("div",{style:{maxWidth:(n==null?void 0:n.form_width)||600,margin:"0 auto",background:O,borderRadius:14,overflow:"hidden",boxShadow:"0 2px 12px rgba(0,0,0,0.08)"},children:[(n.logo_url||n.header_text)&&t.jsx("div",{style:{background:N,padding:"20px 24px",color:"#fff",display:"flex",alignItems:"center",justifyContent:"center"},children:n.logo_url?t.jsx("div",{style:{background:"#fff",borderRadius:10,padding:"12px 22px",display:"flex",alignItems:"center",maxWidth:"80%"},children:t.jsx("img",{src:n.logo_url,alt:"logo",style:{width:"100%",maxWidth:360,height:"auto",maxHeight:90,objectFit:"contain",display:"block"}})}):n.header_text?t.jsx("span",{style:{fontSize:n.header_text_size??22,fontWeight:700,color:n.header_text_color||"#ffffff",textAlign:"center"},children:n.header_text}):null}),n.hero_url&&t.jsx("img",{src:n.hero_url,alt:"",style:{width:"100%",height:140,objectFit:"cover"}}),t.jsxs("div",{style:{padding:"22px 24px"},children:[n.schedule_enabled&&n.show_progress_steps!==!1&&t.jsx("div",{style:{display:"flex",gap:6,marginBottom:18,fontSize:12},children:Q.map((ne,ge)=>{const be=ge+1<=o;return t.jsxs("span",{style:{color:be?"#fff":"#5F5E5A",background:be?N:"#eef0ee",borderRadius:20,padding:"4px 12px"},children:[ge+1," ",ne]},ne)})}),o===V&&t.jsxs(t.Fragment,{children:[n.intro_text&&t.jsx("div",{style:{color:z,opacity:.7,fontSize:13,marginBottom:14},children:n.intro_text}),t.jsx("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12},children:U.map(ne=>{const ge=ne.key==="address"||ne.key==="notes"||ne.key==="water_concern";return t.jsxs("div",{style:{gridColumn:ge?"1 / -1":"auto"},children:[ne.showLabel!==!1&&t.jsxs("label",{style:{color:z,fontSize:12,display:"block",marginBottom:4},children:[ne.label,ne.required&&t.jsx("span",{style:{color:"#d85a30"},children:" *"})]}),t.jsx("input",{value:l[ne.key]||"",onChange:be=>J(ne.key,be.target.value),className:"cev-form-input",placeholder:ne.showLabel===!1&&ne.required?ne.label+" *":ne.label,style:jP(M,k,q)})]},ne.key)})}),t.jsx("input",{type:"text",name:wv,tabIndex:-1,autoComplete:"off",value:c,onChange:ne=>f(ne.target.value),style:{position:"absolute",left:-9999,width:1,height:1,opacity:0},"aria-hidden":"true"}),V===re&&oe,S&&t.jsx("div",{style:{color:"#d85a30",fontSize:12,marginTop:10},children:S}),t.jsx("button",{onClick:()=>{const ne=ae();if(ne){T(ne);return}T(""),V===re?te():a(V+1)},disabled:j,style:{...Sv(P),marginTop:18,opacity:j?.5:1},children:V===re?j?"Bookingâ¦":n.submit_button_text||"Submit":"Next: choose date and time"}),V===2&&t.jsx("button",{onClick:()=>{T(""),a(1)},style:{...kv($),marginTop:8},children:"â Back"})]}),o===ee&&n.schedule_enabled&&t.jsxs(t.Fragment,{children:[t.jsx("div",{style:{color:z,fontSize:12,fontWeight:600,marginBottom:8},children:"Choose a preferred day"}),t.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit,minmax(96px,1fr))",gap:8,marginBottom:18},children:L.map(ne=>t.jsxs("button",{onClick:()=>{ne.tooSoon||R(ne.iso)},disabled:ne.tooSoon,style:{padding:"8px 4px",borderRadius:8,cursor:ne.tooSoon?"not-allowed":"pointer",lineHeight:1.3,border:`1px solid ${m===ne.iso?N:M}`,background:m===ne.iso?N:k,color:m===ne.iso?"#fff":q||z,opacity:ne.tooSoon?.45:1},children:[t.jsx("div",{style:{fontSize:11,opacity:.75},children:ne.dow}),t.jsx("div",{style:{fontSize:14},children:ne.md}),ne.tooSoon&&t.jsx("div",{style:{fontSize:9,marginTop:1},children:ne.unavailableLabel||"Unavailable"})]},ne.iso))}),t.jsxs("div",{style:{color:z,fontSize:12,fontWeight:600,marginBottom:8},children:["Choose a preferred time ",t.jsx("span",{style:{opacity:.55,fontWeight:400},children:"· Eastern Time (US & Canada)"})]}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit,minmax(80px,1fr))",gap:8},children:[!m&&t.jsx("span",{style:{fontSize:12,color:"#aaa"},children:"Pick a day first"}),m&&E.map(ne=>{const ge=W.includes(ne.value);return t.jsx("button",{onClick:()=>{ge||v(ne.value)},disabled:ge,style:{padding:"9px 4px",borderRadius:8,cursor:ge?"not-allowed":"pointer",fontSize:13,border:`1px solid ${A===ne.value?N:M}`,background:A===ne.value?N:k,color:A===ne.value?"#fff":q||z,opacity:ge?.45:1},children:ge?"Booked":ne.display},ne.value)}),m&&E.length>0&&E.every(ne=>W.includes(ne.value))&&t.jsx("span",{style:{fontSize:12,color:"#aaa"},children:"All times booked this day"})]}),ee===re&&oe,S&&t.jsx("div",{style:{color:"#d85a30",fontSize:12,marginTop:12},children:S}),t.jsx("button",{onClick:()=>
346{if(!m||!A){T("Please choose a date and time");return}T(""),ee===re?te():a(ee+1)},disabled:j||!m||!A,style:{...Sv(P),marginTop:20,opacity:j||!m||!A?.5:1},children:ee===re?j?"Bookingâ¦":n.submit_button_text||"Book my site visit":"Next: your details"}),ee===2&&t.jsx("button",{onClick:()=>{T(""),a(1)},style:{...kv($),marginTop:8},children:"â Back"})]}),o===3&&t.jsxs("div",{style:{textAlign:"center",padding:"16px 0"},children:[t.jsx("div",{style:{width:64,height:64,borderRadius:"50%",background:`${N}22`,display:"flex",alignItems:"center",justifyContent:"center",margin:"0 auto 14px",fontSize:34,color:N},children:"â"}),t.jsx("div",{style:{color:z,fontSize:20,fontWeight:600,marginBottom:6},children:"You're booked!"}),t.jsx("div",{style:{color:z,opacity:.7,fontSize:14},children:n.success_message||(m&&A?`Your visit is requested for ${wP(m)} at ${O4(A)}. We'll call to confirm.`:"Thanks â we'll be in touch shortly.")})]})]})]}),t.jsx("div",{style:{maxWidth:(n==null?void 0:n.form_width)||600,margin:"10px auto 0",textAlign:"center",fontSize:11,color:"#9aa0a8"},children:"Powered by Cevora"})]})}function jP(e,n,r){return{width:"100%",height:38,boxSizing:"border-box",padding:"0 10px",border:`1px solid ${e}`,background:n,color:r,borderRadius:8,fontSize:14}}function Sv(e){return{width:"100%",background:e,color:"#fff",border:"none",borderRadius:8,height:44,fontSize:15,fontWeight:600,cursor:"pointer"}}function kv(e){return{width:"100%",background:"transparent",color:e,border:"none",height:34,fontSize:13,cursor:"pointer"}}function Cv({children:e}){return t.jsx("div",{style:{minHeight:"100vh",display:"flex",alignItems:"center",justifyContent:"center",background:"#eef1f4"},children:e})}function wP(e){const[n,r,s]=e.split("-").map(Number);return new Date(n,r-1,s).toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric"})}const Ge={navy:"#0d2b4e",navyDk:"#0a2038",teal:"#17a2b8",tealDk:"#0e7d8f",gold:"#f4b731",ink:"#1a2b3a",muted:"#5a6b7b",line:"#e2e8ef",bg:"#f5f8fb",btn:"#12a05e",btnDk:"#0c7d47",green:"#22a45d"},Fs="'Segoe UI', system-ui, -apple-system, Arial, sans-serif",SP=["navy","navyDk","teal","tealDk","gold","ink","muted","line","bg","btn","btnDk","green"];function kP(e){return{...Ge,fontStack:Fs,...e??{}}}function CP(e){const n=kP(e),r={};for(const s of SP)r[`--lp-${s}`]=n[s];return r["--lp-font"]=n.fontStack||Fs,r["--lp-hero-overlay"]="linear-gradient(180deg, rgba(13,43,78,.78), rgba(10,32,56,.88)), radial-gradient(circle at 30% 20%, rgba(23,162,184,.25), transparent 55%)",r}const TP=` 347.lp-root *{box-sizing:border-box} 348.lp-container{max-width:1140px;margin:0 auto;padding:0 20px} 349 350/* ---- offer bar ---- */ 351.lp-offer{background:var(--lp-section-bg,var(--lp-gold));color:var(--lp-navy);font-weight:800;text-align:center;font-size:.92rem;padding:10px 16px;line-height:1.4} 352 353/* ---- header ---- */ 354.lp-header{background:var(--lp-section-bg,#fff);border-bottom:1px solid var(--lp-line)} 355.lp-header-inner{display:flex;align-items:center;justify-content:space-between;padding:12px 20px;max-width:1140px;margin:0 auto} 356.lp-logo{height:38px;width:auto;display:block} 357.lp-callbtn{color:var(--lp-navy);font-weight:800;font-size:1.05rem;text-decoration:none;white-space:nowrap} 358.lp-callbtn span{color:var(--lp-tealDk)} 359 360/* ---- hero ---- */ 361.lp-hero{position:relative;background:var(--lp-section-bg,var(--lp-navy));color:#fff;padding:44px 0 54px;overflow:hidden} 362.lp-hero-overlay{position:absolute;inset:0;background:var(--lp-hero-overlay)} 363.lp-hero-inner{position:relative;text-align:center;max-width:940px;margin:0 auto;padding:0 20px} 364.lp-hero-trust{display:flex;align-items:center;justify-content:center;gap:8px;font-size:.9rem;color:#c8d6e5;margin-bottom:14px} 365.lp-hero-stars{color:var(--lp-gold);letter-spacing:2px} 366.lp-hero h1{font-size:clamp(1.9rem,5vw,2.5rem);line-height:1.14;font-weight:800;max-width:820px;margin:0 auto 8px} 367.lp-hero-gold{color:var(--lp-gold)} 368.lp-hero-sub{font-size:1.05rem;color:#dbe6f2;font-style:italic;margin-bottom:26px} 369 370/* ---- product grid ---- */ 371.lp-pg{padding:44px 0 10px;background:var(--lp-section-bg,#fff)} 372.lp-pg-head{text-align:center;max-width:820px;margin:0 auto 30px;padding:0 20px} 373.lp-pg-head h2{font-size:clamp(1.4rem,3.4vw,1.9rem);line-height:1.2;font-weight:800;color:var(--lp-ink);margin:0 0 6px} 374.lp-pg-accent{color:var(--lp-tealDk)} 375.lp-systems{display:grid;grid-template-columns:repeat(3,1fr);gap:20px;margin:0 auto 34px;max-width:1000px;padding:0 20px;align-items:end} 376.lp-sys{text-align:center} 377.lp-sys-imgbox{height:150px;display:flex;align-items:flex-end;justify-content:center;margin-bottom:12px} 378.lp-sys img{max-width:100%;max-height:150px;width:auto;height:auto;display:block;margin:0 auto} 379.lp-sys-label{font-weight:700;color:var(--lp-ink);font-size:.98rem;white-space:pre-line;line-height:1.3} 380.lp-pg-cta{display:block;width:max-content;max-width:90%;margin:6px auto 0;background:var(--lp-btn);color:#fff;font-weight:800;font-size:1.05rem;text-decoration:none;padding:14px 34px;border-radius:8px} 381 382/* ---- certifications ---- */ 383.lp-cert{padding:30px 0;background:var(--lp-section-bg,#fff);border-top:1px solid var(--lp-line);border-bottom:1px solid var(--lp-line)} 384.lp-cert-inner{max-width:1140px;margin:0 auto;padding:0 20px;display:flex;align-items:center;justify-content:center;gap:34px;flex-wrap:wrap} 385.lp-cert-label{width:100%;text-align:center;color:var(--lp-muted);font-size:.78rem;font-weight:700;letter-spacing:.08em;text-transform:uppercase;margin-bottom:4px} 386.lp-cert img{height:46px;width:auto} 387 388/* ---- footer ---- */ 389.lp-footer{background:var(--lp-section-bg,var(--lp-navyDk));color:#c8d6e5;padding:34px 0} 390.lp-footer-inner{max-width:1140px;margin:0 auto;padding:0 20px;text-align:center} 391.lp-footer img{height:34px;width:auto;margin-bottom:12px;
391filter:brightness(0) invert(1);opacity:.9} 392.lp-footer-name{color:#fff;font-weight:700;margin-bottom:4px} 393.lp-footer-addr{font-size:.85rem;margin-bottom:10px} 394.lp-footer-legal{font-size:.75rem;color:#8ba0b6} 395.lp-footer-legal a{color:var(--lp-link,#c8d6e5);text-decoration:underline} 396 397/* ---- spacer / dividers ---- */ 398.lp-spacer{width:100%} 399.lp-spacer-line{border-top:1px solid var(--lp-line)} 400 401/* ---- lead form ---- */ 402.lp-form{padding:40px 0;background:var(--lp-section-bg,var(--lp-bg))} 403.lp-form-card{max-width:560px;margin:0 auto;padding:0 20px} 404.lp-form-heading{font-size:clamp(1.3rem,3vw,1.7rem);font-weight:800;color:var(--lp-ink);text-align:center;margin:0 0 6px} 405.lp-form-sub{color:var(--lp-muted);text-align:center;margin:0 0 20px} 406.lp-form-grid{display:grid;grid-template-columns:1fr 1fr;gap:14px} 407.lp-field{display:flex;flex-direction:column} 408.lp-field:nth-child(odd):last-child{grid-column:1 / -1} 409.lp-label{font-size:.82rem;font-weight:700;color:var(--lp-ink);margin-bottom:4px} 410.lp-req{color:var(--lp-btn)} 411.lp-input{border:1px solid var(--lp-line);border-radius:8px;padding:12px 12px;font-size:1rem;min-height:44px;background:#fff;color:var(--lp-ink)} 412.lp-input:focus{outline:2px solid var(--lp-teal);outline-offset:1px} 413.lp-consent{display:flex;align-items:flex-start;gap:8px;margin-top:14px;font-size:.85rem;color:var(--lp-muted);line-height:1.4} 414.lp-consent a{color:var(--lp-link,var(--lp-teal));text-decoration:underline} 415.lp-consent input{margin-top:3px} 416.lp-legal{font-size:.75rem;color:var(--lp-muted);margin:12px 0 0} 417.lp-legal a{color:var(--lp-link,var(--lp-teal));text-decoration:underline} 418.lp-form-error{color:#c0392b;font-size:.88rem;margin-top:12px;text-align:center} 419.lp-form-submit{width:100%;margin-top:18px;background:var(--lp-btn);color:#fff;font-weight:800;font-size:1.05rem;border:none;border-radius:8px;padding:15px;cursor:pointer;min-height:50px} 420.lp-form-submit:disabled{opacity:.6;cursor:default} 421.lp-form-success{max-width:560px;margin:0 auto;padding:28px 20px;text-align:center;font-size:1.1rem;font-weight:700;color:var(--lp-green)} 422 423/* ---- responsive ---- */ 424@media(max-width:720px){ 425 .lp-systems{grid-template-columns:1fr;gap:16px} 426 .lp-sys-imgbox{height:auto} 427 .lp-sys img{max-height:200px} 428} 429@media(max-width:560px){ 430 .lp-header-inner{padding:10px 16px} 431 .lp-callbtn{font-size:.95rem} 432 .lp-form-grid{grid-template-columns:1fr} 433} 434 435/* ---- lead form: multi-step ---- */ 436.lp-form-steps{min-height:320px;display:flex;flex-direction:column} 437.lp-steps-progress{height:6px;background:var(--lp-line);border-radius:99px;overflow:hidden;margin-bottom:8px} 438.lp-steps-bar{height:100%;background:var(--lp-btn);border-radius:99px;transition:width .25s ease} 439.lp-steps-count{font-size:.72rem;font-weight:700;letter-spacing:.06em;text-transform:uppercase;color:var(--lp-muted);text-align:center;margin-bottom:18px} 440.lp-step-screen{display:flex;flex-direction:column} 441.lp-step-prompt{font-size:clamp(1.25rem,3vw,1.6rem);font-weight:800;color:var(--lp-ink);text-align:center;line-height:1.25;margin:0 0 22px} 442.lp-options{display:flex;flex-direction:column;gap:12px} 443.lp-option{width:100%;text-align:left;background:#fff;border:2px solid var(--lp-line);border-radius:10px;padding:16px 18px;font-size:1.05rem;font-weight:600;color:var(--lp-ink);cursor:pointer;transition:border-color .12s ease,background .12s ease} 444.lp-option:hover{border-color:var(--lp-teal)} 445.lp-option-active{border-color:var(--lp-btn);background:var(--lp-hero-overlay,rgba(0,0,0,.02))} 446.lp-step-nav{display:flex;align-items:center;justify-content:space-between;gap:14px;margin-top:20px} 447.lp-step-back{background:none;border:none;color:var(--lp-muted);font-weight:700;font-size:.95rem;cursor:pointer;padding:10px 4px} 448.lp-step-back:hover{color:var(--lp-ink)} 449.lp-step-next{width:auto;margin-top:0;min-width:130px;padding:14px 28px} 450@media(max-width:480px){ 451 .lp-step-next{flex:1} 452 .lp-option{font-size:1rem;padding:14px 16px} 453} 454 455/* ---- lead form: booking / time-slot screen ---- */ 456.lp-book-label{font-size:.82rem;font-weight:700;color:var(--lp-ink);margin:18px 0 8px} 457.lp-book-label:first-of-type{margin-top:4px} 458.lp-book-tz{font-weight:400;color:var(--lp-muted)} 459.lp-book-days{display:grid;grid-template-columns:repeat(auto-fit,minmax(88px,1fr));gap:8px} 460.lp-book-day{display:flex;flex-direction:column;align-items:center;gap:2px;background:#fff;border:1px solid var(--lp-line);border-radius:10px;padding:10px 4px;
460cursor:pointer;line-height:1.25;transition:border-color .12s ease,background .12s ease} 461.lp-book-day:hover:not(.lp-book-day-off){border-color:var(--lp-teal)} 462.lp-book-dow{font-size:.72rem;color:var(--lp-muted)} 463.lp-book-md{font-size:.95rem;font-weight:700;color:var(--lp-ink)} 464.lp-book-day-active{border-color:var(--lp-btn);background:var(--lp-btn)} 465.lp-book-day-active .lp-book-dow,.lp-book-day-active .lp-book-md{color:#fff} 466.lp-book-day-off{background:#f1f1f1;color:var(--lp-muted);cursor:not-allowed;opacity:.6} 467.lp-book-times{display:grid;grid-template-columns:repeat(auto-fit,minmax(84px,1fr));gap:8px} 468.lp-book-time{background:#fff;border:1px solid var(--lp-line);border-radius:8px;padding:11px 4px;font-size:.95rem;font-weight:600;color:var(--lp-ink);cursor:pointer;transition:border-color .12s ease,background .12s ease} 469.lp-book-time:hover:not(.lp-book-time-off){border-color:var(--lp-teal)} 470.lp-book-time-active{border-color:var(--lp-btn);background:var(--lp-btn);color:#fff} 471.lp-book-time-off{background:#f1f1f1;color:var(--lp-muted);cursor:not-allowed} 472.lp-book-hint{font-size:.85rem;color:var(--lp-muted);grid-column:1 / -1} 473@media(max-width:480px){ 474 .lp-book-days{grid-template-columns:repeat(auto-fit,minmax(72px,1fr))} 475 .lp-book-times{grid-template-columns:repeat(auto-fit,minmax(76px,1fr))} 476} 477 478 479/* ---- announcement bar (extends .lp-offer) ---- */ 480.lp-annc{display:flex;align-items:center;justify-content:center;gap:14px} 481.lp-annc-cta{color:var(--lp-navy);text-decoration:underline;font-weight:800;white-space:nowrap} 482.lp-annc-x{background:none;border:none;color:var(--lp-navy);font-size:1.2rem;line-height:1;font-weight:800;cursor:pointer;padding:0 4px;opacity:.7} 483.lp-annc-x:hover{opacity:1} 484 485/* ---- nav header (extends .lp-header) ---- */ 486.lp-nav{position:sticky;top:0;z-index:20} 487.lp-nav-links{display:flex;align-items:center;gap:22px;flex-wrap:wrap} 488.lp-nav-link{color:var(--lp-ink);font-weight:700;font-size:.95rem;text-decoration:none} 489.lp-nav-link:hover{color:var(--lp-tealDk)} 490.lp-nav-right{display:flex;align-items:center;gap:18px} 491.lp-nav-cta{background:var(--lp-btn);color:#fff;font-weight:800;font-size:.95rem;text-decoration:none;padding:10px 20px;border-radius:8px;white-space:nowrap} 492 493/* ---- benefits ---- */ 494.lp-benefits{padding:44px 0;background:var(--lp-section-bg,#fff)} 495.lp-benefits-head{font-size:clamp(1.4rem,3.4vw,1.9rem);line-height:1.2;font-weight:800;color:var(--lp-ink);text-align:center;margin:0 auto 30px;max-width:820px} 496.lp-benefits-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:24px;max-width:1000px;margin:0 auto} 497.lp-benefit{text-align:center;padding:8px 10px} 498.lp-benefit-icon{font-size:2.2rem;line-height:1;margin-bottom:12px} 499.lp-benefit-title{font-weight:800;color:var(--lp-ink);font-size:1.08rem;margin-bottom:6px} 500.lp-benefit-text{color:var(--lp-muted);font-size:.95rem;line-height:1.5} 501@media(max-width:820px){.lp-benefits-grid{grid-template-columns:1fr 1fr}} 502@media(max-width:560px){.lp-benefits-grid{grid-template-columns:1fr;gap:18px}} 503 504/* ---- faq ---- */ 505.lp-faq{padding:44px 0;background:var(--lp-section-bg,var(--lp-bg))} 506.lp-faq-inner{max-width:760px} 507.lp-faq-head{font-size:clamp(1.4rem,3.4vw,1.9rem);line-height:1.2;font-weight:800;color:var(--lp-ink);text-align:center;margin:0 0 26px} 508.lp-faq-list{display:flex;flex-direction:column;gap:10px} 509.lp-faq-item{background:#fff;border:1px solid var(--lp-line);border-radius:10px;overflow:hidden} 510.lp-faq-item-open{border-color:var(--lp-teal)} 511.lp-faq-q{width:100%;display:flex;align-items:center;justify-content:space-between;gap:14px;text-align:left;background:none;border:none;cursor:pointer;padding:16px 18px;font-size:1.02rem;font-weight:700;color:var(--lp-ink)} 512.lp-faq-q-mark{flex-shrink:0;font-size:1.35rem;line-height:1;color:var(--lp-tealDk);font-weight:800} 513.lp-faq-a{padding:0 18px 18px;color:var(--lp-muted);font-size:.98rem;line-height:1.6;white-space:pre-line} 514 515/* ---- cta band ---- */ 516.lp-cta{background:var(--lp-section-bg,var(--lp-navy));color:#fff;padding:48px 0} 517.lp-cta-inner{text-align:center;max-width:760px} 518.lp-cta-headline{font-size:clamp(1.5rem,3.6vw,2.1rem);line-height:1.18;font-weight:800;color:#fff;margin:0 0 10px} 519.lp-cta-sub{font-size:1.05rem;color:#dbe6f2;margin:0 0 24px} 520.lp-cta-actions{display:flex;align-items:center;justify-content:center;gap:14px;flex-wrap:wrap} 521.lp-cta-primary{background:var(--lp-btn);color:#fff;font-weight:800;font-size:1.05rem;text-decoration:none;padding:14px 34px;border-radius:8px} 522.lp-cta-secondary{background:transparent;color:#fff;font-weight:800;font-size:1.05rem;text-decoration:none;padding:14px 30px;border-radius:8px;border:2px solid rgba(255,255,255,.5)} 523.lp-cta-secondary:hover{border-color:#fff} 524@media(max-width:480px){ 525 .lp-cta-actions{flex-direction:column} 526 .lp-cta-primary,.lp-cta-secondary{width:100%} 527} 528`,zP=({section:e})=>{const n=e.content||{},r=n.offer,s=n.logo_url,i=n.phone,o=n.head_pre!=null||n.head_gold!=null||n.head_post!=null;return t.jsxs(t.Fragment,{children:[r?t.jsx("div",{className:"lp-offer",children:r}):null,s||i?t.jsx("header",{className:"lp-header",children:t.jsxs("div",{className:"lp-header-inner",children:[t.jsx("span",{}),i?t.jsxs("a",{className:"lp-callbtn",href:`tel:1${String(i).replace(/\D/g,"")}`,children:["Call ",t.jsx("span",{children:i})]}):null]})}):null,t.jsxs("section",{id:"top",className:"lp-hero",children:[t.jsx("div",{className:"lp-hero-overlay"}),t.jsxs("div",{className:"lp-hero-inner",children:[n.trust_line?t.jsxs("div",{className:"lp-hero-trust",children:[t.jsx("span",{className:"lp-hero-stars",children:"â â â â â "})," ",n.trust_line]}):null,t.jsx("h1",{children:o?t.jsxs(t.Fragment,{children:[n.head_pre,t.jsx("span",{className:"lp-hero-gold",children:n.head_gold}),n.head_post]}):n.headline}),n.subhead?t.jsx("p",{className:"lp-hero-sub",children:n.subhead}):null]})]})]})},NP="https://yktemdaxnvraobkjfvnn.supabase.co",RP="landing-assets",Tv="asset:";function gd(e){if(!e)return;if(!e.startsWith(Tv))return e;const n=e.slice(Tv.length);return`${NP}/storage/v1/object/public/${RP}/${n}`}const EP=({section:e})=>{const n=e.content||{},r=Array.isArray(n.products)?n.products:[],s=e.media||{};return t.jsxs("section",{className:"lp-pg",children:[n.heading||n.heading_accent?t.jsx("div",{className:"lp-pg-head",children:t.jsxs("h2",{children:[n.heading,n.heading_accent?t.jsxs("span",{className:"lp-pg-accent",children:[" ",n.heading_accent]}):null]})}):null,t.jsx("div",{className:"lp-systems",children:r.map((i,o)=>{const a=i!=null&&i.media_key?s[i.media_key]:void 0,l=gd(a==null?void 0:a.asset);return t.jsxs("div",{className:"lp-sys",children:[t.jsx("div",{className:"lp-sys-imgbox",children:l?t.jsx("img",{src:l,alt:(a==null?void 0:a.alt)||i.label||""}):null}),t.jsx("div",{className:"lp-sys-label",children:i.label})]},o)})}),n.cta_label?t.jsx("a",{className:"lp-pg-cta",href:n.cta_href||"#top",children:n.cta_label}):null]})},PP=({section:e})=>{const n=e.content||{},r=Array.isArray(n.badges)?n.badges:[],s=e.media||{};return t.jsx("section",{className:"lp-cert",children:t.jsxs("div",{className:"lp-cert-inner",children:[t.jsx("div",{className:"lp-cert-label",children:n.heading||"Certified & Accredited"}),r.map((i,o)=>{const a=i!=null&&i.media_key?s[i.media_key]:void 0,l=gd(a==null?void 0:a.asset);return l?t.jsx("img",{src:l,alt:(i==null?void 0:i.alt)||(a==null?void 0:a.alt)||""},o):null})]})})},qP=({section:e})=>{const n=e.content||{},r=Array.isArray(n.legal_links)?n.legal_links:[];return t.jsx("footer",{className:"lp-footer",children:t.jsxs("div",{className:"lp-footer-inner",children:[n.logo_url?t.jsx("img",{src:gd(n.logo_url),alt:""}):null,n.brand_line?t.jsx("div",{className:"lp-footer-name",children:n.brand_line}):null,n.address?t.jsx("div",{className:"lp-footer-addr",children:n.address}):null,t.jsxs("div",{className:"lp-footer-legal",children:[r.map((s,i)=>t.jsxs(ut.Fragment,{children:[i>0?" · ":null,t.jsx("a",{href:s.href,children:s.label})]},i)),n.copyright?t.jsx("div",{style:{marginTop:8},children:n.copyright}):null]})]})})},zv={sm:16,md:32,lg:56,xl:88},DP=({section:e})=>{const n=e.content||{},r=zv[n.height]??zv.md,s=n.divider==="line";return t.jsx("div",{className:`lp-spacer${s?" lp-spacer-line":""}`,style:{height:r}})},md="https://app.termly.io/policy-viewer/policy.html?policyUUID=e9899f57-2949-4c56-af3a-cad0fb55e72c",xd="https://app.termly.io/policy-viewer/policy.html?policyUUID=c2402a15-5a4a-4761-b3c7-dd05d35181b9",yd="zenith_v1_2026-07",OP="Opt in to receive text updates from Zenith Pure Solutions (optional). You agree to re
528ceive appointment reminders and occasional offers by automated text at the number provided, up to 4 msgs/month. Consent is not a condition of purchase. Msg & data rates may apply. Reply HELP for help or call (317) 690-4172. Reply STOP to opt out anytime. View our ",IP="Company Terms",LP="Privacy Policy",WP="Send me water tips and offers by email. Unsubscribe anytime.",Nv="company_website",$P="/api/leads/capture",MP="/api/forms/availability",Rv={first_name:"First name",last_name:"Last name",phone:"Phone",email:"Email",address:"Address",city:"City",state:"State",zip:"ZIP",water_concern:"Water concern",notes:"Notes"},FP=({section:e})=>{const n=e.content||{},r=n.form_slug,s=n.flow==="multi_step"?"multi_step":"single",i=Array.isArray(n.contact_fields)?n.contact_fields:[],o=Array.isArray(n.questions)?n.questions:[],a=n.booking&&typeof n.booking=="object"?n.booking:null,l=!!(a&&a.enabled===!0),[d,c]=g.useState(null),[f,p]=g.useState({}),[u,h]=g.useState({}),[y,m]=g.useState(!1),[b,A]=g.useState(!1),[v,x]=g.useState(""),[_,j]=g.useState(null),[C,S]=g.useState(null),[T,L]=g.useState({}),[E,R]=g.useState(!1),[N,O]=g.useState(null),[z,P]=g.useState(!1);g.useEffect(()=>{if(!r)return;let ee=!0;return w.from("public_lead_forms").select("slug, title, submit_button_text, success_message, terms_url, privacy_url, schedule_enabled, schedule_rules").eq("slug",r).maybeSingle().then(({data:re})=>{ee&&c(re??null)}),()=>{ee=!1}},[r]);const D=d&&d.schedule_rules&&Array.isArray(d.schedule_rules.days)?d.schedule_rules:null,M=l&&!!D,k=M&&(a==null?void 0:a.required)!==!1,q=(ee,re)=>p(Q=>({...Q,[ee]:re})),$=(ee,re)=>{O(null),h(Q=>{if(ee.type==="single_select")return{...Q,[ee.key]:[re]};const oe=Q[ee.key]||[],ne=oe.includes(re)?oe.filter(ge=>ge!==re):[...oe,re];return{...Q,[ee.key]:ne}})},I=()=>{for(const ee of i)if(ee.required&&!(f[ee.key]||"").trim())return`Please fill in ${ee.label||Rv[ee.key]||ee.key}`;for(const ee of o)if(ee.required&&!(u[ee.key]&&u[ee.key].length))return`Please answer: ${ee.prompt}`;return k&&(!_||!C)?"Please choose a date and time":null},B=()=>{var re;const ee={form_slug:r,first_name:f.first_name||"",last_name:f.last_name||"",phone:f.phone||"",email:f.email||"",address:f.address||"",city:f.city||"",state:f.state||"",zip:f.zip||"",water_concern:f.water_concern||"",notes:f.notes||"",sms_opt_in:y,email_opt_in:b,consent_text_version:((re=n.consent)==null?void 0:re.version)||yd,[Nv]:v,...d0()};for(const Q of o){const oe=u[Q.key];if(!oe||!oe.length)continue;const ne=be=>{const we=(Q.options||[]).find(F=>F.value===be);return we&&we.label||be},ge=oe.map(ne);ee[`qa_${Q.key}`]=Q.type==="multi_select"?ge.join(", "):ge[0],Q.maps_to==="water_concern"&&ge[0]&&(ee.water_concern=ge[0])}return _&&C&&(ee.preferred_slot_at=`${_} ${C}`),ee},J=async()=>{const ee=I();if(ee){O(ee);return}O(null),R(!0);try{const re=await fetch($P,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(B())}),Q=await re.json().catch(()=>({}));if(!re.ok&&re.status!==201){O(Q.error||"Something went wrong. Please try again."),R(!1);return}P(!0)}catch{O("Network error. Please try again."),R(!1)}},ae=async ee=>{if(j(ee),S(null),O(null),!!r&&!T[ee])try{const Q=await(await fetch(`${MP}?slug=${encodeURIComponent(r)}&date=${ee}`)).json();L(oe=>({...oe,[ee]:Array.isArray(Q.taken)?Q.taken:[]}))}catch{L(re=>({...re,[ee]:[]}))}};if(z)return t.jsx("section",{className:"lp-form",children:t.jsx("div",{className:"lp-form-card lp-form-success",children:n.success_message||(d==null?void 0:d.success_message)||"Thank you! Weâll be in touch shortly."})});const te=n.submit_label||(d==null?void 0:d.submit_button_text)||"Submit",U=t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"lp-form-grid",children:i.map(ee=>t.jsxs("div",{className:"lp-field",children:[t.jsxs("label",{className:"lp-label",children:[ee.label||Rv[ee.key]||ee.key,ee.required?t.jsx("span",{className:"lp-req",children:" *"}):null]}),t.jsx("input",{className:"lp-input",type:ee.key==="email"?"email":ee.key==="phone"?"tel":"text",inputMode:ee.key==="phone"?"tel":ee.key==="email"?"email":void 0,placeholder:ee.placeholder||"",value:f[ee.key]||"",onChange:re=>q(ee.key,re.target.value),autoComplete:ee.key==="first_name"?"given-name":ee.key==="last_name"?"family-name":ee.key})]},ee.key))}),t.jsx("input",{type:"text",name:Nv,tabIndex:-1,autoComplete:"off",value:v,onCh
528ange:ee=>x(ee.target.value),style:{position:"absolute",left:"-9999px",width:1,height:1,opacity:0},"aria-hidden":"true"})]}),W=(d==null?void 0:d.terms_url)||md,G=(d==null?void 0:d.privacy_url)||xd,V=t.jsxs(t.Fragment,{children:[t.jsxs("label",{className:"lp-consent",children:[t.jsx("input",{type:"checkbox",checked:y,onChange:ee=>m(ee.target.checked)}),t.jsxs("span",{children:[OP,t.jsx("a",{href:W,target:"_blank",rel:"noopener noreferrer",children:IP})," and ",t.jsx("a",{href:G,target:"_blank",rel:"noopener noreferrer",children:LP}),"."]})]}),t.jsxs("label",{className:"lp-consent",children:[t.jsx("input",{type:"checkbox",checked:b,onChange:ee=>A(ee.target.checked)}),t.jsx("span",{children:WP})]})]});return s==="single"?t.jsx("section",{className:"lp-form",children:t.jsxs("div",{className:"lp-form-card",children:[n.heading?t.jsx("h2",{className:"lp-form-heading",children:n.heading}):null,n.subtext?t.jsx("p",{className:"lp-form-sub",children:n.subtext}):null,o.map(ee=>t.jsxs(ut.Fragment,{children:[t.jsxs("h2",{className:"lp-step-prompt",children:[ee.prompt,ee.required?t.jsx("span",{className:"lp-req",children:" *"}):null]}),t.jsx(F4,{q:ee,answers:u,onPick:$})]},ee.key)),U,V,N?t.jsx("div",{className:"lp-form-error",children:N}):null,t.jsx("button",{className:"lp-form-submit",onClick:J,disabled:E,children:E?"Sendingâ¦":te})]})}):t.jsx(BP,{c:n,questions:o,answers:u,setAnswers:h,contactFields:U,consentBlock:V,bookingActive:M,bookingRequired:k,bookingHeading:(a==null?void 0:a.heading)||"Choose a time",scheduleRules:D,pickedDay:_,pickedTime:C,setPickedTime:S,pickDay:ae,takenByDay:T,submit:J,submitting:E,submitLabel:te,error:N,setError:O})},BP=({c:e,questions:n,answers:r,setAnswers:s,contactFields:i,consentBlock:o,bookingActive:a,bookingRequired:l,bookingHeading:d,scheduleRules:c,pickedDay:f,pickedTime:p,setPickedTime:u,pickDay:h,takenByDay:y,submit:m,submitting:b,submitLabel:A,error:v,setError:x})=>{const _=g.useMemo(()=>{const I=n.map(B=>({kind:"question",q:B}));return I.push({kind:"contact"}),a&&I.push({kind:"booking"}),I},[n,a]),[j,C]=g.useState(0),S=_.length,T=Math.min(j,S-1),L=_[T],E=T===S-1,R=()=>{x(null),C(I=>Math.min(I+1,S-1))},N=()=>{x(null),C(I=>Math.max(I-1,0))},O=I=>{if(I.required&&!(r[I.key]&&r[I.key].length)){x(`Please answer: ${I.prompt}`);return}R()},z=(I,B)=>{x(null),s(J=>({...J,[I.key]:[B]})),setTimeout(()=>C(J=>Math.min(J+1,S-1)),140)},P=(I,B)=>{x(null),s(J=>{const ae=J[I.key]||[],te=ae.includes(B)?ae.filter(U=>U!==B):[...ae,B];return{...J,[I.key]:te}})},D=()=>{if(l&&(!f||!p)){x("Please choose a date and time");return}R()},M=Math.round((T+1)/S*100),k=g.useMemo(()=>c?L4(c):[],[c]),q=g.useMemo(()=>c?l0(c,f):[],[c,f]),$=f?y[f]||[]:[];return t.jsx("section",{className:"lp-form",children:t.jsxs("div",{className:"lp-form-card lp-form-steps",children:[e.heading?t.jsx("h2",{className:"lp-form-heading",children:e.heading}):null,e.subtext?t.jsx("p",{className:"lp-form-sub",children:e.subtext}):null,t.jsx("div",{className:"lp-steps-progress","aria-hidden":"true",children:t.jsx("div",{className:"lp-steps-bar",style:{width:`${M}%`}})}),t.jsxs("div",{className:"lp-steps-count",children:["Step ",T+1," of ",S]}),L.kind==="question"?t.jsxs("div",{className:"lp-step-screen",children:[t.jsxs("h2",{className:"lp-step-prompt",children:[L.q.prompt,L.q.required?t.jsx("span",{className:"lp-req",children:" *"}):null]}),t.jsx(F4,{q:L.q,answers:r,onPick:(I,B)=>I.type==="single_select"?z(I,B):P(I,B)}),v?t.jsx("div",{className:"lp-form-error",children:v}):null,t.jsxs("div",{className:"lp-step-nav",children:[T>0?t.jsx("button",{type:"button",className:"lp-step-back",onClick:N,children:"Back"}):t.jsx("span",{}),L.q.type==="multi_select"?t.jsx("button",{type:"button",className:"lp-form-submit lp-step-next",onClick:()=>O(L.q),children:"Next"}):t.jsx("span",{})]})]}):L.kind==="contact"?t.jsxs("div",{className:"lp-step-screen",children:[i,E?o:null,v?t.jsx("div",{className:"lp-form-error",children:v}):null,t.jsxs("div",{className:"lp-step-nav",children:[T>0?t.jsx("button",{type:"button",className:"lp-step-back",onClick:N,children:"Back"}):t.jsx("span",{}),E?t.jsx("button",{type:"button",className:"lp-form-submit lp-step-next",onClick:m,disabled:b,children:b?"Sendingâ¦":A}):t.jsx("button",{type:"button",className:"lp-form-submit lp-step-next",onClick:R,children:"Next"})]})]}):t.jsxs("div",{className:"lp-step-screen",children:[t.jsx("h2",{className:"lp-step-prompt",children:d}),t.jsx("div",{className:"lp-book-label",children:"Choose a preferred day"}),t.jsx("div",{className:"lp-book-days",children:k.map(I=>t.jsxs("button",{type:"button",className:`lp-book-day${f===I.iso?" lp-book-day-active":""}${I.tooSoon?" lp-book-day-off":""}`,disabled:I.tooSoon,onClick:()=>{I.tooSoon||h(I.iso)},children:[t.jsx("span",{className:"lp-book-dow",children:I.dow}),t.jsx("span",{className:"lp-book-md",children:I.md})]},I.iso))}),t.jsxs("div",{className:"lp-book-label",children:["Choose a preferred time ",t.jsx("span",{className:"lp-book-tz",children:"· Indiana time"})]}),t.jsxs("div",{className:"lp-book-times",children:[f?null:t.jsx("span",{className:"lp-book-hint",children:"Pick a day first"}),f?q.map(I=>{const B=$.includes(I.value);return t.jsx("button",{type:"button",className:`lp-book-time${p===I.value?" lp-book-time-active":""}${B?" lp-book-time-off":""}`,disabled:B,onClick:()=>{B||(u(I.value),x(null))},children:B?"Booked":I.display},I.value)}):null,f&&q.length>0&&q.every(I=>$.includes(I.value))?t.jsx("span",{className:"lp-book-hint",children:"All times booked this day"}):null]}),o,v?t.jsx("div",{className:"lp-form-error",children:v}):null,t.jsxs("div",{className:"lp-step-nav",children:[T>0?t.jsx("button",{type:"button",className:"lp-step-back",onClick:N,children:"Back"}):t.jsx("span",{}),E?t.jsx("button",{type:"button",className:"lp-form-submit lp-step-next",onClick:m,disabled:b||l&&(!f||!p),children:b?"Bookingâ¦":A}):t.jsx("button",{type:"button",className:"lp-form-submit lp-step-next",onClick:D,children:"Next"})]})]})]})})};
528function F4(e){const{q:n,answers:r,onPick:s}=e;return t.jsx("div",{className:"lp-options",children:n.options.map(i=>{const o=(r[n.key]||[]).includes(i.value);return t.jsx("button",{type:"button",className:"lp-option"+(o?" lp-option-active":""),onClick:()=>s(n,i.value),children:i.label},i.value)})})}const UP=({section:e})=>{const n=e.content,[r,s]=ut.useState(!1);return!n.message||r?null:t.jsxs("div",{className:"lp-offer lp-annc",children:[t.jsx("span",{className:"lp-annc-msg",children:n.message}),n.cta_label&&n.cta_href?t.jsx("a",{className:"lp-annc-cta",href:n.cta_href,children:n.cta_label}):null,n.dismissible?t.jsx("button",{type:"button",className:"lp-annc-x","aria-label":"Dismiss",onClick:()=>s(!0),children:"Ã"}):null]})},HP=({section:e})=>{const n=e.content,r=n.links||[],s=n.show_phone&&n.phone;return t.jsx("header",{className:"lp-header lp-nav",children:t.jsxs("div",{className:"lp-header-inner lp-nav-inner",children:[n.logo_url?t.jsx("img",{className:"lp-logo",src:gd(n.logo_url),alt:""}):null,t.jsx("nav",{className:"lp-nav-links",children:r.map((i,o)=>t.jsx("a",{className:"lp-nav-link",href:`#${i.anchor}`,children:i.label},`${i.anchor}-${o}`))}),t.jsxs("div",{className:"lp-nav-right",children:[s?t.jsxs("a",{className:"lp-callbtn",href:`tel:1${String(n.phone).replace(/\D/g,"")}`,children:["Call ",t.jsx("span",{children:n.phone})]}):null,n.cta?t.jsx("a",{className:"lp-nav-cta",href:n.cta.href,children:n.cta.label}):null]})]})})},VP=({section:e})=>{const n=e.content,r=n.items||[];return r.length===0?null:t.jsx("section",{className:"lp-benefits",children:t.jsxs("div",{className:"lp-container",children:[n.heading?t.jsx("h2",{className:"lp-benefits-head",children:n.heading}):null,t.jsx("div",{className:"lp-benefits-grid",children:r.map((s,i)=>t.jsxs("div",{className:"lp-benefit",children:[s.icon?t.jsx("div",{className:"lp-benefit-icon",children:s.icon}):null,t.jsx("div",{className:"lp-benefit-title",children:s.title}),s.text?t.jsx("div",{className:"lp-benefit-text",children:s.text}):null]},`${s.title}-${i}`))})]})})},ZP=({section:e})=>{const n=e.content,r=n.items||[],[s,i]=ut.useState({});if(r.length===0)return null;const o=a=>i(l=>({...l,[a]:!l[a]}));return t.jsx("section",{className:"lp-faq",children:t.jsxs("div",{className:"lp-container lp-faq-inner",children:[n.heading?t.jsx("h2",{className:"lp-faq-head",children:n.heading}):null,t.jsx("div",{className:"lp-faq-list",children:r.map((a,l)=>{const d=!!s[l];return t.jsxs("div",{className:`lp-faq-item${d?" lp-faq-item-open":""}`,children:[t.jsxs("button",{type:"button",className:"lp-faq-q","aria-expanded":d,onClick:()=>o(l),children:[t.jsx("span",{className:"lp-faq-q-text",children:a.q}),t.jsx("span",{className:"lp-faq-q-mark","aria-hidden":"true",children:d?"â":"+"})]}),d?t.jsx("div",{className:"lp-faq-a",children:a.a}):null]},`${l}-${a.q.slice(0,24)}`)})})]})})},KP=({section:e})=>{const n=e.content;return t.jsx("section",{className:"lp-cta",children:t.jsxs("div",{className:"lp-container lp-cta-inner",children:[t.jsx("h2",{className:"lp-cta-headline",children:n.headline}),n.sub?t.jsx("p",{className:"lp-cta-sub",children:n.sub}):null,t.jsxs("div",{className:"lp-cta-actions",children:[t.jsx("a",{className:"lp-cta-primary",href:n.cta_primary.href,children:n.cta_primary.label}),n.cta_secondary?t.jsx("a",{className:"lp-cta-secondary",href:n.cta_secondary.href,children:n.cta_secondary.label}):null]})]})})},YP={hero:zP,product_grid:EP,certifications:PP,footer:qP,spacer:DP,lead_form:FP,announcement_bar:UP,nav_header:HP,benefits:VP,faq:ZP,cta:KP};class XP extends ut.Component{constructor(n){super(n),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(n){console.error(`[landing] section ${this.props.sectionId} failed to render`,n)}render(){return this.state.hasError?t.jsx("div",{style:{padding:16,textAlign:"center",color:"var(--lp-muted)",fontSize:".85rem"},children:"(This section could not be displayed.)"}):this.props.children}}const dp={none:0,sm:12,md:28,lg:48,xl:72};function GP(e){const n=e!=null&&e.style&&typeof e.style=="object"?e.style:null,r=e!=null&&e.spacing&&typeof e.spacing=="object"?e.spacing:null;if(!n&&!r)return null;const s={};if(n)for(const i of Object.keys(n)){const o=n[i];
528typeof o=="string"&&o&&(s["--lp-"+i]=o)}return r&&(r.pt&&dp[r.pt]!=null&&(s.paddingTop=dp[r.pt]),r.pb&&dp[r.pb]!=null&&(s.paddingBottom=dp[r.pb])),Object.keys(s).length?s:null}const JP=({section:e})=>{if(e.hidden)return null;const n=YP[e.type];if(!n)return null;const r=t.jsx(XP,{sectionId:e.id,children:t.jsx(n,{section:e})}),s=GP(e);return s?t.jsx("div",{style:s,children:r}):r},bd=({config:e,tokens:n})=>{const r=CP(n??(e==null?void 0:e.tokens_override)??null),s=Array.isArray(e==null?void 0:e.sections)?e.sections:[];return t.jsxs("div",{className:"lp-root",style:{...r,fontFamily:"var(--lp-font)",color:"var(--lp-ink)",background:"#fff",lineHeight:1.5},children:[t.jsx("style",{children:TP}),s.map(i=>t.jsx(JP,{section:i},i.id))]})},QP={schema_version:1,meta:{title:"Zenith Pure Solutions â Water Systems"},sections:[{id:"sec_hero",type:"hero",content:{offer:"LIMITED-TIME: $500 OFF a whole-home system + FREE water test â when you request your estimate this month",logo_url:"/lp/zenith/zenith_logo_trimmed.png",phone:"(317) 690-4172",trust_line:"Trusted by Indianapolis-area homeowners ⢠WQA & BBB Accredited",head_pre:"What Would a ",head_gold:"Whole-Home Water System",head_post:" Cost for Your Home?",subhead:"(Answer the question below to get started!)",headline:"What Would a Whole-Home Water System Cost for Your Home?"}},{id:"sec_products",type:"product_grid",content:{heading:"We'll Design a Custom Solution Based on Your Specific Needs and Budget",heading_accent:"(And Install It Fast!)",products:[{img:"/lp/zenith/system_wholehome.png",label:`City Water 529Filtration Systems`},{img:"/lp/zenith/system_bundle.png",label:`Well Water 530Filtration Systems`},{img:"/lp/zenith/system_ro.png",label:`Under-Sink 531Filtration Systems`}],cta_label:"See Local Price",cta_href:"#sec_form"}},{id:"sec_certs",type:"certifications",content:{badges:[{img:"/lp/zenith/wqa_sm.png",alt:"WQA Certified"},{img:"/lp/zenith/ewqa_sm.png",alt:"EWQA"},{img:"/lp/zenith/viqua_sm.png",alt:"VIQUA"},{img:"/lp/zenith/enpress_sm.png",alt:"ENPRESS"},{img:"/lp/zenith/bbb_sm.png",alt:"BBB Accredited"}]}},{id:"sec_form",type:"lead_form",content:{form_slug:"facebook-lp",flow:"single",heading:"Book your free water test",subtext:"Tell us where to reach you and weâll get you a local price.",submit_label:"Book my site visit",contact_fields:[{key:"first_name",required:!0},{key:"last_name"},{key:"phone",required:!0},{key:"email"},{key:"address"},{key:"city"},{key:"state"},{key:"zip"}],consent:{version:yd,locked:!0}}},{id:"sec_footer",type:"footer",content:{brand_line:"Zenith Pure Solutions LLC",address:"6951 E 30th St, Suite B, Indianapolis, IN 46219",legal_links:[{label:"Terms",href:md},{label:"Privacy",href:xd}],copyright:"© 2026 Zenith Pure Solutions LLC"}}]},e9=()=>t.jsx(bd,{config:QP}),t9={schema_version:1,meta:{title:"Zenith Pure Solutions â Get Your Price"},sections:[{id:"sec_hero",type:"hero",content:{offer:"LIMITED-TIME: $500 OFF a whole-home system + FREE water test â when you request your estimate this month",logo_url:"/lp/zenith/zenith_logo_trimmed.png",phone:"(317) 690-4172",trust_line:"Trusted by Indianapolis-area homeowners ⢠WQA & BBB Accredited",head_pre:"What Would a ",head_gold:"Whole-Home Water System",head_post:" Cost for Your Home?",subhead:"(Answer a few quick questions to get started!)",headline:"What Would a Whole-Home Water System Cost for Your Home?"}},{id:"sec_form",type:"lead_form",content:{form_slug:"facebook-lp",flow:"multi_step",heading:"Almost there â where should we send your price?",subtext:"Tell us where to reach you and weâll get you a local price.",submit_label:"Get my price",questions:[{key:"water_type",prompt:"Is your home on city water or well water?",type:"single_select",required:!0,options:[{value:"City",label:"City water"},{value:"Well",label:"Well water"},{value:"Not sure",label:"Not sure"}]},{key:"concern",prompt:"Whatâs your main water concern?",type:"multi_select",required:!0,options:[{value:"Hard water",label:"Hard water / scale"},{value:"Taste or smell",label:"Taste or smell"},{value:"Staining",label:"Staining"},{value:"Contaminants",label:"Contaminants / safety"}]},{key:"ownership",prompt:"Do you own your home?",type:"single_select",required:!0,options:[{value:"Yes, I own",label:"Yes, I own"},{value:"No, I rent",label:"No, I rent"}]}],contact_fields:[{key:"first_name",required:!0},{key:"last_name"},{key:"phone",required:!0},{key:"email"},{key:"address"},{key:"city"},{key:"state"},{key:"zip"}],consent:{version:yd,locked:!0}}},{id:"sec_footer",type:"footer",content:{brand_line:"Zenith Pure Solutions LLC",address:"6951 E 30th St, Suite B, Indianapolis, IN 46219",legal_links:[{label:"Terms",href:md},{label:"Privacy",href:xd}],copyright:"© 2026 Zenith Pure Solutions LLC"}}]},n9=()=>t.jsx(bd,{config:t9}),r9={schema_version:1,meta:{title:"Zenith Pure Solutions â Book Your Visit"},sections:[{id:"sec_hero",type:"hero",content:{offer:"LIMITED-TIME: $500 OFF a whole-home system + FREE water test â when you request your estimate this month",logo_url:"/lp/zenith/zenith_logo_trimmed.png",phone:"(317) 690-4172",trust_line:"Trusted by Indianapolis-area homeowners ⢠WQA & BBB Accredited",head_pre:"What Would a ",head_gold:"Whole-Home Water System",head_post:"
531Cost for Your Home?",subhead:"(Answer a few quick questions to get started!)",headline:"What Would a Whole-Home Water System Cost for Your Home?"}},{id:"sec_form",type:"lead_form",content:{form_slug:"facebook-lp",flow:"multi_step",heading:"Almost there â where should we send your price?",subtext:"Tell us where to reach you and weâll get you a local price.",submit_label:"Book my visit",questions:[{key:"water_type",prompt:"Is your home on city water or well water?",type:"single_select",required:!0,options:[{value:"City",label:"City water"},{value:"Well",label:"Well water"},{value:"Not sure",label:"Not sure"}]},{key:"concern",prompt:"Whatâs your main water concern?",type:"multi_select",required:!0,options:[{value:"Hard water",label:"Hard water / scale"},{value:"Taste or smell",label:"Taste or smell"},{value:"Staining",label:"Staining"},{value:"Contaminants",label:"Contaminants / safety"}]},{key:"ownership",prompt:"Do you own your home?",type:"single_select",required:!0,options:[{value:"Yes, I own",label:"Yes, I own"},{value:"No, I rent",label:"No, I rent"}]}],contact_fields:[{key:"first_name",required:!0},{key:"last_name"},{key:"phone",required:!0},{key:"email"},{key:"address"},{key:"city"},{key:"state"},{key:"zip"}],booking:{enabled:!0,required:!0,heading:"Pick a time that works for you"},consent:{version:yd,locked:!0}}},{id:"sec_footer",type:"footer",content:{brand_line:"Zenith Pure Solutions LLC",address:"6951 E 30th St, Suite B, Indianapolis, IN 46219",legal_links:[{label:"Terms",href:md},{label:"Privacy",href:xd}],copyright:"© 2026 Zenith Pure Solutions LLC"}}]},s9=()=>t.jsx(bd,{config:r9}),i9={schema_version:1,meta:{title:"Zenith Pure Solutions â Section Types Proof"},sections:[{id:"sec_annc",type:"announcement_bar",content:{message:"LIMITED-TIME: $500 OFF a whole-home system + FREE water test this month",cta_label:"Claim offer",cta_href:"#book",dismissible:!0}},{id:"sec_nav",type:"nav_header",content:{links:[{label:"Systems",anchor:"systems"},{label:"Why Zenith",anchor:"benefits"},{label:"FAQ",anchor:"faq"}],cta:{label:"Get a price",href:"#book"},show_phone:!0,phone:"(317) 690-4172"}},{id:"sec_hero",type:"hero",content:{trust_line:"Trusted by Indianapolis-area homeowners ⢠WQA & BBB Accredited",head_pre:"Cleaner Water for Your ",head_gold:"Whole Home",head_post:" â Starting Today",subhead:"(See why thousands of Indiana families trust Zenith.)",headline:"Cleaner Water for Your Whole Home â Starting Today"}}
531,{id:"sec_benefits",type:"benefits",advanced:{anchor_id:"benefits"},content:{heading:"Why homeowners choose Zenith",items:[{icon:"ð§",title:"Whole-Home Filtration",text:"Softer, cleaner water at every tap â not just the kitchen sink."},{icon:"ð¡ï¸",title:"WQA & BBB Accredited",text:"Certified equipment installed by licensed local technicians."},{icon:"ð§",title:"Free Water Test",text:"We test your water on-site and size the right system for your home."},{icon:"â",title:"5-Star Local Service",text:"Hundreds of happy Indianapolis-area homeowners and counting."},{icon:"ðµ",title:"Flexible Financing",text:"Affordable monthly plans so clean water fits any budget."},{icon:"ð ",title:"Fast Scheduling",text:"Most visits booked within days â pick a time that works for you."}]}},{id:"sec_faq",type:"faq",advanced:{anchor_id:"faq"},content:{heading:"Questions? We have answers.",items:[{q:"How much does a whole-home system cost?",a:"It depends on your water and home size. That is exactly what the free on-site water test determines â we size the right system and give you a local, no-obligation price."},{q:"How long does installation take?",a:"Most standard installs are completed in a single visit, typically a few hours. Your technician will confirm timing when they arrive."},{q:"Do you offer financing?",a:"Yes. We offer flexible monthly financing plans so a whole-home system fits comfortably into your budget."},{q:"Is the water test really free?",a:"Completely free and no-obligation. A technician tests your water on-site and walks you through the results."},{q:"What areas do you serve?",a:"We serve Indianapolis and the surrounding Indiana communities. Enter your ZIP when you request a price and we will confirm coverage."}]}},{id:"sec_cta",type:"cta",advanced:{anchor_id:"book"},content:{headline:"Ready for cleaner water?",sub:"Get your free water test and a local price â no obligation.",cta_primary:{label:"Get my free price",href:"/lp/zenith-booking"},cta_secondary:{label:"Call (317) 690-4172",href:"tel:13176904172"}}},{id:"sec_footer",type:"footer",content:{brand_line:"Zenith Pure Solutions LLC",legal_links:[{label:"Terms",href:md},{label:"Privacy",href:xd}],copyright:"© 2026 Zenith Pure Solutions LLC"}}]},o9=()=>t.jsx(bd,{config:i9}),tm={display:"flex",alignItems:"center",justifyContent:"center",minHeight:"100vh",background:"#0b1622",color:"#94a3b8",fontSize:15,padding:24,textAlign:"center"},a9=()=>{const{slug:e}=di(),[n,r]=g.useState({kind:"loading"});if(g.useEffect(()=>{let i=!1;if(!e){r({kind:"notfound"});return}return(async()=>{r({kind:"loading"});const{data:o,error:a}=await w.from("public_landing_pages").select("slug, published_config").eq("slug",e).maybeSingle();if(!i){if(a){r({kind:"error",message:"This page could not be loaded."});return}if(!o||!o.published_config){r({kind:"notfound"});return}r({kind:"ok",config:o.published_config})}})(),()=>{i=!0}},[e]),n.kind==="loading")return t.jsx("div",{style:tm,children:"Loadingâ¦"});if(n.kind==="error")return t.jsx("div",{style:tm,children:n.message});if(n.kind==="notfound")return t.jsx("div",{style:tm,children:"This page isnât available."});const s=n.config;return t.jsx(bd,{config:s,tokens:s&&s.tokens_override||null})},l9={tokens:Ge,brand:{logoUrl:"/lp/zenith/zenith_logo_trimmed.png",phone:"(317) 690-4172",name:"Zenith Pure Solutions LLC",address:"6951 E 30th St, Suite B, Indianapolis, IN 46219"},capture:{formSlug:"facebook-lp",source:"facebook",consentVersion:yd,termsUrl:md,privacyUrl:xd},offer:"LIMITED-TIME: $500 OFF a whole-home system + FREE water test â when you request your estimate this month",hero:{trustLine:"Trusted by Indianapolis-area homeowners ⢠WQA & BBB Accredited",headPre:"What Would a ",headGold:"Whole-Home Water System",headPost:" Cost for Your Home?",subline:"(Answer the question below to get started!)"},productGrid:{heading:"We'll Design a Custom Solution Based on Your Specific Needs and Budget",headingAccent:"(And Install It Fast!)",items:[{img:"/lp/zenith/system_wholehome.png",label:`City Water 532Filtration Systems`},{img:"/lp/zenith/system_bundle.png",label:`Well Water 533Filtration Systems`},{img:"/lp/zenith/system_ro.png",label:`Under-Sink 534Filtration Systems`}],ctaLabel:"See Local Price"},certBadges:[{img:"/lp/zenith/wqa_sm.png",alt:"WQA Certified"},{img:"/lp/zenith/ewqa_sm.png",alt:"EWQA"}
534,{img:"/lp/zenith/viqua_sm.png",alt:"VIQUA"},{img:"/lp/zenith/enpress_sm.png",alt:"ENPRESS"},{img:"/lp/zenith/bbb_sm.png",alt:"BBB Accredited"}]},B4=e=>{var n;e==null||e.preventDefault(),(n=document.getElementById("top"))==null||n.scrollIntoView({behavior:"smooth"})},Ev=e=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e),Pv=e=>{const n=e.replace(/\D/g,"");return n.length===10||n.length===11&&n.startsWith("1")},fl=({d:e,s:n=Ge.gold,w:r=20})=>t.jsx("svg",{width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:n,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e}),Uf=({label:e,dark:n})=>t.jsxs("div",{style:{textAlign:"center",margin:"6px 0 4px"},children:[t.jsx("a",{href:"#top",onClick:B4,style:{display:"inline-block",background:`linear-gradient(180deg, ${Ge.btn}, ${Ge.btnDk})`,color:"#fff",border:"none",borderRadius:12,padding:"20px 60px",fontSize:"1.5rem",fontWeight:800,cursor:"pointer",fontFamily:Fs,boxShadow:"0 8px 22px rgba(12,125,71,.3)",textDecoration:"none",transition:".15s"},onMouseEnter:r=>r.currentTarget.style.filter="brightness(1.07)",onMouseLeave:r=>r.currentTarget.style.filter="none",children:e}),t.jsx("div",{style:{fontSize:".72rem",color:n?"#a9bccf":Ge.muted,marginTop:12,maxWidth:520,marginLeft:"auto",marginRight:"auto",lineHeight:1.5},children:"Your answers help us prepare accurate local pricing. No obligation to buy."})]}),qv="company_website",d9="/api/leads/capture",Ia={scale:t.jsxs(t.Fragment,{children:[t.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),t.jsx("path",{d:"M8 8h.01M12 8h.01M16 8h.01M8 12h.01M12 12h.01M16 12h.01"})]}),taste:t.jsx("path",{d:"M6 2h12M6 2l1 8a5 5 0 0 0 10 0l1-8M9 22h6M12 15v7"}),pfas:t.jsx("path",{d:"M12 2l8 4v6c0 5-3.5 8.5-8 10-4.5-1.5-8-5-8-10V6z"}),skin:t.jsx("path",{d:"M12 2a5 5 0 0 0-5 5c0 3 5 9 5 9s5-6 5-9a5 5 0 0 0-5-5z"}),own:t.jsx("polyline",{points:"20 6 9 17 4 12"}),rent:t.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})},c9=({capture:e})=>{const[n,r]=g.useState(!1),[s,i]=g.useState(1),[o,a]=g.useState({water_type:"",concern:"",ownership:""}),[l,d]=g.useState({first_name:"",last_name:"",email:"",phone:"",zip:""}),[c,f]=g.useState(!1),[p,u]=g.useState(!1),[h,y]=g.useState(""),[m,b]=g.useState(!1),[A,v]=g.useState(""),x=P=>{a(D=>({...D,water_type:P})),r(!0),i(2)},_=(P,D)=>{const M={...o,[P]:D};a(M),P==="concern"&&i(3),P==="ownership"&&i(4)},j=(P,D)=>d(M=>({...M,[P]:D})),C=!!l.first_name.trim()&&Pv(l.phone)&&(!l.email||Ev(l.email));async function S(){if(v(""),!l.first_name.trim())return v("Please enter your first name.");if(!Pv(l.phone))return v("Please enter a valid 10-digit phone number.");if(l.email&&!Ev(l.email))return v("Please enter a valid email address.");const P={form_slug:e.formSlug,source:e.source,first_name:l.first_name.trim(),last_name:l.last_name.trim(),email:l.email.trim(),phone:l.phone.trim(),address:"",city:"",state:"",zip:l.zip.trim(),water_concern:o.concern,waterType:o.water_type,ownership:o.ownership,sms_opt_in:c,email_opt_in:p,consent_text_version:e.consentVersion,[qv]:h,...d0()};b(!0);try{const D=await fetch(d9,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(P)}),M=await D.json().catch(()=>({}));if(!D.ok&&D.status!==201){v(M.error||"Something went wrong. Please try again."),b(!1);return}i(5)}catch{v("Network error. Please try again.")}b(!1)}const T=P=>({flex:1,height:6,borderRadius:6,background:s>=P?Ge.gold:"rgba(255,255,255,.2)",transition:".3s"}),L={display:"flex",alignItems:"center",gap:12,border:"2px solid rgba(255,255,255,.25)",borderRadius:10,padding:"14px 16px",cursor:"pointer",fontWeight:700,fontSize:"1rem",background:"rgba(255,255,255,.06)",color:"#fff",textAlign:"left",width:"100%",transition:".15s",fontFamily:Fs},E=(P,D)=>{P.currentTarget.style.borderColor=D?Ge.gold:"rgba(255,255,255,.25)",P.currentTarget.style.background=D?"rgba(244,183,49,.12)":"rgba(255,255,255,.06)"},R={background:"none",border:"none",color:"#a9bccf",fontWeight:600,cursor:"pointer",fontSize:".86rem",padding:"10px 4px 0",fontFamily:Fs},N={marginBottom:12},O={display:"block",fontSize:".78rem",fontWeight:800,color:"#dbe6f2",marginBottom:5,textTransform:"uppercase",letterSpacing:".03em"}
534,z={width:"100%",padding:"13px 14px",border:"2px solid rgba(255,255,255,.2)",borderRadius:9,fontSize:"1rem",fontFamily:Fs,background:"#fff",color:Ge.ink,boxSizing:"border-box"};if(!n){const P={background:`linear-gradient(180deg, ${Ge.btn}, ${Ge.btnDk})`,color:"#fff",border:"none",borderRadius:12,padding:"26px 10px",fontSize:"1.5rem",fontWeight:800,cursor:"pointer",fontFamily:Fs,boxShadow:"0 8px 20px rgba(12,125,71,.35)",transition:".15s"};return t.jsxs("div",{style:{border:"2px dashed rgba(255,255,255,.4)",borderRadius:14,padding:"26px 24px 20px",maxWidth:660,margin:"0 auto",background:"rgba(255,255,255,.04)"},children:[t.jsx("h2",{style:{fontSize:"1.4rem",fontWeight:800,marginBottom:20,color:"#fff"},children:"What kind of water do you have?"}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:16},children:[t.jsxs("button",{style:P,onClick:()=>x("City"),children:["City",t.jsx("small",{style:{display:"block",fontSize:".82rem",fontWeight:600,opacity:.9,marginTop:4},children:"Municipal water"})]}),t.jsxs("button",{style:P,onClick:()=>x("Well"),children:["Well",t.jsx("small",{style:{display:"block",fontSize:".82rem",fontWeight:600,opacity:.9,marginTop:4},children:"Private well water"})]})]}),t.jsx("div",{style:{fontSize:".72rem",color:"#a9bccf",marginTop:16,lineHeight:1.5},children:"Your answers help us prepare accurate local pricing. No obligation."})]})}return t.jsxs("div",{style:{border:"2px dashed rgba(255,255,255,.4)",borderRadius:14,padding:"26px 24px",maxWidth:520,margin:"0 auto",background:"rgba(255,255,255,.06)",textAlign:"left"},children:[s<=4&&t.jsxs(t.Fragment,{children:[t.jsx("div",{style:{display:"flex",gap:6,marginBottom:8},children:[1,2,3,4].map(P=>t.jsx("span",{style:T(P)},P))}),t.jsxs("div",{style:{fontSize:".76rem",color:"#a9bccf",fontWeight:700,marginBottom:16,textAlign:"right"},children:["Step ",s," of 4"]})]}),s===2&&t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:"1.2rem",fontWeight:800,marginBottom:4,color:"#fff",textAlign:"center"},children:"What bothers you most about your water?"}),t.jsx("div",{style:{fontSize:".85rem",color:"#c8d6e5",marginBottom:16,textAlign:"center"},children:"We'll price the right solution for it."}),t.jsx("div",{style:{display:"grid",gap:10},children:[["Hard water / scale","Hard water, spots & scale",Ia.scale],["Taste / odor","Bad taste or smell",Ia.taste],["Contaminants / PFAS","Contaminants, PFAS or lead",Ia.pfas],["Dry skin / appliances","Dry skin, hair & appliance damage",Ia.skin]].map(([P,D,M])=>t.jsxs("button",{style:L,onClick:()=>_("concern",P),onMouseEnter:k=>E(k,!0),onMouseLeave:k=>E(k,!1),children:[t.jsx(fl,{d:M})," ",D]},P))}),t.jsx("button",{style:R,onClick:()=>{r(!1),i(1)},children:"â Back"})]}),s===3&&t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:"1.2rem",fontWeight:800,marginBottom:4,color:"#fff",textAlign:"center"},children:"Do you own your home?"}),t.jsx("div",{style:{fontSize:".85rem",color:"#c8d6e5",marginBottom:16,textAlign:"center"},children:"Free estimates are available to homeowners."}),t.jsxs("div",{style:{display:"grid",gap:10},children:[t.jsxs("button",{style:L,onClick:()=>_("ownership","Yes, I own"),onMouseEnter:P=>E(P,!0),onMouseLeave:P=>E(P,!1),children:[t.jsx(fl,{d:Ia.own})," Yes â I own my home"]}),t.jsxs("button",{style:L,onClick:()=>_("ownership","Renting"),onMouseEnter:P=>E(P,!0),onMouseLeave:P=>E(P,!1),children:[t.jsx(fl,{d:Ia.rent})," No â I rent"]})]}),t.jsx("button",{style:R,onClick:()=>i(2),children:"â Back"})]}),s===4&&t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:"1.2rem",fontWeight:800,marginBottom:4,color:"#fff",textAlign:"center"},children:"Where should we send your pricing?"}),t.jsx("div",{style:{fontSize:".85rem",color:"#c8d6e5",marginBottom:16,textAlign:"center"},children:"A local specialist will call to confirm and lock in your offer."}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[t.jsxs("div",{style:N,children:[t.jsx("label",{style:O,children:"First Name"}),t.jsx("input",{style:z,value:l.first_name,onChange:P=>j("first_name",P.target.value),placeholder:"Jane"})]}),t.jsxs("div",{style:N,children:[t.jsx("label",{style:O,children:"Last Name"}),t.jsx("input",{style:z,value:l.last_name,onChange:P=>j("last_name",P.target.value),placeholder:"Smith"})]})]}),t.jsxs("div",{style:N,children:[t.jsx("label",{style:O,children:"Email"}),t.jsx("input",{style:z,type:"email",value:l.email,onChange:P=>j("email",P.target.value),placeholder:"[email protected]"})]}),t.jsxs("div",{style:N,children:[t.jsx("label",{style:O,children:"Phone"}),t.jsx("input",{style:z,type:"tel",value:l.phone,onChange:P=>j("phone",P.target.value),placeholder:"(317) 000-0000"})]}),t.jsxs("div",{style:N,children:[t.jsx("label",{style:O,children:"Zip Code"}),t.jsx("input",{style:z,inputMode:"numeric",value:l.zip,onChange:P=>j("zip",P.target.value),placeholder:"46219"})]}),t.jsx("input",{type:"text",name:qv,tabIndex:-1,autoComplete:"off",value:h,onChange:P=>y(P.target.value),style:{position:"absolute",left:"-9999px",width:1,height:1,opacity:0}
534,"aria-hidden":"true"}),t.jsxs("div",{style:{marginTop:20,display:"flex",flexDirection:"column",gap:10},children:[t.jsxs("label",{style:{display:"flex",alignItems:"flex-start",gap:8,cursor:"pointer"},children:[t.jsx("input",{type:"checkbox",checked:c,onChange:P=>f(P.target.checked),style:{marginTop:3}}),t.jsxs("span",{style:{fontSize:12,color:"#dbe6f2",opacity:.9,lineHeight:1.5},children:["Opt in to receive text updates from Zenith Pure Solutions (optional). You agree to receive appointment reminders and occasional offers by automated text at the number provided, up to 4 msgs/month. Consent is not a condition of purchase. Msg & data rates may apply. Reply HELP for help or call (317) 690-4172. Reply STOP to opt out anytime. View our"," ",t.jsx("a",{href:e.termsUrl,target:"_blank",rel:"noopener noreferrer",style:{color:"#cfe0f0"},children:"Company Terms"})," ","and"," ",t.jsx("a",{href:e.privacyUrl,target:"_blank",rel:"noopener noreferrer",style:{color:"#cfe0f0"},children:"Privacy Policy"}),"."]})]}),t.jsxs("label",{style:{display:"flex",alignItems:"flex-start",gap:8,cursor:"pointer"},children:[t.jsx("input",{type:"checkbox",checked:p,onChange:P=>u(P.target.checked),style:{marginTop:3}}),t.jsx("span",{style:{fontSize:12,color:"#dbe6f2",opacity:.9,lineHeight:1.5},children:"Send me water tips and offers by email. Unsubscribe anytime."})]})]}),A&&t.jsx("div",{style:{color:"#ffb4a2",fontSize:12,marginTop:12},children:A}),t.jsx("button",{onClick:S,disabled:m||!C,style:{width:"100%",background:`linear-gradient(180deg, ${Ge.btn}, ${Ge.btnDk})`,color:"#fff",border:"none",borderRadius:11,padding:17,fontSize:"1.15rem",fontWeight:800,cursor:m||!C?"default":"pointer",fontFamily:Fs,boxShadow:"0 8px 20px rgba(12,125,71,.35)",marginTop:20,opacity:m||!C?.5:1},children:m?"Sendingâ¦":"Get My Local Price (FREE) â"}),t.jsx("button",{style:R,onClick:()=>i(3),children:"â Back"})]}),s===5&&t.jsxs("div",{style:{textAlign:"center",color:"#fff",padding:"8px 0"},children:[t.jsx("div",{style:{width:66,height:66,borderRadius:"50%",background:"rgba(34,164,93,.25)",display:"flex",alignItems:"center",justifyContent:"center",margin:"0 auto 14px"},children:t.jsx(fl,{d:t.jsx("polyline",{points:"20 6 9 17 4 12"}),s:Ge.green,w:34})}),t.jsx("h3",{style:{fontSize:"1.35rem",marginBottom:8},children:"You're all set!"}),t.jsx("p",{style:{color:"#c8d6e5"},children:"A Zenith specialist will call you shortly to prepare your personalized pricing â usually within minutes."}),t.jsxs("div",{style:{marginTop:14,border:`2px dashed ${Ge.gold}`,borderRadius:11,padding:12,background:"rgba(244,183,49,.12)"},children:[t.jsx("b",{style:{color:Ge.gold,fontSize:"1.05rem"},children:"$500 OFF locked in"}),t.jsx("br",{}),t.jsx("span",{style:{fontSize:".85rem",color:"#c8d6e5"},children:"Watch for our call â usually within minutes."})]})]})]})},u9=({logoUrl:e,phone:n})=>t.jsx("header",{style:{background:"#fff",borderBottom:`1px solid ${Ge.line}`},children:t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 20px",maxWidth:1140,margin:"0 auto"},children:[t.jsx("img",{src:e,alt:"Zenith Pure Solutions",style:{height:38,width:"auto",display:"block"}}),t.jsxs("a",{href:`tel:1${n.replace(/\D/g,"")}`,style:{color:Ge.navy,fontWeight:800,fontSize:"1.05rem",textDecoration:"none",whiteSpace:"nowrap"},children:["Call ",t.jsx("span",{style:{color:Ge.tealDk},children:n})]})]})}),p9=({brand:e,hero:n,offer:r,capture:s})=>t.jsxs(t.Fragment,{children:[t.jsx("div",{style:{background:Ge.gold,color:Ge.navy,fontWeight:800,textAlign:"center",fontSize:".92rem",padding:"10px 16px",lineHeight:1.4},children:r}),t.jsx(u9,{logoUrl:e.logoUrl,phone:e.phone}),t.jsxs("section",{id:"top",style:{position:"relative",background:Ge.navy,color:"#fff",padding:"44px 0 54px",overflow:"hidden"},children:[t.jsx("div",{style:{position:"absolute",inset:0,background:"linear-gradient(180deg, rgba(13,43,78,.78), rgba(10,32,56,.88)), radial-gradient(circle at 30% 20%, rgba(23,162,184,.25), transparent 55%)"}}),t.jsxs("div",{style:{position:"relative",textAlign:"center",maxWidth:940,margin:"0 auto",padding:"0 20px"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",gap:8,fontSize:".9rem",color:"#c8d6e5",marginBottom:14},children:[t.jsx("span",{style:{color:Ge.gold,letterSpacing:2},children:"â â â â â "})," ",n.trustLine]}),t.jsxs("h1",{style:{fontSize:"clamp(1.9rem, 5vw, 2.5rem)",lineHeight:1.14,fontWeight:800,maxWidth:820,margin:"0 auto 8px"},children:[n.headPre,t.jsx("span",{style:{color:Ge.gold},children:n.headGold}),n.headPost]}),t.jsx("p",{style:{fontSize:"1.05rem",color:"#dbe6f2",fontStyle:"italic",marginBottom:26},children:n.subline}),t.jsx(c9,{capture:s})]})]})]}),h9=({heading:e,headingAccent:n,items:r,ctaLabel:s})=>t.jsx("section",{style:{padding:"56px 0"},children:t.jsxs("div",{style:{maxWidth:1140,margin:"0 auto",padding:"0 20px"},children:[t.jsxs("div",{style:{textAlign:"center",fontSize:"2rem",color:Ge.navy,fontWeight:800,lineHeight:1.2,maxWidth:760,margin:"0 auto 34px"},children:[e," ",t.jsx("span",{style:{color:Ge.tealDk},children:n})]}),t.jsx("div",{className:"lp-systems",children:r.map((i,o)=>t.jsxs("div",{style:{textAlign:"center"},children:[t.jsx("div",{className:"lp-sys-imgbox",style:{background:"#fff",borderRadius:12,height:240,display:"flex",alignItems:"flex-end",justifyContent:"center",padding:14,boxShadow:"0 6px 18px rgba(10,32,56,.08)"},children:t.jsx("img",{src:i.img,alt:i.label.replace(` 535`," "),style:{maxHeight:210,width:"auto"}})}),t.jsx("h3",{style:{color:Ge.navy,fontSize:"1.15rem",fontWeight:800,marginTop:14,lineHeight:1.25,whiteSpace:"pre-line"},children:i.label})]},o))}),t.jsx(Uf,{label:s})]})}),f9=({logoUrl:e})=>t.jsx("section",{style:{padding:"56px 0",background:Ge.bg},children:t.jsxs("div",{style:{maxWidth:1140,margin:"0 auto",padding:"0 20px",textAlign:"center"},children:[t.jsx("img",{src:e,alt:"Zenith Pure Solutions",style:{height:40,width:"auto",margin:"0 auto 14px"}}),t.jsx("div",{style:{fontSize:"1.05rem",fontStyle:"italic",color:Ge.muted,fontWeight:700,marginBottom:6},children:"Local, Certified & Backed by a 10-Year Warranty"}),t.jsxs("div",{style:{fontSize:"1.7rem",color:Ge.navy,fontWeight:800,lineHeight:1.2,maxWidth:760,margin:"18px auto 26px"},children:["Affordable Whole-Home and Under-Sink Water Solutions from Zenith â ",t.jsx("span",{style:{color:Ge.tealDk},children:"Tested Free, Priced Honestly"})]}),t.jsx(Uf,{label:"Get Pricing Now (FREE)"}),t.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:8,marginTop:18,color:Ge.muted,fontSize:".9rem"},children:[t.jsx("span",{style:{color:"#00b67a",letterSpacing:1,fontSize:"1.2rem"},children:"â â â â â "})," Rated 5 stars by local homeowners ⢠WQA & BBB Accredited"]})]})}),g9=[[t.jsx("path",{d:"M4 3h16M6 3v4a4 4 0 0 0 8 0V3M10 11v4M8 15h4M7 21h6l-1-6H8z"}),`Budget-Friendly 536Under-Sink Option`],[t.jsx("path",{d:"M14.7 6.3a4 4 0 0 0-5.4 5.4l-6 6a1.5 1.5 0 0 0 2 2l6-6a4 4 0 0 0 5.4-5.4l-2.3 2.3-2-2z"}),`Fast Expert
537Installation`],[t.jsx("path",{d:"M12 2.7C12 2.7 5 10 5 15a7 7 0 0 0 14 0c0-5-7-12.3-7-12.3z"}),`Customized Based 538on Your Water`],[t.jsxs(t.Fragment,{children:[t.jsx("circle",{cx:"12",cy:"12",r:"4"}),t.jsx("path",{d:"M12 2v3M12 19v3M2 12h3M19 12h3M5 5l2 2M17 17l2 2M19 5l-2 2M7 17l-2 2"})]}),`UV Defense Protects 539Against Bacteria/Viruses`]],m9=()=>t.jsx("section",{style:{padding:"56px 0"},children:t.jsxs("div",{style:{maxWidth:1140,margin:"0 auto",padding:"0 20px"},children:[t.jsx("div",{className:"lp-proof",children:g9.map(([e,n],r)=>t.jsxs("div",{style:{textAlign:"center"},children:[t.jsx("div",{style:{borderRadius:12,background:"linear-gradient(135deg,#eaf7fa,#dbeef3)",height:210,display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 6px 18px rgba(10,32,56,.1)"},children:t.jsx(fl,{d:e,s:Ge.tealDk,w:78})}),t.jsx("h3",{style:{color:Ge.navy,fontSize:"1.2rem",fontWeight:800,marginTop:14,lineHeight:1.25,whiteSpace:"pre-line"},children:n})]},r))}),t.jsx(Uf,{label:"See Local Price"})]})}),x9=[[t.jsx("path",{d:"M9 2v6l-5 9a2 2 0 0 0 1.8 3h12.4A2 2 0 0 0 20 17l-5-9V2M9 2h6M8 14h8"}),"Free Lab Test","Know exactly what's in your water"],[t.jsxs(t.Fragment,{children:[t.jsx("path",{d:"M12 2l8 4v6c0 5-3.5 8.5-8 10-4.5-1.5-8-5-8-10V6z"}),t.jsx("polyline",{points:"9 12 11 14 15 10"})]}),"10-Yr Warranty","Maintenance included"],[t.jsxs(t.Fragment,{children:[t.jsx("circle",{cx:"12",cy:"12",r:"9"}),t.jsx("path",{d:"M12 7v10"})]}),"Honest Pricing","Only pay for what you need"],[t.jsxs(t.Fragment,{children:[t.jsx("path",{d:"M12 21s-7-5.2-7-11a7 7 0 0 1 14 0c0 5.8-7 11-7 11z"}),t.jsx("circle",{cx:"12",cy:"10",r:"2.5"})]}),"Local Team","Real people, right here"]],y9=()=>t.jsx("section",{style:{padding:"56px 0",background:Ge.navy,color:"#fff"},children:t.jsxs("div",{style:{maxWidth:1140,margin:"0 auto",padding:"0 20px"},children:[t.jsx("div",{style:{textAlign:"center",fontSize:"2rem",fontWeight:800,lineHeight:1.2,margin:"0 auto 34px"},children:"Why Homeowners Choose Zenith"}),t.jsx("div",{className:"lp-chips",children:x9.map(([e,n,r],s)=>t.jsxs("div",{style:{background:"rgba(255,255,255,.06)",border:"1px solid rgba(255,255,255,.14)",borderRadius:12,padding:"20px 14px",textAlign:"center"},children:[t.jsx("div",{style:{width:46,height:46,margin:"0 auto 12px",borderRadius:11,background:"rgba(23,162,184,.2)",display:"flex",alignItems:"center",justifyContent:"center"},children:t.jsx(fl,{d:e,s:"#8fe3f0",w:24})}),t.jsx("h4",{style:{fontSize:"1rem",marginBottom:5},children:n}),t.jsx("p",{style:{fontSize:".83rem",color:"#c8d6e5"},children:r})]},s))}),t.jsx(Uf,{label:"Get My Free Pricing",dark:!0})]})}),b9=({badges:e})=>t.jsx("section",{style:{padding:"30px 0",background:"#fff",borderTop:`1px solid ${Ge.line}`,borderBottom:`1px solid ${Ge.line}`},children:t.jsxs("div",{style:{maxWidth:1140,margin:"0 auto",padding:"0 20px",display:"flex",alignItems:"center",justifyContent:"center",gap:34,flexWrap:"wrap"},children:[t.jsx("div",{style:{width:"100%",textAlign:"center",color:Ge.muted,fontSize:".78rem",fontWeight:700,letterSpacing:".08em",textTransform:"uppercase",marginBottom:4},children:"Certified & Accredited"}),e.map((n,r)=>t.jsx("img",{src:n.img,alt:n.alt,style:{height:46,width:"auto"}},r))]})}),A9=({brand:e,capture:n})=>t.jsx("footer",{style:{background:"#e9eef3",color:Ge.muted,padding:"30px 0",fontSize:".85rem",textAlign:"center"},children:t.jsxs("div",{style:{maxWidth:1140,margin:"0 auto",padding:"0 20px"},children:[t.jsx("img",{src:e.logoUrl,alt:"Zenith Pure Solutions",style:{height:34,width:"auto",margin:"0 auto 12px"}}),t.jsxs("div",{style:{marginBottom:5},children:[e.name," | ",e.address," | ",e.phone]}),t.jsxs("div",{style:{marginBottom:5},children:[t.jsx("a",{href:"#top",onClick:B4,style:{color:Ge.tealDk,textDecoration:"none"},children:"Home"})," · ",t.jsx("a",{href:`tel:1${e.phone.replace(/\D/g,"")}`,style:{color:Ge.tealDk,textDecoration:"none"},children:"Contact"})," · ",t.jsx("a",{href:n.privacyUrl,target:"_blank",rel:"noopener noreferrer",style:{color:Ge.tealDk,textDecoration:"none"},children:"Privacy"})," · ",t.jsx("a",{href:n.termsUrl,target:"_blank",rel:"noopener noreferrer",style:{color:Ge.tealDk,textDecoration:"none"},children:"Terms"})]}),t.jsxs("div",{style:{fontSize:".78rem",marginTop:8},children:["© ",new Date().getFullYear()," ",e.name,". $500 offer valid on qualifying installs; one per household; no obligation."]})]})}),v9=({config:e=l9})=>{const{brand:n,capture:r,offer:s,hero:i,productGrid:o,certBadges:a}=e;return t.jsxs("div",{style:{fontFamily:Fs,color:Ge.ink,background:"#fff",lineHeight:1.5},children:[t.jsx("style",{children:` 540.lp-systems{display:grid;grid-template-columns:repeat(3,1fr);gap:20px;margin-bottom:34px;align-items:end} 541.lp-proof{display:grid;grid-template-columns:repeat(2,1fr);gap:26px 40px;max-width:760px;margin:0 auto 34px}
542.lp-chips{display:grid;grid-template-columns:repeat(4,1fr);gap:16px;max-width:880px;margin:0 auto 30px} 543@media(max-width:720px){.lp-systems{grid-template-columns:1fr;gap:16px}.lp-chips{grid-template-columns:1fr 1fr}.lp-sys-imgbox{height:auto!important}} 544@media(max-width:560px){.lp-proof{grid-template-columns:1fr}} 545@media(max-width:430px){.lp-chips{grid-template-columns:1fr}} 546`}),t.jsx(p9,{brand:n,hero:i,offer:s,capture:r}),t.jsx(h9,{...o}),t.jsx(f9,{logoUrl:n.logoUrl}),t.jsx(m9,{}),t.jsx(y9,{}),t.jsx(b9,{badges:a}),t.jsx(A9,{brand:n,capture:r})]})};async function _9(e){try{let n=w.from("checklist_templates").select("*").order("created_at",{ascending:!0});e!=null&&e.type,e==null||e.system_type,e==null||e.is_active;const{data:r,error:s}=await n;if(s)throw s;return r||[]}catch(n){return console.error("fetchTemplates error:",n),[]}}async function j9(e){try{const{data:n,error:r}=await w.from("checklist_templates").select("*").eq("id",e).single();if(r)throw r;if(!n)return null;const{data:s,error:i}=await w.from("checklist_sections").select("*").eq("template_id",e).eq("is_active",!0).order("sort_order",{ascending:!0});if(i)throw i;const o=(s||[]).map(d=>d.id);let a=[];if(o.length>0){const{data:d,error:c}=await w.from("checklist_items").select("*").in("section_id",o).eq("is_active",!0).order("sort_order",{ascending:!0});if(c)throw c;a=d||[]}const l=(s||[]).map(d=>({...d,items:a.filter(c=>c.section_id===d.id)}));return{...n,sections:l}}catch(n){return console.error("fetchTemplateWithSections error:",n),null}}async function w9(e){try{const{data:n,error:r}=await w.from("checklist_templates").insert({name:e.name,checklist_type:e.type,system_type:e.system_type}).select().single();if(r)throw r;return n}catch(n){return console.error("createTemplate error:",n),null}}async function Dv(e,n){try{const r={...n};r.type&&(r.checklist_type=r.type,delete r.type);const{data:s,error:i}=await w.from("checklist_templates").update(r).eq("id",e).select().single();if(i)throw i;return s}catch(r){return console.error("updateTemplate error:",r),null}}async function S9(e){try{const{error:n}=await w.from("checklist_templates").delete().eq("id",e);if(n)throw n;return!0}catch(n){return console.error("deleteTemplate error:",n),!1}}async function k9(e){try{const{data:n,error:r}=await w.from("checklist_sections").insert({template_id:e.template_id,title:e.title,letter_label:e.letter_label||null,is_conditional:e.is_conditional||!1,condition_label:e.condition_label||null,sort_order:e.sort_order||0}).select().single();if(r)throw r;return n}catch(n){return console.error("createSection error:",n),null}}async function Ov(e,n){try{const{data:r,error:s}=await w.from("checklist_sections").update(n).eq("id",e).select().single();if(s)throw s;return r}catch(r){return console.error("updateSection error:",r),null}}async function C9(e){try{const{error:n}=await w.from("checklist_sections").delete().eq("id",e);if(n)throw n;return!0}catch(n){return console.error("deleteSection error:",n),!1}}async function Iv(e){try{for(const n of e){const{error:r}=await w.from("checklist_sections").update({sort_order:n.sort_order}).eq("id",n.id);if(r)throw r}return!0}catch(n){return console.error("reorderSections error:",n),!1}}async function T9(e){try{const{data:n,error:r}=await w.from("checklist_items").insert({section_id:e.section_id,item_text:e.item_text,field_type:e.field_type||"checkbox",options:e.options||[],is_required:e.is_required||!1,requires_photo:e.requires_photo||!1,sort_order:e.sort_order||0}).select().single();if(r)throw r;return n}catch(n){return console.error("createItem error:",n),null}}async function nm(e,n){try{const{data:r,error:s}=await w.from("checklist_items").update(n).eq("id",e).select().single();if(s)throw s;return r}catch(r){return console.error("updateItem error:",r),null}}async function z9(e){try{const{error:n}=await w.from("checklist_items").delete().eq("id",e);if(n)throw n;return!0}catch(n){return console.error("deleteItem error:",n),!1}}async function Lv(e){try{for(const n of e){const{error:r}=await w.from("checklist_items").update({sort_order:n.sort_order}).eq("id",n.id);if(r)throw r}return!0}catch(n){return console.error("reorderItems error:",n),!1}}const N9={installer:"ð§ Installer Checklist",handover:"ð¤ Customer Handover",site_survey:"ð Site Survey"},U4={ro:"Reverse Osmosis",softener:"Water Softener",whole_home:"Whole Home"},R9={checkbox:"âï¸ Checkbox",text:"ð Text",dropdown:"ð Dropdown",photo:"ð· Photo",number:"ð¢ Number"},rm={checkbox:"#4ade80",text:"#60a5fa",dropdown:"#a78bfa",photo:"#f59e0b",number:"#22d3ee"},E9={background:"#162232",border:"1px solid #1e3a4f",borderRadius:14,overflow:"hidden"},vo={textAlign:"left",padding:"10px 16px",fontSize:10,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.06em",color:"#64748b",background:"rgba(255,255,255,0.03)",borderBottom:"1px solid #1e3a4f"},_o={padding:"11px 16px",borderBottom:"1px solid rgba(255,255,255,0.04)",fontSize:13,color:"#e2e8f0"},Is={width:"100%",boxSizing:"border-box",background:"rgba(255,255,255,0.05)",border:"1px solid #1e3a4f",borderRadius:10,padding:"9px 14px",color:"#e2e8f0",fontSize:13,outline:"none"},Ei={display:"block",fontSize:11,color:"#64748b",marginBottom:6},vy={padding:"8px 20px",borderRadius:10,fontSize:13,fontWeight:700,color:"#fff",background:"linear-gradient(135deg, #8b5cf6, #7c3aed)",border:"none",cursor:"pointer"},_y={padding:"8px 16px",borderRadius:10,fontSize:13,color:"#64748b",cursor:"pointer",background:"rgba(255,255,255,0.04)",border:"1px solid #1e3a4f"};function P9(){const[e,n]=g.useState([]),[r,s]=g.useState(!0),[i,o]=g.useState(null),[a,l]=g.useState(!1),[d,c]=g.useState(null),[f,p]=g.useState(""),[u,h]=g.useState("installer"),[y,m]=g.useState(""),[b,A]=g.useState(!1);g.useEffect(()=>
546{v()},[]);async function v(){s(!0);const R=await _9();n(R),s(!1)}function x(){c(null),p(""),h("installer"),m(""),l(!0)}function _(R){c(R),p(R.name),h(R.type),m(R.system_type||""),l(!0)}async function j(){if(!f.trim())return;A(!0);const R=y||null;d?await Dv(d.id,{name:f.trim(),type:u,system_type:R}):await w9({name:f.trim(),type:u,system_type:R}),l(!1),c(null),A(!1),v()}async function C(R){confirm(`Delete "${R.name}" and all its sections/items? This cannot be undone.`)&&(await S9(R.id),(i==null?void 0:i.id)===R.id&&o(null),v())}async function S(R){await Dv(R.id,{is_active:!R.is_active}),n(N=>N.map(O=>O.id===R.id?{...O,is_active:!O.is_active}:O))}async function T(R){const N=await j9(R.id);o(N)}const L=e.filter(R=>R.is_active).length,E={installer:e.filter(R=>R.checklist_type==="installer"),handover:e.filter(R=>R.checklist_type==="handover"),site_survey:e.filter(R=>R.checklist_type==="site_survey")};return t.jsxs("div",{style:{display:"flex",height:"100%",gap:0},children:[t.jsxs("div",{style:{width:i?280:360,flexShrink:0,background:"#162232",border:"1px solid #1e3a4f",borderRadius:i?"14px 0 0 14px":14,display:"flex",flexDirection:"column",overflow:"hidden"},children:[t.jsx("div",{style:{padding:"14px 16px",borderBottom:"1px solid #1e3a4f"},children:t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[t.jsxs("div",{children:[t.jsx("div",{style:{color:"#e2e8f0",fontWeight:700,fontSize:14},children:"Checklist Templates"}),t.jsxs("div",{style:{color:"#64748b",fontSize:11,marginTop:3},children:[e.length," total · ",L," active"]})]}),t.jsx("button",{onClick:x,style:{padding:"6px 14px",borderRadius:8,fontSize:12,fontWeight:700,background:"linear-gradient(135deg, #8b5cf6, #7c3aed)",color:"#fff",border:"none",cursor:"pointer"},children:"+ Add"})]})}),a&&t.jsxs("div",{style:{padding:16,borderBottom:"1px solid #1e3a4f",background:"rgba(139,92,246,0.04)"},children:[t.jsx("div",{style:{fontSize:12,fontWeight:700,color:"#e2e8f0",marginBottom:12},children:d?"Edit Template":"New Template"}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[t.jsxs("div",{children:[t.jsx("label",{style:Ei,children:"Name"}),t.jsx("input",{type:"text",value:f,onChange:R=>p(R.target.value),placeholder:"e.g., RO Installer Checklist",style:Is})]}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8},children:[t.jsxs("div",{children:[t.jsx("label",{style:Ei,children:"Type"}),t.jsxs("select",{value:u,onChange:R=>h(R.target.value),style:Is,children:[t.jsx("option",{value:"installer",style:{background:"#0f1923"},children:"Installer"}),t.jsx("option",{value:"handover",style:{background:"#0f1923"},children:"Handover"}),t.jsx("option",{value:"site_survey",style:{background:"#0f1923"},children:"Site Survey"})]})]}),t.jsxs("div",{children:[t.jsx("label",{style:Ei,children:"System Type"}),t.jsxs("select",{value:y,onChange:R=>m(R.target.value),style:Is,children:[t.jsx("option",{value:"",style:{background:"#0f1923"},children:"All Systems"}),t.jsx("option",{value:"ro",style:{background:"#0f1923"},children:"RO"}),t.jsx("option",{value:"softener",style:{background:"#0f1923"},children:"Softener"}),t.jsx("option",{value:"whole_home",style:{background:"#0f1923"},children:"Whole Home"})]})]})]}),t.jsxs("div",{style:{display:"flex",gap:8},children:[t.jsx("button",{onClick:()=>{l(!1),c(null)},style:_y,children:"Cancel"}),t.jsx("button",{onClick:j,disabled:b||!f.trim(),style:{...vy,opacity:b||!f.trim()?.5:1,cursor:b||!f.trim()?"not-allowed":"pointer"},children:b?"Saving...":d?"Update":"Create"})]})]})]}),t.jsx("div",{style:{flex:1,overflowY:"auto"},children:r?t.jsx("div",{style:{textAlign:"center",color:"#64748b",padding:48},children:"Loading..."}):e.length===0?t.jsxs("div",{style:{textAlign:"center",padding:"48px 16px"},children:[t.jsx("div",{style:{fontSize:36,marginBottom:12},children:"ð"}),t.jsx("p",{style:{color:"#64748b",fontSize:13},children:"No checklist templates yet."})]}):["installer","handover","site_survey"].map(R=>{const N=E[R];return N.length===0?null:t.jsxs("div",{children:[t.jsx("div",{style:{padding:"10px 16px",fontSize:10,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.06em",color:"#64748b",background:"rgba(255,255,255,0.02)",borderBottom:"1px solid #1e3a4f"},children:N9[R]}),N.map(O=>{const z=(i==null?void 0:i.id)===O.id;return t.jsx("div",{onClick:()=>T(O),style:{padding:"12px 16px",cursor:"pointer",borderBottom:"1px solid rgba(255,255,255,0.04)",borderLeft:z?"3px solid #8b5cf6":"3px solid transparent",background:z?"rgba(139,92,246,0.08)":"transparent",opacity:O.is_active?1:.4},onMouseEnter:P=>{z||(P.currentTarget.style.background="rgba(255,255,255,0.02)")},onMouseLeave:P=>{z||(P.currentTarget.style.background="transparent")},children:t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsx("div",{style:{color:"#e2e8f0",fontWeight:600,fontSize:13},children:O.name}),t.jsx("div",{style:{fontSize:11,color:"#64748b",marginTop:3},children:O.system_type?U4[O.system_type]:"All Systems"})]}),t.jsxs("div",{style:{display:"flex",gap:6,flexShrink:0,alignItems:"center"},children:[t.jsx("button",{onClick:P=>{P.stopPropagation(),S(O)},style:{fontSize:10,padding:"2px 8px",borderRadius:20,cursor:"pointer",background:O.is_active?"rgba(74,222,128,0.12)":"rgba(100,116,139,0.12)",color:O.is_active?"#4ade80":"#64748b",border:`1px solid ${O.is_active?"rgba(74,222,128,0.25)":"rgba(100,116,139,0.2)"}`},children:O.is_active?"Active":"Off"}),t.jsx("button",{onClick:P=>{P.stopPropagation(),_(O)},style:{fontSize:11,color:"#60a5fa",background:"none",border:"none",cursor:"pointer"},children:"âï¸"}),t.jsx("button",{onClick:P=>{P.stopPropagation(),C(O)},style:{fontSize:11,color:"#f87171",background:"none",border:"none",cursor:"pointer"},children:"ð"})]})]})},O.id)})]},R)})})]}),i?t.jsx(q9,{template:i,onRefresh:()=>T(i)}):t.jsx("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",background:"#0f1923",border:"1px solid #1e3a4f",borderLeft:"none",borderRadius:"0 14px 14px 0"},children:t.jsxs("div",{style:{textAlign:"center"},children:[t.jsx("div",{style:{fontSize:48,marginBottom:12,opacity:.4},children:"ð"}),t.jsx("p",{style:{color:"#64748b",fontSize:13},children:"Select a template to manage its sections and items"})]})})]})}function q9({template:e,onRefresh:n}){const r=e.sections||[],[s,i]=g.useState(r.length>0?r[0].id:null),[o,a]=g.useState(!1),[l,d]=g.useState(null),[c,f]=g.useState(""),[p,u]=g.useState(""),[h,y]=g.useState(!1),[m,b]=g.useState(""),[A,v]=g.useState(!1),[x,_]=g.useState(!1),[j,C]=g.useState(null),[S,T]=g.useState(""),[L,E]=g.useState(""),[R,N]=g.useState("checkbox"),[O,z]=g.useState(""),[P,D]=g.useState(!1),[M,k]=g.useState(!1),[q,$]=g.useState(!1);function I(){d(null),f(""),u(""),y(!1),b(""),a(!0)}function B(F){d(F),f(F.title),u(F.letter_label||""),y(F.is_conditional),b(F.condition_label||""),a(!0)}async function J(){if(c.trim()){if(v(!0),l)await Ov(l.id,{title:c.trim(),letter_label:p.trim()||null,is_conditional:h,condition_label:h&&m.trim()||null});else{const F=r.reduce((K,Z)=>Math.max(K,Z.sort_order),0);await k9({template_id:e.id,title:c.trim(),letter_label:p.trim()||null,is_conditional:h,condition_label:h&&m.trim()||null,sort_order:F+1})}a(!1),d(null),v(!1),n()}}async function ae(F){confirm(`Delete section "${F.title}" and all its items?`)&&(await C9(F.id),s===F.id&&i(null),n())}async function te(F){await Ov(F.id,{is_active:!F.is_active}),n()}async function U(F){if(F===0)return;const K=[{id:r[F].id,sort_order:r[F-1].sort_order},{id:r[F-1].id,sort_order:r[F].sort_order}];await Iv(K),n()}
546async function W(F){if(F>=r.length-1)return;const K=[{id:r[F].id,sort_order:r[F+1].sort_order},{id:r[F+1].id,sort_order:r[F].sort_order}];await Iv(K),n()}function G(F){C(null),T(F),E(""),N("checkbox"),z(""),D(!1),k(!1),_(!0)}function V(F,K){C(F),T(K),E(F.item_text),N(F.field_type),z(Array.isArray(F.options)?F.options.join(", "):""),D(F.is_required),k(F.requires_photo),_(!0)}async function ee(){if(!L.trim())return;$(!0);const F=R==="dropdown"?O.split(",").map(Z=>Z.trim()).filter(Boolean):[],K=M||R==="photo";if(j)await nm(j.id,{item_text:L.trim(),field_type:R,options:F,is_required:P,requires_photo:K});else{const Z=r.find(Y=>Y.id===S),ie=((Z==null?void 0:Z.items)||[]).reduce((Y,X)=>Math.max(Y,X.sort_order),0);await T9({section_id:S,item_text:L.trim(),field_type:R,options:F,is_required:P,requires_photo:K,sort_order:ie+1})}_(!1),C(null),$(!1),n()}async function re(F){confirm(`Delete "${F.item_text}"?`)&&(await z9(F.id),n())}async function Q(F){await nm(F.id,{is_active:!F.is_active}),n()}async function oe(F){await nm(F.id,{is_required:!F.is_required}),n()}async function ne(F,K){if(K===0)return;const Z=[{id:F[K].id,sort_order:F[K-1].sort_order},{id:F[K-1].id,sort_order:F[K].sort_order}];await Lv(Z),n()}async function ge(F,K){if(K>=F.length-1)return;const Z=[{id:F[K].id,sort_order:F[K+1].sort_order},{id:F[K+1].id,sort_order:F[K].sort_order}];await Lv(Z),n()}const be=r.reduce((F,K)=>{var Z;return F+(((Z=K.items)==null?void 0:Z.length)||0)},0),we=r.reduce((F,K)=>{var Z;return F+(((Z=K.items)==null?void 0:Z.filter(ie=>ie.is_required).length)||0)},0);return t.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",background:"#0f1923",border:"1px solid #1e3a4f",borderLeft:"none",borderRadius:"0 14px 14px 0"},children:[t.jsxs("div",{style:{padding:"14px 20px",borderBottom:"1px solid #1e3a4f",background:"rgba(255,255,255,0.02)",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[t.jsxs("div",{children:[t.jsx("div",{style:{color:"#e2e8f0",fontWeight:700,fontSize:14},children:e.name}),t.jsxs("div",{style:{color:"#64748b",fontSize:11,marginTop:3},children:[r.length," sections · ",be," items · ",we," required",e.system_type&&t.jsx("span",{style:{marginLeft:8,fontSize:10,padding:"1px 8px",borderRadius:10,background:"rgba(139,92,246,0.1)",color:"#a78bfa",border:"1px solid rgba(139,92,246,0.25)"},children:U4[e.system_type]})]})]}),t.jsx("button",{onClick:I,style:{padding:"6px 14px",borderRadius:8,fontSize:12,fontWeight:700,background:"linear-gradient(135deg, #3b82f6, #2563eb)",color:"#fff",border:"none",cursor:"pointer"},children:"+ Add Section"})]}),o&&t.jsxs("div",{style:{padding:16,borderBottom:"1px solid #1e3a4f",background:"rgba(59,130,246,0.04)"},children:[t.jsx("div",{style:{fontSize:12,fontWeight:700,color:"#e2e8f0",marginBottom:12},children:l?"Edit Section":"New Section"}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 80px",gap:8},children:[t.jsxs("div",{children:[t.jsx("label",{style:Ei,children:"Section Title"}),t.jsx("input",{type:"text",value:c,onChange:F=>f(F.target.value),placeholder:"e.g., Pre-Installation",style:Is})]}),t.jsxs("div",{children:[t.jsx("label",{style:Ei,children:"Label"}),t.jsx("input",{type:"text",value:p,onChange:F=>u(F.target.value),placeholder:"A",maxLength:3,style:Is})]})]}),t.jsxs("div",{children:[t.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer"},children:[t.jsx("input",{type:"checkbox",checked:h,onChange:F=>y(F.target.checked),style:{width:15,height:15,accentColor:"#f59e0b"}}),t.jsx("span",{style:{fontSize:13,color:"#e2e8f0"},children:"Conditional section"})]}),h&&t.jsx("input",{type:"text",value:m,onChange:F=>b(F.target.value),placeholder:"e.g., If Pure Start applicable",style:{...Is,marginTop:8}})]}),t.jsxs("div",{style:{display:"flex",gap:8},children:[t.jsx("button",{onClick:()=>{a(!1),d(null)},style:_y,children:"Cancel"}),t.jsx("button",{onClick:J,disabled:A||!c.trim(),style:{...vy,background:"linear-gradient(135deg, #3b82f6, #2563eb)",opacity:A||!c.trim()?.5:1},children:A?"Saving...":l?"Update":"Add Section"})]})]})]}),x&&t.jsxs("div",{style:{padding:16,borderBottom:"1px solid #1e3a4f",background:"rgba(74,222,128,0.04)"},children:[t.jsx("div",{style:{fontSize:12,fontWeight:700,color:"#e2e8f0",marginBottom:12},children:j?"Edit Item":"New Item"}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[t.jsxs("div",{children:[t.jsx("label",{style:Ei,children:"Item Text"}),t.jsx("input",{type:"text",value:L,onChange:F=>E(F.target.value),placeholder:"e.g., Verify water supply is turned off",style:Is})]}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8},children:[t.jsxs("div",{children:[t.jsx("label",{style:Ei,children:"Field Type"}),t.jsxs("select",{value:R,onChange:F=>{N(F.target.value),F.target.value==="photo"&&k(!0)},style:Is,children:[t.jsx("option",{value:"checkbox",style:{background:"#0f1923"},children:"Checkbox"}),t.jsx("option",{value:"text",style:{background:"#0f1923"},children:"Text"}),t.jsx("option",{value:"dropdown",style:{background:"#0f1923"},children:"Dropdown"}),t.jsx("option",{value:"photo",style:{background:"#0f1923"},children:"Photo"}),t.jsx("option",{value:"number",style:{background:"#0f1923"},children:"Number"})]})]}),t.jsxs("div",{style:{display:"flex",alignItems:"flex-end",gap:16,paddingBottom:4},children:[t.jsxs("label",{style:{display:"flex",alignItems:"center",gap:6,cursor:"pointer"},children:[t.jsx("input",{type:"checkbox",checked:P,onChange:F=>D(F.target.checked),style:{width:14,height:14,accentColor:"#f87171"}}),t.jsx("span",{style:{fontSize:12,color:"#e2e8f0"},children:"Required"})]}),t.jsxs("label",{style:{display:"flex",alignItems:"center",gap:6,cursor:"pointer"},children:[t.jsx("input",{type:"checkbox",checked:M,onChange:F=>k(F.target.checked),style:{width:14,height:14,accentColor:"#f59e0b"}}),t.jsx("span",{style:{fontSize:12,color:"#e2e8f0"},children:"Photo"})]})]})]}),R==="dropdown"&&t.jsxs("div",{children:[t.jsxs("label",{style:Ei,children:["Options ",t.jsx("span",{style:{color:"#334155"},children:"(comma separated)"})]}),t.jsx("input",{type:"text",value:O,onChange:F=>z(F.target.value),placeholder:"e.g., Pass, Fail, N/A",style:Is})]}),t.jsxs("div",{style:{display:"flex",gap:8},children:[t.jsx("button",{onClick:()=>{_(!1),C(null)},style:_y,children:"Cancel"}),t.jsx("button",{onClick:ee,disabled:q||!L.trim(),style:{...vy,background:"linear-gradient(135deg, #4ade80, #22c55e)",opacity:q||!L.trim()?.5:1},children:q?"Saving...":j?"Update":"Add Item"})]})]})]}),t.jsx("div",{style:{flex:1,overflowY:"auto",padding:"0"},children:r.length===0?t.jsxs("div",{style:{textAlign:"center",padding:"48px 20px"},children:[t.jsx("div",{style:{fontSize:36,marginBottom:12,opacity:.4},children:"ð"}),t.jsx("p",{style:{color:"#64748b",fontSize:13},children:'No sections yet. Click "+ Add Section" to get started.'})]}):r.map((F,K)=>{const Z=s===F.id,ie=F.items||[];return t.jsxs("div",{style:{borderBottom:"1px solid #1e3a4f"},children:[t.jsxs("div",{onClick:()=>i(Z?null:F.id),style:{display:"flex",alignItems:"center",gap:12,padding:"12px 20px",cursor:"pointer",background:Z?"rgba(255,255,255,0.02)":"transparent",opacity:F.is_active?1:.4},onMouseEnter:Y=>{Z||(Y.currentTarget.style.background="rgba(255,255,255,0.015)")},onMouseLeave:Y=>{Z||(Y.currentTarget.style.background="transparent")},children:[t.jsx("span",{style:{color:"#64748b",fontSize:12,fontFamily:"monospace",width:20},children:Z?"â¼":"â¶"}),t.jsxs("div",{style:{flex:1},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[F.letter_label&&t.jsx("span",{style:{fontSize:11,fontWeight:700,padding:"2px 8px",borderRadius:6,background:"rgba(139,92,246,0.12)",color:"#a78bfa",border:"1px solid rgba(139,92,246,0.25)"},children:F.letter_label}),t.jsx("span",{style:{color:"#e2e8f0",fontWeight:600,fontSize:13},children:F.title}),F.is_conditional&&t.jsx("span",{style:{fontSize:10,padding:"1px 8px",borderRadius:10,background:"rgba(245,158,11,0.1)",color:"#f59e0b",border:"1px solid rgba(245,158,11,0.25)"},children:F.condition_label||"Conditional"})]}),t.jsxs("div",{style:{fontSize:11,color:"#64748b",marginTop:2},children:[ie.length," items · ",ie.filter(Y=>Y.is_required).length," required"]})]}),t.jsxs("div",{style:{display:"flex",gap:4,flexShrink:0,alignItems:"center"},onClick:Y=>Y.stopPropagation(),children:[t.jsx("button",{onClick:()=>U(K),disabled:K===0,style:{color:"#64748b",background:"none",border:"none",cursor:"pointer",fontSize:11,opacity:K===0?.2:1},children:"â²"}),t.jsx("button",{onClick:()=>W(K),disabled:K===r.length-1,style:{color:"#64748b",background:"none",border:"none",cursor:"pointer",fontSize:11,opacity:K===r.length-1?.2:1},children:"â¼"}),t.jsx("button",{onClick:()=>te(F),style:{fontSize:9,padding:"2px 6px",borderRadius:10,cursor:"pointer",marginLeft:4,background:F.is_active?"rgba(74,222,128,0.12)":"rgba(100,116,139,0.12)",color:F.is_active?"#4ade80":"#64748b",border:`1px solid ${F.is_active?"rgba(74,222,128,0.25)":"rgba(100,116,139,0.2)"}`},children:F.is_active?"On":"Off"}),t.jsx("button",{onClick:()=>B(F),style:{fontSize:11,color:"#60a5fa",background:"none",border:"none",cursor:"pointer"},children:"âï¸"}),t.jsx("button",{onClick:()=>ae(F),style:{fontSize:11,color:"#f87171",background:"none",border:"none",cursor:"pointer"},children:"ð"})]})]}),Z&&t.jsxs("div",{style:{padding:"0 20px 12px 52px"},children:[ie.length===0?t.jsx("div",{style:{padding:"16px 0",color:"#64748b",fontSize:12},children:"No items in this section yet."}):t.jsx("div",{style:{...E9,marginBottom:8},children:t.jsxs("table",{style:{width:"100%",borderCollapse:"collapse"},children:[t.jsx("thead",{children:t.jsxs("tr",{children:[t.jsx("th",{style:{...vo,width:28},children:"#"}),t.jsx("th",{style:vo,children:"Item"}),t.jsx("th",{style:{...vo,width:90},children:"Type"}),t.jsx("th",{style:{...vo,width:70,textAlign:"center"},children:"Req"}),t.jsx("th",{style:{...vo,width:50,textAlign:"center"},children:"ð·"}),t.jsx("th",{style:{...vo,width:60,textAlign:"center"},children:"Order"}),t.jsx("th",{style:{...vo,width:90,textAlign:"right"},children:"Actions"})]})}),t.jsx("tbody",{children:ie.map((Y,X)=>{var H;return t.jsxs("tr",{style:{opacity:Y.is_active?1:.4},children:[t.jsx("td",{style:{..._o,color:"#64748b",fontFamily:"monospace",fontSize:11},children:X+1}),t.jsxs("td",{style:{..._o,fontSize:12},children:[t.jsx("div",{style:{fontWeight:500},children:Y.item_text}),Y.field_type==="dropdown"&&((H=Y.options)==null?void 0:H.length)>
5460&&t.jsx("div",{style:{fontSize:10,color:"#64748b",marginTop:2},children:Y.options.join(" · ")})]}),t.jsx("td",{style:_o,children:t.jsx("span",{style:{fontSize:10,padding:"2px 6px",borderRadius:10,background:`${rm[Y.field_type]||"#64748b"}15`,color:rm[Y.field_type]||"#64748b",border:`1px solid ${rm[Y.field_type]||"#64748b"}30`},children:R9[Y.field_type]||Y.field_type})}),t.jsx("td",{style:{..._o,textAlign:"center"},children:t.jsx("button",{onClick:()=>oe(Y),style:{fontSize:10,padding:"2px 6px",borderRadius:10,cursor:"pointer",background:Y.is_required?"rgba(248,113,113,0.12)":"rgba(100,116,139,0.08)",color:Y.is_required?"#f87171":"#64748b",border:`1px solid ${Y.is_required?"rgba(248,113,113,0.3)":"rgba(100,116,139,0.15)"}`},children:Y.is_required?"Yes":"No"})}),t.jsx("td",{style:{..._o,textAlign:"center",fontSize:11},children:Y.requires_photo?"ð·":"â"}),t.jsx("td",{style:{..._o,textAlign:"center"},children:t.jsxs("div",{style:{display:"flex",justifyContent:"center",gap:2},children:[t.jsx("button",{onClick:()=>ne(ie,X),disabled:X===0,style:{color:"#64748b",background:"none",border:"none",cursor:"pointer",fontSize:10,opacity:X===0?.2:1},children:"â²"}),t.jsx("button",{onClick:()=>ge(ie,X),disabled:X===ie.length-1,style:{color:"#64748b",background:"none",border:"none",cursor:"pointer",fontSize:10,opacity:X===ie.length-1?.2:1},children:"â¼"})]})}),t.jsx("td",{style:{..._o,textAlign:"right"},children:t.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:8},children:[t.jsx("button",{onClick:()=>V(Y,F.id),style:{fontSize:11,color:"#60a5fa",background:"none",border:"none",cursor:"pointer"},children:"Edit"}),t.jsx("button",{onClick:()=>Q(Y),style:{fontSize:11,color:Y.is_active?"#64748b":"#4ade80",background:"none",border:"none",cursor:"pointer"},children:Y.is_active?"Off":"On"}),t.jsx("button",{onClick:()=>re(Y),style:{fontSize:11,color:"#f87171",background:"none",border:"none",cursor:"pointer"},children:"Del"})]})})]},Y.id)})})]})}),t.jsxs("button",{onClick:()=>G(F.id),style:{padding:"6px 14px",borderRadius:8,fontSize:12,fontWeight:600,background:"rgba(74,222,128,0.08)",color:"#4ade80",border:"1px solid rgba(74,222,128,0.2)",cursor:"pointer"},children:["+ Add Item to ",F.letter_label||F.title]})]})]},F.id)})})]})}const D9=[{key:"first_name",label:"First name",show:!0,required:!0},{key:"last_name",label:"Last name",show:!0,required:!0},{key:"phone",label:"Phone",show:!0,required:!0},{key:"email",label:"Email",show:!0,required:!1},{key:"address",label:"Address",show:!0,required:!1},{key:"city",label:"City",show:!0,required:!1},{key:"state",label:"State",show:!0,required:!1},{key:"zip",label:"ZIP",show:!0,required:!0},{key:"water_concern",label:"Water concern",show:!1,required:!1},{key:"notes",label:"Notes",show:!1,required:!1}],Wv=["first_name","phone"],O9={days:[1,2,3,4,5],start:"09:30",end:"16:30",slot_minutes:30,min_notice_days:1,min_notice_minutes:0,visit_duration_minutes:30,horizon_days:14,tz:"America/Indiana/Indianapolis"},I9="company_website";async function L9(){const{data:e,error:n}=await w.from("lead_forms").select("*").order("created_at",{ascending:!1});if(n)throw new Error(n.message);return e||[]}async function W9(e){const n={slug:e.slug,name:e.name,title:e.title??e.name,intro_text:e.intro_text??null,source_tag:e.source_tag??"website_form",f
546ields:e.fields??D9,schedule_enabled:e.schedule_enabled??!0,schedule_rules:e.schedule_rules??O9,accent_color:e.accent_color??"#0f6e56",bg_color:e.bg_color??"#ffffff",text_color:e.text_color??"#111111",submit_button_text:e.submit_button_text??"Book my site visit",success_message:e.success_message??null,slot_capacity:e.slot_capacity??1,honeypot_key:I9,branch_id:e.branch_id??null,enabled:!0},{data:r,error:s}=await w.from("lead_forms").insert(n).select("*").single();if(s)throw new Error(s.message);return r}async function $9(e,n){const{data:r,error:s}=await w.from("lead_forms").update({...n,updated_at:new Date().toISOString()}).eq("id",e).select("*").single();if(s)throw new Error(s.message);return r}async function M9(e){const{error:n}=await w.from("lead_forms").delete().eq("id",e);if(n)throw new Error(n.message)}async function $v(e,n){let r=w.from("lead_forms").select("id").eq("slug",e).limit(1);n&&(r=r.neq("id",n));const{data:s}=await r.maybeSingle();return!!s}const Mv="form-assets";async function F9(e,n,r,s){const i=s.name.replace(/[^a-zA-Z0-9._-]/g,"_"),o=Date.now(),a=`${e}/${n}/${r}_${o}_${i}`,{error:l}=await w.storage.from(Mv).upload(a,s,{cacheControl:"3600",upsert:!0});if(l)throw new Error(`Upload failed: ${l.message}`);const{data:d}=w.storage.from(Mv).getPublicUrl(a);return d.publicUrl}const sm=[{name:"Zenith Green",hex:"#0f6e56"},{name:"Teal",hex:"#1D9E75"},{name:"Blue",hex:"#185FA5"},{name:"Navy",hex:"#042C53"},{name:"Slate",hex:"#334155"},{name:"Amber",hex:"#BA7517"}],Fv=[{name:"White",hex:"#ffffff"},{name:"Off-white",hex:"#f8fafc"},{name:"Light gray",hex:"#f1f5f9"},{name:"Dark",hex:"#0d1117"}],Id=[{name:"Near-black",hex:"#111111"},{name:"Slate",hex:"#334155"},{name:"White",hex:"#ffffff"}],im={};var S2;const Bv=typeof window<"u"&&((S2=window.location)==null?void 0:S2.origin)||(im==null?void 0:im.VITE_APP_URL)||"https://cevora-app.vercel.app",B9=[{n:1,label:"Mon"},{n:2,label:"Tue"},{n:3,label:"Wed"},{n:4,label:"Thu"},{n:5,label:"Fri"},{n:6,label:"Sat"},{n:7,label:"Sun"}],Ce={head:"#e2e8f0",muted:"#64748b",accent:"#38bdf8",panel:"rgba(13,126,163,0.06)",panelBorder:"rgba(13,126,163,0.2)",card:"rgba(255,255,255,0.02)",cardBorder:"rgba(255,255,255,0.08)"},wt=e=>t.jsx("div",{style:{color:Ce.muted,fontSize:11,fontWeight:600,marginBottom:6},children:e});function U9(e){return e.toLowerCase().trim().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)}function H9(){const{tenant:e,profile:n}=Ee(),r=(n==null?void 0:n.tenant_id)??(e==null?void 0:e.id)??null,[s,i]=g.useState([]),[o,a]=g.useState(!0),[l,d]=g.useState(null),[c,f]=g.useState(null),[p,u]=g.useState(!1),[h,y]=g.useState(""),[m,b]=g.useState(null);g.useEffect(()=>{A()},[]);async function A(){a(!0);try{const N=await L9();i(N),N.length&&!l&&v(N[0])}catch(N){y("â "+N.message)}a(!1)}function v(N){d(N.id),f(JSON.parse(JSON.stringify(N))),y("")}async function x(){const N="New form";let O="new-form",z=O,P=1;for(;await $v(z);)z=`${O}-${P++}`;try{const D=await W9({slug:z,name:N});await A(),v(D)}catch(D){y("â "+D.message)}}async function _(){if(c){u(!0),y("");try{if(await $v(c.slug,c.id)){y("â That URL slug is already used by another form"),u(!1);return}const N=await $9(c.id,{slug:c.slug,name:c.name,title:c.title,intro_text:c.intro_text,source_tag:c.source_tag,fields:c.fields,schedule_enabled:c.schedule_enabled,schedule_rules:c.schedule_rules,accent_color:c.accent_color,bg_color:c.bg_color,text_color:c.text_color,logo_url:c.logo_url,hero_url:c.hero_url,header_text:c.header_text,header_text_size:c.header_text_size,header_text_color:c.header_text_color,button_color:c.button_color,placeholder_color:c.placeholder_color,input_border_color:c.input_border_color,input_bg_color:c.input_bg_color,input_text_color:c.input_text_color,link_color:c.link_color,terms_url:c.terms_url,privacy_url:c.privacy_url,submit_button_text:c.submit_button_text,success_message:c.success_message,redirect_url:c.redirect_url,enabled:c.enabled,slot_capacity:c.slot_capacity,form_width:c.form_width,embed_height:c.embed_height,show_progress_steps:c.show_progress_steps,booking_first:c.booking_first});i(O=>O.map(z=>z.id===N.id?N:z)),y("â
Saved"),setTimeout(()=>y(""),3e3)}catch(N){y("â "+N.message)}u(!1)}}async function j(N){if(confirm(`Delete "${N.name}"? This cannot be undone.`))try{await M9(N.id);const O=s.filter(z=>z.id!==N.id);i(O),l===N.id&&(d(null),f(null))}catch(O){y("â "+O.message)}}async function C(N,O){if(!c||!r){y("â Missing tenant context");return}b(N);try{const z=await F9(r,c.id,N,O);f({...c,[N==="logo"?"logo_url":"hero_url"]:z}),y("â
Image uploaded â remember to Save")}catch(z){y("â "+z.message)}b(null)}function S(N,O){c&&f({...c,[N]:O})}function T(N,O){c&&f({...c,schedule_rules:{...c.schedule_rules,[
546N]:O}})}function L(N,O){if(!c)return;const z=c.fields.map((P,D)=>{if(D!==N)return P;if(O==="showLabel")return{...P,showLabel:P.showLabel===!1};if(Wv.includes(P.key))return P;if(O==="show"){const M=!P.show;return{...P,show:M,required:M?P.required:!1}}return{...P,required:!P.required}});f({...c,fields:z})}function E(N){var P;if(!c)return;const O=((P=c.schedule_rules)==null?void 0:P.days)||[],z=O.includes(N)?O.filter(D=>D!==N):[...O,N].sort((D,M)=>D-M);T("days",z)}const R=c?`<iframe id="cevora-form-${c.slug}" 547 style="width:100%;max-width:${c.form_width??600}px;height:${c.embed_height??660}px;border:0" 548 title="${c.title||c.name}"> 549</iframe> 550<script> 551(function () { 552 var slug = '${c.slug}'; 553 var origin = '${Bv}'; 554 var f = document.getElementById('cevora-form-' + slug); 555 if (!f) return; 556 f.src = origin + '/f/' + slug + window.location.search; 557 window.addEventListener('message', function (e) { 558 if (e.origin !== origin) return; 559 if (e.data && e.data.cevoraFormHeight && e.data.slug === slug) { 560 f.style.height = e.data.cevoraFormHeight + 'px'; 561 } 562 }); 563})(); 564<\/script>`:"";return o?t.jsx("div",{style:{textAlign:"center",color:Ce.muted,padding:"48px 0"},children:"Loading formsâ¦"}):t.jsxs("div",{style:{display:"flex",gap:16,height:"100%",minHeight:0},children:[t.jsxs("div",{style:{width:240,flexShrink:0,display:"flex",flexDirection:"column",minHeight:0},children:[t.jsx("button",{onClick:x,style:{width:"100%",padding:"10px",borderRadius:10,marginBottom:12,background:"rgba(13,126,163,0.15)",color:Ce.accent,fontWeight:600,fontSize:13,border:"1px solid rgba(13,126,163,0.4)",cursor:"pointer"},children:"+ New form"}),t.jsxs("div",{style:{overflowY:"auto",flex:1},children:[s.length===0&&t.jsx("div",{style:{color:Ce.muted,fontSize:12,padding:"8px 4px"},children:"No forms yet."}),s.map(N=>t.jsxs("div",{onClick:()=>v(N),style:{padding:"10px 12px",borderRadius:10,marginBottom:8,cursor:"pointer",background:l===N.id?"rgba(13,126,163,0.12)":Ce.card,border:`1px solid ${l===N.id?"rgba(13,126,163,0.4)":Ce.cardBorder}`},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[t.jsx("span",{style:{color:Ce.head,fontSize:13,fontWeight:600,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:N.name}),t.jsx("span",{style:{fontSize:9,padding:"2px 6px",borderRadius:10,fontWeight:600,background:N.enabled?"rgba(34,197,94,0.12)":"rgba(148,163,184,0.12)",color:N.enabled?"#22c55e":"#94a3b8"},children:N.enabled?"live":"off"})]}),t.jsxs("div",{style:{color:Ce.muted,fontSize:10,fontFamily:"monospace",marginTop:2},children:["/f/",N.slug]})]},N.id))]})]}),t.jsx("div",{style:{flex:1,minWidth:0,overflowY:"auto",paddingRight:4},children:c?t.jsxs(t.Fragment,{children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,marginBottom:16},children:[t.jsx("input",{value:c.name,onChange:N=>S("name",N.target.value),placeholder:"Form name",style:{flex:1,background:Ce.card,border:`1px solid ${Ce.cardBorder}`,borderRadius:8,padding:"8px 10px",color:Ce.head,fontSize:15,fontWeight:600}}),t.jsxs("label",{style:{display:"flex",alignItems:"center",gap:6,color:Ce.muted,fontSize:12},children:[t.jsx("input",{type:"checkbox",checked:c.enabled,onChange:N=>S("enabled",N.target.checked)})," Enabled"]}),t.jsx("button",{onClick:_,disabled:p,style:{padding:"8px 16px",borderRadius:8,fontWeight:600,fontSize:13,cursor:"pointer",background:"rgba(34,197,94,0.15)",color:"#22c55e",border:"1px solid rgba(34,197,94,0.4)"},children:p?"Savingâ¦":"Save"}),t.jsx("button",{onClick:()=>j(c),style:{padding:"8px 12px",borderRadius:8,fontSize:13,cursor:"pointer",background:"rgba(239,68,68,0.1)",color:"#ef4444",border:"1px solid rgba(239,68,68,0.3)"},children:"Delete"})]}),h&&t.jsx("div",{style:{fontSize:12,marginBottom:12,color:h.startsWith("â ")?"#22c55e":"#ef4444"},children:h}),t.jsxs("div",{style:{background:Ce.panel,border:`1px solid ${Ce.panelBorder}`,borderRadius:12,padding:"12px 14px",marginBottom:16},children:[wt("PUBLIC URL SLUG"),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[t.jsxs("span",{style:{color:Ce.muted,fontSize:12,fontFamily:"monospace"},children:[Bv,"/f/"]}),t.jsx("input",{value:c.slug,onChange:N=>S("slug",U9(N.target.value)),style:{flex:1,background:Ce.card,border:`1px solid ${Ce.cardBorder}`,borderRadius:6,padding:"6px 8px",color:Ce.head,fontSize:12,fontFamily:"monospace"}})]}
564),wt("EMBED SNIPPET (paste on your website)"),t.jsxs("div",{style:{position:"relative"},children:[t.jsx("pre",{style:{background:Ce.card,border:`1px solid ${Ce.cardBorder}`,borderRadius:6,padding:"10px",color:"#94a3b8",fontSize:11,whiteSpace:"pre-wrap",margin:0},children:R}),t.jsx("button",{onClick:()=>{navigator.clipboard.writeText(R),y("â
Snippet copied"),setTimeout(()=>y(""),2e3)},style:{position:"absolute",top:6,right:6,fontSize:11,padding:"3px 8px",borderRadius:6,cursor:"pointer",background:"rgba(13,126,163,0.15)",color:Ce.accent,border:"1px solid rgba(13,126,163,0.4)"},children:"Copy"})]})]}),t.jsxs("div",{style:{marginBottom:16},children:[wt("FORM TITLE"),t.jsx("input",{value:c.title||"",onChange:N=>S("title",N.target.value),placeholder:"Book your free water test",style:{width:"100%",background:Ce.card,border:`1px solid ${Ce.cardBorder}`,borderRadius:8,padding:"8px 10px",color:Ce.head,fontSize:13,marginBottom:10}}),wt("INTRO TEXT"),t.jsx("textarea",{value:c.intro_text||"",onChange:N=>S("intro_text",N.target.value),rows:2,placeholder:"Short line under the title",style:{width:"100%",background:Ce.card,border:`1px solid ${Ce.cardBorder}`,borderRadius:8,padding:"8px 10px",color:Ce.head,fontSize:13,resize:"vertical"}})]}),t.jsxs("div",{style:{marginBottom:16},children:[wt("FIELDS â SHOW / REQUIRED"),t.jsx("div",{style:{background:Ce.card,border:`1px solid ${Ce.cardBorder}`,borderRadius:12,overflow:"hidden"},children:c.fields.map((N,O)=>{const z=Wv.includes(N.key);return t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"9px 12px",borderBottom:O<c.fields.length-1?`1px solid ${Ce.cardBorder}`:"none"},children:[t.jsxs("span",{style:{flex:1,color:Ce.head,fontSize:13},children:[N.label,z&&t.jsx("span",{style:{color:Ce.muted,fontSize:10},children:" (always)"})]}),t.jsx("button",{onClick:()=>L(O,"show"),disabled:z,style:cp(N.show,"#22c55e",z),children:N.show?"shown":"hidden"}),N.show?t.jsx("button",{onClick:()=>L(O,"required"),disabled:z,style:cp(N.required,"#ef4444",z),children:N.required?"required":"optional"}):t.jsx("span",{style:{fontSize:11,color:Ce.muted,width:62,textAlign:"center"},children:"â"}),N.show?t.jsx("button",{onClick:()=>L(O,"showLabel"),style:cp(N.showLabel!==!1,"#38bdf8",!1),children:N.showLabel!==!1?"label":"no label"}):t.jsx("span",{style:{fontSize:11,color:Ce.muted,width:62,textAlign:"center"},children:"â"})]},N.key)})})]}),t.jsxs("div",{style:{marginBottom:16},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:8},children:[wt("SITE-VISIT SCHEDULING"),t.jsxs("label",{style:{marginLeft:"auto",display:"flex",alignItems:"center",gap:6,color:Ce.muted,fontSize:11},children:[t.jsx("input",{type:"checkbox",checked:c.schedule_enabled,onChange:N=>S("schedule_enabled",N.target.checked)})," On"]})]}),c.schedule_enabled&&t.jsxs("div",{style:{background:Ce.card,border:`1px solid ${Ce.cardBorder}`,borderRadius:12,padding:14},children:[wt("BOOKABLE DAYS"),t.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6,marginBottom:14},children:B9.map(N=>{var O;return t.jsx("button",{onClick:()=>E(N.n),style:cp((((O=c.schedule_rules)==null?void 0:O.days)||[]).includes(N.n),"#38bdf8",!1),children:N.label},N.n)})}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12,marginBottom:12},children:[t.jsxs("div",{children:[wt("DAY STARTS"),t.jsx("input",{type:"time",value:c.schedule_rules.start,onChange:N=>T("start",N.target.value),style:hi})]}),t.jsxs("div",{children:[wt("DAY ENDS"),t.jsx("input",{type:"time",value:c.schedule_rules.end,onChange:N=>T("end",N.target.value),style:hi})]})]}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(150px, 1fr))",gap:12},children:[t.jsxs("div",{children:[wt("SLOT LENGTH"),t.jsxs("select",{value:c.schedule_rules.slot_minutes,onChange:N=>T("slot_minutes",+N.target.value),style:hi,children:[t.jsx("option",{value:15,children:"15 min"}),t.jsx("option",{value:30,children:"30 min"}),t.jsx("option",{value:45,children:"45 min"}),t.jsx("option",{value:60,children:"60 min"}),t.jsx("option",{value:90,children:"90 min"}),t.jsx("option",{value:120,children:"120 min"})]})]}),t.jsxs("div",{children:[wt("VISIT LENGTH"),t.jsxs("select",{value:c.schedule_rules.visit_duration_minutes??c.schedule_rules.slot_minutes??30,onChange:N=>T("visit_duration_minutes",+N.target.value),style:hi,children:[t.jsx("option",{value:15,children:"15 min"}),t.jsx("option",{value:30,children:"30 min"}),t.jsx("option",{value:45,children:"45 min"}),t.jsx("option",{value:60,children:"1 hour"}),t.jsx("option",{value:90,children:"90 min"}),t.jsx("option",{value:120,children:"2 hours"}),t.jsx("option",{value:180,children:"3 hours"}),t.jsx("option",{value:240,children:"4 hours"})]})]}),t.jsxs("div",{children:[wt("MIN NOTICE"),t.jsxs("select",{value:c.schedule_rules.min_notice_days,onChange:N=>T("min_notice_days",+N.target.value),style:hi,children:[t.jsx("option",{value:0,children:"Same day"}),t.jsx("option",{value:1,children:"1 day out"}),t.jsx("option",{value:2,children:"2 days out"}),t.jsx("option",{value:3,children:"3 days out"})]})]}),t.jsxs("div",{children:[wt("SAME-DAY LEAD TIME"),t.jsxs("select",{value:c.schedule_rules.min_notice_minutes??0,onChange:N=>T("min_notice_minutes",+N.target.value),style:hi,children:[t.jsx("option",{value:0,children:"No buffer"}),t.jsx("option",{value:15,children:"15 min"}),t.jsx("option",{value:30,children:"30 min"}),t.jsx("option",{value:60,children:"1 hour"}),t.jsx("option",{value:90,children:"90 min"}),t.jsx("option",{value:120,children:"2 hours"}),t.jsx("option",{value:240,children:"4 hours"})]})]}),t.jsxs("div",{children:[wt("BOOK AHEAD"),t.jsxs("select",{value:c.schedule_rules.horizon_days,onChange:N=>T("horizon_days",+N.target.value),style:hi,children:[t.jsx("option",{value:7,children:"7 days"}),t.jsx("option",{value:14,children:"14 days"}),t.jsx("option",{value:30,children:"30 days"})]})]})]}),t.jsxs("div",{style:{marginTop:12},children:[wt("STEP ORDER"),t.jsxs("label",{style:{display:"flex",alignItems:"center",gap:6,color:Ce.muted,fontSize:11},children:[t.jsx("input",{type:"checkbox",checked:!!c.booking_first,onChange:N=>S("booking_first",N.target.checked)}),"Ask for date and time FIRST, contact details second"]})]}),t.jsxs("div",{style:{marginTop:12},children:[wt("PROGRESS STEPS"),t.jsxs("label",{style:{display:"flex",alignItems:"center",gap:6,color:Ce.muted,fontSize:11},children:[t.jsx("input",{type:"checkbox",checked:c.show_progress_steps!==!1,onChange:N=>S("show_progress_steps",N.target.checked)}),"Show the 1 Your info / 2 Pick a time / 3 Confirm strip"]})]}),t.jsxs("div",{style:{marginTop:12},children:[wt("SLOTS PER TIME (how many reps can take the same slot)"),t.jsx("input",{type:"number",min:1,max:20,value:c.slot_capacity??1,onChange:N=>S("slot_capacity",Math.max(1,parseInt(N.target.value||"1",10))),style:{...hi,width:120}})]})]})]}),t.jsxs("div",{style:{marginBottom:16},children:[wt("THEME"),t.jsxs("div",{style:{background:Ce.card,border:`1px solid ${Ce.cardBorder}`,borderRadius:12,padding:14},children:[t.jsx(ds,{title:"Accent",swatches:sm,value:c.accent_color,onPick:N=>S("accent_color",N)}
564),t.jsx(ds,{title:"Background",swatches:Fv,value:c.bg_color,onPick:N=>S("bg_color",N)}),t.jsx(ds,{title:"Text",swatches:Id,value:c.text_color,onPick:N=>S("text_color",N)}),t.jsx(ds,{title:"Button",swatches:sm,value:c.button_color,onPick:N=>S("button_color",N)}),t.jsx(ds,{title:"Placeholder",swatches:Id,value:c.placeholder_color,onPick:N=>S("placeholder_color",N)}),t.jsx(ds,{title:"Box border",swatches:Id,value:c.input_border_color,onPick:N=>S("input_border_color",N)}),t.jsx(ds,{title:"Box fill",swatches:Fv,value:c.input_bg_color,onPick:N=>S("input_bg_color",N)}),t.jsx(ds,{title:"Box text",swatches:Id,value:c.input_text_color,onPick:N=>S("input_text_color",N)})]})]}),t.jsxs("div",{style:{marginBottom:16},children:[wt("IMAGES"),t.jsxs("div",{style:{background:Ce.card,border:`1px solid ${Ce.cardBorder}`,borderRadius:12,padding:14,display:"grid",gridTemplateColumns:"1fr 1fr",gap:12},children:[t.jsx(Uv,{title:"Logo",url:c.logo_url,busy:m==="logo",onFile:N=>C("logo",N),onClear:()=>S("logo_url",null)}),t.jsx(Uv,{title:"Hero / banner",url:c.hero_url,busy:m==="hero",onFile:N=>C("hero",N),onClear:()=>S("hero_url",null)})]})]}),t.jsxs("div",{style:{marginBottom:16},children:[wt("HEADER TEXT (shown when no logo)"),t.jsxs("div",{style:{background:Ce.card,border:`1px solid ${Ce.cardBorder}`,borderRadius:12,padding:14},children:[t.jsx("input",{value:c.header_text||"",onChange:N=>S("header_text",N.target.value),placeholder:"e.g. Zenith Pure Solutions",style:{width:"100%",background:Ce.card,border:`1px solid ${Ce.cardBorder}`,borderRadius:8,padding:"8px 10px",color:Ce.head,fontSize:13,marginBottom:12,boxSizing:"border-box"}}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:12},children:[t.jsx("span",{style:{color:Ce.head,fontSize:12,minWidth:70},children:"Size (px)"}),t.jsx("input",{type:"number",min:10,max:80,value:c.header_text_size??22,onChange:N=>S("header_text_size",parseInt(N.target.value,10)||22),style:{width:90,background:Ce.card,border:`1px solid ${Ce.cardBorder}`,borderRadius:8,padding:"8px 10px",color:Ce.head,fontSize:13,boxSizing:"border-box"}})]}),t.jsx(ds,{title:"Color",swatches:Id,value:c.header_text_color,onPick:N=>S("header_text_color",N)})]})]}),t.jsxs("div",{style:{marginBottom:16},children:[wt("CONSENT LINKS (Terms & Privacy shown on the form)"),t.jsxs("div",{style:{background:Ce.card,border:`1px solid ${Ce.cardBorder}`,borderRadius:12,padding:14},children:[t.jsxs("div",{style:{marginBottom:10},children:[t.jsx("div",{style:{color:Ce.muted,fontSize:11,marginBottom:4},children:"Terms URL"}),t.jsx("input",{value:c.terms_url||"",onChange:N=>S("terms_url",N.target.value),placeholder:"https://â¦",style:{width:"100%",background:Ce.card,border:`1px solid ${Ce.cardBorder}`,borderRadius:8,padding:"8px 10px",color:Ce.head,fontSize:12,boxSizing:"border-box",fontFamily:"monospace"}})]}),t.jsxs("div",{style:{marginBottom:12},children:[t.jsx("div",{style:{color:Ce.muted,fontSize:11,marginBottom:4},children:"Privacy URL"}),t.jsx("input",{value:c.privacy_url||"",onChange:N=>S("privacy_url",N.target.value),placeholder:"https://â¦",style:{width:"100%",background:Ce.card,border:`1px solid ${Ce.cardBorder}`,borderRadius:8,padding:"8px 10px",color:Ce.head,fontSize:12,boxSizing:"border-box",fontFamily:"monospace"}})]}),t.jsx(ds,{title:"Link color",swatches:sm,value:c.link_color,onPick:N=>S("link_color",N)})]})]}),t.jsxs("div",{style:{marginBottom:16},children:[wt("EMBED SIZE (for pasting the form on your website)"),t.jsxs("div",{style:{background:Ce.card,border:`1px solid ${Ce.cardBorder}`,borderRadius:12,padding:14,display:"flex",gap:16,alignItems:"center"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[t.jsx("span",{style:{color:Ce.head,fontSize:12},children:"Form width (px)"}),t.jsx("input",{type:"number",min:320,max:1e3,value:c.form_width??600,onChange:N=>S("form_width",parseInt(N.target.value,10)||600),style:{width:90,background:Ce.card,border:`1px solid ${Ce.cardBorder}`,borderRadius:8,padding:"8px 10px",color:Ce.head,fontSize:13,boxSizing:"border-box"}})]}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[t.jsx("span",{style:{color:Ce.head,fontSize:12},children:"Embed height (px)"}),t.jsx("input",{type:"number",min:300,max:2e3,value:c.embed_height??660,onChange:N=>
564S("embed_height",parseInt(N.target.value,10)||660),style:{width:90,background:Ce.card,border:`1px solid ${Ce.cardBorder}`,borderRadius:8,padding:"8px 10px",color:Ce.head,fontSize:13,boxSizing:"border-box"}})]})]}),t.jsx("div",{style:{color:Ce.muted,fontSize:10,marginTop:4},children:"Embed height is a starting size â the embed auto-resizes to fit the form."})]}),t.jsxs("div",{style:{marginBottom:24},children:[wt("SUBMIT BUTTON TEXT"),t.jsx("input",{value:c.submit_button_text||"",onChange:N=>S("submit_button_text",N.target.value),placeholder:"Book my site visit",style:{width:"100%",background:Ce.card,border:`1px solid ${Ce.cardBorder}`,borderRadius:8,padding:"8px 10px",color:Ce.head,fontSize:13,marginBottom:10}}),wt("SUCCESS MESSAGE"),t.jsx("input",{value:c.success_message||"",onChange:N=>S("success_message",N.target.value),placeholder:"Thanks! We'll call to confirm your visit.",style:{width:"100%",background:Ce.card,border:`1px solid ${Ce.cardBorder}`,borderRadius:8,padding:"8px 10px",color:Ce.head,fontSize:13}})]})]}):t.jsx("div",{style:{color:Ce.muted,fontSize:13,padding:"48px 0",textAlign:"center"},children:"Select a form on the left, or create one."})}),t.jsxs("div",{style:{width:320,flexShrink:0,overflowY:"auto"},children:[wt("LIVE PREVIEW"),c?t.jsx(V9,{form:c}):t.jsx("div",{style:{color:Ce.muted,fontSize:12},children:"â"})]})]})}const hi={width:"100%",background:"rgba(255,255,255,0.02)",border:"1px solid rgba(255,255,255,0.08)",borderRadius:6,padding:"6px 8px",color:"#e2e8f0",fontSize:12};function cp(e,n,r){return{fontSize:11,padding:"3px 10px",borderRadius:20,width:62,textAlign:"center",cursor:r?"default":"pointer",opacity:r?.5:1,background:e?`${n}22`:"transparent",color:e?n:"#64748b",border:`1px solid ${e?`${n}66`:"rgba(255,255,255,0.12)"}`}}function ds({title:e,swatches:n,value:r,onPick:s}){const i=n.some(a=>a.hex.toLowerCase()===(r||"").toLowerCase()),o=/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/.test(r||"")?r:"#000000";return t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,marginBottom:10,flexWrap:"wrap"},children:[t.jsx("span",{style:{color:"#64748b",fontSize:11,width:84},children:e}),t.jsxs("div",{style:{display:"flex",gap:6,alignItems:"center"},children:[n.map(a=>t.jsx("button",{title:a.name,onClick:()=>s(a.hex),style:{width:24,height:24,borderRadius:6,cursor:"pointer",background:a.hex,border:r===a.hex?"2px solid #38bdf8":"1px solid rgba(255,255,255,0.15)"}},a.hex)),t.jsx("span",{style:{width:1,height:20,background:"rgba(255,255,255,0.15)",margin:"0 2px"}}),t.jsx("input",{type:"color",value:o,onChange:a=>s(a.target.value),title:"Custom color",style:{width:26,height:26,padding:0,border:i?"1px solid rgba(255,255,255,0.15)":"2px solid #38bdf8",borderRadius:6,background:"transparent",cursor:"pointer"}}),t.jsx("input",{type:"text",value:r||"",onChange:a=>{const l=a.target.value.trim();s(l.startsWith("#")||l===""?l:"#"+l)},placeholder:"#hex",spellCheck:!1,style:{width:78,background:"rgba(255,255,255,0.02)",border:"1px solid rgba(255,255,255,0.12)",borderRadius:6,padding:"4px 6px",color:"#e2e8f0",fontSize:11,fontFamily:"monospace"}})]})]})}function Uv({title:e,url:n,busy:r,onFile:s,onClear:i}){return t.jsxs("div",{children:[t.jsx("div",{style:{color:"#64748b",fontSize:11,marginBottom:6},children:e}),n?t.jsxs("div",{style:{position:"relative"},children:[t.jsx("img",{src:n,alt:e,style:{width:"100%",height:70,objectFit:"contain",background:"rgba(255,255,255,0.04)",borderRadius:8,border:"1px solid rgba(255,255,255,0.08)"}}),t.jsx("button",{onClick:i,style:{position:"absolute",top:4,right:4,fontSize:10,padding:"2px 6px",borderRadius:6,cursor:"pointer",background:"rgba(239,68,68,0.15)",color:"#ef4444",border:"1px solid rgba(239,68,68,0.4)"},children:"Remove"})]}):t.jsxs("label",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:70,borderRadius:8,border:"1px dashed rgba(255,255,255,0.2)",cursor:"pointer",color:"#64748b",fontSize:12},children:[r?"Uploadingâ¦":"+ Upload",t.jsx("input",{type:"file",accept:"image/png,image/jpeg,image/webp,image/svg+xml",style:{display:"none"},onChange:o=>{var l;const a=(l=o.target.files)==null?void 0:l[0];a&&s(a)}})]})]})}function V9({form:e}){const n=e.accent_color||"#0f6e56",r=e.bg_color||"#ffffff",s=e.text_color||"#111111",i=e.button_color||n,o=e.input_border_color||"#cccccc",a=e.input_bg_color||"rgba(0,0,0,0.04)",l=e.fields.filter(c=>c.show),d=g.useMemo(()=>K9(e.schedule_rules),[e.schedule_rules]);return t.jsxs("div",{style:{background:r,borderRadius:12,overflow:"hidden",border:"1px solid rgba(0,0,0,0.1)"},children:[(e.logo_url||e.header_text)&&t.jsx("div",{style:{background:n,padding:"14px 16px",color:"#fff",display:"flex",alignItems:"center",justifyContent:"center"},children:e.logo_url?t.jsx("div",{style:{background:"#fff",borderRadius:7,padding:"5px 9px",display:"flex",alignItems:"center",maxWidth:"85%"},children:t.jsx("img",{src:e.logo_url,alt:"logo",style:{width:"100%",maxWidth:180,height:"auto",maxHeight:46,objectFit:"contain",display:"block"}})}):e.header_text?t.jsx("span",{style:{fontSize:Math.min((e.header_text_size??22)*.6,26),fontWeight:700,color:e.header_text_color||"#ffffff",textAlign:"center"},children:e.header_text}):null}),e.hero_url&&t.jsx("img",{src:e.hero_url,alt:"hero",style:{width:"100%",height:80,objectFit:"cover"}}),t.jsxs("div",{style:{padding:14},children:[e.intro_text&&t.jsx("div",{style:{color:s,opacity:.7,fontSize:11,marginBottom:10},children:e.intro_text}),t.jsx("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8},children:l.map(c=>
564t.jsxs("div",{style:{gridColumn:c.key==="address"||c.key==="notes"||c.key==="water_concern"?"1 / -1":"auto"},children:[c.showLabel!==!1&&t.jsxs("div",{style:{color:s,fontSize:10,marginBottom:2},children:[c.label,c.required&&t.jsx("span",{style:{color:"#d85a30"},children:" *"})]}),t.jsx("div",{style:{height:26,borderRadius:5,background:a,border:`1px solid ${o}`,display:"flex",alignItems:"center",padding:"0 6px",boxSizing:"border-box",color:s,opacity:.45,fontSize:9},children:c.showLabel===!1?c.label+(c.required?" *":""):""})]},c.key))}),e.schedule_enabled&&t.jsxs("div",{style:{marginTop:12},children:[t.jsx("div",{style:{color:s,fontSize:10,marginBottom:6},children:"Choose a preferred day"}),t.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:4,marginBottom:10},children:Z9(e.schedule_rules).map((c,f)=>t.jsx("span",{style:{fontSize:10,padding:"3px 7px",borderRadius:5,border:`1px solid ${f===0?n:o}`,background:f===0?n:a,color:f===0?"#fff":s},children:c},c))}),t.jsxs("div",{style:{color:s,fontSize:10,marginBottom:6},children:["Choose a preferred time (",e.schedule_rules.slot_minutes,"-min · ",d.length," slots/day)"]}),t.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:[d.slice(0,8).map(c=>t.jsx("span",{style:{fontSize:10,padding:"3px 7px",borderRadius:5,border:`1px solid ${o}`,background:a,color:s},children:c},c)),d.length>8&&t.jsxs("span",{style:{fontSize:10,color:s,opacity:.5},children:["+",d.length-8]})]})]}),t.jsx("div",{style:{marginTop:12,textAlign:"center",background:i,color:"#fff",borderRadius:7,padding:"9px 0",fontSize:12,fontWeight:600},children:e.submit_button_text||"Book my site visit"})]})]})}function Z9(e){const n=new Set(e.days&&e.days.length?e.days:[1,2,3,4,5]),r=e.min_notice_days??1,s=e.horizon_days??14,i=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],o=new Date,a=[];for(let l=r;l<=s&&a.length<5;l++){const d=new Date(o.getTime()+l*864e5),c=(d.getDay()+6)%7+1;n.has(c)&&a.push(`${i[c-1]} ${d.getMonth()+1}/${d.getDate()}`)}return a}function K9(e){const[n,r]=(e.start||"09:30").split(":").map(Number),[s,i]=(e.end||"16:30").split(":").map(Number),o=n*60+r,a=s*60+i,l=e.slot_minutes||30,d=[];for(let c=o;c+l<=a+1;c+=l){const f=Math.floor(c/60),p=c%60,u=f>=12?"PM":"AM",h=f>12?f-12:f===0?12:f;d.push(`${h}:${p<10?"0":""}${p}${u}`)}return d}const om={},Y9=[{key:"first_name",label:"First name",hint:"required"},{key:"last_name",label:"Last name"},{key:"full_name",label:"Full name",hint:"split into first/last if the vendor sends one field"},{key:"phone",label:"Phone",hint:"required"},{key:"email",label:"Email"},{key:"address",label:"Address"},{key:"city",label:"City"},{key:"state",label:"State"},{key:"zip_code",label:"ZIP"},{key:"water_concern",label:"Water concern"},{key:"notes",label:"Notes"},{key:"consent_cert_url",label:"Consent certificate",hint:"TrustedForm URL or Jornaya LeadiD"},{key:"sms_opt_in",label:"SMS opt-in",hint:"no opt-in means no confirmation text"},{key:"email_opt_in",label:"Email opt-in"},{key:"utm_source",label:"UTM source"},{key:"utm_medium",label:"UTM medium"},{key:"utm_campaign",label:"UTM campaign"}],Hv=((om==null?void 0:om.VITE_APP_URL)||"https://cevora-app.vercel.app")+"/api/leads/capture";function H4(){const e=new Uint8Array(24);return crypto.getRandomValues(e),Array.from(e).map(n=>n.toString(16).padStart(2,"0")).join("")}function V4(e,n="",r=0){if(!e||typeof e!="object"||Array.isArray(e)||r>4)return[];const s=[];for(const[i,o]of Object.entries(e)){const a=n?`${n}.${i}`:i;o&&typeof o=="object"&&!Array.isArray(o)?s.push(...V4(o,a,r+1)):s.push(a)}return s}function X9(e,n){if(!n)return"";const r=String(n).split(".").reduce((i,o)=>i==null?void 0:i[o],e);if(r==null)return"";const s=Array.isArray(r)?r.join(", "):String(r);return s.length>40?s.slice(0,40)+"â¦":s}async function G9(){const{data:e,error:n}=await w.from("lead_sources").select("*").order("created_at",{ascending:!0});if(n)throw n;return e||[]}async function J9(e,n){const{data:r,error:s}=await w.from("lead_sources").insert({tenant_id:e,name:n,token:H4(),source_tag:"partner_api",enabled:!1,require_consent:!0,chase_kind:"booking",duplicate_policy:"new_flagged",field_map:{}}).select("*").single();if(s)throw s;return r}async function Q9(e,n){const{data:r,error:s}=await w.from("lead_sources").update({...n,updated_at:new Date().toISOString()}).eq("id",e).select("*").single();if(s)throw s;return r}async function eq(e){const{error:n}=await w.from("lead_sources").delete().eq("id",e);if(n)throw n}async function tq(e){const{count:n,error:r}=await w.from("leads").select("id",{count:"exact",head:!0}).eq("lead_source_id",e);if(r)throw r;return n||0}const st={head:"#e2e8f0",muted:"#64748b",accent:"#38bdf8",border:"#1e3a4f",panel:"rgba(13,126,163,0.06)",panelBorder:"rgba(13,126,163,0.2)",card:"rgba(255,255,255,0.02)",cardBorder:"rgba(255,255,255,0.08)",warn:"#fbbf24",good:"#4ade80"},La=e=>t.jsx("div",{style:{color:st.muted,fontSize:11,fontWeight:600,marginBottom:6},children:e}),Wa={width:"100%",padding:"8px 10px",borderRadius:8,fontSize:13,background:"rgba(255,255,255,0.03)",border:`1px solid ${st.border}`,color:st.head},jo=e=>({padding:"7px 14px",borderRadius:8,fontSize:12,fontWeight:700,color:"#fff",background:e,border:"none",cursor:"pointer"});function am(e){if(!e)return"never";const n=Math.floor((Date.now()-new Date(e).getTime())/6e4);if(n<1)return"just now";if(n<60)return`${n}m ago`;const r=Math.floor(n/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}function nq(){const{tenant:e,profile:n}=Ee(),r=(n==null?void 0:n.tenant_id)??(e==null?void 0:e.id)??null,[s,i]=g.useState([]),[o,a]=g.useState({}),[l,d]=g.useState(!0),[c,f]=g.useState(null),[p,u]=g.useState(null),[h,y]=g.useState(!1),[m,b]=g.useState(""),[A,v]=g.useState("");g.useEffect(()=>{x()},[]);async function x(){d(!0);try{const O=await G9();i(O),O.length&&!c&&_(O[0]);const z={};for(const P of O)try{z[P.id]=await tq(P.id)}catch{z[P.id]=0}a(z)}catch(O){b("â "+O.message)}d(!1)}function _(O){f(O.id),u(JSON.parse(JSON.stringify(O))),b(""),v("")}async function j(){if(!r){b("â No tenant in session");return}try{const O=await J9(r,"New source");await x(),_(O)}catch(O){b("â "+O.message)}}async function C(){if(p){y(!0),b("");try{const O=await Q9(p.id,{name:p.name,source_tag:p.source_tag,token:p.token,enabled:p.enabled,require_consent:p.require_consent,duplicate_policy:p.duplicate_policy,field_map:p.field_map});b("â
Saved"),i(z=>z.map(P=>P.id===O.id?O:P)),u(JSON.parse(JSON.stringify(O)))}catch(O){b("â "+O.message)}y(!1)}}async function S(O){const z=o[O.id]||0,P=z>0?`${O.name} has captured ${z} lead${z===1?"":"s"}. Those leads stay, but lose their link back to this source. Delete anyway?`:`Delete ${O.name}? The vendor's posts will start failing immediately.`;if(confirm(P))try{await eq(O.id),f(null),u(null),await x()}catch(D){b("â "+D.message)}}function T(O,z){navigator.clipboard.writeText(O),v(z),setTimeout(()=>v(""),1800)}function L(O,z){if(!p)return;const P={...p.field_map||{}};z?P[O]=z:delete P[O],u({...p,field_map:P})}const E=p!=null&&p.last_payload?V4(p.last_payload):[],R=new Set(Object.values((p==null?void 0:p.field_map)||{})),N=E.filter(O=>!R.has(O));return l?t.jsx("div",{style:{color:st.muted,padding:20},children:"Loadingâ¦"}):t.jsxs("div",{style:{display:"flex",gap:16,alignItems:"flex-start",height:"100%",overflowY:"auto",paddingRight:4,paddingBottom:24},children:[t.jsxs("div",{style:{width:260,flexShrink:0},children:[t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:10},children:[t.jsx("div",{style:{color:st.head,fontSize:13,fontWeight:700},children:"Lead sources"}),t.jsx("button",{onClick:j,style:jo("linear-gradient(135deg, #3b82f6, #2563eb)"),children:"+ Add"})]}),s.length===0&&t.jsx("div",{style:{color:st.muted,fontSize:12,padding:12,border:`1px dashed ${st.border}`,borderRadius:10},children:"No partner feeds yet. Add one to give a lead vendor a URL and token."}),s.map(O=>{const z=O.id===c;return t.jsxs("button",{onClick:()=>_(O),style:{width:"100%",textAlign:"left",padding:"10px 12px",borderRadius:10,marginBottom:4,cursor:"pointer",background:z?"rgba(13,126,163,0.15)":"transparent",border:`1px solid ${z?st.panelBorder:"transparent"}`},children:[t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",gap:6},children:[t.jsx("span",{style:{color:z?st.accent:st.head,fontSize:13,fontWeight:600},children:O.name}),t.jsx("span",{style:{fontSize:9,padding:"2px 7px",borderRadius:20,flexShrink:0,background:O.enabled?"rgba(74,222,128,0.12)":"rgba(251,191,36,0.12)",color:O.enabled?st.good:st.warn,border:`1px solid ${O.enabled?"rgba(74,222,128,0.25)":"rgba(251,191,36,0.25)"}`},children:O.enabled?"LIVE":"LEARNING"})]}),t.jsxs("div",{style:{color:st.muted,fontSize:10,marginTop:3},children:[o[O.id]??0," leads · last post ",am(O.last_received_at)]})]},O.id)})]}),p&&t.jsxs("div",{style:{flex:1,minWidth:0},children:[m&&t.jsx("div",{style:{marginBottom:10,fontSize:12,color:m.startsWith("â
")?st.good:"#f87171"},children:m}),t.jsxs("div",{style:{background:st.panel,border:`1px solid ${st.panelBorder}`,borderRadius:12,padding:14,marginBottom:14},children:[t.jsxs("div",{style:{color:st.accent,fontSize:12,fontWeight:700,marginBottom:10},children:["Send these to ",p.name]}),La("Endpoint URL â POST, Content-Type: application/json"),t.jsxs("div",{style:{display:"flex",gap:6,marginBottom:10},children:[t.jsx("input",{readOnly:!0,value:Hv,style:{...Wa,fontFamily:"monospace",fontSize:12}}),t.jsx("button",{onClick:()=>T(Hv,"url"),style:jo("rgba(13,126,163,0.3)"),children:A==="url"?"â":"Copy"})]}),La("Header â X-Capture-Token"),t.jsxs("div",{style:{display:"flex",gap:6},children:[t.jsx("input",{readOnly:!0,value:p.token,style:{...Wa,fontFamily:"monospace",fontSize:12}}),t.jsx("button",{onClick:()=>T(p.token,"token"),style:jo("rgba(13,126,163,0.3)"),children:A==="token"?"â":"Copy"}),t.jsx("button",{onClick:()=>{confirm("Generate a new token? The vendor stops delivering until you give them the new one.")&&(u({...p,token:H4()}),b("New token generated â Save, then send it to the vendor."))},style:jo("rgba(251,191,36,0.2)"),children:"Regenerate"})]}),t.jsx("div",{style:{color:st.muted,fontSize:10,marginTop:6},children:"Anyone holding this token can create leads in your account. Treat it like a password."})]}),t.jsxs("div",{style:{background:st.card,border:`1px solid ${st.cardBorder}`,borderRadius:12,padding:14,marginBottom:14},children:[t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12,marginBottom:12},children:[t.jsxs("div",{children:[La("Name"),t.jsx("input",{value:p.name,onChange:O=>u({...p,name:O.target.value}),style:Wa})]}),t.jsxs("div",{children:[La("Source tag â what shows on the lead"),t.jsx("input",{value:p.source_tag,onChange:O=>u({...p,source_tag:O.target.value}),style:Wa})]})]}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12},children:[t.jsxs("div",{children:[La("Duplicate handling"),t.jsxs("select",{value:p.duplicate_policy,onChange:O=>u({...p,duplicate_policy:O.target.value}),style:Wa,children:[t.jsx("option",{value:"new_flagged",children:"Keep as a new lead, flagged as duplicate"}
564),t.jsx("option",{value:"reopen",children:"Reopen the existing lead"})]}),t.jsx("div",{style:{color:st.muted,fontSize:10,marginTop:5},children:p.duplicate_policy==="new_flagged"?"Right for paid feeds â a lead you paid for stays countable instead of merging into an old record.":"Right for your own forms â a returning visitor updates their existing lead."})]}),t.jsxs("div",{children:[La("Requirements"),t.jsxs("label",{style:{display:"flex",gap:8,alignItems:"center",color:st.head,fontSize:12,marginBottom:8,cursor:"pointer"},children:[t.jsx("input",{type:"checkbox",checked:p.require_consent,onChange:O=>u({...p,require_consent:O.target.checked})}),"Require consent proof"]}),t.jsx("div",{style:{color:st.muted,fontSize:10,marginBottom:10},children:"Leads with no TrustedForm or Jornaya certificate are rejected rather than accepted and texted."}),t.jsxs("label",{style:{display:"flex",gap:8,alignItems:"center",color:st.head,fontSize:12,cursor:"pointer"},children:[t.jsx("input",{type:"checkbox",checked:p.enabled,onChange:O=>u({...p,enabled:O.target.checked})}),"Enabled â create real leads"]}),t.jsx("div",{style:{color:st.muted,fontSize:10,marginTop:4},children:"While off, posts are accepted and recorded below but no lead is created."})]})]})]}),t.jsxs("div",{style:{background:st.card,border:`1px solid ${st.cardBorder}`,borderRadius:12,padding:14,marginBottom:14},children:[t.jsx("div",{style:{color:st.head,fontSize:12,fontWeight:700,marginBottom:4},children:"Field mapping"}),t.jsx("div",{style:{color:st.muted,fontSize:11,marginBottom:12},children:E.length===0?"No posts received yet. Ask the vendor to send one test lead, then reload this tab â their real field names will appear here to choose from.":`Received ${E.length} field${E.length===1?"":"s"} ${am(p.last_received_at)}. Match each to yours.`}),E.length>0&&t.jsxs(t.Fragment,{children:[Y9.map(O=>{var P;const z=((P=p.field_map)==null?void 0:P[O.key])||"";return t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"150px 1fr 150px",gap:10,alignItems:"center",marginBottom:6},children:[t.jsxs("div",{style:{color:st.head,fontSize:12},children:[O.label,O.hint&&t.jsx("span",{style:{color:st.muted,fontSize:10,display:"block"},children:O.hint})]}),t.jsxs("select",{value:z,onChange:D=>L(O.key,D.target.value),style:Wa,children:[t.jsx("option",{value:"",children:"â not sent â"}),E.map(D=>t.jsx("option",{value:D,children:D},D))]}),t.jsx("div",{style:{color:st.muted,fontSize:11,fontFamily:"monospace",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:z?X9(p.last_payload,z):""})]},O.key)}),N.length>0&&t.jsxs("div",{style:{marginTop:12,paddingTop:10,borderTop:`1px solid ${st.border}`},children:[t.jsxs("div",{style:{color:st.muted,fontSize:11},children:["Not mapped: ",N.join(", ")]}),t.jsx("div",{style:{color:st.muted,fontSize:10,marginTop:4},children:"Anything left unmapped is discarded. Map it above if you need it on the lead."})]})]})]}),p.last_payload&&t.jsxs("details",{style:{marginBottom:14},children:[t.jsxs("summary",{style:{color:st.muted,fontSize:11,cursor:"pointer"},children:["Last payload received (",am(p.last_received_at),")"]}),t.jsx("pre",{style:{marginTop:8,padding:12,borderRadius:10,fontSize:11,overflow:"auto",maxHeight:260,background:"rgba(0,0,0,0.3)",border:`1px solid ${st.border}`,color:"#94a3b8"},children:JSON.stringify(p.last_payload,null,2)})]}),t.jsxs("div",{style:{display:"flex",gap:8},children:[t.jsx("button",{onClick:C,disabled:h,style:{...jo("linear-gradient(135deg, #3b82f6, #2563eb)"),opacity:h?.5:1},children:h?"Savingâ¦":"Save"}),t.jsx("button",{onClick:()=>x(),style:jo("rgba(255,255,255,0.06)"),children:"Reload"}),t.jsx("div",{style:{flex:1}}),t.jsx("button",{onClick:()=>S(p),style:jo("rgba(248,113,113,0.15)"),children:"Delete"})]})]})]})}async function Z4(){const{data:{session:e}}=await w.auth.getSession(),n=e==null?void 0:e.access_token;return{"Content-Type":"application/json",...n?{Authorization:`Bearer ${n}`}:{}}}async function rq(){const{data:e,error:n}=await w.from("landing_pages").select("id, tenant_id, internal_name, slug, campaign_name, campaign_type, status, schema_version, preset_id, revision, updated_at, published_at, created_at").is("deleted_at",null).order("updated_at",{ascending:!1});if(n)throw n;return e??[]}async function K4(e){const{data:n,error:r}=await w.from("landing_pages").select("*").eq("id",e).is("deleted_at",null).maybeSingle();if(r)throw r;return n??null}async function sq(e){const{data:n,error:r}=await w.from("landing_pages").insert({internal_name:e.internal_name,slug:e.slug,campaign_name:e.campaign_name??null,campaign_type:e.campaign_type??null,preset_id:e.preset_id??null,default_form_id:e.default_form_id??null,tracking_source:e.tracking_source??null,seo_title:e.seo_title??null,seo_description:e.seo_description??null,status:"draft",schema_version:1,draft_config:{schema_version:1,meta:{},sections:[]},revision:0}).select("*").single();if(r)throw r;return n}async function iq(e,n){const r=await K4(e);if(!r)throw new Error("Source page not found");const s=(n||"").trim();if(!s)throw new Error("A name is required");const i=s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,58)||"page",{data:o,error:a}=await w.from("landing_pages").select("slug").is("deleted_at",null).like("slug",i+"%");if(a)throw a;const l=new Set((o??[]).map(y=>y.slug));let d=i,c=2;for(;l.has(d);)d=i+"-"+c,c++;const f=r.draft_config??{schema_version:1,meta:{},sections:[]},p=JSON.parse(JSON.stringify(f)),{data:u,error:h}=await w.from("landing_pages").insert({internal_name:s,slug:d,campaign_name:r.campaign_name??null,campaign_type:r.campaign_type??null,preset_id:r.preset_id??null,tracking_source:r.tracking_source??null,seo_title:r.seo_title??null,seo_description:r.seo_description??null,status:"draft",schema_version:r.schema_version??1,draft_config:p,revision:0}).select("*").single();if(h)throw h;return u}async function oq(e,n,r){const s=await fetch("/api/landing/save",{method:"POST",headers:await Z4(),body:JSON.stringify({page_id:e,config:n,expected_revision:r})}),i=await s.json().catch(()=>({}));return s.status===200&&i.ok?{ok:!0,revision:i.revision}:s.status===409?{ok:!1,conflict:!0,server_revision:i.server_revision,your_revision:i.your_revision}:{ok:!1,conflict:!1,error:i.error||`Save failed (${s.status})`,details:i.details}}async function aq(e,n){const r=await fetch("/api/landing/publish",{method:"POST",headers:await Z4(),body:JSON.stringify({page_id:e,publish_notes:n})}),s=await r.json().catch(()=>({}));return(r.status===200||r.status===207)&&s.published?{ok:!0,version_number:s.version_number,...s.version_
vendor: 4,538 bytes, line 564
564warning?{error:s.version_warning}:{}}:{ok:!1,error:s.error||`Publish failed (${r.status})`,details:s.details}}async function lq(e){const{data:n,error:r}=await w.from("landing_page_versions").select("id, version_number, action_type, created_by, created_at, publish_notes").eq("page_id",e).order("version_number",{ascending:!1});if(r)throw r;return n??[]}var Vv;function ye(e,n,r){function s(l,d){if(l._zod||Object.defineProperty(l,"_zod",{value:{def:d,constr:a,traits:new Set},enumerable:!1}),l._zod.traits.has(e))return;l._zod.traits.add(e),n(l,d);const c=a.prototype,f=Object.keys(c);for(let p=0;p<f.length;p++){const u=f[p];u in l||(l[u]=c[u].bind(l))}}const i=(r==null?void 0:r.Parent)??Object;class o extends i{}Object.defineProperty(o,"name",{value:e});function a(l){var d;const c=r!=null&&r.Parent?new o:this;s(c,l),(d=c._zod).deferred??(d.deferred=[]);for(const f of c._zod.deferred)f();return c}return Object.defineProperty(a,"init",{value:s}),Object.defineProperty(a,Symbol.hasInstance,{value:l=>{var d,c;return r!=null&&r.Parent&&l instanceof r.Parent?!0:(c=(d=l==null?void 0:l._zod)==null?void 0:d.traits)==null?void 0:c.has(e)}}),Object.defineProperty(a,"name",{value:e}),a}class kl extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class Y4 extends Error{constructor(n){super(`Encountered unidirectional transform during encode: ${n}`),this.name="ZodEncodeError"}}(Vv=globalThis).__zod_globalConfig??(Vv.__zod_globalConfig={});const c0=globalThis.__zod_globalConfig;function ti(e){return c0}function X4(e){const n=Object.values(e).filter(s=>typeof s=="number");return Object.entries(e).filter(([s,i])=>n.indexOf(+s)===-1).map(([s,i])=>i)}function jy(e,n){return typeof n=="bigint"?n.toString():n}function Hf(e){return{get value(){{const n=e();return Object.defineProperty(this,"value",{value:n}),n}}}}function u0(e){return e==null}function p0(e){const n=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(n,r)}function dq(e,n){const r=e/n,s=Math.round(r),i=Number.EPSILON*Math.max(Math.abs(r),1);return Math.abs(r-s)<i?0:r-s}const Zv=Symbol("evaluating");function mt(e,n,r){let s;Object.defineProperty(e,n,{get(){if(s!==Zv)return s===void 0&&(s=Zv,s=r()),s},set(i){Object.defineProperty(e,n,{value:i})},configurable:!0})}function wa(e,n,r){Object.defineProperty(e,n,{value:r,writable:!0,enumerable:!0,configurable:!0})}function ho(...e){const n={};for(const r of e){const s=Object.getOwnPropertyDescriptors(r);Object.assign(n,s)}return Object.defineProperties({},n)}function Kv(e){return JSON.stringify(e)}function cq(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const G4="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Gc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const uq=Hf(()=>{var e;if(c0.jitless||typeof navigator<"u"&&((e=navigator==null?void 0:navigator.userAgent)!=null&&e.includes("Cloudflare")))return!1;try{const n=Function;return new n(""),!0}catch{return!1}});function Jl(e){if(Gc(e)===!1)return!1;const n=e.constructor;if(n===void 0||typeof n!="function")return!0;const r=n.prototype;return!(Gc(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function J4(e){return Jl(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const pq=new Set(["string","number","symbol"]);function Ql(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function fo(e,n,r){const s=new e._zod.constr(n??e._zod.def);return(!n||r!=null&&r.parent)&&(s._zod.parent=e),s}function We(e){const n=e;if(!n)return{};if(typeof n=="string")return{error:()=>n};if((n==null?void 0:n.message)!==void 0){if((n==null?void 0:n.error)!==void 0)throw new Error("Cannot specify both `message` and `error` params");n.error=n.message}return delete n.message,typeof n.error=="string"?{...n,error:()=>n.error}:n}function hq(e){return Object.keys(e).filter(n=>e[n]._zod.optin==="optional"&&e[n]._zod.optout==="optional")}const fq={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 gq(e,n){const r=e._zod.def,s=r.checks;if(s&&s.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const o=ho(e._zod.def,{get shape(){const a={};for(const l in n){if(!(l in r.shape))throw new Error(`Unrecognized key: "${l}"`);
564n[l]&&(a[l]=r.shape[l])}return wa(this,"shape",a),a},checks:[]});return fo(e,o)}function mq(e,n){const r=e._zod.def,s=r.checks;if(s&&s.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const o=ho(e._zod.def,{get shape(){const a={...e._zod.def.shape};for(const l in n){if(!(l in r.shape))throw new Error(`Unrecognized key: "${l}"`);n[l]&&delete a[l]}return wa(this,"shape",a),a},checks:[]});return fo(e,o)}function xq(e,n){if(!Jl(n))throw new Error("Invalid input to extend: expected a plain object");const r=e._zod.def.checks;if(r&&r.length>0){const o=e._zod.def.shape;for(const a in n)if(Object.getOwnPropertyDescriptor(o,a)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const i=ho(e._zod.def,{get shape(){const o={...e._zod.def.shape,...n};return wa(this,"shape",o),o}});return fo(e,i)}function yq(e,n){if(!Jl(n))throw new Error("Invalid input to safeExtend: expected a plain object");const r=ho(e._zod.def,{get shape(){const s={...e._zod.def.shape,...n};return wa(this,"shape",s),s}});return fo(e,r)}function bq(e,n){var s;if((s=e._zod.def.checks)!=null&&s.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");const r=ho(e._zod.def,{get shape(){const i={...e._zod.def.shape,...n._zod.def.shape};return wa(this,"shape",i),i},get catchall(){return n._zod.def.catchall},checks:n._zod.def.checks??[]});return fo(e,r)}function Aq(e,n,r){const i=n._zod.def.checks;if(i&&i.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const a=ho(n._zod.def,{get shape(){const l=n._zod.def.shape,d={...l};if(r)for(const c in r){if(!(c in l))throw new Error(`Unrecognized key: "${c}"`);r[c]&&(d[c]=e?new e({type:"optional",innerType:l[c]}):l[c])}else for(const c in l)d[c]=e?new e({type:"optional",innerType:l[c]}):l[c];return wa(this,"shape",d),d},checks:[]});return fo(n,a)}function vq(e,n,r){const s=ho(n._zod.def,{get shape(){const i=n._zod.def.shape,o={...i};if(r)for(const a in r){if(!(a in o))throw new Error(`Unrecognized key: "${a}"`);r[a]&&(o[a]=new e({type:"nonoptional",innerType:i[a]}))}else for(const a in i)o[a]=new e({type:"nonoptional",innerType:i[a]});return wa(this,"shape",o),o}});return fo(n,s)}function gl(e,n=0){var r;if(e.aborted===!0)return!0;for(let s=n;s<e.issues.length;s++)if(((r=e.issues[s])==null?void 0:r.continue)!==!0)return!0;return!1}function _q(e,n=0){var r;if(e.aborted===!0)return!0;for(let s=n;s<e.issues.length;s++)if(((r=e.issues[s])==null?void 0:r.continue)===!1)return!0;return!1}function ml(e,n){return n.map(r=>{var s;return(s=r).path??(s.path=[]),r.path.unshift(e),r})}function up(e){return typeof e=="string"?e:e==null?void 0:e.message}function ni(e,n,r){var d,c,f,p,u,h;const s=e.message?e.message:up((f=(c=(d=e.inst)==null?void 0:d._zod.def)==null?void 0:c.error)==null?void 0:f.call(c,e))??up((p=n==null?void 0:n.error)==null?void 0:p.call(n,e))??up((u=r.customError)==null?void 0:u.call(r,e))??up((h=r.localeError)==null?void 0:h.call(r,e))??"Invalid input",{inst:i,continue:o,input:a,...l}=e;return l.path??(l.path=[]),l.message=s,n!=null&&n.reportInput&&(l.input=a),l}function h0(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Jc(...e){const[n,r,s]=e;return typeof n=="string"?{message:n,code:"custom",input:r,inst:s}:{...n}}const Q4=(e,n)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:n,enumerable:!1}),e.message=JSON.stringify(n,jy,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},ek=ye("$ZodError",Q4),tk=ye("$ZodError",Q4,{Parent:Error});function jq(e,n=r=>r.message){const r={},s=[];for(const i of e.issues)i.path.length>0?(r[i.path[0]]=r[i.path[0]]||[],r[i.path[0]].push(n(i))):s.push(n(i));return{formErrors:s,fieldErrors:r}}function wq(e,n=r=>r.message){const r={_errors:[]},s=(i,o=[])=>{for(const a of i.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(l=>s({issues:l},[...o,...a.path]));else if(a.code==="invalid_key")s({issues:a.issues},[...o,...a.path]);else if(a.code==="invalid_element")s({issues:a.issues},[...o,...a.path]);else{const l=[...o,...a.path];if(l.length===0)r._errors.push(n(a));else{let d=r,c=0;for(;c<l.length;){const f=l[c];c===l.length-1?(d[f]=d[f]||{_errors:[]},d[f]._errors.push(n(a))):d[f]=d[f]||{_errors:[]}
vendor: 22,494 bytes, lines 564-609
564,d=d[f],c++}}}};return s(e),r}const f0=e=>(n,r,s,i)=>{const o=s?{...s,async:!1}:{async:!1},a=n._zod.run({value:r,issues:[]},o);if(a instanceof Promise)throw new kl;if(a.issues.length){const l=new((i==null?void 0:i.Err)??e)(a.issues.map(d=>ni(d,o,ti())));throw G4(l,i==null?void 0:i.callee),l}return a.value},g0=e=>async(n,r,s,i)=>{const o=s?{...s,async:!0}:{async:!0};let a=n._zod.run({value:r,issues:[]},o);if(a instanceof Promise&&(a=await a),a.issues.length){const l=new((i==null?void 0:i.Err)??e)(a.issues.map(d=>ni(d,o,ti())));throw G4(l,i==null?void 0:i.callee),l}return a.value},Vf=e=>(n,r,s)=>{const i=s?{...s,async:!1}:{async:!1},o=n._zod.run({value:r,issues:[]},i);if(o instanceof Promise)throw new kl;return o.issues.length?{success:!1,error:new(e??ek)(o.issues.map(a=>ni(a,i,ti())))}:{success:!0,data:o.value}},Sq=Vf(tk),Zf=e=>async(n,r,s)=>{const i=s?{...s,async:!0}:{async:!0};let o=n._zod.run({value:r,issues:[]},i);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new e(o.issues.map(a=>ni(a,i,ti())))}:{success:!0,data:o.value}},kq=Zf(tk),Cq=e=>(n,r,s)=>{const i=s?{...s,direction:"backward"}:{direction:"backward"};return f0(e)(n,r,i)},Tq=e=>(n,r,s)=>f0(e)(n,r,s),zq=e=>async(n,r,s)=>{const i=s?{...s,direction:"backward"}:{direction:"backward"};return g0(e)(n,r,i)},Nq=e=>async(n,r,s)=>g0(e)(n,r,s),Rq=e=>(n,r,s)=>{const i=s?{...s,direction:"backward"}:{direction:"backward"};return Vf(e)(n,r,i)},Eq=e=>(n,r,s)=>Vf(e)(n,r,s),Pq=e=>async(n,r,s)=>{const i=s?{...s,direction:"backward"}:{direction:"backward"};return Zf(e)(n,r,i)},qq=e=>async(n,r,s)=>Zf(e)(n,r,s),Dq=/^[cC][0-9a-z]{6,}$/,Oq=/^[0-9a-z]+$/,Iq=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Lq=/^[0-9a-vA-V]{20}$/,Wq=/^[A-Za-z0-9]{27}$/,$q=/^[a-zA-Z0-9_-]{21}$/,Mq=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Fq=/^([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})$/,Yv=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[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)$/,Bq=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Uq="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Hq(){return new RegExp(Uq,"u")}const Vq=/^(?:(?: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])$/,Zq=/^(([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}|:))$/,Kq=/^((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])$/,Yq=/^(([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])$/,Xq=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,nk=/^[A-Za-z0-9_-]*$/,Gq=/^https?$/,Jq=/^\+[1-9]\d{6,14}$/,rk="(?:(?:\\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])))",Qq=new RegExp(`^${rk}$`);function sk(e){const n="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${n}`:e.precision===0?`${n}:[0-5]\\d`:`${n}:[0-5]\\d\\.\\d{${e.precision}}`:`${n}(?::[0-5]\\d(?:\\.\\d+)?)?`}function eD(e){return new RegExp(`^${sk(e)}$`)}function tD(e){const n=sk({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const s=`${n}(?:${r.join("|")})`;return new RegExp(`^${rk}T(?:${s})$`)}const nD=e=>{const n=e?`[\\s\\S]{${(e==null?void 0:e.minimum)??0},${(e==null?void 0:e.maximum)??""}}`:"[\\s\\S]*";return new RegExp(`^${n}$`)},rD=/^-?\d+$/,ik=/^-?\d+(?:\.\d+)?$/,sD=/^(?:true|false)$/i,iD=/^[^A-Z]*$/,oD=/^[^a-z]*$/,ur=ye("$ZodCheck",(e,n)=>{var r;e._zod??(e._zod={}),e._zod.def=n,(r=e._zod).onattach??(r.onattach=[])}),ok={number:"number",bigint:"bigint",object:"date"},ak=ye("$ZodCheckLessThan",(e,n)=>{ur.init(e,n);const r=ok[typeof n.value];e._zod.onattach.push(s=>{const i=s._zod.bag,o=(n.inclusive?i.maximum:i.exclusiveMaximum)??Number.POSITIVE_INFINITY;n.value<o&&(n.inclusive?i.maximum=n.value:i.exclusiveMaximum=n.value)}),e._zod.check=s=>{(n.inclusive?s.value<=n.value:s.value<n.value)||s.issues.push({origin:r,code:"too_big",maximum:typeof n.value=="object"?n.value.getTime():n.value,input:s.value,inclusive:n.inclusive,inst:e,continue:!n.abort})}}),lk=ye("$ZodCheckGreaterThan",(e,n)=>{ur.init(e,n);const r=ok[typeof n.value];e._zod.onattach.push(s=>{const i=s._zod.bag,o=(n.inclusive?i.minimum:i.exclusiveMinimum)??Number.NEGATIVE_INFINITY;n.value>o&&(n.inclusive?i.minimum=n.value:i.exclusiveMinimum=n.value)}),e._zod.check=s=>{(n.inclusive?s.value>=n.value:s.value>n.value)||s.issues.push({origin:r,code:"too_small",minimum:typeof n.value=="object"?n.value.getTime():n.value,input:s.value,inclusive:n.inclusive,inst:e,continue:!n.abort})}}),aD=ye("$ZodCheckMultipleOf",(e,n)=>{ur.init(e,n),e._zod.onattach.push(r=>{var s;(s=r._zod.bag).multipleOf??(s.multipleOf=n.value)}),e._zod.check=r=>{if(typeof r.value!=typeof n.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%n.value===BigInt(0):dq(r.value,n.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:n.value,input:r.value,inst:e,continue:!n.abort})}}),lD=ye("$ZodCheckNumberFormat",(e,n)=>{var a;ur.init(e,n),n.format=n.format||"float64";const r=(a=n.format)==null?void 0:a.includes("int"),s=r?"int":"number",[i,o]=fq[n.format];e._zod.onattach.push(l=>{const d=l._zod.bag;d.format=n.format,d.minimum=i,d.maximum=o,r&&(d.pattern=rD)}),e._zod.check=l=>{const d=l.value;if(r){if(!Number.isInteger(d)){l.issues.push({expected:s,format:n.format,code:"invalid_type",continue:!1,input:d,inst:e});return}if(!Number.isSafeInteger(d)){d>0?l.issues.push({input:d,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:s,inclusive:!0,continue:!n.abort}):l.issues.push({input:d,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:s,inclusive:!0,continue:!n.abort});return}}d<i&&l.issues.push({origin:"number",input:d,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!n.abort}),d>o&&l.issues.push({origin:"number",input:d,code:"too_big",maximum:o,inclusive:!0,inst:e,continue:!n.abort})}}),dD=ye("$ZodCheckMaxLength",(e,n)=>{var r;ur.init(e,n),(r=e._zod.def).when??(r.when=s=>{const i=s.value;return!u0(i)&&i.length!==void 0}),e._zod.onattach.push(s=>{const i=s._zod.bag.maximum??Number.POSITIVE_INFINITY;n.maximum<i&&(s._zod.bag.maximum=n.maximum)}),e._zod.check=s=>{const i=s.value;if(i.length<=n.maximum)return;const a=h0(i);s.issues.push({origin:a,code:"too_big",maximum:n.maximum,inclusive:!0,input:i,inst:e,continue:!n.abort})}}),cD=ye("$ZodCheckMinLength",(e,n)=>{var r;ur.init(e,n),(r=e._zod.def).when??(r.when=s=>{const i=s.value;return!u0(i)&&i.length!==void 0}),e._zod.onattach.push(s=>{const i=s._zod.bag.minimum??Number.NEGATIVE_INFINITY;n.minimum>i&&(s._zod.bag.minimum=n.minimum)}),e._zod.check=s=>{const i=s.value;if(i.length>=n.minimum)return;const a=h0(i);s.issues.push({origin:a,code:"too_small",minimum:n.minimum,inclusive:!0,input:i,inst:e,continue:!n.abort})}}),uD=ye("$ZodCheckLengthEquals",(e,n)=>{var r;ur.init(e,n),(r=e._zod.def).when??(r.when=s=>{const i=s.value;return!u0(i)&&i.length!==void 0}),e._zod.onattach.push(s=>{const i=s._zod.bag;i.minimum=n.length,i.maximum=n.length,i.length=n.length}),e._zod.check=s=>{const i=s.value,o=i.length;if(o===n.length)return;const a=h0(i),l=o>n.length;s.issues.push({origin:a,...l?{code:"too_big",maximum:n.length}:{code:"too_small",minimum:n.length},inclusive:!0,exact:!0,input:s.value,inst:e,continue:!n.abort})}}),Kf=ye("$ZodCheckStringFormat",(e,n)=>{var r,s;ur.init(e,n),e._zod.onattach.push(i=>{const o=i._zod.bag;o.format=n.format,n.pattern&&(o.patterns??(o.patterns=new Set),o.patterns.add(n.pattern))}),n.pattern?(r=e._zod).check??(r.check=i=>{n.pattern.lastIndex=0,!n.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:n.format,input:i.value,...n.pattern?{pattern:n.pattern.toString()}:{},inst:e,continue:!n.abort})}):(s=e._zod).check??(s.check=()=>{})}),pD=ye("$ZodCheckRegex",(e,n)=>{Kf.init(e,n),e._zod.check=r=>{n.pattern.lastIndex=0,!n.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:n.pattern.toString(),inst:e,continue:!n.abort})}}),hD=ye("$ZodCheckLowerCase",(e,n)=>{n.pattern??(n.pattern=iD),Kf.init(e,n)}),fD=ye("$ZodCheckUpperCase",(e,n)=>{n.pattern??(n.pattern=oD),Kf.init(e,n)}),gD=ye("$ZodCheckIncludes",(e,n)=>{ur.init(e,n);const r=Ql(n.includes),s=new RegExp(typeof n.position=="number"?`^.{${n.position}}${r}`:r);n.pattern=s,e._zod.onattach.push(i=>{const o=i._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(s)}),e._zod.check=i=>{i.value.includes(n.includes,n.position)||i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:n.includes,input:i.value,inst:e,continue:!n.abort})}}),mD=ye("$ZodCheckStartsWith",(e,n)=>{ur.init(e,n);const r=new RegExp(`^${Ql(n.prefix)}.*`);n.pattern??(n.pattern=r),e._zod.onattach.push(s=>{const i=s._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(r)}),e._zod.check=s=>{s.value.startsWith(n.prefix)||s.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:n.prefix,input:s.value,inst:e,continue:!n.abort})}}),xD=ye("$ZodCheckEndsWith",(e,n)=>{ur.init(e,n);const r=new RegExp(`.*${Ql(n.suffix)}$`);n.pattern??(n.pattern=r),e._zod.onattach.push(s=>{const i=s._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(r)}),e._zod.check=s=>{s.value.endsWith(n.suffix)||s.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:n.suffix,input:s.value,inst:e,continue:!n.abort})}}),yD=ye("$ZodCheckOverwrite",(e,n)=>{ur.init(e,n),e._zod.check=r=>{r.value=n.tx(r.value)}});class bD{constructor(n=[]){this.content=[],this.indent=0,this&&(this.args=n)}indented(n){this.indent+=1,n(this),this.indent-=1}write(n){if(typeof n=="function"){n(this,{execution:"sync"}),n(this,{execution:"async"});return}const s=n.split(` 565`).filter(a=>a),i=Math.min(...s.map(a=>a.length-a.trimStart().length)),o=s.map(a=>a.slice(i)).map(a=>" ".repeat(this.indent*2)+a);for(const a of o)this.content.push(a)}compile(){const n=Function,r=this==null?void 0:this.args,i=[...((this==null?void 0:this.content)??[""]).map(o=>` ${o}`)];return new n(...r,i.join(` 566`))}}const AD={major:4,minor:4,patch:3},$t=ye("$ZodType",(e,n)=>{var i;var r;e??(e={}),e._zod.def=n,e._zod.bag=e._zod.bag||{},e._zod.version=AD;const s=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&s.unshift(e);for(const o of s)for(const a of o._zod.onattach)a(e);if(s.length===0)(r=e._zod).deferred??(r.deferred=[]),(i=e._zod.deferred)==null||i.push(()=>{e._zod.run=e._zod.parse});else{const o=(l,d,c)=>{let f=gl(l),p;for(const u of d){if(u._zod.def.when){if(_q(l)||!u._zod.def.when(l))continue}else if(f)continue;const h=l.issues.length,y=u._zod.check(l);if(y instanceof Promise&&(c==null?void 0:c.async)===!1)throw new kl;if(p||y instanceof Promise)p=(p??Promise.resolve()).then(async()=>{await y,l.issues.length!==h&&(f||(f=gl(l,h)))});else{if(l.issues.length===h)continue;f||(f=gl(l,h))}}return p?p.then(()=>l):l},a=(l,d,c)=>{if(gl(l))return l.aborted=!0,l;const f=o(d,s,c);if(f instanceof Promise){if(c.async===!1)throw new kl;return f.then(p=>e._zod.parse(p,c))}return e._zod.parse(f,c)};e._zod.run=(l,d)=>{if(d.skipChecks)return e._zod.parse(l,d);if(d.direction==="backward"){const f=e._zod.parse({value:l.value,issues:[]},{...d,skipChecks:!0});return f instanceof Promise?f.then(p=>a(p,l,d)):a(f,l,d)}const c=e._zod.parse(l,d);if(c instanceof Promise){if(d.async===!1)throw new kl;return c.then(f=>o(f,s,d))}return o(c,s,d)}}mt(e,"~standard",()=>({validate:o=>{var a;try{const l=Sq(e,o);return l.success?{value:l.data}:{issues:(a=l.error)==null?void 0:a.issues}}catch{return kq(e,o).then(d=>{var c;return d.success?{value:d.data}:{issues:(c=d.error)==null?void 0:c.issues}})}},vendor:"zod",version:1}))}),m0=ye("$ZodString",(e,n)=>{var r;$t.init(e,n),e._zod.pattern=[...((r=e==null?void 0:e._zod.bag)==null?void 0:r.patterns)??[]].pop()??nD(e._zod.bag),e._zod.parse=(s,i)=>{if(n.coerce)try{s.value=String(s.value)}catch{}return typeof s.value=="string"||s.issues.push({expected:"string",code:"invalid_type",input:s.value,inst:e}),s}}),Pt=ye("$ZodStringFormat",(e,n)=>{Kf.init(e,n),m0.init(e,n)}),vD=ye("$ZodGUID",(e,n)=>{n.pattern??(n.pattern=Fq),Pt.init(e,n)}),_D=ye("$ZodUUID",(e,n)=>{if(n.version){const s={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[n.version];if(s===void 0)throw new Error(`Invalid UUID version: "${n.version}"`);n.pattern??(n.pattern=Yv(s))}else n.pattern??(n.pattern=Yv());Pt.init(e,n)}),jD=ye("$ZodEmail",(e,n)=>{n.pattern??(n.pattern=Bq),Pt.init(e,n)}),wD=ye("$ZodURL",(e,n)=>{Pt.init(e,n),e._zod.check=r=>{var s;try{const i=r.value.trim();if(!n.normalize&&((s=n.protocol)==null?void 0:s.source)===Gq.source&&!/^https?:\/\//i.test(i)){r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:e,continue:!n.abort});return}const o=new URL(i);n.hostname&&(n.hostname.lastIndex=0,n.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:n.hostname.source,input:r.value,inst:e,continue:!n.abort})),n.protocol&&(n.protocol.lastIndex=0,n.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:n.protocol.source,input:r.value,inst:e,continue:!n.abort})),n.normalize?r.value=o.href:r.value=i;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!n.abort})}}}),SD=ye("$ZodEmoji",(e,n)=>{n.pattern??(n.pattern=Hq()),Pt.init(e,n)}),kD=ye("$ZodNanoID",(e,n)=>{n.pattern??(n.pattern=$q),Pt.init(e,n)}),CD=ye("$ZodCUID",(e,n)=>{n.pattern??(n.pattern=Dq),Pt.init(e,n)}),TD=ye("$ZodCUID2",(e,n)=>{n.pattern??(n.pattern=Oq),Pt.init(e,n)}),zD=ye("$ZodULID",(e,n)=>{n.pattern??(n.pattern=Iq),Pt.init(e,n)}),ND=ye("$ZodXID",(e,n)=>{n.pattern??(n.pattern=Lq),Pt.init(e,n)}),RD=ye("$ZodKSUID",(e,n)=>{n.pattern??(n.pattern=Wq),Pt.init(e,n)}),ED=ye("$ZodISODateTime",(e,n)=>{n.pattern??(n.pattern=tD(n)),Pt.init(e,n)}),PD=ye("$ZodISODate",(e,n)=>{n.pattern??(n.pattern=Qq),Pt.init(e,n)}),qD=ye("$ZodISOTime",(e,n)=>{n.pattern??(n.pattern=eD(n)),Pt.init(e,n)}),DD=ye("$ZodISODuration",(e,n)=>{n.pattern??(n.pattern=Mq),Pt.init(e,n)}),OD=ye("$ZodIPv4",(e,n)=>{n.pattern??(n.pattern=Vq),Pt.init(e,n),e._zod.bag.format="ipv4"}),ID=ye("$ZodIPv6",(e,n)=>{n.pattern??(n.pattern=Zq),Pt.init(e,n),e._zod.bag.format="ipv6",e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!n.abort})}}}),LD=ye("$ZodCIDRv4",(e,n)=>{n.pattern??(n.pattern=Kq),Pt.init(e,n)}),WD=ye("$ZodCIDRv6",(e,n)=>{n.pattern??(n.pattern=Yq),Pt.init(e,n),e._zod.check=r=>{const s=r.value.split("/");try{if(s.length!==2)throw new Error;const[i,o]=s;if(!o)throw new Error;const a=Number(o);if(`${a}`!==o)throw new Error;if(a<0||a>128)throw new Error;new URL(`http://[${i}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!n.abort})}}});function dk(e){if(e==="")return!0;if(/\s/.test(e)||e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const $D=ye("$ZodBase64",(e,n)=>{n.pattern??(n.pattern=Xq),Pt.init(e,n),e._zod.bag.contentEncoding="base64",e._zod.check=r=>{dk(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!n.abort})}});function MD(e){if(!nk.test(e))return!1;const n=e.replace(/[-_]/g,s=>s==="-"?"+":"/"),r=n.padEnd(Math.ceil(n.length/4)*4,"=");return dk(r)}const FD=ye("$ZodBase64URL",(e,n)=>{n.pattern??(n.pattern=nk),Pt.init(e,n),e._zod.bag.contentEncoding="base64url",e._zod.check=r=>{MD(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!n.abort})}}),BD=ye("$ZodE164",(e,n)=>{n.pattern??(n.pattern=Jq),Pt.init(e,n)});function UD(e,n=null){try{const r=e.split(".");if(r.length!==3)return!1;const[s]=r;if(!s)return!1;const i=JSON.parse(atob(s));return!("typ"in i&&(i==null?void 0:i.typ)!=="JWT"||!i.alg||n&&(!("alg"in i)||i.alg!==n))}catch{return!1}}const HD=ye("$ZodJWT",(e,n)=>{Pt.init(e,n),e._zod.check=r=>{UD(r.value,n.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!n.abort})}}),ck=ye("$ZodNumber",(e,n)=>{$t.init(e,n),e._zod.pattern=e._zod.bag.pattern??ik,e._zod.parse=(r,s)=>{if(n.coerce)try{r.value=Number(r.value)}catch{}const i=r.value;if(typeof i=="number"&&!Number.isNaN(i)&&Number.isFinite(i))return r;const o=typeof i=="number"?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...o?{received:o}:{}}),r}}),VD=ye("$ZodNumberFormat",(e,n)=>{lD.init(e,n),ck.init(e,n)}),ZD=ye("$ZodBoolean",(e,n)=>{$t.init(e,n),e._zod.pattern=sD,e._zod.parse=(r,s)=>{if(n.coerce)try{r.value=!!r.value}catch{}const i=r.value;return typeof i=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:e}),r}}),KD=ye("$ZodUnknown",(e,n)=>{$t.init(e,n),e._zod.parse=r=>r}),YD=ye("$ZodNever",(e,n)=>{$t.init(e,n),e._zod.parse=(r,s)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function Xv(e,n,r){e.issues.length&&n.issues.push(...ml(r,e.issues)),n.value[r]=e.value}const XD=ye("$ZodArray",(e,n)=>{$t.init(e,n),e._zod.parse=(r,s)=>{const i=r.value;if(!Array.isArray(i))return r.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),r;r.value=Array(i.length);const o=[];for(let a=0;a<i.length;a++){const l=i[a],d=n.element._zod.run({value:l,issues:[]},s);d instanceof Promise?o.push(d.then(c=>Xv(c,r,a))):Xv(d,r,a)}return o.length?Promise.all(o).then(()=>r):r}});function Xh(e,n,r,s,i,o){const a=r in s;if(e.issues.length){if(i&&o&&!a)return;n.issues.push(...ml(r,e.issues))}if(!a&&!i){e.issues.length||n.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}e.value===void 0?a&&(n.value[r]=void 0):n.value[r]=e.value}function uk(e){var s,i,o,a;const n=Object.keys(e.shape);for(const l of n)if(!((a=(o=(i=(s=e.shape)==null?void 0:s[l])==null?void 0:i._zod)==null?void 0:o.traits)!=null&&a.has("$ZodType")))throw new Error(`Invalid element at key "${l}": expected a Zod schema`);const r=hq(e.shape);return{...e,keys:n,keySet:new Set(n),numKeys:n.length,optionalKeys:new Set(r)}}function pk(e,n,r,s,i,o){const a=[],l=i.keySet,d=i.catchall._zod,c=d.def.type,f=d.optin==="optional",p=d.optout==="optional";for(const u in n){if(u==="__proto__"||l.has(u))continue;if(c==="never"){a.push(u);continue}const h=d.run({value:n[u],issues:[]},s);h instanceof Promise?e.push(h.then(y=>Xh(y,r,u,n,f,p))):Xh(h,r,u,n,f,p)}return a.length&&r.issues.push({code:"unrecognized_keys",keys:a,input:n,inst:o}),e.length?Promise.all(e).then(()=>r):r}const GD=ye("$ZodObject",(e,n)=>{$t.init(e,n);const r=Object.getOwnPropertyDescriptor(n,"shape");if(!(r!=null&&r.get)){const l=n.shape;Object.defineProperty(n,"shape",{get:()=>{const d={...l};return Object.defineProperty(n,"shape",{value:d}),d}})}const s=Hf(()=>uk(n));mt(e._zod,"propValues",()=>{const l=n.shape,d={};for(const c in l){const f=l[c]._zod;if(f.values){d[c]??(d[c]=new Set);for(const p of f.values)d[c].add(p)}}return d});const i=Gc,o=n.catchall;let a;e._zod.parse=(l,d)=>{a??(a=s.value);const c=l.value;if(!i(c))return l.issues.push({expected:"object",code:"invalid_type",input:c,inst:e}),l;l.value={};const f=[],p=a.shape;for(const u of a.keys){const h=p[u],y=h._zod.optin==="optional",m=h._zod.optout==="optional",b=h._zod.run({value:c[u],issues:[]},d);b instanceof Promise?f.push(b.then(A=>Xh(A,l,u,c,y,m))):Xh(b,l,u,c,y,m)}return o?pk(f,c,l,d,s.value,e):f.length?Promise.all(f).then(()=>l):l}}),JD=ye("$ZodObjectJIT",(e,n)=>{GD.init(e,n);const r=e._zod.parse,s=Hf(()=>uk(n)),i=u=>{var x,_;const h=new bD(["shape","payload","ctx"]),y=s.value,m=j=>{const C=Kv(j);return`shape[${C}]._zod.run({ value: input[${C}], issues: [] }, ctx)`};h.write("const input = payload.value;");const b=Object.create(null);let A=0;for(const j of y.keys)b[j]=`key_${A++}`;h.write("const newResult = {};");for(const j of y.keys){const C=b[j],S=Kv(j),T=u[j],L=((x=T==null?void 0:T._zod)==null?void 0:x.optin)==="optional",E=((_=T==null?void 0:T._zod)==null?void 0:_.optout)==="optional";h.write(`const ${C} = ${m(j)};`),L&&E?h.write(` 567 if (${C}.issues.length) { 568 if (${S} in input) { 569 payload.issues = payload.issues.concat(${C}.issues.map(iss => ({ 570 ...iss, 571 path: iss.path ? [${S}, ...iss.path] : [${S}] 572 }))); 573 } 574 } 575 576 if (${C}.value === undefined) { 577 if (${S} in input) { 578 newResult[${S}] = undefined; 579 } 580 } else { 581 newResult[${S}] = ${C}.value; 582 } 583 584 `):L?h.write(` 585 if (${C}.issues.length) { 586 payload.issues = payload.issues.concat(${C}.issues.map(iss => ({ 587 ...iss, 588 path: iss.path ? [${S}, ...iss.path] : [${S}] 589 }))); 590 } 591 592 if (${C}.value === undefined) { 593 if (${S} in input) { 594 newResult[${S}] = undefined; 595 } 596 } else { 597 newResult[${S}] = ${C}.value; 598 } 599 600 `):h.write(` 601 const ${C}_present = ${S} in input; 602 if (${C}.issues.length) { 603 payload.issues = payload.issues.concat(${C}.issues.map(iss => ({ 604 ...iss, 605 path: iss.path ? [${S}, ...iss.path] : [${S}] 606 }))); 607 } 608 if (!${C}_present && !${C}.issues.length) { 609 payload.issues.push({
610 code: "invalid_type", 611 expected: "nonoptional", 612 input: undefined, 613 path: [${S}] 614 }); 615 } 616 617 if (${C}_present) { 618 if (${C}.value === undefined) { 619 newResult[${S}] = undefined; 620 } else { 621 newResult[${S}] = ${C}.value; 622 } 623 } 624 625 `)}h.write("payload.value = newResult;"),h.write("return payload;");const v=h.compile();return(j,C)=>v(u,j,C)};let o;const a=Gc,l=!c0.jitless,c=l&&uq.value,f=n.catchall;let p;e._zod.parse=(u,h)=>{p??(p=s.value);const y=u.value;return a(y)?l&&c&&(h==null?void 0:h.async)===!1&&h.jitless!==!0?(o||(o=i(n.shape)),u=o(u,h),f?pk([],y,u,h,p,e):u):r(u,h):(u.issues.push({expected:"object",code:"invalid_type",input:y,inst:e}),u)}});function Gv(e,n,r,s){for(const o of e)if(o.issues.length===0)return n.value=o.value,n;const i=e.filter(o=>!gl(o));return i.length===1?(n.value=i[0].value,i[0]):(n.issues.push({code:"invalid_union",input:n.value,inst:r,errors:e.map(o=>o.issues.map(a=>ni(a,s,ti())))}),n)}const hk=ye("$ZodUnion",(e,n)=>{$t.init(e,n),mt(e._zod,"optin",()=>n.options.some(s=>s._zod.optin==="optional")?"optional":void 0),mt(e._zod,"optout",()=>n.options.some(s=>s._zod.optout==="optional")?"optional":void 0),mt(e._zod,"values",()=>{if(n.options.every(s=>s._zod.values))return new Set(n.options.flatMap(s=>Array.from(s._zod.values)))}),mt(e._zod,"pattern",()=>{if(n.options.every(s=>s._zod.pattern)){const s=n.options.map(i=>i._zod.pattern);return new RegExp(`^(${s.map(i=>p0(i.source)).join("|")})$`)}});const r=n.options.length===1?n.options[0]._zod.run:null;e._zod.parse=(s,i)=>{if(r)return r(s,i);let o=!1;const a=[];for(const l of n.options){const d=l._zod.run({value:s.value,issues:[]},i);if(d instanceof Promise)a.push(d),o=!0;else{if(d.issues.length===0)return d;a.push(d)}}return o?Promise.all(a).then(l=>Gv(l,s,e,i)):Gv(a,s,e,i)}}),QD=ye("$ZodDiscriminatedUnion",(e,n)=>{n.inclusive=!1,hk.init(e,n);const r=e._zod.parse;mt(e._zod,"propValues",()=>{const i={};for(const o of n.options){const a=o._zod.propValues;if(!a||Object.keys(a).length===0)throw new Error(`Invalid discriminated union option at index "${n.options.indexOf(o)}"`);for(const[l,d]of Object.entries(a)){i[l]||(i[l]=new Set);for(const c of d)i[l].add(c)}}return i});const s=Hf(()=>{var a;const i=n.options,o=new Map;for(const l of i){const d=(a=l._zod.propValues)==null?void 0:a[n.discriminator];if(!d||d.size===0)throw new Error(`Invalid discriminated union option at index "${n.options.indexOf(l)}"`);for(const c of d){if(o.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);o.set(c,l)}}return o});e._zod.parse=(i,o)=>{const a=i.value;if(!Gc(a))return i.issues.push({code:"invalid_type",expected:"object",input:a,inst:e}),i;const l=s.value.get(a==null?void 0:a[n.discriminator]);return l?l._zod.run(i,o):n.unionFallback||o.direction==="backward"?r(i,o):(i.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:n.discriminator,options:Array.from(s.value.keys()),input:a,path:[n.discriminator],inst:e}),i)}}),eO=ye("$ZodIntersection",(e,n)=>{$t.init(e,n),e._zod.parse=(r,s)=>{const i=r.value,o=n.left._zod.run({value:i,issues:[]},s),a=n.right._zod.run({value:i,issues:[]},s);return o instanceof Promise||a instanceof Promise?Promise.all([o,a]).then(([d,c])=>Jv(r,d,c)):Jv(r,o,a)}});function wy(e,n){if(e===n)return{valid:!0,data:e};if(e instanceof Date&&n instanceof Date&&+e==+n)return{valid:!0,data:e};if(Jl(e)&&Jl(n)){const r=Object.keys(n),s=Object.keys(e).filter(o=>r.indexOf(o)!==-1),i={...e,...n};for(const o of s){const a=wy(e[o],n[o]);if(!a.valid)return{valid:!1,mergeErrorPath:[o,...a.mergeErrorPath]};i[o]=a.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(n)){if(e.length!==n.length)return{valid:!1,mergeErrorPath:[]};const r=[];for(let s=0;s<e.length;s++){const i=e[s],o=n[s],a=wy(i,o);if(!a.valid)return{valid:!1,mergeErrorPath:[s,...a.mergeErrorPath]};r.push(a.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function Jv(e,n,r){const s=new Map;let i;for(const l of n.issues)if(l.code==="unrecognized_keys"){i??(i=l);for(const d of l.keys)s.has(d)||s.set(d,{}),s.get(d).l=!0}else e.issues.push(l);for(const l of r.issues)if(l.code==="unrecognized_keys")for(const d of l.keys)s.has(d)||s.set(d,{}),s.get(d).r=!0;else e.issues.push(l);const o=[...s].filter(([,l])=>l.l&&l.r).map(([l])=>l);if(o.length&&i&&e.issues.push({...i,keys:o}),gl(e))return e;const a=wy(n.value,r.value);
vendor: 21,742 bytes, lines 625-627
625if(!a.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(a.mergeErrorPath)}`);return e.value=a.data,e}const tO=ye("$ZodRecord",(e,n)=>{$t.init(e,n),e._zod.parse=(r,s)=>{const i=r.value;if(!Jl(i))return r.issues.push({expected:"record",code:"invalid_type",input:i,inst:e}),r;const o=[],a=n.keyType._zod.values;if(a){r.value={};const l=new Set;for(const c of a)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){l.add(typeof c=="number"?c.toString():c);const f=n.keyType._zod.run({value:c,issues:[]},s);if(f instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(f.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:f.issues.map(h=>ni(h,s,ti())),input:c,path:[c],inst:e});continue}const p=f.value,u=n.valueType._zod.run({value:i[c],issues:[]},s);u instanceof Promise?o.push(u.then(h=>{h.issues.length&&r.issues.push(...ml(c,h.issues)),r.value[p]=h.value})):(u.issues.length&&r.issues.push(...ml(c,u.issues)),r.value[p]=u.value)}let d;for(const c in i)l.has(c)||(d=d??[],d.push(c));d&&d.length>0&&r.issues.push({code:"unrecognized_keys",input:i,inst:e,keys:d})}else{r.value={};for(const l of Reflect.ownKeys(i)){if(l==="__proto__"||!Object.prototype.propertyIsEnumerable.call(i,l))continue;let d=n.keyType._zod.run({value:l,issues:[]},s);if(d instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof l=="string"&&ik.test(l)&&d.issues.length){const p=n.keyType._zod.run({value:Number(l),issues:[]},s);if(p instanceof Promise)throw new Error("Async schemas not supported in object keys currently");p.issues.length===0&&(d=p)}if(d.issues.length){n.mode==="loose"?r.value[l]=i[l]:r.issues.push({code:"invalid_key",origin:"record",issues:d.issues.map(p=>ni(p,s,ti())),input:l,path:[l],inst:e});continue}const f=n.valueType._zod.run({value:i[l],issues:[]},s);f instanceof Promise?o.push(f.then(p=>{p.issues.length&&r.issues.push(...ml(l,p.issues)),r.value[d.value]=p.value})):(f.issues.length&&r.issues.push(...ml(l,f.issues)),r.value[d.value]=f.value)}}return o.length?Promise.all(o).then(()=>r):r}}),nO=ye("$ZodEnum",(e,n)=>{$t.init(e,n);const r=X4(n.entries),s=new Set(r);e._zod.values=s,e._zod.pattern=new RegExp(`^(${r.filter(i=>pq.has(typeof i)).map(i=>typeof i=="string"?Ql(i):i.toString()).join("|")})$`),e._zod.parse=(i,o)=>{const a=i.value;return s.has(a)||i.issues.push({code:"invalid_value",values:r,input:a,inst:e}),i}}),rO=ye("$ZodLiteral",(e,n)=>{if($t.init(e,n),n.values.length===0)throw new Error("Cannot create literal schema with no valid values");const r=new Set(n.values);e._zod.values=r,e._zod.pattern=new RegExp(`^(${n.values.map(s=>typeof s=="string"?Ql(s):s?Ql(s.toString()):String(s)).join("|")})$`),e._zod.parse=(s,i)=>{const o=s.value;return r.has(o)||s.issues.push({code:"invalid_value",values:n.values,input:o,inst:e}),s}}),sO=ye("$ZodTransform",(e,n)=>{$t.init(e,n),e._zod.optin="optional",e._zod.parse=(r,s)=>{if(s.direction==="backward")throw new Y4(e.constructor.name);const i=n.transform(r.value,r);if(s.async)return(i instanceof Promise?i:Promise.resolve(i)).then(a=>(r.value=a,r.fallback=!0,r));if(i instanceof Promise)throw new kl;return r.value=i,r.fallback=!0,r}});function Qv(e,n){return n===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}const fk=ye("$ZodOptional",(e,n)=>{$t.init(e,n),e._zod.optin="optional",e._zod.optout="optional",mt(e._zod,"values",()=>n.innerType._zod.values?new Set([...n.innerType._zod.values,void 0]):void 0),mt(e._zod,"pattern",()=>{const r=n.innerType._zod.pattern;return r?new RegExp(`^(${p0(r.source)})?$`):void 0}),e._zod.parse=(r,s)=>{if(n.innerType._zod.optin==="optional"){const i=r.value,o=n.innerType._zod.run(r,s);return o instanceof Promise?o.then(a=>Qv(a,i)):Qv(o,i)}return r.value===void 0?r:n.innerType._zod.run(r,s)}}),iO=ye("$ZodExactOptional",(e,n)=>{fk.init(e,n),mt(e._zod,"values",()=>n.innerType._zod.values),mt(e._zod,"pattern",()=>n.innerType._zod.pattern),e._zod.parse=(r,s)=>n.innerType._zod.run(r,s)}),oO=ye("$ZodNullable",(e,n)=>{$t.init(e,n),mt(e._zod,"optin",()=>n.innerType._zod.optin),mt(e._zod,"optout",()=>n.innerType._zod.optout),mt(e._zod,"pattern",()=>{const r=n.innerType._zod.pattern;return r?new RegExp(`^(${p0(r.source)}|null)$`):void 0}),mt(e._zod,"values",()=>n.innerType._zod.values?new Set([...n.innerType._zod.values,null]):void 0),e._zod.parse=(r,s)=>r.value===null?r:n.innerType._zod.run(r,s)}),aO=ye("$ZodDefault",(e,n)=>{$t.init(e,n),e._zod.optin="optional",mt(e._zod,"values",()=>n.innerType._zod.values),e._zod.parse=(r,s)=>{if(s.direction==="backward")return n.innerType._zod.run(r,s);if(r.value===void 0)return r.value=n.defaultValue,r;const i=n.innerType._zod.run(r,s);return i instanceof Promise?i.then(o=>e_(o,n)):e_(i,n)}});function e_(e,n){return e.value===void 0&&(e.value=n.defaultValue),e}const lO=ye("$ZodPrefault",(e,n)=>{$t.init(e,n),e._zod.optin="optional",mt(e._zod,"values",()=>n.innerType._zod.values),e._zod.parse=(r,s)=>(s.direction==="backward"||r.value===void 0&&(r.value=n.defaultValue),n.innerType._zod.run(r,s))}),dO=ye("$ZodNonOptional",(e,n)=>{$t.init(e,n),mt(e._zod,"values",()=>{const r=n.innerType._zod.values;return r?new Set([...r].filter(s=>s!==void 0)):void 0}),e._zod.parse=(r,s)=>{const i=n.innerType._zod.run(r,s);return i instanceof Promise?i.then(o=>t_(o,e)):t_(i,e)}});function t_(e,n){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:n}),e}const cO=ye("$ZodCatch",(e,n)=>{$t.init(e,n),e._zod.optin="optional",mt(e._zod,"optout",()=>n.innerType._zod.optout),mt(e._zod,"values",()=>n.innerType._zod.values),e._zod.parse=(r,s)=>{if(s.direction==="backward")return n.innerType._zod.run(r,s);const i=n.innerType._zod.run(r,s);return i instanceof Promise?i.then(o=>(r.value=o.value,o.issues.length&&(r.value=n.catchValue({...r,error:{issues:o.issues.map(a=>ni(a,s,ti()))},input:r.value}),r.issues=[],r.fallback=!0),r)):(r.value=i.value,i.issues.length&&(r.value=n.catchValue({...r,error:{issues:i.issues.map(o=>ni(o,s,ti()))},input:r.value}),r.issues=[],r.fallback=!0),r)}}),gk=ye("$ZodPipe",(e,n)=>{$t.init(e,n),mt(e._zod,"values",()=>n.in._zod.values),mt(e._zod,"optin",()=>n.in._zod.optin),mt(e._zod,"optout",()=>n.out._zod.optout),mt(e._zod,"propValues",()=>n.in._zod.propValues),e._zod.parse=(r,s)=>{if(s.direction==="backward"){const o=n.out._zod.run(r,s);return o instanceof Promise?o.then(a=>pp(a,n.in,s)):pp(o,n.in,s)}const i=n.in._zod.run(r,s);return i instanceof Promise?i.then(o=>pp(o,n.out,s)):pp(i,n.out,s)}});function pp(e,n,r){return e.issues.length?(e.aborted=!0,e):n._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},r)}const uO=ye("$ZodPreprocess",(e,n)=>{gk.init(e,n)}),pO=ye("$ZodReadonly",(e,n)=>{$t.init(e,n),mt(e._zod,"propValues",()=>n.innerType._zod.propValues),mt(e._zod,"values",()=>n.innerType._zod.values),mt(e._zod,"optin",()=>{var r,s;return(s=(r=n.innerType)==null?void 0:r._zod)==null?void 0:s.optin}),mt(e._zod,"optout",()=>{var r,s;return(s=(r=n.innerType)==null?void 0:r._zod)==null?void 0:s.optout}),e._zod.parse=(r,s)=>{if(s.direction==="backward")return n.innerType._zod.run(r,s);const i=n.innerType._zod.run(r,s);return i instanceof Promise?i.then(n_):n_(i)}});function n_(e){return e.value=Object.freeze(e.value),e}const hO=ye("$ZodCustom",(e,n)=>{ur.init(e,n),$t.init(e,n),e._zod.parse=(r,s)=>r,e._zod.check=r=>{const s=r.value,i=n.fn(s);if(i instanceof Promise)return i.then(o=>r_(o,r,s,e));r_(i,r,s,e)}});function r_(e,n,r,s){if(!e){const i={code:"custom",input:r,inst:s,path:[...s._zod.def.path??[]],continue:!s._zod.def.abort};s._zod.def.params&&(i.params=s._zod.def.params),n.issues.push(Jc(i))}}var s_;class fO{constructor(){this._map=new WeakMap,this._idmap=new Map}add(n,...r){const s=r[0];return this._map.set(n,s),s&&typeof s=="object"&&"id"in s&&this._idmap.set(s.id,n),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(n){const r=this._map.get(n);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(n),this}get(n){const r=n._zod.parent;if(r){const s={...this.get(r)??{}};delete s.id;const i={...s,...this._map.get(n)};return Object.keys(i).length?i:void 0}return this._map.get(n)}has(n){return this._map.has(n)}}function gO(){return new fO}(s_=globalThis).__zod_globalRegistry??(s_.__zod_globalRegistry=gO());const oc=globalThis.__zod_globalRegistry;function mO(e,n){return new e({type:"string",...We(n)})}function xO(e,n){return new e({type:"string",format:"email",check:"string_format",abort:!1,...We(n)})}function i_(e,n){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...We(n)})}function yO(e,n){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...We(n)})}function bO(e,n){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...We(n)})}function AO(e,n){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...We(n)})}function vO(e,n){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...We(n)})}function _O(e,n){return new e({type:"string",format:"url",check:"string_format",abort:!1,...We(n)})}function jO(e,n){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...We(n)})}function wO(e,n){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...We(n)})}function SO(e,n){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...We(n)})}function kO(e,n){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...We(n)})}function CO(e,n){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...We(n)})}function TO(e,n){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...We(n)})}function zO(e,n){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...We(n)})}function NO(e,n){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...We(n)})}function RO(e,n){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...We(n)})}function EO(e,n){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...We(n)})}function PO(e,n){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...We(n)})}function qO(e,n){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...We(n)})}function DO(e,n){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...We(n)})}function OO(e,n){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...We(n)})}function IO(e,n){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...We(n)})}function LO(e,n){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...We(n)})}function WO(e,n){return new e({type:"string",format:"date",check:"string_format",...We(n)})}function $O(e,n){return new e({type:"string",format:"time",check:"string_format",precision:null,...We(n)})}function MO(e,n){return new e({type:"string",format:"duration",check:"string_format",...We(n)})}function FO(e,n){return new e({type:"number",checks:[],...We(n)})}function BO(e,n){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...We(n)})}function UO(e,n){return new e({type:"boolean",...We(n)})}function HO(e){return new e({type:"unknown"})}function VO(e,n){return new e({type:"never",...We(n)})}function o_(e,n){return new ak({check:"less_than",...We(n),value:e,inclusive:!1})}function lm(e,n){return new ak({check:"less_than",...We(n),value:e,inclusive:!0})}function a_(e,n){return new lk({check:"greater_than",...We(n),value:e,inclusive:!1})}function dm(e,n){return new lk({check:"greater_than",...We(n),value:e,inclusive:!0})}function l_(e,n){return new aD({check:"multiple_of",...We(n),value:e})}function mk(e,n){return new dD({check:"max_length",...We(n),maximum:e})}function Gh(e,n){return new cD({check:"min_length",...We(n),minimum:e})}function xk(e,n){return new uD({check:"length_equals",...We(n),length:e})}function ZO(e,n){return new pD({check:"string_format",format:"regex",...We(n),pattern:e})}function KO(e){return new hD({check:"string_format",format:"lowercase",...We(e)})}function YO(e){return new fD({check:"string_format",format:"uppercase",...We(e)})}function XO(e,n){return new gD({check:"string_format",format:"includes",...We(n),includes:e})}function GO(e,n){return new mD({check:"string_format",format:"starts_with",...We(n),prefix:e})}function JO(e,n){return new xD({check:"string_format",format:"ends_with",...We(n),suffix:e})}function Ad(e){return new yD({check:"overwrite",tx:e})}function QO(e){return Ad(n=>n.normalize(e))}function eI(){return Ad(e=>e.trim())}function tI(){return Ad(e=>e.toLowerCase())}function nI(){return Ad(e=>e.toUpperCase())}function rI(){return Ad(e=>cq(e))}function sI(e,n,r){return new e({type:"array",element:n,...We(r)})}function iI(e,n,r){return new e({type:"custom",check:"custom",fn:n,...We(r)})}function oI(e,n){const r=aI(s=>(s.addIssue=i=>{if(typeof i=="string")s.issues.push(Jc(i,s.value,r._zod.def));else{const o=i;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=s.value),o.inst??(o.inst=r),o.continue??(o.continue=!r._zod.def.abort),s.issues.push(Jc(o))}},e(s.value,s)),n);return r}function aI(e,n){const r=new ur({check:"custom",...We(n)});return r._zod.check=e,r}function yk(e){let n=(e==null?void 0:e.target)??"draft-2020-12";return n==="draft-4"&&(n="draft-04"),n==="draft-7"&&(n="draft-07"),{processors:e.processors??{},metadataRegistry:(e==null?void 0:e.metadata)??oc,target:n,unrepresentable:(e==null?void 0:e.unrepresentable)??"throw",override:(e==null?void 0:e.override)??(()=>{}),io:(e==null?void 0:e.io)??"output",counter:0,seen:new Map,cycles:(e==null?void 0:e.cycles)??"ref",reused:(e==null?void 0:e.reused)??"inline",external:(e==null?void 0:e.external)??void 0}}function rn(e,n,r={path:[],schemaPath:[]}){var f,p;var s;const i=e._zod.def,o=n.seen.get(e);if(o)return o.count++,r.schemaPath.includes(e)&&(o.cycle=r.path),o.schema;const a={schema:{},count:1,cycle:void 0,path:r.path};n.seen.set(e,a);const l=(p=(f=e._zod).toJSONSchema)==null?void 0:p.call(f);if(l)a.schema=l;else{const u={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(n,a.schema,u);else{const y=a.schema,m=n.processors[i.type];if(!m)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);m(e,n,y,u)}const h=e._zod.parent;h&&(a.ref||(a.ref=h),rn(h,n,u),n.seen.get(h).isParent=!0)}const d=n.metadataRegistry.get(e);return d&&Object.assign(a.schema,d),n.io==="input"&&On(e)&&(delete a.schema.examples,delete a.schema.default),n.io==="input"&&"_prefault"in a.schema&&((s=a.schema).default??(s.default=a.schema._prefault)),delete a.schema._prefault,n.seen.get(e).schema}function bk(e,n){var a,l,d,c;const r=e.seen.get(n);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");const s=new Map;for(const f of e.seen.entries()){const p=(a=e.metadataRegistry.get(f[0]))==null?void 0:a.id;if(p){const u=s.get(p);if(u&&u!==f[0])throw new Error(`Duplicate schema id "${p}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);s.set(p,f[0])}}const i=f=>{var m;const p=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const b=(m=e.external.registry.get(f[0]))==null?void 0:m.id,A=e.external.uri??(x=>x);if(b)return{ref:A(b)};const v=f[1].defId??f[1].schema.id??`schema${e.counter++}`;return f[1].defId=v,{defId:v,ref:`${A("__shared")}#/${p}/${v}`}}if(f[1]===r)return{ref:"#"};const h=`#/${p}/`,y=f[1].schema.id??`__schema${e.counter++}`;return{defId:y,ref:h+y}},o=f=>{if(f[1].schema.$ref)return;const p=f[1],{ref:u,defId:h}=i(f);p.def={...p.schema},h&&(p.defId=h);const y=p.schema;for(const m in y)delete y[m];y.$ref=u};if(e.cycles==="throw")for(const f of e.seen.entries()){const p=f[1];if(p.cycle)throw new Error(`Cycle detected: #/${(l=p.cycle)==null?void 0:l.join("/")}/<root> 626 627Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const f of e.seen.entries()){const p=f[1];if(n===f[0]){o(f);continue}if(e.external){const h=(d=e.external.registry.get(f[0]))==null?void 0:d.id;if(n!==f[0]&&h){o(f);continue}}if((c=e.metadataRegistry.get(f[0]))==null?void 0:c.id){o(f);continue}if(p.cycle){o(f);continue}if(p.count>1&&e.reused==="ref"){o(f);continue}}}function Ak(e,n){var l,d,c,f;const r=e.seen.get(n);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");const s=p=>{const u=e.seen.get(p);if(u.ref===null)return;const h=u.def??u.schema,y={...h},m=u.ref;if(u.ref=null,m){s(m);const A=e.seen.get(m),v=A.schema;if(v.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(h.allOf=h.allOf??[],h.allOf.push(v)):Object.assign(h,v),Object.assign(h,y),p._zod.parent===m)for(const _ in h)_==="$ref"||_==="allOf"||_ in y||delete h[_];if(v.$ref&&A.def)for(const _ in h)_==="$ref"||_==="allOf"||_ in A.def&&JSON.stringify(h[_])===JSON.stringify(A.def[_])&&delete h[_]}const b=p._zod.parent;if(b&&b!==m){s(b);const A=e.seen.get(b);if(A!=null&&A.schema.$ref&&(h.$ref=A.schema.$ref,A.def))for(const v in h)v==="$ref"||v==="allOf"||v in A.def&&JSON.stringify(h[v])===JSON.stringify(A.def[v])&&delete h[v]}e.override({zodSchema:p,jsonSchema:h,path:u.path??[]})};for(const p of[...e.seen.entries()].reverse())s(p[0]);const i={};if(e.target==="draft-2020-12"?i.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?i.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?i.$schema="http://json-schema.org/draft-04/schema#":e.target,(l=e.external)!=null&&l.uri){const p=(d=e.external.registry.get(n))==null?void 0:d.id;if(!p)throw new Error("Schema is missing an `id` property");i.$id=e.external.uri(p)}Object.assign(i,r.def??r.schema);const o=(c=e.metadataRegistry.get(n))==null?void 0:c.id;o!==void 0&&i.id===o&&delete i.id;const a=((f=e.external)==null?void 0:f.defs)??{};for(const p of e.seen.entries()){const u=p[1];u.def&&u.defId&&(u.def.id===u.defId&&delete u.def.id,a[u.defId]=u.def)}e.external||Object.keys(a).length>0&&(e.target==="draft-2020-12"?i.$defs=a:i.definitions=a);try{const p=JSON.parse(JSON.stringify(i));return Object.defineProperty(p,"~standard",{value:{...n["~standard"],jsonSchema:{input:Jh(n,"input",e.processors),output:Jh(n,"output",e.processors)}},enumerable:!1,writable:!1}),p}catch{throw new Error("Error converting schema to JSON.")}}function On(e,n){const r=n??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);const s=e._zod.def;if(s.type==="transform")return!0;if(s.type==="array")return On(s.element,r);if(s.type==="set")return On(s.valueType,r);if(s.type==="lazy")return On(s.getter(),r);if(s.type==="promise"||s.type==="optional"||s.type==="nonoptional"||s.type==="nullable"||s.type==="readonly"||s.type==="default"||s.type==="prefault")return On(s.innerType,r);if(s.type==="intersection")return On(s.left,r)||On(s.right,r);if(s.type==="record"||s.type==="map")return On(s.keyType,r)||On(s.valueType,r);if(s.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:On(s.in,r)||On(s.out,r);if(s.type==="object"){for(const i in s.shape)if(On(s.shape[i],r))return!0;return!1}if(s.type==="union"){for(const i of s.options)if(On(i,r))return!0;return!1}if(s.type==="tuple"){for(const i of s.items)if(On(i,r))return!0;return!!(s.rest&&On(s.rest,r))}return!1}const lI=(e,n={})=>r=>{const s=yk({...r,processors:n});return rn(e,s),bk(s,e),Ak(s,e)},Jh=(e,n,r={})=>s=>{const{libraryOptions:i,target:o}=s??{},a=yk({...i??{},target:o,io:n,processors:r});return rn(e,a),bk(a,e),Ak(a,e)},dI={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},cI=(e,n,r,s)=>{const i=r;i.type="string";const{minimum:o,maximum:a,format:l,patterns:d,contentEncoding:c}=e._zod.bag;if(typeof o=="number"&&(i.minLength=o),typeof a=="number"&&(i.maxLength=a),l&&(i.format=dI[l]??l,i.format===""&&delete i.format,l==="time"&&delete i.format),c&&(i.contentEncoding=c),d&&d.size>0){const f=[...d];f.length===1?i.pattern=f[0].source:f.length>1&&(i.allOf=[...f.map(p=>({...n.target==="draft-07"||n.target==="draft-04"||n.target==="openapi-3.0"?{type:"string"}:{},pattern:p.source}))])}},uI=(e,n,r,s)=>{const i=r,{minimum:o,maximum:a,format:l,multipleOf:d,exclusiveMaximum:c,exclusiveMinimum:f}=e._zod.bag;typeof l=="string"&&l.includes("int")?i.type="integer":i.type="number";const p=typeof f=="number"&&f>=(o??Number.NEGATIVE_INFINITY),u=typeof c=="number"&&c<=(a??Number.POSITIVE_INFINITY),h=n.target==="draft-04"||n.target==="openapi-3.0";p?h?(i.minimum=f,i.exclusiveMinimum=!0):i.exclusiveMinimum=f:typeof o=="number"&&(i.minimum=o),u?h?(i.maximum=c,i.exclusiveMaximum=!0):i.exclusiveMaximum=c:typeof a=="number"&&(i.maximum=a),typeof d=="number"&&(i.multipleOf=d)},pI=(e,n,r,s)=>{r.type="boolean"},hI=(e,n,r,s)=>{r.not={}},fI=(e,n,r,s)=>{},gI=(e,n,r,s)=>{const i=e._zod.def,o=X4(i.entries);o.every(a=>typeof a=="number")&&(r.type="number"),o.every(a=>typeof a=="string")&&(r.type="string"),r.enum=o},mI=(e,n,r,s)=>{const i=e._zod.def,o=[];for(const a of i.values)if(a===void 0){if(n.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof a=="bigint"){if(n.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");o.push(Number(a))}else o.push(a);if(o.length!==0)if(o.length===1){const a=o[0];r.type=a===null?"null":typeof a,n.target==="draft-04"||n.target==="openapi-3.0"?r.enum=[a]:r.const=a}else o.every(a=>typeof a=="number")&&(r.type="number"),o.every(a=>
vendor: 8,751 bytes, line 627
627typeof a=="string")&&(r.type="string"),o.every(a=>typeof a=="boolean")&&(r.type="boolean"),o.every(a=>a===null)&&(r.type="null"),r.enum=o},xI=(e,n,r,s)=>{if(n.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},yI=(e,n,r,s)=>{if(n.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},bI=(e,n,r,s)=>{const i=r,o=e._zod.def,{minimum:a,maximum:l}=e._zod.bag;typeof a=="number"&&(i.minItems=a),typeof l=="number"&&(i.maxItems=l),i.type="array",i.items=rn(o.element,n,{...s,path:[...s.path,"items"]})},AI=(e,n,r,s)=>{var c;const i=r,o=e._zod.def;i.type="object",i.properties={};const a=o.shape;for(const f in a)i.properties[f]=rn(a[f],n,{...s,path:[...s.path,"properties",f]});const l=new Set(Object.keys(a)),d=new Set([...l].filter(f=>{const p=o.shape[f]._zod;return n.io==="input"?p.optin===void 0:p.optout===void 0}));d.size>0&&(i.required=Array.from(d)),((c=o.catchall)==null?void 0:c._zod.def.type)==="never"?i.additionalProperties=!1:o.catchall?o.catchall&&(i.additionalProperties=rn(o.catchall,n,{...s,path:[...s.path,"additionalProperties"]})):n.io==="output"&&(i.additionalProperties=!1)},vI=(e,n,r,s)=>{const i=e._zod.def,o=i.inclusive===!1,a=i.options.map((l,d)=>rn(l,n,{...s,path:[...s.path,o?"oneOf":"anyOf",d]}));o?r.oneOf=a:r.anyOf=a},_I=(e,n,r,s)=>{const i=e._zod.def,o=rn(i.left,n,{...s,path:[...s.path,"allOf",0]}),a=rn(i.right,n,{...s,path:[...s.path,"allOf",1]}),l=c=>"allOf"in c&&Object.keys(c).length===1,d=[...l(o)?o.allOf:[o],...l(a)?a.allOf:[a]];r.allOf=d},jI=(e,n,r,s)=>{const i=r,o=e._zod.def;i.type="object";const a=o.keyType,l=a._zod.bag,d=l==null?void 0:l.patterns;if(o.mode==="loose"&&d&&d.size>0){const f=rn(o.valueType,n,{...s,path:[...s.path,"patternProperties","*"]});i.patternProperties={};for(const p of d)i.patternProperties[p.source]=f}else(n.target==="draft-07"||n.target==="draft-2020-12")&&(i.propertyNames=rn(o.keyType,n,{...s,path:[...s.path,"propertyNames"]})),i.additionalProperties=rn(o.valueType,n,{...s,path:[...s.path,"additionalProperties"]});const c=a._zod.values;if(c){const f=[...c].filter(p=>typeof p=="string"||typeof p=="number");f.length>0&&(i.required=f)}},wI=(e,n,r,s)=>{const i=e._zod.def,o=rn(i.innerType,n,s),a=n.seen.get(e);n.target==="openapi-3.0"?(a.ref=i.innerType,r.nullable=!0):r.anyOf=[o,{type:"null"}]},SI=(e,n,r,s)=>{const i=e._zod.def;rn(i.innerType,n,s);const o=n.seen.get(e);o.ref=i.innerType},kI=(e,n,r,s)=>{const i=e._zod.def;rn(i.innerType,n,s);const o=n.seen.get(e);o.ref=i.innerType,r.default=JSON.parse(JSON.stringify(i.defaultValue))},CI=(e,n,r,s)=>{const i=e._zod.def;rn(i.innerType,n,s);const o=n.seen.get(e);o.ref=i.innerType,n.io==="input"&&(r._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},TI=(e,n,r,s)=>{const i=e._zod.def;rn(i.innerType,n,s);const o=n.seen.get(e);o.ref=i.innerType;let a;try{a=i.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}r.default=a},zI=(e,n,r,s)=>{const i=e._zod.def,o=i.in._zod.traits.has("$ZodTransform"),a=n.io==="input"?o?i.out:i.in:i.out;rn(a,n,s);const l=n.seen.get(e);l.ref=a},NI=(e,n,r,s)=>{const i=e._zod.def;rn(i.innerType,n,s);const o=n.seen.get(e);o.ref=i.innerType,r.readOnly=!0},vk=(e,n,r,s)=>{const i=e._zod.def;rn(i.innerType,n,s);const o=n.seen.get(e);o.ref=i.innerType},RI=ye("ZodISODateTime",(e,n)=>{ED.init(e,n),Ft.init(e,n)});function EI(e){return LO(RI,e)}const PI=ye("ZodISODate",(e,n)=>{PD.init(e,n),Ft.init(e,n)});function qI(e){return WO(PI,e)}const DI=ye("ZodISOTime",(e,n)=>{qD.init(e,n),Ft.init(e,n)});function OI(e){return $O(DI,e)}const II=ye("ZodISODuration",(e,n)=>{DD.init(e,n),Ft.init(e,n)});function LI(e){return MO(II,e)}const WI=(e,n)=>{ek.init(e,n),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>wq(e,r)},flatten:{value:r=>jq(e,r)},addIssue:{value:r=>{e.issues.push(r),e.message=JSON.stringify(e.issues,jy,2)}},addIssues:{value:r=>{e.issues.push(...r),e.message=JSON.stringify(e.issues,jy,2)}},isEmpty:{get(){return e.issues.length===0}}})},Ir=ye("ZodError",WI,{Parent:Error}),$I=f0(Ir),MI=g0(Ir),FI=Vf(Ir),BI=Zf(Ir),UI=Cq(Ir),HI=Tq(Ir),VI=zq(Ir),ZI=Nq(Ir),KI=Rq(Ir),YI=Eq(Ir),XI=Pq(Ir),GI=qq(Ir),d_=new WeakMap;function xu(e,n,r){const s=Object.getPrototypeOf(e);let i=d_.get(s);if(i||(i=new Set,d_.set(s,i)),!i.has(n)){i.add(n);for(const o in r){const a=r[o];Object.defineProperty(s,o,{configurable:!0,enumerable:!1,get(){const l=a.bind(this);return Object.defineProperty(this,o,{configurable:!0,writable:!0,enumerable:!0,value:l}),l},set(l){Object.defineProperty(this,o,{configurable:!0,writable:!0,enumerable:!0,value:l})}})}}}const Mt=ye("ZodType",(e,n)=>($t.init(e,n),Object.assign(e["~standard"],{jsonSchema:{input:Jh(e,"input"),output:Jh(e,"output")}}),e.toJSONSchema=lI(e,{}),e.def=n,e.type=n.type,Object.defineProperty(e,"_def",{value:n}),e.parse=(r,s)=>$I(e,r,s,{callee:e.parse}),e.safeParse=(r,s)=>FI(e,r,s),e.parseAsync=async(r,s)=>MI(e,r,s,{callee:e.parseAsync}),e.safeParseAsync=async(r,s)=>BI(e,r,s),e.spa=e.safeParseAsync,e.encode=(r,s)=>UI(e,r,s),e.decode=(r,s)=>HI(e,r,s),e.encodeAsync=async(r,s)=>VI(e,r,s),e.decodeAsync=async(r,s)=>ZI(e,r,s),e.safeEncode=(r,s)=>KI(e,r,s),e.safeDecode=(r,s)=>YI(e,r,s),e.safeEncodeAsync=async(r,s)=>XI(e,r,s),e.safeDecodeAsync=async(r,s)=>GI(e,r,s),xu(e,"ZodType",{check(...r){const s=this.def;return this.clone(ho(s,{checks:[...s.checks??[],...r.map(i=>typeof i=="function"?{_zod:{check:i,def:{check:"custom"},onattach:[]}}:i)]}),{parent:!0})},with(...r){return this.check(...r)},clone(r,s){return fo(this,r,s)},brand(){return this},register(r,s){return r.add(this,s),this},refine(r,s){return this.check(UL(r,s))},superRefine(r,s){return this.check(HL(r,s))},overwrite(r){return this.check(Ad(r))},optional(){return p_(this)},exactOptional(){return RL(this)},nullable(){return h_(this)},nullish(){return p_(h_(this))},nonoptional(r){return IL(this,r)},array(){return cr(this)},or(r){return Sk([this,r])},and(r){return kL(this,r)},transform(r){return f_(this,kk(r))},default(r){return qL(this,r)},prefault(r){return OL(this,r)},catch(r){return WL(this,r)},pipe(r){return f_(this,r)},readonly(){return FL(this)},describe(r){const s=this.clone();return oc.add(s,{description:r}),s},meta(...r){if(r.length===0)return oc.get(this);const s=this.clone();return oc.add(s,r[0]),s},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(r){return r(this)}}),Object.defineProperty(e,"description",{get(){var r;return(r=oc.get(e))==null?void 0:r.description},configurable:!0}),e)),_k=ye("_ZodString",(e,n)=>{m0.init(e,n),Mt.init(e,n),e._zod.processJSONSchema=(s,i,o)=>cI(e,s,i);const r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,xu(e,"_ZodString",{regex(...s){return this.check(ZO(...s))},includes(...s){return this.check(XO(...s))},startsWith(...s){return this.check(GO(...s))},endsWith(...s){return this.check(JO(...s))},min(...s){return this.check(Gh(...s))},max(...s){return this.check(mk(...s))},length(...s){return this.check(xk(...s))},nonempty(...s){return this.check(Gh(1,...s))},lowercase(s){return this.check(KO(s))},uppercase(s){return this.check(YO(s))},trim(){return this.check(eI())},normalize(...s){return this.check(QO(...s))},toLowerCase(){return this.check(tI())},toUpperCase(){return this.check(nI())},slugify(){return this.check(rI())}})}),JI=ye("ZodString",(e,n)=>{m0.init(e,n),_k.init(e,n),e.email=r=>e.check(xO(QI,r)),e.url=r=>e.check(_O(eL,r)),e.jwt=r=>e.check(IO(gL,r)),e.emoji=r=>e.check(jO(tL,r)),e.guid=r=>e.check(i_(c_,r)),e.uuid=r=>e.check(yO(hp,r)),e.uuidv4=r=>e.check(bO(hp,r)),e.uuidv6=r=>e.check(AO(hp,r)),e.uuidv7=r=>e.check(vO(hp,r)),e.nanoid=r=>e.check(wO(nL,r)),e.guid=r=>e.check(i_(c_,r)),e.cuid=r=>e.check(SO(rL,r)),e.cuid2=r=>e.check(kO(sL,r)),e.ulid=r=>e.check(CO(iL,r)),e.base64=r=>e.check(qO(pL,r)),e.base64url=r=>e.check(DO(hL,r)),e.xid=r=>e.check(TO(oL,r)),e.ksuid=r=>e.check(zO(aL,r)),e.ipv4=r=>e.check(NO(lL,r)),e.ipv6=r=>e.check(RO(dL,r)),e.cidrv4=r=>e.check(EO(cL,r)),e.cidrv6=r=>e.check(PO(uL,r)),e.e164=r=>e.check(OO(fL,r)),e.datetime=r=>e.check(EI(r)),e.date=r=>e.check(qI(r)),e.time=r=>e.check(OI(r)),e.duration=r=>e.check(LI(r))});function Re(e){return mO(JI,e)}const Ft=ye("ZodStringFormat",(e,n)=>{Pt.init(e,n),_k.init(e,n)}),QI=ye("ZodEmail",(e,n)=>{jD.init(e,n),Ft.init(e,n)}),c_=ye("ZodGUID",(e,n)=>{vD.init(e,n),Ft.init(e,n)}),hp=ye("ZodUUID",(e,n)=>{_D.init(e,n),Ft.init(e,n)}),eL=ye("ZodURL",(e,n)=>{wD.init(e,n),Ft.init(e,n)}),tL=ye("ZodEmoji",(e,n)=>{SD.init(e,n),Ft.init(e,n)}),nL=ye("ZodNanoID",(e,n)=>{kD.init(e,n),Ft.init(e,n)}),rL=ye("ZodCUID",(e,n)=>{CD.init(e,n),Ft.init(e,n)}),sL=ye("ZodCUID2",(e,n)=>{TD.init(e,n),Ft.init(e,n)}
627),iL=ye("ZodULID",(e,n)=>{zD.init(e,n),Ft.init(e,n)}),oL=ye("ZodXID",(e,n)=>{ND.init(e,n),Ft.init(e,n)}),aL=ye("ZodKSUID",(e,n)=>{RD.init(e,n),Ft.init(e,n)}),lL=ye("ZodIPv4",(e,n)=>{OD.init(e,n),Ft.init(e,n)}),dL=ye("ZodIPv6",(e,n)=>{ID.init(e,n),Ft.init(e,n)}),cL=ye("ZodCIDRv4",(e,n)=>{LD.init(e,n),Ft.init(e,n)}),uL=ye("ZodCIDRv6",(e,n)=>{WD.init(e,n),Ft.init(e,n)}),pL=ye("ZodBase64",(e,n)=>{$D.init(e,n),Ft.init(e,n)}),hL=ye("ZodBase64URL",(e,n)=>{FD.init(e,n),Ft.init(e,n)}),fL=ye("ZodE164",(e,n)=>{BD.init(e,n),Ft.init(e,n)}),gL=ye("ZodJWT",(e,n)=>{HD.init(e,n),Ft.init(e,n)}),jk=ye("ZodNumber",(e,n)=>{ck.init(e,n),Mt.init(e,n),e._zod.processJSONSchema=(s,i,o)=>uI(e,s,i),xu(e,"ZodNumber",{gt(s,i){return this.check(a_(s,i))},gte(s,i){return this.check(dm(s,i))},min(s,i){return this.check(dm(s,i))},lt(s,i){return this.check(o_(s,i))},lte(s,i){return this.check(lm(s,i))},max(s,i){return this.check(lm(s,i))},int(s){return this.check(u_(s))},safe(s){return this.check(u_(s))},positive(s){return this.check(a_(0,s))},nonnegative(s){return this.check(dm(0,s))},negative(s){return this.check(o_(0,s))},nonpositive(s){return this.check(lm(0,s))},multipleOf(s,i){return this.check(l_(s,i))},step(s,i){return this.check(l_(s,i))},finite(){return this}});const r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null});function Sy(e){return FO(jk,e)}const mL=ye("ZodNumberFormat",(e,n)=>{VD.init(e,n),jk.init(e,n)});function u_(e){return BO(mL,e)}const xL=ye("ZodBoolean",(e,n)=>{ZD.init(e,n),Mt.init(e,n),e._zod.processJSONSchema=(r,s,i)=>pI(e,r,s)});function ri(e){return UO(xL,e)}const yL=ye("ZodUnknown",(e,n)=>{KD.init(e,n),Mt.init(e,n),e._zod.processJSONSchema=(r,s,i)=>fI()});function ky(){return HO(yL)}const bL=ye("ZodNever",(e,n)=>{YD.init(e,n),Mt.init(e,n),e._zod.processJSONSchema=(r,s,i)=>hI(e,r,s)});function AL(e){return VO(bL,e)}const vL=ye("ZodArray",(e,n)=>{XD.init(e,n),Mt.init(e,n),e._zod.processJSONSchema=(r,s,i)=>bI(e,r,s,i),e.element=n.element,xu(e,"ZodArray",{min(r,s){return this.check(Gh(r,s))},nonempty(r){return this.check(Gh(1,r))},max(r,s){return this.check(mk(r,s))},length(r,s){return this.check(xk(r,s))},unwrap(){return this.element}})});function cr(e,n){return sI(vL,e,n)}const _L=ye("ZodObject",(e,n)=>{JD.init(e,n),Mt.init(e,n),e._zod.processJSONSchema=(r,s,i)=>AI(e,r,s,i),mt(e,"shape",()=>n.shape),xu(e,"ZodObject",{keyof(){return ns(Object.keys(this._zod.def.shape))},catchall(r){return this.clone({...this._zod.def,catchall:r})},passthrough(){return this.clone({...this._zod.def,catchall:ky()})},loose(){return this.clone({...this._zod.def,catchall:ky()})},strict(){return this.clone({...this._zod.def,catchall:AL()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(r){return xq(this,r)},safeExtend(r){return yq(this,r)},merge(r){return bq(this,r)},pick(r){return gq(this,r)},omit(r){return mq(this,r)},partial(...r){return Aq(Ck,this,r[0])},required(...r){return vq(Tk,this,r[0])}})});function Ye(e,n){const r={type:"object",shape:e??{},...We(n)};return new _L(r)}const wk=ye("ZodUnion",(e,n)=>{hk.init(e,n),Mt.init(e,n),e._zod.processJSONSchema=(r,s,i)=>vI(e,r,s,i),e.options=n.options});function Sk(e,n){return new wk({type:"union",options:e,...We(n)})}const jL=ye("ZodDiscriminatedUnion",(e,n)=>{wk.init(e,n),QD.init(e,n)});function wL(e,n,r){return new jL({type:"union",options:n,discriminator:e,...We(r)})}const SL=ye("ZodIntersection",(e,n)=>{eO.init(e,n),Mt.init(e,n),e._zod.processJSONSchema=(r,s,i)=>_I(e,r,s,i)});function kL(e,n){return new SL({type:"intersection",left:e,right:n})}const CL=ye("ZodRecord",(e,n)=>{tO.init(e,n),Mt.init(e,n),e._zod.processJSONSchema=(r,s,i)=>jI(e,r,s,i),e.keyType=n.keyType,e.valueType=n.valueType});function x0(e,n,r){return new CL({type:"record",keyType:Re(),valueType:e,...We(n)})}const Cy=ye("ZodEnum",(e,n)=>{nO.init(e,n),Mt.init(e,n),e._zod.processJSONSchema=(s,i,o)=>gI(e,s,i),e.enum=n.entries,e.options=Object.values(n.entries);const r=new Set(Object.keys(n.entries));e.extract=(s,i)=>{const o={};for(const a of s)if(r.has(a))o[a]=n.entries[a];else throw new Error(`Key ${a} not found in enum`);
627return new Cy({...n,checks:[],...We(i),entries:o})},e.exclude=(s,i)=>{const o={...n.entries};for(const a of s)if(r.has(a))delete o[a];else throw new Error(`Key ${a} not found in enum`);return new Cy({...n,checks:[],...We(i),entries:o})}});function ns(e,n){const r=Array.isArray(e)?Object.fromEntries(e.map(s=>[s,s])):e;return new Cy({type:"enum",entries:r,...We(n)})}const TL=ye("ZodLiteral",(e,n)=>{rO.init(e,n),Mt.init(e,n),e._zod.processJSONSchema=(r,s,i)=>mI(e,r,s),e.values=new Set(n.values),Object.defineProperty(e,"value",{get(){if(n.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return n.values[0]}})});function wr(e,n){return new TL({type:"literal",values:Array.isArray(e)?e:[e],...We(n)})}const zL=ye("ZodTransform",(e,n)=>{sO.init(e,n),Mt.init(e,n),e._zod.processJSONSchema=(r,s,i)=>yI(e,r),e._zod.parse=(r,s)=>{if(s.direction==="backward")throw new Y4(e.constructor.name);r.addIssue=o=>{if(typeof o=="string")r.issues.push(Jc(o,r.value,n));else{const a=o;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=r.value),a.inst??(a.inst=e),r.issues.push(Jc(a))}};const i=n.transform(r.value,r);return i instanceof Promise?i.then(o=>(r.value=o,r.fallback=!0,r)):(r.value=i,r.fallback=!0,r)}});function kk(e){return new zL({type:"transform",transform:e})}const Ck=ye("ZodOptional",(e,n)=>{fk.init(e,n),Mt.init(e,n),e._zod.processJSONSchema=(r,s,i)=>vk(e,r,s,i),e.unwrap=()=>e._zod.def.innerType});function p_(e){return new Ck({type:"optional",innerType:e})}const NL=ye("ZodExactOptional",(e,n)=>{iO.init(e,n),Mt.init(e,n),e._zod.processJSONSchema=(r,s,i)=>vk(e,r,s,i),e.unwrap=()=>e._zod.def.innerType});function RL(e){return new NL({type:"optional",innerType:e})}const EL=ye("ZodNullable",(e,n)=>{oO.init(e,n),Mt.init(e,n),e._zod.processJSONSchema=(r,s,i)=>wI(e,r,s,i),e.unwrap=()=>e._zod.def.innerType});function h_(e){return new EL({type:"nullable",innerType:e})}const PL=ye("ZodDefault",(e,n)=>{aO.init(e,n),Mt.init(e,n),e._zod.processJSONSchema=(r,s,i)=>kI(e,r,s,i),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function qL(e,n){return new PL({type:"default",innerType:e,get defaultValue(){return typeof n=="function"?n():J4(n)}})}const DL=ye("ZodPrefault",(e,n)=>{lO.init(e,n),Mt.init(e,n),e._zod.processJSONSchema=(r,s,i)=>CI(e,r,s,i),e.unwrap=()=>e._zod.def.innerType});function OL(e,n){return new DL({type:"prefault",innerType:e,get defaultValue(){return typeof n=="function"?n():J4(n)}})}const Tk=ye("ZodNonOptional",(e,n)=>{dO.init(e,n),Mt.init(e,n),e._zod.processJSONSchema=(r,s,i)=>SI(e,r,s,i),e.unwrap=()=>e._zod.def.innerType});function IL(e,n){return new Tk({type:"nonoptional",innerType:e,...We(n)})}const LL=ye("ZodCatch",(e,n)=>{cO.init(e,n),Mt.init(e,n),e._zod.processJSONSchema=(r,s,i)=>TI(e,r,s,i),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function WL(e,n){return new LL({type:"catch",innerType:e,catchValue:typeof n=="function"?n:()=>n})}const zk=ye("ZodPipe",(e,n)=>{gk.init(e,n),Mt.init(e,n),e._zod.processJSONSchema=(r,s,i)=>zI(e,r,s,i),e.in=n.in,e.out=n.out});function f_(e,n){return new zk({type:"pipe",in:e,out:n})}const $L=ye("ZodPreprocess",(e,n)=>{zk.init(e,n),uO.init(e,n)}),ML=ye("ZodReadonly",(e,n)=>{pO.init(e,n),Mt.init(e,n),e._zod.processJSONSchema=(r,s,i)=>NI(e,r,s,i),e.unwrap=()=>e._zod.def.innerType});function FL(e){return new ML({type:"readonly",innerType:e})}const BL=ye("ZodCustom",(e,n)=>{hO.init(e,n),Mt.init(e,n),e._zod.processJSONSchema=(r,s,i)=>xI(e,r)});function UL(e,n={}){return iI(BL,e,n)}function HL(e,n){return oI(e,n)}function VL(e,n){return new $L({type:"pipe",in:kk(e),out:n})}const Nk=1,Ty=Re().min(1).max(1024),si=Re().max(2048).refine(e=>!/^\s*javascript:/i.test(e)&&!/^\s*data:/i.test(e),{message:"javascript: and data: URLs are not allowed"}),ZL=Ye({asset:Ty,alt:Re().max(300).default(""),aspect:Re().max(16).optional(),focal:Ye({x:Sy().min(0).max(1),y:Sy().min(0).max(1)}).optional(),treatment:Ye({fit:ns(["cover","contain"]).optional(),grayscale:ri().optional(),radius:Re().max(16).optional()}).optional()}),Rk=Ye({pt:ns(["none","sm","md","lg","xl"]).optional(),pb:ns(["none","sm","md","lg","xl"]).optional()}).optional(),KL=x0(Sk([Re().max(400),Sy(),ri()])).optional(),YL=Ye({variant_override:Re().max(64).optional(),stack_order:cr(Re().max(24)).max(6).optional(),align:ns(["left","center","right"]).optional(),spacing:Rk}).optional(),XL=Ye({anchor_id:Re().max(64).regex(/^[a-zA-Z0-9_-]*$/,"anchor_id: letters, numbers, - and _ only").optional(),custom_class:Re().max(120).regex(/^[a-zA-Z0-9 _-]*$/,"custom_class: no special characters").optional()}).optional(),ss={id:Re().min(1).max(64),hidden:ri().optional(),variant:Re().max(64).optional(),media:x0(ZL).optional(),style:KL,spacing:Rk,mobile:YL,advanced:XL}
627,GL=Ye({...ss,type:wr("announcement_bar"),content:Ye({message:Re().max(120).default(""),cta_label:Re().max(24).optional(),cta_href:si.optional(),dismissible:ri().optional()})}),JL=Ye({...ss,type:wr("nav_header"),content:Ye({links:cr(Ye({label:Re().max(40),anchor:Re().max(64)})).max(8).default([]),logo_url:Re().max(2048).optional(),cta:Ye({label:Re().max(24),href:si}).optional(),show_phone:ri().optional(),phone:Re().max(32).optional()})}),QL=Ye({...ss,type:wr("hero"),content:Ye({eyebrow:Re().max(40).optional(),headline:Re().min(1).max(120),subhead:Re().max(240).optional(),trust_line:Re().max(120).optional(),cta_primary:Ye({label:Re().max(32),href:si}).optional(),cta_secondary:Ye({label:Re().max(32),href:si}).optional(),form_ref:Re().max(64).optional()})}),eW=Ye({version:Re().min(1).max(64),locked:wr(!0)}),tW=ns(["first_name","last_name","phone","email","address","city","state","zip","water_concern","notes"]),nW=Ye({key:tW,label:Re().max(80).optional(),required:ri().optional(),placeholder:Re().max(80).optional()}),rW=Ye({key:Re().max(40),prompt:Re().max(200),type:ns(["single_select","multi_select"]),options:cr(Ye({value:Re().max(60),label:Re().max(120)})).min(2).max(8),required:ri().optional(),maps_to:VL(e=>e===""||e===null?void 0:e,ns(["water_concern"]).optional())}),sW=Ye({...ss,type:wr("lead_form"),content:Ye({form_slug:Re().min(1).max(120),flow:ns(["single","multi_step"]).default("single"),heading:Re().max(120).optional(),subtext:Re().max(240).optional(),submit_label:Re().max(32).default("Submit"),success_message:Re().max(400).optional(),contact_fields:cr(nW).max(12).default([]),questions:cr(rW).max(12).default([]),booking:Ye({enabled:ri().default(!1),required:ri().optional(),heading:Re().max(120).optional()}).optional(),consent:eW})}),iW=Ye({...ss,type:wr("benefits"),content:Ye({heading:Re().max(120).optional(),items:cr(Ye({icon:Re().max(64).optional(),title:Re().max(80),text:Re().max(240).optional()})).min(1).max(6)})}),oW=Ye({...ss,type:wr("product_grid"),content:Ye({heading:Re().max(160).optional(),heading_accent:Re().max(120).optional(),cta_label:Re().max(32).optional(),products:cr(Ye({label:Re().max(80),tagline:Re().max(120).optional(),price:Re().max(40).optional(),cta_href:si.optional(),media_key:Re().max(64).optional()})).min(1).max(12)})}),aW=Ye({...ss,type:wr("certifications"),content:Ye({heading:Re().max(120).optional(),badges:cr(Ye({media_key:Re().max(64),alt:Re().max(120),label:Re().max(80).optional()})).min(1).max(12)})}),lW=Ye({...ss,type:wr("faq"),content:Ye({heading:Re().max(120).optional(),items:cr(Ye({q:Re().max(240),a:Re().max(2e3)})).min(1).max(30)})}),dW=Ye({...ss,type:wr("cta"),content:Ye({headline:Re().min(1).max(160),sub:Re().max(240).optional(),cta_primary:Ye({label:Re().max(32),href:si}),cta_secondary:Ye({label:Re().max(32),href:si}).optional()})}),cW=Ye({...ss,type:wr("footer"),content:Ye({columns:cr(Ye({title:Re().max(60).optional(),links:cr(Ye({label:Re().max(60),href:si})).max(10).default([])})).max(5).optional(),legal_links:cr(Ye({label:Re().max(60),href:si})).max(6).optional(),copyright:Re().max(160).optional(),brand_line:Re().max(120).optional()})}),uW=Ye({...ss,type:wr("spacer"),content:Ye({height:ns(["sm","md","lg","xl"]).default("md"),divider:ns(["none","line","wave","angle","curve","gradient"]).optional(),divider_color:Re().max(32).optional()})}),pW=wL("type",[GL,JL,QL,sW,iW,oW,aW,lW,dW,cW,uW]);Ye({schema_version:wr(Nk),meta:Ye({title:Re().max(200).optional(),seo:Ye({meta_title:Re().max(200).optional(),meta_description:Re().max(400).optional(),og_image:Ty.optional()}).optional(),favicon:Ty.optional()}).default({}),preset_id:Re().max(64).optional(),tokens_override:x0(ky()).optional(),sections:cr(pW).max(60).default([])});function hW(e){if(e==null||typeof e!="object")return{schema_version:Nk,meta:{},sections:[]};const n=e,r=typeof n.schema_version=="number"?n.schema_version:0;let s={...n};return r<1&&(s={...s,schema_version:1,meta:s.meta??{},sections:Array.isArray(s.sections)?s.sections:[]}),s}const fW={announcement_bar:[{path:"message",label:"Message",kind:"text",maxLength:120,required:!0},{path:"cta_label",label:"CTA label",kind:"text",maxLength:24},{path:"cta_href",label:"CTA link",kind:"text",maxLength:2048,placeholder:"#book or https://â¦"}
627,{path:"dismissible",label:"Dismissible",kind:"checkbox"}],nav_header:[{path:"links",label:"Nav links",kind:"list",itemLabel:"Link",min:0,max:8,item:[{path:"label",label:"Label",kind:"text",maxLength:40,required:!0},{path:"anchor",label:"Anchor",kind:"text",maxLength:64,required:!0,placeholder:"section id"}],defaultItem:{label:"Link",anchor:"section"}},{path:"cta.label",label:"CTA label",kind:"text",maxLength:24},{path:"cta.href",label:"CTA link",kind:"text",maxLength:2048},{path:"logo_url",label:"Logo image",kind:"image",hint:"PNG with a transparent background, about 400x120px. Under 500KB keeps the page fast (5MB hard limit)."},{path:"show_phone",label:"Show phone",kind:"checkbox"},{path:"phone",label:"Phone",kind:"text",maxLength:32}],hero:[{path:"headline",label:"Headline",kind:"text",maxLength:120,required:!0},{path:"subhead",label:"Subhead",kind:"textarea",maxLength:240},{path:"trust_line",label:"Trust line",kind:"text",maxLength:120},{path:"eyebrow",label:"Eyebrow",kind:"text",maxLength:40},{path:"cta_primary.label",label:"Primary button label",kind:"text",maxLength:32},{path:"cta_primary.href",label:"Primary button link",kind:"text",maxLength:2048}],benefits:[{path:"heading",label:"Heading",kind:"text",maxLength:120},{path:"items",label:"Benefits",kind:"list",itemLabel:"Benefit",min:1,max:6,item:[{path:"icon",label:"Icon",kind:"text",maxLength:64,placeholder:"emoji or glyph"},{path:"title",label:"Title",kind:"text",maxLength:80,required:!0},{path:"text",label:"Text",kind:"textarea",maxLength:240}],defaultItem:{title:"New benefit"}}],product_grid:[{path:"heading",label:"Heading",kind:"text",maxLength:160},{path:"heading_accent",label:"Heading accent",kind:"text",maxLength:120},{path:"cta_label",label:"CTA label",kind:"text",maxLength:32},{path:"products",label:"Products",kind:"list",itemLabel:"Product",min:1,max:12,item:[{path:"label",label:"Label",kind:"text",maxLength:80,required:!0},{path:"tagline",label:"Tagline",kind:"text",maxLength:120},{path:"price",label:"Price",kind:"text",maxLength:40},{path:"media_key",label:"Product image",kind:"media",hint:"About 800x600 (4:3) or 1200x675 (16:9). Under 500KB keeps the page fast (5MB hard limit)."}],defaultItem:{label:"New product"}}],certifications:[{path:"heading",label:"Heading",kind:"text",maxLength:120},{path:"badges",label:"Badges",kind:"list",itemLabel:"Badge",min:1,max:12,item:[{path:"media_key",label:"Badge image",kind:"media",required:!0,hint:"Square PNG or WebP, about 200x200. Transparent background works best."},{path:"alt",label:"Alt text",kind:"text",maxLength:120,required:!0},{path:"label",label:"Label",kind:"text",maxLength:80}],defaultItem:{media_key:"badge",alt:"Certification"}}],faq:[{path:"heading",label:"Heading",kind:"text",maxLength:120},{path:"items",label:"Questions",kind:"list",itemLabel:"Question",min:1,max:30,item:[{path:"q",label:"Question",kind:"text",maxLength:240,required:!0},{path:"a",label:"Answer",kind:"textarea",maxLength:2e3,required:!0}],defaultItem:{q:"New question?",a:"Answer."}}],cta:[{path:"headline",label:"Headline",kind:"text",maxLength:160,required:!0},{path:"sub",label:"Subtext",kind:"textarea",maxLength:240},{path:"cta_primary.label",label:"Primary button label",kind:"text",maxLength:32,required:!0},{path:"cta_primary.href",label:"Primary button link",kind:"text",maxLength:2048,required:!0},{path:"cta_secondary.label",label:"Secondary button label",kind:"text",maxLength:32},{path:"cta_secondary.href",label:"Secondary button link",kind:"text",maxLength:2048}],lead_form:[{path:"form_slug",label:"Form slug",kind:"text",maxLength:120,required:!0,placeholder:"existing lead_forms slug",hint:"Must match an existing lead_forms slug for this tenant, or the page will not save."},{path:"flow",label:"Flow",kind:"select",options:[{value:"single",label:"Single page"},{value:"multi_step",label:"Multi-step"}]},{path:"heading",label:"Heading",kind:"text",maxLength:120},{path:"subtext",label:"Subtext",kind:"textarea",maxLength:240},{path:"submit_label",label:"Submit label",kind:"text",maxLength:32},{path:"success_message",label:"Success message",kind:"textarea",maxLength:400},{path:"contact_fields",label:"Contact fields",kind:"list",itemLabel:"Field",min:0,max:12,uniqueBy:"key",
627item:[{path:"key",label:"Field",kind:"select",required:!0,options:[{value:"first_name",label:"First name"},{value:"last_name",label:"Last name"},{value:"phone",label:"Phone"},{value:"email",label:"Email"},{value:"address",label:"Address"},{value:"city",label:"City"},{value:"state",label:"State"},{value:"zip",label:"ZIP"},{value:"water_concern",label:"Water concern"},{value:"notes",label:"Notes"}]},{path:"label",label:"Label override",kind:"text",maxLength:80},{path:"placeholder",label:"Placeholder",kind:"text",maxLength:80},{path:"required",label:"Required",kind:"checkbox"}],defaultItem:{key:"first_name",required:!0}},{path:"questions",label:"Qualifying questions",kind:"list",itemLabel:"Question",min:0,max:12,uniqueBy:"key",item:[{path:"key",label:"Answer key",kind:"text",maxLength:40,required:!0,hint:"Sent to capture.js as qa_<key> and folded into qualifying_answers. Lowercase, no spaces, unique within this form."},{path:"prompt",label:"Prompt",kind:"text",maxLength:200,required:!0},{path:"type",label:"Type",kind:"select",required:!0,options:[{value:"single_select",label:"Single select (auto-advances)"},{value:"multi_select",label:"Multi select (Next button)"}]},{path:"options",label:"Options",kind:"list",itemLabel:"Option",min:2,max:8,uniqueBy:"value",item:[{path:"label",label:"Label (shown)",kind:"text",maxLength:120,required:!0},{path:"value",label:"Stored value",kind:"text",maxLength:60,required:!0}],defaultItem:{label:"New option",value:"new_option"}},{path:"required",label:"Required",kind:"checkbox"},{path:"maps_to",label:"Also save to lead field",kind:"select",options:[{value:"water_concern",label:"Water concern"}],hint:"Writes this answer to a real column on the lead, not just qualifying_answers. Water concern drives the personalised line in the lead confirmation message. Multi-select contributes its first selection."}],defaultItem:{key:"q1",prompt:"New question",type:"single_select",options:[{label:"Option A",value:"option_a"},{label:"Option B",value:"option_b"}]}},{path:"booking.enabled",label:"Booking screen (multi-step only)",kind:"checkbox"},{path:"booking.required",label:"Booking required to submit",kind:"checkbox"},{path:"booking.heading",label:"Booking heading",kind:"text",maxLength:120,placeholder:"Choose a time"}],footer:[{path:"brand_line",label:"Brand line",kind:"text",maxLength:120},{path:"copyright",label:"Copyright",kind:"text",maxLength:160},{path:"legal_links",label:"Legal links",kind:"list",itemLabel:"Link",min:0,max:6,item:[{path:"label",label:"Label",kind:"text",maxLength:60,required:!0},{path:"href",label:"Link",kind:"text",maxLength:2048,required:!0}],defaultItem:{label:"Terms",href:"/terms"}}],spacer:[{path:"height",label:"Height",kind:"select",options:[{value:"sm",label:"Small"},{value:"md",label:"Medium"},{value:"lg",label:"Large"},{value:"xl",label:"Extra large"}]},{path:"divider",label:"Divider",kind:"select",options:[{value:"none",label:"None"},{value:"line",label:"Line"},{value:"wave",label:"Wave"},{value:"angle",label:"Angle"},{value:"curve",label:"Curve"},{value:"gradient",label:"Gradient"}]}]};function Wo(e,n){return n.split(".").reduce((r,s)=>r==null?void 0:r[s],e)}function Qh(e,n,r){const s=n.split("."),i=Array.isArray(e)?[...e]:{...e??{}};let o=i;for(let a=0;a<s.length-1;a++){const l=s[a],d=o[l];o[l]=Array.isArray(d)?[...d]:{...d??{}},o=o[l]}return o[s[s.length-1]]=r,i}function gW(e,n){const r=n.split("."),s={...e??{}};let i=s;for(let o=0;o<r.length-1;o++){const a=r[o];if(i[a]==null)return s;i[a]={...i[a]},i=i[a]}return delete i[r[r.length-1]],s}const cm={},mW=[{key:"navy",label:"Navy (hero bg)",affects:"Hero + footer background"},{key:"navyDk",label:"Navy dark",affects:"Darker navy shading"},{key:"teal",label:"Teal",affects:"Accents, link hovers"},{key:"tealDk",label:"Teal dark",affects:"FAQ markers, borders"},{key:"gold",label:"Gold (accent)",affects:"Announcement bar, headline accent, stars"},{key:"ink",label:"Ink (body text)",affects:"Main text color"},{key:"muted",label:"Muted text",affects:"Secondary / gray text"},{key:"line",label:"Lines / borders",affects:"Dividers, card borders"},{key:"bg",label:"Page background",affects:"Light section backgrounds"},{key:"btn",label:"Button",affects:"CTA buttons"}
627,{key:"btnDk",label:"Button dark",affects:"Button hover / dark"},{key:"green",label:"Green (success)",affects:"Success elements"}],xW=[{key:"section-bg",label:"Background",affects:"This section only",defaultFrom:"bg"},{key:"ink",label:"Text",affects:"Body text in this section",defaultFrom:"ink"},{key:"muted",label:"Secondary text",affects:"Consent, step counter, Back",defaultFrom:"muted"},{key:"link",label:"Links",affects:"Terms / Privacy links",defaultFrom:"teal"},{key:"tealDk",label:"Accent",affects:"Heading accent, markers",defaultFrom:"tealDk"},{key:"btn",label:"Button",affects:"Buttons in this section",defaultFrom:"btn"}],g_=[{value:"",label:"Default"},{value:"none",label:"None"},{value:"sm",label:"Small"},{value:"md",label:"Medium"},{value:"lg",label:"Large"},{value:"xl",label:"X-large"}];var k2;const m_=typeof window<"u"&&((k2=window.location)==null?void 0:k2.origin)||(cm==null?void 0:cm.VITE_APP_URL)||"https://cevora-app.vercel.app",me={head:"#e2e8f0",muted:"#64748b",accent:"#38bdf8",border:"#1e3a4f",panel:"rgba(13,126,163,0.06)",panelBorder:"rgba(13,126,163,0.2)",card:"rgba(255,255,255,0.02)",cardBorder:"rgba(255,255,255,0.08)",danger:"#f87171",ok:"#22c55e",input:"rgba(255,255,255,0.04)",inputBorder:"rgba(255,255,255,0.12)"},x_={draft:{bg:"rgba(245,158,11,0.14)",fg:"#f59e0b"},published:{bg:"rgba(34,197,94,0.14)",fg:"#22c55e"},archived:{bg:"rgba(100,116,139,0.16)",fg:"#94a3b8"}};function y_({status:e}){const n=x_[e]||x_.archived;return t.jsx("span",{style:{background:n.bg,color:n.fg,fontSize:10,fontWeight:700,padding:"2px 8px",borderRadius:6,textTransform:"uppercase",letterSpacing:".04em"},children:e})}function yW(e){if(!e)return"â";try{return new Date(e).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",timeZone:"America/Indiana/Indianapolis"})}catch{return"â"}}const bW=[{type:"announcement_bar",label:"Announcement bar"},{type:"nav_header",label:"Nav header"},{type:"hero",label:"Hero"},{type:"benefits",label:"Benefits"},{type:"product_grid",label:"Product grid"},{type:"certifications",label:"Certifications"},{type:"faq",label:"FAQ"},{type:"cta",label:"Call to action"},{type:"lead_form",label:"Lead form"},{type:"footer",label:"Footer"},{type:"spacer",label:"Spacer"}];function AW(){try{return"sec_"+crypto.randomUUID().slice(0,8)}catch{return"sec_"+Math.random().toString(36).slice(2,10)}}function vW(e){const n=AW();switch(e){case"announcement_bar":return{id:n,type:e,content:{message:"Limited-time offer"}};case"nav_header":return{id:n,type:e,content:{links:[]}};case"hero":return{id:n,type:e,content:{headline:"Your headline here"}};case"benefits":return{id:n,type:e,content:{items:[{title:"Benefit one"}]}};case"product_grid":return{id:n,type:e,content:{products:[{label:"Product one"}]}};case"certifications":return{id:n,type:e,content:{badges:[{media_key:"badge1",alt:"Certification"}]}};case"faq":return{id:n,type:e,content:{items:[{q:"Question?",a:"Answer."}]}};case"cta":return{id:n,type:e,content:{headline:"Ready to start?",cta_primary:{label:"Get started",href:"#"}}};case"lead_form":return{id:n,type:e,content:{form_slug:"CHANGE_ME",consent:{version:yd,locked:!0}}};case"footer":return{id:n,type:e,content:{copyright:"© 2026"}};case"spacer":return{id:n,type:e,content:{height:"md"}};default:return{id:n,type:e,content:{}}}}const so={width:"100%",background:me.input,border:`1px solid ${me.inputBorder}`,borderRadius:6,color:me.head,fontSize:12.5,padding:"7px 9px",outline:"none"},ed={color:me.muted,fontSize:10.5,fontWeight:700,marginBottom:4,display:"block"};function _W({fd:e,value:n,onChange:r}){const[s,i]=g.useState(!1),[o,a]=g.useState(""),[l,d]=g.useState(""),c=gd(typeof n=="string"?n:"");async function f(p){var h,y;const u=(y=(h=p==null?void 0:p.target)==null?void 0:h.files)==null?void 0:y[0];if(u){if(!l.trim()){a("Enter alt text first (describe the image).");return}i(!0),a("");try{const m=await e0(u,l.trim());r(m.assetRef)}catch(m){a((m==null?void 0:m.message)||"Upload failed")}i(!1),p!=null&&p.target&&(p.target.value="")}}return t.jsxs("div",{style:{marginBottom:10},children:[t.jsxs("label",{style:ed,children:[e.label,e.required?" *":""]}),e.hint?t.jsx("div",{style:{color:me.muted,fontSize:10.5,lineHeight:1.35,marginBottom:6,opacity:.85},children:e.hint}):null,c?t.jsxs("div",{style:{marginBottom:6,display:"flex",alignItems:"center",gap:8},children:[t.jsx("img",{src:c,alt:"",style:{height:40,width:"auto",borderRadius:4,border:`1px solid ${me.inputBorder}`,background:"#fff"}}),t.jsx("button",{onClick:()=>r(""),style:{cursor:"pointer",background:"none",border:`1px solid ${me.inputBorder}`,color:me.muted,borderRadius:6,fontSize:10.5,fontWeight:700,padding:"3px 8px"},children:"Remove"})]}):null,t.jsx("input",{value:l,placeholder:"Alt text (required before upload)",onChange:p=>d(p.target.value),style:{...so,marginBottom:6,fontSize:11.5}}),t.jsx("input",{type:"file",accept:"image/jpeg,image/png,image/webp",disabled:s,onChange:f,style:{fontSize:11,color:me.muted}}),s?t.jsx("div",{style:{color:me.muted,fontSize:11,marginTop:4},children:"Uploadingâ¦"}):null,o?t.jsx("div",{style:{color:me.danger,fontSize:11,marginTop:4},children:o}):null]})}function jW(){var n,r;return"m_"+(((r=(n=globalThis.crypto)==null?void 0:n.randomUUID)==null?void 0:r.call(n))||Math.random().toString(36).slice(2)).replace(/-/g,"").slice(0,8)}function wW({fd:e,value:n,onChange:r,ctx:s}){const[i,o]=g.useState(!1),[a,l]=g.useState(""),[d,c]=g.useState(""),f=typeof n=="string"?n:"",p=s&&f?s.media[f]:void 0,u=gd((p==null?void 0:p.asset)||"");async function h(m){var A,v;const b=(v=(A=m==null?void 0:m.target)==null?void 0:A.files)==null?void 0:v[0];if(b){if(!s){l("Media registry unavailable for this field.");return}if(!d.trim()){l("Enter alt text first (describe the image).");return}o(!0),l("");try{const x=await e0(b,d.trim()),_=f&&s.media[f]?f:jW();
627s.setSlot(_,{asset:x.assetRef,alt:d.trim()}),_!==f&&r(_)}catch(x){l((x==null?void 0:x.message)||"Upload failed")}o(!1),m!=null&&m.target&&(m.target.value="")}}function y(){s&&f&&s.setSlot(f,null),r("")}return t.jsxs("div",{style:{marginBottom:10},children:[t.jsxs("label",{style:ed,children:[e.label,e.required?" *":""]}),e.hint?t.jsx("div",{style:{color:me.muted,fontSize:10.5,lineHeight:1.35,marginBottom:6,opacity:.85},children:e.hint}):null,u?t.jsxs("div",{style:{marginBottom:6,display:"flex",alignItems:"center",gap:8},children:[t.jsx("img",{src:u,alt:"",style:{height:40,width:"auto",borderRadius:4,border:"1px solid "+me.inputBorder,background:"#fff"}}),t.jsx("button",{onClick:y,style:{cursor:"pointer",background:"none",border:"1px solid "+me.inputBorder,color:me.muted,borderRadius:6,fontSize:10.5,fontWeight:700,padding:"3px 8px"},children:"Remove"})]}):null,t.jsx("input",{value:d,placeholder:"Alt text (required before upload)",onChange:m=>c(m.target.value),style:{...so,marginBottom:6,fontSize:11.5}}),t.jsx("input",{type:"file",accept:"image/jpeg,image/png,image/webp",disabled:i,onChange:h,style:{fontSize:11,color:me.muted}}),i?t.jsx("div",{style:{color:me.muted,fontSize:11,marginTop:4},children:"Uploadingâ¦"}):null,a?t.jsx("div",{style:{color:me.danger,fontSize:11,marginTop:4},children:a}):null]})}function Ek({fd:e,value:n,onChange:r,ctx:s}){return e.kind==="image"?t.jsx(_W,{fd:e,value:n,onChange:r}):e.kind==="media"?t.jsx(wW,{fd:e,value:n,onChange:r,ctx:s}):e.kind==="list"?t.jsx(Pk,{fd:e,rows:Array.isArray(n)?n:[],onChange:r,ctx:s}):e.kind==="checkbox"?t.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer",margin:"4px 0 10px"},children:[t.jsx("input",{type:"checkbox",checked:!!n,onChange:i=>r(i.target.checked)}),t.jsx("span",{style:{color:me.head,fontSize:12.5},children:e.label})]}):t.jsxs("div",{style:{marginBottom:10},children:[t.jsxs("label",{style:ed,children:[e.label,e.required?" *":""]}),e.hint?t.jsx("div",{style:{color:me.muted,fontSize:10.5,lineHeight:1.35,marginBottom:6,opacity:.85},children:e.hint}):null,e.kind==="select"?t.jsxs("select",{style:so,value:n??"",onChange:i=>r(i.target.value),children:[e.required?null:t.jsx("option",{value:"",children:"â"}),(e.options||[]).map(i=>t.jsx("option",{value:i.value,children:i.label},i.value))]}):e.kind==="textarea"?t.jsx("textarea",{style:{...so,minHeight:60,resize:"vertical"},maxLength:e.maxLength,value:n??"",placeholder:e.placeholder,onChange:i=>r(i.target.value)}):t.jsx("input",{style:so,maxLength:e.maxLength,value:n??"",placeholder:e.placeholder,onChange:i=>r(i.target.value)})]})}function Pk({fd:e,rows:n,onChange:r,ctx:s}){const i=Array.isArray(n)?n:[],o=e.max==null||i.length<e.max,a=(e.min??0)<i.length;function l(p,u,h){const y=i.map((m,b)=>b===p?Qh(m,u,h):m);r(y)}function d(){let p=e.defaultItem?JSON.parse(JSON.stringify(e.defaultItem)):{};if(e.uniqueBy){const u=e.uniqueBy,h=new Set(i.map(m=>Wo(m,u)).filter(m=>typeof m=="string"&&m)),y=Wo(p,u);if(typeof y=="string"&&h.has(y)){const m=(e.item||[]).find(A=>A.path===u);let b;if(m&&m.options&&m.options.length&&(b=m.options.map(A=>A.value).find(A=>!h.has(A))),!b){let A=2;for(b=y+"_"+A;h.has(b);)A++,b=y+"_"+A}p=Qh(p,u,b)}}r([...i,p])}function c(p){const u=i[p],h=i.filter((y,m)=>m!==p);if(s&&u){const y=(e.item||[]).filter(m=>m.kind==="media");for(const m of y){const b=Wo(u,m.path);typeof b=="string"&&b&&(h.some(v=>y.some(x=>Wo(v,x.path)===b))||s.setSlot(b,null))}}r(h)}function f(p,u){const h=p+u;if(h<0||h>=i.length)return;const y=[...i],m=y[p];y[p]=y[h],y[h]=m,r(y)}return t.jsxs("div",{style:{marginBottom:12},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:6},children:[t.jsxs("label",{style:{...ed,marginBottom:0},children:[e.label," (",i.length,")"]}),t.jsxs("button",{onClick:d,disabled:!o,style:{cursor:o?"pointer":"default",background:me.panel,border:`1px solid ${me.panelBorder}`,color:me.accent,borderRadius:6,fontSize:10.5,fontWeight:700,padding:"2px 8px",opacity:o?1:.4},children:["+ ",e.itemLabel||"Item"]})]}),i.length===0?t.jsx("div",{style:{color:me.muted,fontSize:11},children:"None yet."}):t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:i.map((p,u)=>t.jsxs("div",{style:{border:`1px solid ${me.cardBorder}`,borderRadius:8,padding:8,background:me.card},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:6},children:[t.jsxs("span",{style:{color:me.muted,fontSize:10,fontWeight:700},children:[e.itemLabel," ",u+1]}),t.jsxs("span",{style:{display:"flex",gap:2},children:[t.jsx("button",{onClick:()=>f(u,-1),disabled:u===0,title:"Up",style:{cursor:u===0?"default":"pointer",background:"none",border:"none",color:u===0?me.muted:me.accent,fontSize:12,padding:"0 3px",opacity:u===0?.4:1},children:"â²"}),t.jsx("button",{onClick:()=>f(u,1),disabled:u===i.length-1,title:"Down",style:{cursor:u===i.length-1?"default":"pointer",background:"none",border:"none",color:u===i.length-1?me.muted:me.accent,fontSize:12,padding:"0 3px",opacity:u===i.length-1?.4:1},children:"â¼"}),t.jsx("button",{onClick:()=>c(u),disabled:!a,title:"Remove",style:{cursor:a?"pointer":"default",background:"none",border:"none",color:me.danger,fontSize:12,padding:"0 3px",opacity:a?1:.4},children:"â"})]})]}),(e.item||[]).map(h=>t.jsx(Ek,{fd:h,ctx:s,value:Wo(p,h.path),onChange:y=>l(u,h.path,y)},h.path))]},u))})]})}function SW({section:e,onChange:n,onMediaChange:r}){const s=fW[e.type]||[],i=e.content||{},o=e.media||{},a={media:o,setSlot:(d,c)=>{const f={...o};c==null?delete f[d]:f[d]=c,r(Object.keys(f).length?f:void 0)}};function l(d,c){const f=s.find(p=>p.path===d);(c===""||c==null)&&f&&!f.required?n(gW(i,d)):n(Qh(i,d,c))}return s.length===0?t.jsx("div",{style:{color:me.muted,fontSize:12},children:"No editable fields for this type."}):t.jsx("div",{children:s.map(d=>d.kind==="list"?t.jsx(Pk,{fd:d,ctx:a,rows:Wo(i,d.path)||[],onChange:c=>n(Qh(i,d.path,c))},d.path):t.jsx(Ek,{fd:d,ctx:a,value:Wo(i,d.path),onChange:c=>l(d.path,c)},d.path))})}const kW=[{id:"zenith",name:"Zenith Classic",tokens:{navy:"#0d2b4e",navyDk:"#0a2038",teal:"#17a2b8",tealDk:"#0e7d8f",gold:"#f4b731",ink:"#1a2b3a",muted:"#5a6b7b",line:"#e2e8ef",bg:"#f5f8fb",btn:"#12a05e",btnDk:"#0c7d47",green:"#22a45d"}},{id:"clinical",name:"Cool Clinical",tokens:{navy:"#0a3d62",navyDk:"#072c48",teal:"#00b4d8",tealDk:"#0089a8",gold:"#48cae4",ink:"#12303f",muted:"#5b7285",line:"#dce8ef",bg:"#f2f8fb",btn:"#0091b8",btnDk:"#006d8c",green:"#12a0b0"}},{id:"natural",name:"Fresh Natural",tokens:{navy:"#1b4332",navyDk:"#123024",teal:"#52b788",tealDk:"#3a8f68",gold:"#95d5b2",ink:"#1e352a",muted:"#5f7568",line:"#dceee3",bg:"#f2faf5",btn:"#40916c",btnDk:"#2d6a4f",green:"#40916c"}},{id:"urgent",name:"Bold Urgent",tokens:{navy:"#1a1a2e",navyDk:"#111121",teal:"#e63946",tealDk:"#b02a35",gold:"#f77f00",ink:"#1f1f2e",muted:"#6a6a7a",line:"#e6e2ea",bg:"#faf6f6",btn:"#e63946",btnDk:"#b02a35",green:"#2a9d5f"}},{id:"warm",name:"Warm Trust",tokens:{navy:"#2d3142",navyDk:"#20222f",teal:"#e0a458",tealDk:"#c08640",gold:"#e0a458",ink:"#2b2d3a",muted:"#6f7280",line:"#ece6de",bg:"#faf7f2",btn:"#c9803e",btnDk:"#a4642c",green:"#4a9d6a"}}
627,{id:"premium",name:"Midnight Premium",tokens:{navy:"#0b132b",navyDk:"#070d1f",teal:"#c9a227",tealDk:"#a4831d",gold:"#c9a227",ink:"#141a2b",muted:"#5c6b73",line:"#e0e2e8",bg:"#f5f6f8",btn:"#c9a227",btnDk:"#a4831d",green:"#3a8f68"}},{id:"ocean",name:"Ocean Depth",tokens:{navy:"#003844",navyDk:"#002730",teal:"#00a896",tealDk:"#028090",gold:"#02c39a",ink:"#0f2e33",muted:"#5b7379",line:"#dcecec",bg:"#f1fafa",btn:"#028090",btnDk:"#016170",green:"#02a37f"}},{id:"sunrise",name:"Sunrise Optimism",tokens:{navy:"#3d348b",navyDk:"#2c2666",teal:"#f7b801",tealDk:"#d19a00",gold:"#f18701",ink:"#26224a",muted:"#6a6785",line:"#e8e5f0",bg:"#f7f6fb",btn:"#f18701",btnDk:"#c76e00",green:"#3aa06a"}},{id:"slate",name:"Slate Modern",tokens:{navy:"#2b2d42",navyDk:"#1e1f30",teal:"#4361ee",tealDk:"#2f49c0",gold:"#4895ef",ink:"#22243a",muted:"#63667e",line:"#e2e3ec",bg:"#f5f6fa",btn:"#4361ee",btnDk:"#2f49c0",green:"#2a9d6f"}},{id:"crimson",name:"Crimson Authority",tokens:{navy:"#4a1a2c",navyDk:"#361220",teal:"#c1121f",tealDk:"#9a0e18",gold:"#e5383b",ink:"#2e1a22",muted:"#7a6068",line:"#eee2e5",bg:"#faf5f6",btn:"#c1121f",btnDk:"#9a0e18",green:"#3a8f5f"}}];function CW({theme:e,onClick:n}){const r=e.tokens;return t.jsxs("button",{onClick:n,title:e.name,style:{cursor:"pointer",border:`1px solid ${me.inputBorder}`,borderRadius:7,padding:3,background:"none",display:"flex",flexDirection:"column",alignItems:"center",gap:3,width:52},children:[t.jsxs("span",{style:{display:"flex",width:40,height:18,borderRadius:4,overflow:"hidden",border:`1px solid ${me.inputBorder}`},children:[t.jsx("span",{style:{flex:1,background:r.navy}}),t.jsx("span",{style:{flex:1,background:r.teal}}),t.jsx("span",{style:{flex:1,background:r.gold}}),t.jsx("span",{style:{flex:1,background:r.btn}})]}),t.jsx("span",{style:{color:me.muted,fontSize:8.5,lineHeight:1.1,textAlign:"center",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",width:"100%"},children:e.name.split(" ")[0]})]})}function TW({override:e,onChange:n,onReset:r,onResetOne:s,onApplyTheme:i}){const[o,a]=g.useState(!1);return t.jsxs("div",{children:[t.jsx("div",{style:{color:me.muted,fontSize:10,fontWeight:700,textTransform:"uppercase",letterSpacing:".05em",marginBottom:6},children:"Themes"}),t.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6,marginBottom:12},children:kW.map(l=>t.jsx(CW,{theme:l,onClick:()=>i(l.tokens)},l.id))}),t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:8},children:[t.jsx("button",{onClick:()=>a(l=>!l),style:{cursor:"pointer",background:"none",border:"none",color:me.accent,fontSize:11,fontWeight:700,padding:0},children:o?"â¾ Fine-tune individual colors":"⸠Fine-tune individual colors"}),o?t.jsx("button",{onClick:r,style:{cursor:"pointer",background:"none",border:`1px solid ${me.inputBorder}`,color:me.muted,borderRadius:6,fontSize:10.5,fontWeight:700,padding:"3px 9px"},children:"Reset all"}):null]}),t.jsx("div",{style:{display:o?"flex":"none",flexDirection:"column",gap:10},children:mW.map(l=>{const d=(e==null?void 0:e[l.key])||Ge[l.key],c=(e==null?void 0:e[l.key])!=null;return t.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8},children:[t.jsx("input",{type:"color",value:d,onChange:f=>n(l.key,f.target.value),style:{width:30,height:28,padding:0,border:`1px solid ${me.inputBorder}`,borderRadius:6,background:"none",cursor:"pointer",flexShrink:0,marginTop:1}}),t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[t.jsxs("span",{style:{color:me.head,fontSize:11.5,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:[l.label,c?t.jsx("span",{style:{color:me.accent},children:" â¢"}):null]}),c?t.jsx("button",{onClick:()=>s(l.key),title:"Reset this color",style:{cursor:"pointer",background:"none",border:"none",color:me.accent,fontSize:12,padding:0,lineHeight:1,marginLeft:"auto",flexShrink:0},children:"âº"}):null]}),t.jsx("div",{style:{color:me.muted,fontSize:10,lineHeight:1.3,margin:"1px 0 3px"},children:l.affects}),t.jsx("input",{value:d,onChange:f=>{const p=f.target.value.trim();/^#?[0-9a-fA-F]{0,6}$/.test(p)&&n(l.key,p.startsWith("#")?p:"#"+p)},style:{...so,height:22,fontSize:11,fontFamily:"ui-monospace, monospace",padding:"2px 6px"}})]})]},l.key)})})]})}function zW({section:e,onStyle:n,onResetAll:r,onSpacing:s}){const i=(e==null?void 0:e.style)||{},o=(e==null?void 0:e.spacing)||{},a=Object.keys(i).length>0||Object.keys(o).length>0;return t.jsxs("div",{style:{marginBottom:16,paddingBottom:14,borderBottom:"1px solid "+me.border},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:4},children:[t.jsxs("span",{style:{color:me.muted,fontSize:11,fontWeight:700,textTransform:"uppercase",letterSpacing:".05em"},children:["This section · ",e.type]}),a?t.jsx("button",{onClick:r,style:{cursor:"pointer",background:"none",border:"1px solid "+me.inputBorder,color:me.muted,borderRadius:6,fontSize:10.5,fontWeight:700,padding:"3px 9px"},children:"Reset"}):null]}),t.jsx("div",{style:{color:me.muted,fontSize:10,lineHeight:1.35,marginBottom:10},children:"Anything left unset inherits from the page colors below."}),t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:10},children:xW.map(l=>{const d=i[l.key]||Ge[l.defaultFrom],c=i[l.key]!=null;return t.jsxs("div",{style:{display:"flex",alignItems:"flex-start",ga
627p:8},children:[t.jsx("input",{type:"color",value:d,onChange:f=>n(l.key,f.target.value),style:{width:30,height:28,padding:0,border:"1px solid "+me.inputBorder,borderRadius:6,background:"none",cursor:"pointer",flexShrink:0,marginTop:1}}),t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[t.jsxs("span",{style:{color:me.head,fontSize:11.5,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:[l.label,c?t.jsx("span",{style:{color:me.accent},children:" â¢"}):null]}),c?t.jsx("button",{onClick:()=>n(l.key,null),title:"Inherit from page",style:{cursor:"pointer",background:"none",border:"none",color:me.accent,fontSize:12,padding:0,lineHeight:1,marginLeft:"auto",flexShrink:0},children:"âº"}):null]}),t.jsx("div",{style:{color:me.muted,fontSize:10,lineHeight:1.3,margin:"1px 0 3px"},children:l.affects})]})]},l.key)})}),t.jsxs("div",{style:{display:"flex",gap:8,marginTop:12},children:[t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsx("label",{style:ed,children:"Space above"}),t.jsx("select",{style:so,value:o.pt||"",onChange:l=>s("pt",l.target.value||null),children:g_.map(l=>t.jsx("option",{value:l.value,children:l.label},l.value))})]}),t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsx("label",{style:ed,children:"Space below"}),t.jsx("select",{style:so,value:o.pb||"",onChange:l=>s("pb",l.target.value||null),children:g_.map(l=>t.jsx("option",{value:l.value,children:l.label},l.value))})]})]}),t.jsx("div",{style:{color:me.muted,fontSize:10,lineHeight:1.3,marginTop:4},children:"Extra space added around the section, on top of its own padding."})]})}function NW(){const[e,n]=g.useState([]),[r,s]=g.useState(!0),[i,o]=g.useState(""),[a,l]=g.useState(null),[d,c]=g.useState(null),[f,p]=g.useState(null),[u,h]=g.useState(0),[y,m]=g.useState(!1),[b,A]=g.useState(!1),[v,x]=g.useState(""),[_,j]=g.useState([]),[C,S]=g.useState("desktop"),[T,L]=g.useState(null),[E,R]=g.useState("content"),[N,O]=g.useState(!1),[z,P]=g.useState(!1),[D,M]=g.useState(null),[k,q]=g.useState(!1),[$,I]=g.useState(!1);g.useEffect(()=>{B()},[]);async function B(){s(!0),o("");try{const X=await rq();n(X),X.length&&!a&&J(X[0].id)}catch(X){o((X==null?void 0:X.message)||"Failed to load pages")}s(!1)}async function J(X,H=!1){if(!(!H&&y&&X!==a&&!window.confirm("You have unsaved changes. Discard them and switch pages?"))){l(X),A(!0),x(""),p(null),c(null),j([]),m(!1),M(null),q(!1),L(null);try{const de=await K4(X);if(!de){x("Page not found"),A(!1);return}c(de),h(de.revision),p(hW(de.draft_config));try{j(await lq(X))}catch{}}catch(de){x((de==null?void 0:de.message)||"Failed to load page")}A(!1)}}function ae(X){p(H=>H&&{...H,sections:X([...H.sections])}),m(!0),M(null)}function te(X){ae(H=>[...H,vW(X)]),q(!1)}function U(X){ae(H=>H.filter((de,pe)=>pe!==X)),L(H=>H===X?null:H!=null&&H>X?H-1:H)}function W(X,H){ae(de=>{const pe=X+H;if(pe<0||pe>=de.length)return de;const Ne=[...de],Ie=Ne[X];return Ne[X]=Ne[pe],Ne[pe]=Ie,Ne}),L(de=>de===X?X+H:de===X+H?X:de)}function G(X,H){ae(de=>de.map((pe,Ne)=>Ne===X?{...pe,content:H}:pe))}function V(X,H){ae(de=>de.map((pe,Ne)=>{if(Ne!==X)return pe;const Ie={...pe};return H===void 0?delete Ie.media:Ie.media=H,Ie}))}function ee(X,H,de){ae(pe=>pe.map((Ne,Ie)=>{if(Ie!==X)return Ne;const Ze={...Ne},ht={...Ze.style||{}};return de==null?delete ht[H]:ht[H]=de,Object.keys(ht).length?Ze.style=ht:delete Ze.style,Ze}))}function re(X,H,de){ae(pe=>pe.map((Ne,Ie)=>{if(Ie!==X)return Ne;const Ze={...Ne},ht={...Ze.spacing||{}};return de==null?delete ht[H]:ht[H]=de,Object.keys(ht).length?Ze.spacing=ht:delete Ze.spacing,Ze}))}function Q(X){ae(H=>H.map((de,pe)=>{if(pe!==X)return de;const Ne={...de};return delete Ne.style,delete Ne.spacing,Ne}))}function oe(X,H){p(de=>{if(!de)return de;const pe=de.tokens_override||{};return{...de,tokens_override:{...pe,[X]:H}}}),m(!0),M(null)}function ne(){p(X=>{if(!X)return X;const H={...X};return delete H.tokens_override,H}),m(!0),M(null)}function ge(X){p(H=>{if(!H)return H;const de={...H.tokens_override||{}};delete de[X];const pe={...H};return Object.keys(de).length===0?delete pe.tokens_override:pe.tokens_override=de,pe}),m(!0),M(null)}function be(X){p(H=>H&&{...H,tokens_override:{...X}}),m(!0),M(null)}async function we(){if(!(!a||!f)){O(!0),M(null);try{const X=await oq(a,f,u);if(X.ok)h(X.revision),m(!1),M({kind:"ok",text:`Saved (rev ${X.revision})`});else if(X.conflict){const H=X;M({kind:"conflict",text:`This page changed elsewhere (server rev ${H.server_revision}, yours ${H.your_revision}). Reload to get the latest.`})}else{const H=X,de=Array.isArray(H.details)?H.details.join("; "):H.details||"";M({kind:"err",text:H.error+(de?` â ${de}`:"")})}}catch(X){M({kind:"err",text:(X==null?void 0:X.message)||"Save failed"})}O(!1)}}async function F(){if(!(!a||!f||y)){P(!0),M(null);try{const X=await aq(a);if(X&&X.ok){const H=X.version_number!=null?` v${X.version_number}`:"";X.error?M({kind:"ok",text:`Published${H} â note: ${X.error}`}):M({kind:"ok",text:`Published${H}`}),await J(a,!0)}else{const H=X&&Array.isArray(X.details)?X.details.join("; "):(X==null?void 0:X.details)||"";M({kind:"err",text:((X==null?void 0:X.error)||"Publish failed")+(H?` â ${H}`:"")})}}catch(X){M({kind:"err",text:(X==null?void 0:X.message)||"Publish failed"})}P(!1)}}async function K(){const X=window.prompt("New landing page name:");if(!X||!X.trim())return;const H=X.toLowerCase().trim().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60);if(!H){window.alert("Could not derive a slug from that name.");return}I(!0);try{const de=await sq({internal_name:X.trim(),slug:H});await B(),await J(de.id,!0)}catch(de){window.alert("Create failed: "+((de==null?void 0:de.message)||"unknown error"))}I(!1)}
627async function Z(){const X=e.find(pe=>pe.id===a);if(!X){window.alert("Select a page to copy first.");return}const H=`${X.internal_name} (Copy)`,de=window.prompt("Name for the copy:",H);if(!(!de||!de.trim())){I(!0);try{const pe=await iq(X.id,de.trim());await B(),await J(pe.id,!0)}catch(pe){window.alert("Duplicate failed: "+((pe==null?void 0:pe.message)||"unknown error"))}I(!1)}}const ie=(f==null?void 0:f.sections)??[],Y=T!=null?ie[T]:null;return t.jsxs("div",{style:{display:"flex",gap:14,height:"100%",minHeight:560},children:[t.jsxs("div",{style:{width:190,flexShrink:0,display:"flex",flexDirection:"column"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:10},children:[t.jsx("span",{style:{color:me.muted,fontSize:11,fontWeight:700,textTransform:"uppercase",letterSpacing:".05em"},children:"Pages"}),t.jsxs("div",{style:{display:"flex",gap:6},children:[t.jsx("button",{onClick:Z,disabled:$||!a,title:"Duplicate the selected page as a new draft",style:{cursor:$||!a?"default":"pointer",background:"transparent",border:`1px solid ${me.panelBorder}`,color:$||!a?me.muted:me.accent,borderRadius:6,fontSize:11,fontWeight:700,padding:"3px 9px"},children:"Copy"}),t.jsx("button",{onClick:K,disabled:$,style:{cursor:"pointer",background:me.panel,border:`1px solid ${me.panelBorder}`,color:me.accent,borderRadius:6,fontSize:11,fontWeight:700,padding:"3px 9px"},children:$?"â¦":"+ New"})]})]}),r?t.jsx("div",{style:{color:me.muted,fontSize:13},children:"Loadingâ¦"}):i?t.jsx("div",{style:{color:me.danger,fontSize:12},children:i}):e.length===0?t.jsx("div",{style:{color:me.muted,fontSize:12,lineHeight:1.5},children:"No landing pages yet. Click â+ Newâ."}):t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:4,overflowY:"auto"},children:e.map(X=>{const H=X.id===a;return t.jsxs("button",{onClick:()=>J(X.id),style:{textAlign:"left",cursor:"pointer",border:"1px solid",borderColor:H?me.panelBorder:"transparent",background:H?me.panel:"transparent",borderRadius:8,padding:"8px 10px",color:me.head},children:[t.jsxs("div",{style:{fontSize:12.5,fontWeight:600,marginBottom:3,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:[X.internal_name,H&&y?" â¢":""]}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[t.jsx(y_,{status:X.status}),t.jsxs("span",{style:{color:me.muted,fontSize:11,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:["/",X.slug]})]})]},X.id)})})]}),t.jsxs("div",{style:{width:190,flexShrink:0,display:"flex",flexDirection:"column"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:10},children:[t.jsx("span",{style:{color:me.muted,fontSize:11,fontWeight:700,textTransform:"uppercase",letterSpacing:".05em"},children:"Sections"}),t.jsx("button",{onClick:()=>q(X=>!X),disabled:!f,style:{cursor:f?"pointer":"default",background:me.panel,border:`1px solid ${me.panelBorder}`,color:me.accent,borderRadius:6,fontSize:11,fontWeight:700,padding:"3px 9px",opacity:f?1:.5},children:"+ Add"})]}),k?t.jsx("div",{style:{marginBottom:8,border:`1px solid ${me.cardBorder}`,borderRadius:8,padding:6,background:me.card,display:"flex",flexDirection:"column",gap:2},children:bW.map(X=>t.jsx("button",{onClick:()=>te(X.type),style:{textAlign:"left",cursor:"pointer",background:"transparent",border:"none",color:me.head,fontSize:12,padding:"5px 8px",borderRadius:5},children:X.label},X.type))}):null,b?t.jsx("div",{style:{color:me.muted,fontSize:13},children:"Loadingâ¦"}):ie.length===0?t.jsx("div",{style:{color:me.muted,fontSize:12},children:"No sections. Use â+ Addâ."}):t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:4,overflowY:"auto"},children:ie.map((X,H)=>{const de=T===H;return t.jsxs("div",{onClick:()=>L(H),style:{display:"flex",alignItems:"center",gap:5,padding:"6px 7px",cursor:"pointer",background:de?me.panel:me.card,border:`1px solid ${de?me.panelBorder:me.cardBorder}`,borderRadius:6},children:[t.jsx("span",{style:{color:me.muted,fontSize:10,minWidth:12},children:H+1}),t.jsx("span",{style:{color:me.head,fontSize:11.5,fontFamily:"ui-monospace, monospace",flex:1,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:X.type}),t.jsx("button",{onClick:pe=>{pe.stopPropagation(),W(H,-1)},disabled:H===0,title:"Up",style:{cursor:H===0?"default":"pointer",background:"none",border:"none",color:H===0?me.muted:me.accent,fontSize:12,padding:"0 2px",opacity:H===0?.4:1},children:"â²"}),t.jsx("button",{onClick:pe=>{pe.stopPropagation(),W(H,1)},disabled:H===ie.length-1,title:"Down",style:{cursor:H===ie.length-1?"default":"pointer",background:"none",border:"none",color:H===ie.length-1?me.muted:me.accent,fontSize:12,padding:"0 2px",opacity:H===ie.length-1?.4:1},children:"â¼"}),t.jsx("button",{onClick:pe=>
627{pe.stopPropagation(),U(H)},title:"Remove",style:{cursor:"pointer",background:"none",border:"none",color:me.danger,fontSize:12,padding:"0 2px"},children:"â"})]},X.id)})}),t.jsx("div",{style:{color:me.muted,fontSize:10.5,lineHeight:1.5,marginTop:10},children:"Click a section to edit its content. Colors and images arrive next."})]}),t.jsxs("div",{style:{width:250,flexShrink:0,display:"flex",flexDirection:"column",overflowY:"auto"},children:[t.jsx("div",{style:{display:"flex",border:`1px solid ${me.border}`,borderRadius:8,overflow:"hidden",marginBottom:12},children:["content","design"].map(X=>t.jsx("button",{onClick:()=>R(X),style:{flex:1,cursor:"pointer",border:"none",padding:"5px 0",fontSize:11.5,fontWeight:700,background:E===X?me.panel:"transparent",color:E===X?me.head:me.muted},children:X==="content"?"Content":"Design"},X))}),f?E==="design"?t.jsxs(t.Fragment,{children:[Y?t.jsx(zW,{section:Y,onStyle:(X,H)=>T!=null&&ee(T,X,H),onResetAll:()=>T!=null&&Q(T),onSpacing:(X,H)=>T!=null&&re(T,X,H)}):t.jsx("div",{style:{color:me.muted,fontSize:11,lineHeight:1.4,marginBottom:14,paddingBottom:14,borderBottom:"1px solid "+me.border},children:"Select a section to give it its own colors and spacing."}),t.jsx("div",{style:{color:me.muted,fontSize:11,fontWeight:700,textTransform:"uppercase",letterSpacing:".05em",marginBottom:10},children:"Page colors"}),t.jsx(TW,{override:f.tokens_override||{},onChange:oe,onReset:ne,onResetOne:ge,onApplyTheme:be})]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{style:{color:me.muted,fontSize:11,fontWeight:700,textTransform:"uppercase",letterSpacing:".05em",marginBottom:10},children:Y?`Content · ${Y.type}`:"Content"}),Y==null?t.jsx("div",{style:{color:me.muted,fontSize:12},children:"Select a section to edit its content."}):t.jsx(SW,{section:Y,onChange:X=>T!=null&&G(T,X),onMediaChange:X=>T!=null&&V(T,X)})]}):t.jsx("div",{style:{color:me.muted,fontSize:12},children:"Select a page."})]}),t.jsxs("div",{style:{flex:1,minWidth:0,display:"flex",flexDirection:"column",gap:12},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,flexWrap:"wrap"},children:[t.jsx("div",{style:{display:"flex",alignItems:"center",gap:10},children:d?t.jsxs(t.Fragment,{children:[t.jsx(y_,{status:d.status}),t.jsxs("span",{style:{color:me.muted,fontSize:12},children:["rev ",u,y?" ⢠unsaved":""]}),t.jsxs("a",{href:`${m_}/lp/${d.slug}`,target:"_blank",rel:"noreferrer",style:{color:me.accent,fontSize:12,textDecoration:"none",wordBreak:"break-all"},children:[`${m_}/lp/${d.slug}`," â"]})]}):t.jsx("span",{style:{color:me.muted,fontSize:12},children:"Select a page"})}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[t.jsx("div",{style:{display:"flex",border:`1px solid ${me.border}`,borderRadius:8,overflow:"hidden"},children:["desktop","mobile"].map(X=>t.jsx("button",{onClick:()=>S(X),style:{cursor:"pointer",border:"none",padding:"5px 14px",fontSize:12,background:C===X?me.panel:"transparent",color:C===X?me.head:me.muted},children:X==="desktop"?"Desktop":"Mobile"},X))}),t.jsx("button",{onClick:we,disabled:!y||N||!f,style:{cursor:!y||N||!f?"default":"pointer",background:!y||N?"rgba(56,189,248,0.15)":me.accent,color:!y||N?me.muted:"#04212e",border:"none",borderRadius:8,fontSize:12,fontWeight:700,padding:"6px 16px"},children:N?"Savingâ¦":"Save draft"}),t.jsx("button",{onClick:F,disabled:y||N||z||!f||!d,title:y?"Save your draft first, then publish":"Make the current saved draft live",style:{cursor:y||N||z||!f||!d?"default":"pointer",background:y||N||z||!f||!d?"rgba(34,197,94,0.15)":me.ok,color:y||N||z||!f||!d?me.muted:"#04212e",border:"none",borderRadius:8,fontSize:12,fontWeight:700,padding:"6px 16px"},children:z?"Publishingâ¦":y?"Save to publish":"Publish"})]})]}),D?t.jsxs("div",{style:{fontSize:12,padding:"8px 12px",borderRadius:8,background:D.kind==="ok"?"rgba(34,197,94,0.10)":D.kind==="conflict"?"rgba(245,158,11,0.10)":"rgba(248,113,113,0.10)",color:D.kind==="ok"?me.ok:D.kind==="conflict"?"#f59e0b":me.danger,display:"flex",alignItems:"center",justifyContent:"space-between",gap:12},children:[t.jsx("span",{children:D.text}),D.kind==="conflict"&&a?t.jsx("button",{onClick:()=>J(a,!0),style:{cursor:"pointer",background:"none",border:"1px solid currentColor",color:"inherit",borderRadius:6,fontSize:11,fontWeight:700,padding:"3px 10px",whiteSpace:"nowrap"},children:"Reload"}):null]}):null,t.jsx("div",{style:{flex:1,minHeight:300,border:`1px solid ${me.border}`,borderRadius:10,overflow:"hidden",background:"#0b1622"},children:b?t.jsx("div",{style:{color:me.muted,fontSize:13,padding:20},children:"Loading previewâ¦"}):v?t.jsx("div",{style:{color:me.danger,fontSize:13,padding:20},children:v}):f?t.jsx("div",{style:{height:"100%",overflowY:"auto",display:"flex",justifyContent:"center",background:"#33465a"},children:t.jsx("div",{style:{width:C==="mobile"?390:"100%",maxWidth:C==="mobile"?390:1180,background:"#fff",minHeight:"100%"},children:t.jsx(bd,{config:f,tokens:f.tokens_override||null})})}):t.jsx("div",{style:{color:me.muted,fontSize:13,padding:20},children:"Select a page to preview."})}),t.jsxs("div",{children:[t.jsx("div",{style:{color:me.muted,fontSize:11,fontWeight:700,textTransform:"uppercase",letterSpacing:".05em",marginBottom:8},children:"Version history"}),_.length===0?t.jsx("div",{style:{color:me.muted,fontSize:12},children:"No published versions yet."}):t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:3,maxHeight:110,overflowY:"auto"},children:_.map(X=>t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"6px 10px",background:me.card,border:`1px solid ${me.cardBorder}`,borderRadius:6},children:[t.jsxs("span",{style:{color:me.accent,fontSize:12,fontWeight:700,minWidth:28},children:["v",X.version_number]}),t.jsx("span",{style:{color:me.head,fontSize:12},children:X.action_type}),t.jsx("span",{style:{color:me.muted,fontSize:11,marginLeft:"auto"},children:yW(X.created_at)})]},X.id))})]})]})]})}function RW(e){return e.entity_type&&e.entity_id?{type:e.entity_type,id:e.entity_id}:e.lead_id?{type:"lead",id:e.lead_id}:e.customer_id?{type:"customer",id:e.customer_id}:e.job_id?{type:"job",id:e.job_id}:{}}async function y0(e,n={}){const r=Yt();if(!r){if(n.strict)throw new Error("No tenant in context");return}const{type:s,id:i}=RW(e),o=e.description??e.title??null;if(!s||!i){if(n.strict)throw new Error("Missing entity for activity row");console.error("[activity] insert skipped â missing entity",{event_type:e.event_type});return}const a={tenant_id:r,entity_type:s,entity_id:i,event_type:e.event_type,description:o,metadata:e.metadata??{},actor_id:e.actor_id??null,actor_name:e.actor_name??null};if(!e.branch_id&&s==="customer"){const{data:d}=await w.from("customers").select("branch_id").eq("id",i).eq("tenant_id",r).single();d!=null&&d.branch_id&&(a.branch_id=d.branch_id)}e.branch_id&&(a.branch_id=e.branch_id),s==="lead"&&(a.lead_id=i),e.created_at&&(a.created_at=e.created_at),e.ticket_id&&(a.ticket_id=e.ticket_id);const{error:l}=await w.from("activity_log").insert(a);if(l){if(n.strict)throw new Error(l.message);console.error("[activity] insert failed",{event_type:e.event_type,entity_type:s,error:l.message})}}async function EW(e){await y0(e,{strict:!0})}async function PW(e,n){try{const r=Yt();if(!r)return[];const{data:s}=await w.from("activity_log").select("id, tenant_id, entity_type, entity_id, event_type, description, metadata, actor_name, created_at").eq("entity_type",e).eq("entity_id",n).eq("tenant_id",r).order("created_at",{ascending:!1}).limit(50);return s||[]}catch{return[]}}async function qW(e){return PW("lead",e)}async function ii(e,n,r,s,i){try{await y0({entity_type:"lead",entity_id:e,event_type:n,description:r,metadata:i,actor_id:s.actor_id,actor_name:s.actor_name??null})}catch{}}async function Tt(e){try{await y0(e)}catch{}}async function b0(e=!1){let n=w.from("service_plans").select("*").order("sort_order",{ascending:!0});e&&(n=n.eq("is_active",!0));const{data:r,error:s}=await n;if(s)throw new Error(s.message);return r||[]}async function qk(e){const{data:n,error:r}=await w.from("service_plans").select("*").eq("id",e).single();if(r)throw new Error(r.message);return n}async function DW(e){const n=e.slug||e.name.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,""),{data:r,error:s}=await w.from("service_plans").insert({name:e.name,slug:n,description:e.description||null,internal_notes:e.internal_notes||null,billing_interval:e.billing_interval,price_monthly:e.price_monthly,price_annual:e.billing_interval==="yearly"?e.price_monthly:e.billing_interval==="monthly"?e.price_monthly*12:e.billing_interval==="quarterly"?e.price_monthly*4:e.price_monthly,fulfillment_type:e.fulfillment_type,fulfillment_interval_months:e.fulfillment_interval_months??null,applies_to_categories:e.applies_to_categories||[],requires_installed_system:e.requires_installed_system??!0,auto_activate_on_install:e.auto_activate_on_install??!1,is_active:!0,sort_order:e.sort_order??0}).select().single();if(s)throw new Error(s.message);return r}async function OW(e,n){const r={};if(n.name!==void 0&&(r.name=n.name),n.slug!==void 0&&(r.slug=n.slug),n.description!==void 0&&(r.description=n.description),n.internal_notes!==void 0&&(r.internal_notes=n.internal_notes),n.billing_interval!==void 0&&(r.billing_interval=n.billing_interval),n.price_monthly!==void 0&&(r.price_monthly=n.price_monthly),n.fulfillment_type!==void 0&&(r.fulfillment_type=n.fulfillment_type),n.fulfillment_interval_months!==void 0&&(r.fulfillment_interval_months=n.fulfillment_interval_months),n.applies_to_categories!==void 0&&(r.a
627pplies_to_categories=n.applies_to_categories),n.requires_installed_system!==void 0&&(r.requires_installed_system=n.requires_installed_system),n.auto_activate_on_install!==void 0&&(r.auto_activate_on_install=n.auto_activate_on_install),n.sort_order!==void 0&&(r.sort_order=n.sort_order),n.price_monthly!==void 0||n.billing_interval!==void 0){const o=n.price_monthly??0,a=n.billing_interval??"yearly";r.price_annual=a==="yearly"?o:a==="monthly"?o*12:a==="quarterly"?o*4:o}const{data:s,error:i}=await w.from("service_plans").update(r).eq("id",e).select().single();if(i)throw new Error(i.message);return s}async function IW(e,n){const{error:r}=await w.from("service_plans").update({is_active:n}).eq("id",e);if(r)throw new Error(r.message)}async function LW(e,n){const{error:r}=await w.from("service_plans").update({auto_activate_on_install:n}).eq("id",e);if(r)throw new Error(r.message)}async function WW(e){const{data:n,error:r}=await w.from("customer_service_plans").select(` 628 *, 629 service_plans!plan_id ( name, fulfillment_type ) 630 `).eq("customer_id",e).order("created_at",{ascending:!1});if(r)throw new Error(r.message);return(n||[]).map(s=>{var i,o;return{...s,plan_name:((i=s.service_plans)==null?void 0:i.name)||"Unknown Plan",plan_fulfillment_type:((o=s.service_plans)==null?void 0:o.fulfillment_type)||"none",service_plans:void 0}})}async function Dk(e){const{data:n}=await w.from("payment_methods").select("id").eq("customer_id",e).eq("is_default",!0).limit(1).maybeSingle();return!!n}async function $W(e,n,r){let s=w.from("customer_service_plans").select("id").eq("customer_id",e).eq("plan_id",n).in("status",["active","pending_payment_method","pending_install","paused","payment_failed"]);r?s=s.eq("installed_system_id",r):s=s.is("installed_system_id",null);const{data:i}=await s.maybeSingle();return!!i}async function MW(e){const n=await qk(e.plan_id);if(!n)throw new Error("Plan template not found");if(!n.is_active)throw new Error("Plan template is not active");if(await $W(e.customer_id,e.plan_id,e.installed_system_id||null))throw new Error("Customer already has an active plan of this type for this system");const s=await Dk(e.customer_id),o=n.billing_interval!=="one_time"&&!s?"pending_payment_method":"active",a=new Date,l=a.toISOString().split("T")[0],d=e.price_override??n.price_monthly;let c=null;o==="active"&&(e.billing_start==="next_cycle"?c=Ok(l,n.billing_interval):c=l);let f=null;if((n.fulfillment_type==="tech_visit"||n.fulfillment_type==="shipment")&&n.fulfillment_interval_months){const y=new Date(a);y.setMonth(y.getMonth()+n.fulfillment_interval_months),f=y.toISOString().split("T")[0]}const{data:p}=await w.from("customers").select("tenant_id, branch_id").eq("id",e.customer_id).single();if(!(p!=null&&p.tenant_id))throw new Error("Customer has no tenant_id");const{data:u,error:h}=await w.from("customer_service_plans").insert({customer_id:e.customer_id,plan_id:e.plan_id,installed_system_id:e.installed_system_id||null,tenant_id:p.tenant_id,branch_id:p.branch_id??null,source:"manual",source_quote_id:null,status:o,billing_interval:n.billing_interval,price_monthly:d,effective_start_date:l,start_date:l,billing_start_date:o==="active"?l:null,next_billing_date:c,next_service:f,next_fulfillment_date:f,activated_at:o==="active"?a.toISOString():null}).select().single();if(h)throw h.code==="23505"?new Error("Customer already has an active plan of this type for this system"):new Error(h.message);try{const y=new Date().toISOString().split("T")[0];await JW(u.id,e.plan_id,y)}catch(y){console.error("[BEST-EFFORT] snapshotPlanComponents:",y)}try{await Tt({customer_id:e.customer_id,event_type:"service_plan_added",title:`Service plan added: ${n.name}`,actor_id:null,actor_name:null,metadata:{plan_id:e.plan_id,plan_name:n.name,source:"manual",price:d,billing_interval:n.billing_interval,status:o}}),o==="active"&&await Tt({customer_id:e.customer_id,event_type:"service_plan_activated",title:`Service plan activated: ${n.name}`,actor_id:null,actor_name:null,metadata:{plan_id:e.plan_id,plan_name:n.name}})}catch(y){console.error("[BEST-EFFORT] activity log:",y)}return u}async function FW(e,n){const{data:r,error:s}=await w.from("customer_service_plans").update({status:"paused",paused_at:new Date().toISOString(),pause_reason:n||null}).eq("id",e).in("status",["active","payment_failed"]).select().single();if(s)throw new Error(s.message);try{await Tt({customer_id:r.customer_id,event_type:"service_plan_paused",title:"Service plan paused",actor_id:null,metadata:{plan_id:e,reason:n}})}catch(i){console.error("[BEST-EFFORT] activity:",i)}return r}async function BW(e){const n=new Date().toISOString().split("T")[0],{data:r}=await w.from("customer_service_plans").select("billing_interval, customer_id").eq("id",e).single();if(!r)throw new Error("Plan not found");
630const s=Ok(n,r.billing_interval),{data:i,error:o}=await w.from("customer_service_plans").update({status:"active",paused_at:null,pause_reason:null,next_billing_date:s,failed_billing_count:0}).eq("id",e).eq("status","paused").select().single();if(o)throw new Error(o.message);try{await Tt({customer_id:r.customer_id,event_type:"service_plan_activated",title:"Service plan resumed",actor_id:null,metadata:{plan_id:e}})}catch(a){console.error("[BEST-EFFORT] activity:",a)}return i}async function UW(e,n){const{data:r,error:s}=await w.from("customer_service_plans").update({status:"cancelled",cancelled_at:new Date().toISOString(),cancel_reason:n||null}).eq("id",e).in("status",["active","paused","pending_payment_method","pending_install","payment_failed"]).select().single();if(s)throw new Error(s.message);try{await Tt({customer_id:r.customer_id,event_type:"service_plan_cancelled",title:"Service plan cancelled",actor_id:null,metadata:{plan_id:e,reason:n}})}catch(i){console.error("[BEST-EFFORT] activity:",i)}return r}function Ok(e,n
630){const r=new Date(e+"T00:00:00");switch(n){case"monthly":r.setMonth(r.getMonth()+1);break;case"quarterly":r.setMonth(r.getMonth()+3);break;case"yearly":r.setFullYear(r.getFullYear()+1);break;case"biannual":r.setMonth(r.getMonth()+6);break;case"one_time":return e;default:r.setMonth(r.getMonth()+1)}return r.toISOString().split("T")[0]}const ya={monthly:"/month",quarterly:"/quarter",yearly:"/year",one_time:" (one-time)",biannual:"/6 months"},td={tech_visit:"Technician Visit",shipment:"Filter Shipment",on_demand:"On-Demand Service",none:"Billing Only"},fp={active:{label:"Active",color:"#4ade80",bgColor:"rgba(74,222,128,0.12)"},pending_payment_method:{label:"Card Required",color:"#fbbf24",bgColor:"rgba(251,191,36,0.12)"},pending_install:{label:"Pending Install",color:"#60a5fa",bgColor:"rgba(96,165,250,0.12)"},paused:{label:"Paused",color:"#fbbf24",bgColor:"rgba(251,191,36,0.12)"},payment_failed:{label:"Payment Failed",color:"#f87171",bgColor:"rgba(248,113,113,0.12)"},completed:{label:"Completed",color:"#94a3b8",bgColor:"rgba(148,163,184,0.12)"},cancelled:{label:"Cancelled",color:"#94a3b8",bgColor:"rgba(148,163,184,0.12)"},expired:{label:"Expired",color:"#94a3b8",bgColor:"rgba(148,163,184,0.12)"}},HW=[{value:"annual_maintenance_visit",label:"Annual Maintenance Visit"},{value:"ro_prefilter_replacement",label:"RO Prefilter Replacement"},{value:"ro_membrane_replacement",label:"RO Membrane Replacement"},{value:"quarterly_water_test",label:"Quarterly Water Test"},{value:"quarterly_salt_delivery",label:"Quarterly Salt Delivery"},{value:"emergency_support",label:"Emergency Support"},{value:"water_test_and_service",label:"Water Test & Service Visit"},{value:"on_demand_service",label:"On-Demand Service"},{value:"big_blue_filter",label:"Big Blue Filter"},{value:"ro_prefilter_2",label:"RO Pre-filter 2"},{value:"ro_membrane",label:"RO Membrane"},{value:"annual_tech_visit",label:"Annual Tech Visit"},{value:"custom",label:"Custom"}],VW={tech_visit:"Technician Visit",shipment:"Shipment",delivery:"Delivery",on_demand:"On-Demand"};async function A0(e){const{data:n,error:r}=await w.from("service_plan_components").select("*").eq("plan_id",e).eq("is_active",!0).order("sort_order",{ascending:!0});if(r)throw new Error(r.message);return n||[]}async function Ik(e,n){if(await w.from("service_plan_components").delete().eq("plan_id",e),n.length===0)return[];const{data:r,error:s}=await w.from("service_plan_components").insert(n.map((i,o)=>({plan_id:e,component_name:i.label,label:i.label,component_code:i.component_code,fulfillment_type:i.fulfillment_type,interval_months:i.interval_months,reminder_days_before:i.reminder_days_before??null,sort_order:o,is_active:!0}))).select();if(s)throw new Error(s.message);return r||[]}async function ZW(e){const n=await qk(e),r=await A0(e),s=n.name.toLowerCase().replace(/[^a-z0-9]+/g,"-")+"-copy-"+Date.now(),{data:i,error:o}=await w.from("service_plans").insert({...n,id:void 0,name:n.name+" (Copy)",slug:s,created_at:void 0,updated_at:void 0}).select().single();if(o)throw new Error(o.message);return r.length>0&&await Ik(i.id,r.map(a=>({label:a.label,component_code:a.component_code,fulfillment_type:a.fulfillment_type,interval_months:a.interval_months,reminder_days_before:a.reminder_days_before??null}))),i}async function KW(e){const{data:n,error:r}=await w.from("customer_service_plan_components").select("*").eq("customer_plan_id",e).order("sort_order",{ascending:!0});if(r)throw new Error(r.message);return n||[]}async function YW(e,n){const{data:r,error:s}=await w.from("customer_service_plan_components").update({reminder_days_before:n}).eq("id",e).select().single();if(s)throw new Error(s.message);return r}async function XW(e){const{data:n,error:r}=await w.from("service_plan_component_products").select("*, product_catalog(name)").eq("component_id",e).order("sort_order",{ascending:!0});if(r)throw new Error(r.message);return(n||[]).map(s=>{var i;return{...s,product_name:((i=s.product_catalog)==null?void 0:i.name)||"Unknown",product_catalog:void 0}})}async function GW(e,n){if(await w.from("service_plan_component_products").delete().eq("component_id",e),n.length===0)return[];const{data:r,error:s}=await w.from("service_plan_component_products").insert(n.map((i,o)=>({component_id:e,product_catalog_id:i.product_catalog_id,quantity:i.quantity,sort_order:o}))).select();if(s)throw new Error(s.message);return r||[]}async function JW(e,n,r){const s=await A0(n);if(s.length===0)return[];const i=s.map(l=>{let d=null;if(l.interval_months&&l.fulfillment_type!=="on_demand"){const c=new Date(r+"T12:00:00");c.setMonth(c.getMonth()+l.interval_months),d=c.toISOString().split("T")[0]}return{customer_plan_id:e,plan_component_id:l.id,label:l.label,component_code:l.component_code,fulfillment_type:l.fulfillment_type,interval_months:l.interval_months,reminder_days_before:l.reminder_days_before??null,next_due_date:d,last_completed_at:null,status:"active"}}
630),{data:o,error:a}=await w.from("customer_service_plan_components").insert(i).select();if(a)throw new Error(a.message);return o||[]}async function QW(){const{data:e,error:n}=await w.from("message_templates").select("*").order("group_name",{ascending:!0}).order("channel",{ascending:!0}).order("label",{ascending:!0});return n?(console.error("[messageTemplates] list error:",n),[]):e||[]}async function e$(e){const n=e.tenant_id;try{if(e.source_table==="automation_settings"){e.channel==="sms"?await w.from("automation_settings").update({sms_template:e.body,enabled:e.is_active}).eq("tenant_id",n).eq("key",e.key):await w.from("automation_settings").update({email_template:e.body,email_subject:e.subject,enabled:e.is_active}).eq("tenant_id",n).eq("key",e.key);return}e.source_table&&e.source_table!=="hardcoded"&&console.warn("[messageTemplates] unknown source_table, skipped automation sync:",e.source_table)}catch(r){throw console.error("[messageTemplates] automation_settings sync error:",r),r}}async function Lk(e,n){const r={...e,...n},{error:s}=await w.from("message_templates").update({subject:r.subject,body:r.body,is_active:r.is_active}).eq("id",e.id);if(s)throw console.error("[messageTemplates] unified update error:",s),s;await e$(r)}async function t$(e){await Lk(e,{is_active:!e.is_active})}const $a="#0d7ea3",n$={first_name:"Alex",rep_name:"Sam",company_name:"Your Company",company_phone:"(555) 555-5555",visit_date:"Tue, Jul 22",install_date:"Fri, Jul 25",review_url:"g.page/your-company/review",date:"Tue, Jul 22",time:"10:00 AM",component:"RO membrane",name:"Alex",headline:"Your best price, until Saturday",message:"We put this together after our last conversation.",deadline:"Saturday, September 26",offer_url:"https://get.yourcompany.com/o/abc123",contents:"Water softener and RO system",last_name:"Reyes"};function um(e){return(e||"").replace(/{{(\w+)}}/g,(n,r)=>n$[r]??`{{${r}}}`)}function r$(){const[e,n]=g.useState([]),[r,s]=g.useState(!0),[i,o]=g.useState("all"),[a,l]=g.useState(null),[d,c]=g.useState(""),[f,p]=g.useState(""),[u,h]=g.useState(!1);g.useEffect(()=>{y()},[]);async function y(){s(!0),n(await QW()),s(!1)}function m(C){l(C),c(C.subject||""),p(C.body||"")}function b(){l(null)}async function A(){if(a){h(!0);try{await Lk(a,{subject:a.channel==="email"?d:null,body:f}),await y(),b()}catch(C){console.error(C)}finally{h(!1)}}}async function v(C){await t$(C),await y()}const x=g.useMemo(()=>e.filter(C=>i==="all"||C.channel===i),[e,i]),_=g.useMemo(()=>{const C=new Map;for(const S of x){const T=S.group_name||"Other";C.has(T)||C.set(T,[]),C.get(T).push(S)}return Array.from(C.entries())},[x]),j=g.useMemo(()=>({all:e.length,sms:e.filter(C=>C.channel==="sms").length,email:e.filter(C=>C.channel==="email").length}),[e]);return t.jsxs("div",{style:{height:"100%",overflow:"auto"},children:[t.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:8},children:t.jsxs("div",{children:[t.jsx("h2",{style:{fontSize:17,fontWeight:700,color:"#e2e8f0",margin:0},children:"Messages"}),t.jsx("p",{style:{fontSize:12,color:"#475569",marginTop:4,marginBottom:0},children:"Every SMS and email in one place. Edits apply everywhere the message is sent."})]})}),t.jsx("div",{style:{display:"flex",gap:6,margin:"16px 0 20px"},children:[["all","All"],["sms","SMS"],["email","Email"]].map(([C,S])=>{const T=i===C;return t.jsxs("button",{onClick:()=>o(C),style:{fontSize:12,fontWeight:600,padding:"6px 14px",borderRadius:8,cursor:"pointer",background:T?`${$a}22`:"transparent",border:`1px solid ${T?$a+"55":"#1e3a4f"}`,color:T?"#38bdf8":"#64748b"},children:[S," ",t.jsxs("span",{style:{opacity:.6},children:["· ",j[C]]})]},C)})}),r?t.jsx("div",{style:{textAlign:"center",padding:40,color:"#475569"},children:"Loading messagesâ¦"}):_.length===0?t.jsx("div",{style:{textAlign:"center",padding:40,color:"#334155",fontSize:14},children:"No messages in this view."}):_.map(([C,S])=>t.jsxs("div",{style:{marginBottom:24},children:[t.jsx("div",{style:{fontSize:11,fontWeight:700,color:$a,textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:10},children:C}),t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:10},children:S.map(T=>t.jsx("div",{style:{background:"#162232",border:`1px solid ${T.is_active?"#1e3a4f":"#0d1a26"}`,borderRadius:12,padding:16,opacity:T.is_active?1:.55},children:t.jsxs("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:12},children:[t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:6,flexWrap:"wrap"},children:[t.jsx("span",{style:{fontWeight:700,color:"#e2e8f0",fontSize:14},children:T.label||T.key}),t.jsx("span",{style:{fontSize:10,fontWeight:700,padding:"2px 8px",borderRadius:20,textTransform:"uppercase",letterSpacing:"0.06em",background:T.channel==="email"?"rgba(244,114,182,0.15)":"rgba(34,197,94,0.15)",color:T.channel==="email"?"#f472b6":"#22c55e",border:`1px solid ${T.channel==="email"?"rgba(244,114,182,0.25)":"rgba(34,197,94,0.25)"}`},children:T.channel}),T.is_automation&&t.jsxs("span",{style:{fontSize:10,fontWeight:700,padding:"2px 8px",borderRadius:20,background:"rgba(249,115,22,0.15)",color:"#f97316"},children:["auto",T.timing_label?` · ${T.timing_label}`:""]}),!T.is_active&&t.jsx("span",{style:{fontSize:10,fontWeight:700,padding:"2px 8px",borderRadius:20,background:"rgba(100,116,139,0.15)",color:"#64748b"},children:"Off"})]}),T.channel==="email"&&T.subject&&t.jsxs("div",{style:{fontSize:12,color:"#94a3b8",marginBottom:4},children:[t.jsx("span",{style:{color:"#475569"},children:"Subject: "}),um(T.subject)]}),t.jsx("div",{style:{fontSize:13,color:"#64748b",lineHeight:1.5,whiteSpace:"pre-wrap"},children:T.body?um(T.body).slice(0,240):t.jsx("span",{style:{color:"#334155",fontStyle:"italic"},children:"No custom body â system default is used."})})]}),t.jsxs("div",{style:{display:"flex",gap:6,flexShrink:0},children:[t.jsx("button",{onClick:()=>v(T),style:{padding:"5px 12px",borderRadius:7,border:"1px solid #1e3a4f",background:"transparent",color:"#64748b",fontSize:11,cursor:"pointer",fontWeight:600},children:T.is_active?"Turn off":"Turn on"}),t.jsx("button",{onClick:()=>m(T),style:{padding:"5px 12px",borderRadius:7,border:`1px solid ${$a}55`,background:`${$a}14`,color:"#38bdf8",fontSize:11,cursor:"pointer",fontWeight:600},children:"Edit"})]})]})},T.id))})]},C)),a&&t.jsx("div",{onClick:b,style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.6)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:50,padding:20},children:t.jsxs("div",{onClick:C=>C.stopPropagation(),style:{background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:16,padding:24,width:"100%",maxWidth:640,maxHeight:"90vh",overflow:"auto"},children:[t.jsxs("div",{style:{fontSize:15,fontWeight:700,color:"#e2e8f0",marginBottom:4},children:["Edit: ",a.label||a.key]}),t.jsxs("div",{style:{fontSize:12,color:"#475569",marginBottom:18},children:[a.channel==="email"?"Email":"SMS"," · changes save everywhere this message is sent."]}),a.channel==="email"&&t.jsxs("div",{style:{marginBottom:14},children:[t.jsx("label",{style:{display:"block",fontSize:11,color:"#64748b",fontWeight:700,textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:6},children:"Subject"}),t.jsx("input",{value:d,onChange:C=>c(C.target.value),style:{width:"100%",background:"#162232",border:"1px solid #1e3a4f",borderRadius:8,color:"#e2e8f0",padding:"10px 12px",fontSize:13,outline:"none",boxSizing:"border-box"}})]}),t.jsxs("div",{style:{marginBottom:6},children:[t.jsx("label",{style:{display:"block",fontSize:11,color:"#64748b",fontWeight:700,textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:6},children:a.channel==="email"?"Body":"Message"}),t.jsx("textarea",{value:f,onChange:C=>p(C.target.value),rows:a.channel==="email"?10:5,placeholder:"Use variables like {{first_name}}, {{company_name}}â¦",style:{width:"100%",background:"#162232",border:"1px solid #1e3a4f",borderRadius:8,color:"#e2e8f0",padding:"10px 12px",fontSize:13,outline:"none",boxSizing:"border-box",resize:"vertical",fontFamily:"inherit",lineHeight:1.5}})]}),t.jsxs("div",{style:{marginBottom:18},children:[t.jsx("div",{style:{fontSize:11,color:"#475569",marginBottom:6},children:"Preview (sample data)"}),t.jsx("div",{style:{background:"#0a1119",border:"1px dashed #1e3a4f",borderRadius:8,padding:"10px 12px",fontSize:13,color:"#94a3b8",lineHeight:1.5,whiteSpace:"pre-wrap"},children:um(f)||t.jsx("span",{style:{color:"#334155"},children:"Nothing to preview yet."})})]}),t.jsxs("div",{style:{display:"flex",gap:10,justifyContent:"flex-end"},children:[t.jsx("button",{onClick:b,style:{padding:"8px 18px",borderRadius:8,border:"1px solid #1e3a4f",background:"transparent",color:"#64748b",fontSize:13,cursor:"pointer"},children:"Cancel"}),t.jsx("button",{onClick:A,disabled:u,style:{padding:"8px 22px",borderRadius:8,border:"none",background:$a,color:"#fff",fontWeight:700,fontSize:13,cursor:"pointer",opacity:u?.6:1},children:u?"Savingâ¦":"Save changes"})]})]})})]})}const b_={terms_page:"ð General Terms & Conditions",rental_agreement:"ð Rental Agreement",rental_quote:"ð¬ Rental Quote",purchase_invoice:"ð§¾ Purchase Invoice / Quote",all:"ð All Documents"},s$=["terms_page","rental_agreement","rental_quote","purchase_invoice","all"],A_={dropdown:"Dropdown",yes_no:"Yes / No",number:"Number",text:"Text Input",prefill_water_concern:"Auto-fill: Water Concern",prefill_address:"Auto-fill: Address",prefill_source:"Auto-fill: Lead Source"},v_=[{key:"qualifying",label:"Qualifying Checklist",icon:"â
",color:"#4ade80"},{key:"site_visit",label:"Site Visit Checklist",icon:"ð",color:"#22d3ee"},{key:"terms",label:"Term Blocks",icon:"ð",color:"#a78bfa"},{key:"service_plans",label:"Service Plans",icon:"ð",color:"#f59e0b"},{key:"messages",label:"Messages",icon:"ð¬",color:"#38bdf8"},{key:"checklists",label:"Checklists",icon:"ð",color:"#8b5cf6"},{key:"automations",label:"Automations",icon:"â¡",color:"#f97316"},{key:"branches",label:"Branches",icon:"ð¢",color:"#0d7ea3"},{key:"buyout_config",label:"Buyout Config",icon:"ð·ï¸",color:"#f43f5e"},{key:"forms",label:"Forms",icon:"ð",color:"#0d7ea3"},{key:"lead_sources",label:"Lead Sources",icon:"ð",color:"#a78bfa"},{key:"landing",label:"Landing Pages",icon:"ð¥ï¸",color:"#38bdf8"}];function i$(){const{profile:e}=Ee(),[n,r]=g.useState("qualifying");return(e==null?void 0:e.role)==="admin"||(e==null?void 0:e.role)==="super_admin"?t.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%"},children:[t.jsxs("div",{style:{flexShrink:0,marginBottom:20},children:[t.jsx("h1",{style:{color:"#e2e8f0",fontWeight:700,fontSize:22,margin:0},children:"Admin Settings"}),t.jsx("p",{style:{color:"#64748b",fontSize:13,marginTop:4},children:"Manage qualifying questions, site visit checklist, term blocks, and service plans"})]}),t.jsx("div",{style:{display:"grid",gridTemplateColumns:`repeat(${v_.length}, 1fr)`,gap:3,flexShrink:0,marginBottom:20},children:v_.map(i=>{const o=n===i.key;return t.jsxs("button",{onClick:()=>r(i.key),style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 20px",borderRadius:14,textAlign:"left",background:o?`linear-gradient(135deg, ${i.color}22, ${i.color}0a)`:"rgba(255,255,255,0.03)",border:`1px solid ${o?i.color+"50":"rgba(255,255,255,0.06)"}`,boxShadow:o?`0 0 18px ${i.color}18`:"none",cursor:"pointer",transition:"all 0.15s"},children:[t.jsx("div",{children:t.jsxs("div",{style:{fontSize:11,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.06em",color:o?i.color:"#64748b",marginBottom:4},children:[t.jsx("span",{style:{marginRight:6},children:i.icon}),i.label]})}),o&&t.jsx("div",{style:{width:8,height:8,borderRadius:"50%",flexShrink:0,backgroundColor:i.color,boxShadow:`0 0 8px ${i.color}`}})]},i.key)})}),t.jsxs("div",{style:{flex:1,overflow:"hidden"},children:[n==="qualifying"&&t.jsx(o$,{}),n==="site_visit"&&t.jsx(a$,{}),n==="terms"&&t.jsx(l$,{}),n==="service_plans"&&t.jsx(p$,{}),n==="messages"&&t.jsx(r$,{}),n==="checklists"&&t.jsx(P9,{}),n==="automations"&&t.jsx(h$,{}),n==="branches"&&t.jsx(f$,{}),n==="buyout_config"&&t.jsx(g$,{}),n==="forms"&&t.jsx(H9,{}),n==="lead_sources"&&t.jsx(nq,{}),n==="landing"&&t.jsx(NW,{})]})]}):t.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100%"},children:[t.jsx("div",{style:{fontSize:48,marginBottom:16},children:"ð"}),t.jsx("h2",{style:{color:"#e2e8f0",fontWeight:700,fontSize:20},children:"Admin Access Only"}),t.jsx("p",{style:{color:"#64748b",marginTop:8},children:"You don't have permission to view this page."})]})}const vs={background:"#162232",border:"1px solid #1e3a4f",borderRadius:14,overflow:"hidden"},dt={textAlign:"left",padding:"10px 16px",fontSize:10,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.06em",color:"#64748b",background:"rgba(255,255,255,0.03)",borderBottom:"1px solid #1e3a4f"},ct={padding:"11px 16px",borderBottom:"1px solid rgba(255,255,255,0.04)",fontSize:13,color:"#e2e8f0"};function Wk({required:e,onClick:n}){return t.jsx("button",{onClick:n,style:{fontSize:11,padding:"3px 10px",borderRadius:20,fontWeight:700,cursor:"pointer",background:e?"rgba(248,113,113,0.12)":"rgba(100,116,139,0.12)",color:e?"#f87171":"#64748b",border:`1px solid ${e?"rgba(248,113,113,0.3)":"rgba(100,116,139,0.2)"}`},children:e?"Required":"Optional"})}function Yf({active:e,onClick:n}){return t.jsx("button",{onClick:n,style:{fontSize:11,padding:"3px 10px",borderRadius:20,fontWeight:700,cursor:"pointer",background:e?"rgba(74,222,128,0.12)":"rgba(100,116,139,0.12)",color:e?"#4ade80":"#64748b",border:`1px solid ${e?"rgba(74,222,128,0.25)":"rgba(100,116,139,0.2)"}`},children:e?"Active":"Off"})}function $k({title:e,onCancel:n,onSave:r,saving:s,formText:i,setFormText:o,formType:a,setFormType:l,formOptions:d,setFormOptions:c,formRequired:f,setFormRequired:p,fieldTypeLabels:u,extraFields:h}){return t.jsxs("div",{style:{...vs,marginBottom:16,padding:20},children:[t.jsx("h3",{style:{color:"#e2e8f0",fontWeight:700,fontSize:14,marginBottom:16},children:e}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:14},children:[t.jsxs("div",{children:[t.jsx("label",{style:{display:"block",fontSize:11,color:"#64748b",marginBottom:6},children:"Question / Item Text"}),t.jsx("input",{type:"text",value:i,onChange:y=>o(y.target.value),placeholder:"e.g., Homeowner or renter?",style:{width:"100%",boxSizing:"border-box",background:"rgba(255,255,255,0.05)",border:"1px solid #1e3a4f",borderRadius:10,padding:"9px 14px",color:"#e2e8f0",fontSize:13,outline:"none"}})]}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12},children:[t.jsxs("div",{children:[t.jsx("label",{style:{display:"block",fontSize:11,color:"#64748b",marginBottom:6},children:"Answer Type"}),t.jsx("select",{value:a,onChange:y=>l(y.target.value),style:{width:"100%",background:"rgba(255,255,255,0.05)",border:"1px solid #1e3a4f",borderRadius:10,padding:"9px 14px",color:"#e2e8f0",fontSize:13,outline:"none"},children:Object.entries(u).map(([y,m])=>t.jsx("option",{value:y,style:{background:"#0f1923"},children:m}
630,y))})]}),t.jsx("div",{style:{display:"flex",alignItems:"flex-end",paddingBottom:4},children:t.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer"},children:[t.jsx("input",{type:"checkbox",checked:f,onChange:y=>p(y.target.checked),style:{width:15,height:15,accentColor:"#0d7ea3"}}),t.jsx("span",{style:{fontSize:13,color:"#e2e8f0"},children:"Required"})]})})]}),a==="dropdown"&&t.jsxs("div",{children:[t.jsxs("label",{style:{display:"block",fontSize:11,color:"#64748b",marginBottom:6},children:["Options ",t.jsx("span",{style:{color:"#334155"},children:"(comma separated)"})]}),t.jsx("input",{type:"text",value:d,onChange:y=>c(y.target.value),placeholder:"e.g., Homeowner, Renter",style:{width:"100%",boxSizing:"border-box",background:"rgba(255,255,255,0.05)",border:"1px solid #1e3a4f",borderRadius:10,padding:"9px 14px",color:"#e2e8f0",fontSize:13,outline:"none"}})]}),h,t.jsxs("div",{style:{display:"flex",gap:8,paddingTop:4},children:[t.jsx("button",{onClick:n,style:{padding:"8px 16px",borderRadius:10,fontSize:13,color:"#64748b",cursor:"pointer",background:"rgba(255,255,255,0.04)",border:"1px solid #1e3a4f"},children:"Cancel"}),t.jsx("button",{onClick:r,disabled:s||!i.trim(),style:{padding:"8px 20px",borderRadius:10,fontSize:13,fontWeight:700,color:"#fff",background:"linear-gradient(135deg, #3b82f6, #2563eb)",border:"none",cursor:s||!i.trim()?"not-allowed":"pointer",opacity:s||!i.trim()?.5:1},children:s?"Saving...":e.startsWith("Edit")?"Update":"Add"})]})]})]})}function o$(){const[e,n]=g.useState([]),[r,s]=g.useState(!0),[i,o]=g.useState(null),[a,l]=g.useState(!1),[d,c]=g.useState(""),[f,p]=g.useState("dropdown"),[u,h]=g.useState(""),[y,m]=g.useState(!0),[b,A]=g.useState(!1);g.useEffect(()=>{v()},[]);async function v(){s(!0);const{data:N}
630=await w.from("qualifying_questions").select("*").order("sort_order");N&&n(N),s(!1)}function x(){o(null),c(""),p("dropdown"),h(""),m(!0),l(!0)}function _(N){o(N),c(N.question_text),p(N.field_type),h(Array.isArray(N.options)?N.options.join(", "):""),m(N.is_required),l(!0)}async function j(){if(!d.trim())return;A(!0);const N=f==="dropdown"?u.split(",").map(O=>O.trim()).filter(Boolean):[];if(i)await w.from("qualifying_questions").update({question_text:d.trim(),field_type:f,options:N,is_required:y}).eq("id",i.id);else{const O=e.reduce((z,P)=>Math.max(z,P.sort_order),0);await w.from("qualifying_questions").insert({question_text:d.trim(),field_type:f,options:N,is_required:y,sort_order:O+1,is_active:!0})}l(!1),o(null),A(!1),v()}async function C(N){await w.from("qualifying_questions").update({is_required:!N.is_required}).eq("id",N.id),n(O=>O.map(z=>z.id===N.id?{...z,is_required:!z.is_required}:z))}async function S(N){await w.from("qualifying_questions").update({is_active:!N.is_active}).eq("id",N.id),n(O=>O.map(z=>z.id===N.id?{...z,is_active:!z.is_active}:z))}async function T(N,O){const z=e.findIndex(M=>M.id===N.id),P=O==="up"?z-1:z+1;if(P<0||P>=e.length)return;const D=e[P];
630await w.from("qualifying_questions").update({sort_order:D.sort_order}).eq("id",N.id),await w.from("qualifying_questions").update({sort_order:N.sort_order}).eq("id",D.id),v()}async function L(N){confirm(`Delete "${N.question_text}"?`)&&(await w.from("qualifying_questions").delete().eq("id",N.id),v())}const E=e.filter(N=>N.is_active).length,R=e.filter(N=>N.is_active&&N.is_required).length;return t.jsxs("div",{style:{height:"100%",overflowY:"auto"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:16},children:[t.jsxs("div",{children:[t.jsx("h2",{style:{color:"#e2e8f0",fontWeight:700,fontSize:16,margin:0},children:"Qualifying Questions"}),t.jsxs("p",{style:{color:"#64748b",fontSize:12,marginTop:4},children:[E," active · ",R," required â shown when qualifying a lead"]})]}),t.jsx("button",{onClick:x,style:{padding:"8px 18px",borderRadius:10,fontSize:13,fontWeight:700,background:"linear-gradient(135deg, #3b82f6, #2563eb)",color:"#fff",border:"none",cursor:"pointer"},children:"+ Add Question"})]}),a&&t.jsx($k,{title:i?"Edit Question":"New Question",onCancel:()=>{l(!1),o(null)},onSave:j,saving:b,formText:d,setFormText:c,formType:f,setFormType:p,formOptions:u,setFormOptions:h,formRequired:y,setFormRequired:m,fieldTypeLabels:A_}),r?t.jsx("div",{style:{textAlign:"center",color:"#64748b",padding:"48px 0"},children:"Loading..."}):e.length===0?t.jsxs("div",{style:{textAlign:"center",padding:"48px 0"},children:[t.jsx("div",{style:{fontSize:40,marginBottom:12},children:"ð"}),t.jsx("p",{style:{color:"#64748b"},children:"No qualifying questions yet."})]}):t.jsx("div",{style:{...vs,overflowX:"auto"},children:t.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",minWidth:640},children:[t.jsx("thead",{children:t.jsxs("tr",{children:[t.jsx("th",{style:{...dt,width:36},children:"#"}),t.jsx("th",{style:dt,children:"Question"}),t.jsx("th",{style:{...dt,width:120},children:"Type"}),t.jsx("th",{style:{...dt,width:100,textAlign:"center"},children:"Required"}),t.jsx("th",{style:{...dt,width:80,textAlign:"center"},children:"Active"}),t.jsx("th",{style:{...dt,width:80,textAlign:"center"},children:"Order"}),t.jsx("th",{style:{...dt,width:110,textAlign:"right"},children:"Actions"})]})}),t.jsx("tbody",{children:e.map((N,O)=>{var z;return t.jsxs("tr",{style:{opacity:N.is_active?1:.4},children:[t.jsx("td",{style:{...ct,color:"#64748b",fontFamily:"monospace"},children:O+1}),t.jsxs("td",{style:ct,children:[t.jsx("div",{style:{fontWeight:600},children:N.question_text}),N.field_type==="dropdown"&&((z=N.options)==null?void 0:z.length)>0&&t.jsxs("div",{style:{fontSize:11,color:"#64748b",marginTop:3},children:["Options: ",N.options.join(" · ")]})]}),t.jsx("td",{style:ct,children:t.jsx("span",{style:{fontSize:11,padding:"3px 8px",borderRadius:20,background:"rgba(255,255,255,0.05)",color:"#94a3b8",border:"1px solid #1e3a4f"},children:A_[N.field_type]||N.field_type})}),t.jsx("td",{style:{...ct,textAlign:"center"},children:t.jsx(Wk,{required:N.is_required,onClick:()=>C(N)})}),t.jsx("td",{style:{...ct,textAlign:"center"},children:t.jsx(Yf,{active:N.is_active,onClick:()=>S(N)})}),t.jsx("td",{style:{...ct,textAlign:"center"},children:t.jsxs("div",{style:{display:"flex",justifyContent:"center",gap:4},children:[t.jsx("button",{onClick:()=>T(N,"up"),disabled:O===0,style:{color:"#64748b",background:"none",border:"none",cursor:"pointer",opacity:O===0?.2:1},children:"â²"}),t.jsx("button",{onClick:()=>T(N,"down"),disabled:O===e.length-1,style:{color:"#64748b",background:"none",border:"none",cursor:"pointer",opacity:O===e.length-1?.2:1},children:"â¼"})]})}),t.jsx("td",{style:{...ct,textAlign:"right"},children:t.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:10},children:[t.jsx("button",{onClick:()=>_(N),style:{fontSize:12,color:"#60a5fa",background:"none",border:"none",cursor:"pointer",fontWeight:600},children:"Edit"}),t.jsx("button",{onClick:()=>L(N),style:{fontSize:12,color:"#f87171",background:"none",border:"none",cursor:"pointer",fontWeight:600},children:"Delete"})]})})]},N.id)})})]})})]})}const __={dropdown:"Dropdown",yes_no:"Yes / No",number:"Number",text:"Text Input",photo:"Photo Upload"};function a$(){const[e,n]=g.useState([]),[r,s]=g.useState(!0),[i,o]=g.useState(null),[a,l]=g.useState(!1),[d,c]=g.useState(""),[f,p]=g.useState("dropdown"),[u,h]=g.useState(""),[y,m]=g.useState(!0),[b,A]=g.useState(!1),[v,x]=g.useState(!1);g.useEffect(()=>{_()},[]);async function _(){s(!0);const{data:z}=await w.from("site_visit_questions").select("*").order("sort_order");z&&n(z),s(!1)}function j(){o(null),c(""),p("dropdown"),h(""),m(!0),A(!1),l(!0)}
630function C(z){o(z),c(z.question_text),p(z.field_type),h(Array.isArray(z.options)?z.options.join(", "):""),m(z.is_required),A(z.requires_photo),l(!0)}async function S(){if(!d.trim())return;x(!0);const z=f==="dropdown"?u.split(",").map(D=>D.trim()).filter(Boolean):[],P=b||f==="photo";if(i)await w.from("site_visit_questions").update({question_text:d.trim(),field_type:f,options:z,is_required:y,requires_photo:P}).eq("id",i.id);else{const D=e.reduce((M,k)=>Math.max(M,k.sort_order),0);await w.from("site_visit_questions").insert({question_text:d.trim(),field_type:f,options:z,is_required:y,requires_photo:P,sort_order:D+1,is_active:!0})}l(!1),o(null),x(!1),_()}async function T(z){await w.from("site_visit_questions").update({is_required:!z.is_required}).eq("id",z.id),n(P=>P.map(D=>D.id===z.id?{...D,is_required:!D.is_required}:D))}async function L(z){await w.from("site_visit_questions").update({is_active:!z.is_active}).eq("id",z.id),n(P=>P.map(D=>D.id===z.id?{...D,is_active:!D.is_active}:D))}async function E(z,P){const D=e.findIndex(q=>q.id===z.id),M=P==="up"?D-1:D+1;if(M<0||M>=e.length)return;const k=e[M];await w.from("site_visit_questions").update({sort_order:k.sort_order}).eq("id",z.id),await w.from("site_visit_questions").update({sort_order:z.sort_order}).eq("id",k.id),_()}async function R(z){confirm(`Delete "${z.question_text}"?`)&&(await w.from("site_visit_questions").delete().eq("id",z.id),_())}const N=e.filter(z=>z.is_active).length,O=e.filter(z=>z.is_active&&z.is_required).length;return t.jsxs("div",{style:{height:"100%",overflowY:"auto"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:16},children:[t.jsxs("div",{children:[t.jsx("h2",{style:{color:"#e2e8f0",fontWeight:700,fontSize:16,margin:0},children:"Site Visit Checklist"}),t.jsxs("p",{style:{color:"#64748b",fontSize:12,marginTop:4},children:[N," active · ",O," required â completed during site visits"]})]}),t.jsx("button",{onClick:j,style:{padding:"8px 18px",borderRadius:10,fontSize:13,fontWeight:700,background:"linear-gradient(135deg, #3b82f6, #2563eb)",color:"#fff",border:"none",cursor:"pointer"},children:"+ Add Item"})]}),a&&t.jsx($k,{title:i?"Edit Item":"New Item",onCancel:()=>{l(!1),o(null)},onSave:S,saving:v,formText:d,setFormText:c,formType:f,setFormType:z=>{p(z),z==="photo"&&A(!0)},formOptions:u,setFormOptions:h,formRequired:y,setFormRequired:m,fieldTypeLabels:__}),r?t.jsx("div",{style:{textAlign:"center",color:"#64748b",padding:"48px 0"},children:"Loading..."}):e.length===0?t.jsxs("div",{style:{textAlign:"center",padding:"48px 0"},children:[t.jsx("div",{style:{fontSize:40,marginBottom:12},children:"ð"}),t.jsx("p",{style:{color:"#64748b"},children:"No site visit items yet."})]}):t.jsx("div",{style:{...vs,overflowX:"auto"},children:t.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",minWidth:640},children:[t.jsx("thead",{children:t.jsxs("tr",{children:[t.jsx("th",{style:{...dt,width:36},children:"#"}),t.jsx("th",{style:dt,children:"Item"}),t.jsx("th",{style:{...dt,width:120},children:"Type"}),t.jsx("th",{style:{...dt,width:100,textAlign:"center"},children:"Required"}),t.jsx("th",{style:{...dt,width:80,textAlign:"center"},children:"Active"}),t.jsx("th",{style:{...dt,width:80,textAlign:"center"},children:"Order"}),t.jsx("th",{style:{...dt,width:110,textAlign:"right"},children:"Actions"})]})}),t.jsx("tbody",{children:e.map((z,P)=>{var D;return t.jsxs("tr",{style:{opacity:z.is_active?1:.4},children:[t.jsx("td",{style:{...ct,color:"#64748b",fontFamily:"monospace"},children:P+1}),t.jsxs("td",{style:ct,children:[t.jsxs("div",{style:{fontWeight:600},children:[z.field_type==="photo"&&"ð· ",z.question_text]}),z.field_type==="dropdown"&&((D=z.options)==null?void 0:D.length)>0&&t.jsxs("div",{style:{fontSize:11,color:"#64748b",marginTop:3},children:["Options: ",z.options.join(" · ")]})]}),t.jsx("td",{style:ct,children:t.jsx("span",{style:{fontSize:11,padding:"3px 8px",borderRadius:20,background:"rgba(255,255,255,0.05)",color:"#94a3b8",border:"1px solid #1e3a4f"},children:__[z.field_type]||z.field_type})}),t.jsx("td",{style:{...ct,textAlign:"center"}
630,children:t.jsx(Wk,{required:z.is_required,onClick:()=>T(z)})}),t.jsx("td",{style:{...ct,textAlign:"center"},children:t.jsx(Yf,{active:z.is_active,onClick:()=>L(z)})}),t.jsx("td",{style:{...ct,textAlign:"center"},children:t.jsxs("div",{style:{display:"flex",justifyContent:"center",gap:4},children:[t.jsx("button",{onClick:()=>E(z,"up"),disabled:P===0,style:{color:"#64748b",background:"none",border:"none",cursor:"pointer",opacity:P===0?.2:1},children:"â²"}),t.jsx("button",{onClick:()=>E(z,"down"),disabled:P===e.length-1,style:{color:"#64748b",background:"none",border:"none",cursor:"pointer",opacity:P===e.length-1?.2:1},children:"â¼"})]})}),t.jsx("td",{style:{...ct,textAlign:"right"},children:t.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:10},children:[t.jsx("button",{onClick:()=>C(z),style:{fontSize:12,color:"#60a5fa",background:"none",border:"none",cursor:"pointer",fontWeight:600},children:"Edit"}),t.jsx("button",{onClick:()=>R(z),style:{fontSize:12,color:"#f87171",background:"none",border:"none",cursor:"pointer",fontWeight:600},children:"Delete"})]})})]},z.id)})})]})})]})}function l$(){var W;const[e,n]=g.useState([]),[r,s]=g.useState([]),[i,o]=g.useState(!0),[a,l]=g.useState("terms_page"),[d,c]=g.useState(null),[f,p]=g.useState(""),[u,h]=g.useState(""),[y,m]=g.useState(!1),[b,A]=g.useState(""),[v,x]=g.useState(""),[_,j]=g.useState(!1),[C,S]=g.useState(""),[T,L]=g.useState(""),[E,R]=g.useState(!1),[N,O]=g.useState(""),[z,P]=g.useState("");g.useEffect(()=>{D(),M()},[]);async function D(){const{data:G}=await w.from("term_categories").select("*").eq("is_active",!0).order("sort_order");G&&G.length&&(s(G),G.find(V=>V.key===a)||l(G[0].key))}async function M(){o(!0);try{const{data:G,error:V}=await w.from("term_blocks").select("id, title, content, applies_to, sort_order, is_active, created_at, updated_at").order("applies_to").order("sort_order");!V&&G&&n(G)}catch(G){console.error("Failed to load term blocks:",G)}o(!1)}async function k(){if(!C.trim()||!T.trim())return;const G=C.trim().toLowerCase().replace(/\s+/g,"_").replace(/[^a-z0-9_]/g,""),V=r.reduce((re,Q)=>Math.max(re,Q.sort_order),0),{error:ee}=await w.from("term_categories").insert({key:G,label:T.trim(),sort_order:V+1,is_active:!0});if(ee){alert("Error: "+ee.message);return}S(""),L(""),j(!1),D()}async function q(){if(!N.trim())return;const G=e.filter(ee=>ee.applies_to===a).reduce((ee,re)=>Math.max(ee,re.sort_order),0),{error:V}=await w.from("term_blocks").insert({title:N.trim(),content:z,applies_to:a,sort_order:G+1,is_active:!0});if(V){alert("Error: "+V.message);return}O(""),P(""),R(!1),M()}function $(G){c(G),p(G.content),h(G.title),A("")}async function I(){if(!d)return;m(!0);const{error:G}=await w.from("term_blocks").update({content:f,title:u,updated_at:new Date().toISOString()}).eq("id",d.id);G?A("â Error: "+G.message):(A("â
Saved"),n(V=>V.map(ee=>ee.id===d.id?{...ee,content:f,title:u}:ee)),c(null)),m(!1),setTimeout(()=>A(""),3e3)}async function B(G){const{error:V}=await w.from("term_blocks").update({is_active:!G.is_active}).eq("id",G.id);V||n(ee=>ee.map(re=>re.id===G.id?{...re,is_active:!re.is_active}:re))}const J=e.filter(G=>{const V=G.applies_to===a,ee=!v||G.title.toLowerCase().includes(v.toLowerCase())||G.content.toLowerCase().includes(v.toLowerCase());return V&&ee}),ae=((W=r.find(G=>G.key===a))==null?void 0:W.label)||b_[a]||a,te=r.length?r.map(G=>G.key):s$,U={width:"100%",boxSizing:"border-box",background:"rgba(255,255,255,0.05)",border:"1px solid #1e3a4f",borderRadius:8,padding:"7px 10px",color:"#e2e8f0",fontSize:12,outline:"none",marginBottom:6};return t.jsxs("div",{style:{display:"flex",height:"100%",gap:0},children:[t.jsxs("div",{style:{width:220,flexShrink:0,background:"#162232",border:"1px solid #1e3a4f",borderRadius:"14px 0 0 14px",display:"flex",flexDirection:"column"},children:[t.jsxs("div",{style:{padding:"14px 16px",borderBottom:"1px solid #1e3a4f",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[t.jsxs("div",{style:{minWidth:0},children:[t.jsx("div",{style:{color:"#e2e8f0",fontWeight:700,fontSize:13},children:"Document Categories"}),t.jsx("div",{style:{color:"#64748b",fontSize:11,marginTop:3},children:"Changes go live instantly"})]}),t.jsx("button",{onClick:()=>j(G=>!G),title:"New Category",style:{flexShrink:0,fontSize:11,fontWeight:700,padding:"5px 10px",borderRadius:8,background:"rgba(13,126,163,0.15)",color:"#38bdf8",border:"1px solid rgba(13,126,163,0.3)",cursor:"pointer"},children:"+ New"})]}),_&&t.jsxs("div",{style:{padding:12,borderBottom:"1px solid #1e3a4f",background:"rgba(13,126,163,0.04)"},children:[t.jsx("input",{type:"text",placeholder:"Label (e.g. Service Agreement)",value:T,onChange:G=>{L(G.target.value),C||S(G.target.value.toLowerCase().replace(/\s+/g,"_"))},style:U}),t.jsx("input",{type:"text",placeholder:"key_slug",value:C,onChange:G=>S(G.target.value),style:U}),t.jsxs("div",{style:{display:"flex",gap:6},children:[t.jsx("button",{onClick:()=>{j(!1),S(""),L("")},style:{flex:1,fontSize:11,padding:"6px 0",borderRadius:6,color:"#64748b",background:"rgba(255,255,255,0.04)",border:"1px solid #1e3a4f",cursor:"pointer"},children:"Cancel"}),t.jsx("button",{onClick:k,disabled:!C.trim()||!T.trim(),style:{flex:1,fontSize:11,fontWeight:700,padding:"6px 0",borderRadius:6,color:"#fff",background:"linear-gradient(135deg, #3b82f6, #2563eb)",border:"none",cursor:"pointer",opacity:!C.trim()||!T.trim()?.5:1},children:"Create"})]})]}),t.jsx("div",{style:{padding:"10px 12px",borderBottom:"1px solid #1e3a4f"},children:t.jsx("input",{type:"text",placeholder:"Search terms...",value:v,onCh
630ange:G=>x(G.target.value),style:{...U,marginBottom:0}})}),t.jsx("nav",{style:{flex:1,padding:8,overflowY:"auto"},children:te.map(G=>{var Q;const V=e.filter(oe=>oe.applies_to===G).length,ee=a===G,re=((Q=r.find(oe=>oe.key===G))==null?void 0:Q.label)||b_[G]||G;return t.jsxs("button",{onClick:()=>{l(G),c(null),R(!1)},style:{width:"100%",textAlign:"left",padding:"10px 12px",borderRadius:10,marginBottom:2,cursor:"pointer",background:ee?"rgba(13,126,163,0.15)":"transparent",border:`1px solid ${ee?"rgba(13,126,163,0.3)":"transparent"}`,color:ee?"#38bdf8":"#94a3b8"},children:[t.jsx("div",{style:{fontSize:12,fontWeight:ee?700:500},children:re}),t.jsxs("div",{style:{fontSize:10,color:"#64748b",marginTop:2},children:[V," blocks"]})]},G)})}),t.jsx("div",{style:{padding:12,borderTop:"1px solid #1e3a4f"},children:t.jsxs("a",{href:"/terms",target:"_blank",rel:"noopener noreferrer",style:{display:"flex",alignItems:"center",gap:6,padding:"8px 12px",borderRadius:8,fontSize:12,color:"#64748b",background:"rgba(255,255,255,0.03)",border:"1px solid #1e3a4f",textDecoration:"none"},children:[t.jsx("span",{children:"ð"}),t.jsx("span",{children:"View Public T&C"}),t.jsx("span",{style:{marginLeft:"auto"},children:"â"})]})})]}),t.jsxs("div",{style:{width:d?280:void 0,flex:d?void 0:1,flexShrink:0,overflowY:"auto",background:"#0f1923",borderTop:"1px solid #1e3a4f",borderBottom:"1px solid #1e3a4f",...d?{}:{borderRight:"1px solid #1e3a4f",borderRadius:"0 14px 14px 0"}},children:[t.jsxs("div",{style:{padding:"12px 16px",borderBottom:"1px solid #1e3a4f",background:"rgba(255,255,255,0.02)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[t.jsxs("div",{style:{minWidth:0},children:[t.jsx("div",{style:{color:"#e2e8f0",fontWeight:700,fontSize:13},children:ae}),t.jsxs("div",{style:{color:"#64748b",fontSize:11,marginTop:2},children:[J.length," term blocks"]})]}),t.jsx("button",{onClick:()=>R(G=>!G),style:{flexShrink:0,fontSize:11,fontWeight:700,padding:"6px 12px",borderRadius:8,background:"linear-gradient(135deg, #3b82f6, #2563eb)",color:"#fff",border:"none",cursor:"pointer"},children:"+ Add Block"})]}),E&&t.jsxs("div",{style:{padding:14,borderBottom:"1px solid #1e3a4f",background:"rgba(13,126,163,0.04)"},children:[t.jsx("input",{type:"text",placeholder:"Block title",value:N,onChange:G=>O(G.target.value),style:{...U,fontSize:13,padding:"8px 12px"}}),t.jsx("textarea",{placeholder:"Content...",value:z,onChange:G=>P(G.target.value),rows:5,style:{width:"100%",boxSizing:"border-box",background:"rgba(255,255,255,0.05)",border:"1px solid #1e3a4f",borderRadius:8,padding:"8px 12px",color:"#e2e8f0",fontSize:12,fontFamily:"monospace",outline:"none",resize:"none",marginBottom:8}}),t.jsxs("div",{style:{display:"flex",gap:6},children:[t.jsx("button",{onClick:()=>{R(!1),O(""),P("")},style:{flex:1,fontSize:12,padding:"7px 0",borderRadius:8,color:"#64748b",background:"rgba(255,255,255,0.04)",border:"1px solid #1e3a4f",cursor:"pointer"},children:"Cancel"}),t.jsx("button",{onClick:q,disabled:!N.trim(),style:{flex:1,fontSize:12,fontWeight:700,padding:"7px 0",borderRadius:8,color:"#fff",background:"linear-gradient(135deg, #3b82f6, #2563eb)",border:"none",cursor:"pointer",opacity:N.trim()?1:.5},children:"Create Block"})]})]}),i?t.jsx("div",{style:{textAlign:"center",color:"#64748b",padding:48},children:"Loading..."}):J.length===0?t.jsx("div",{style:{textAlign:"center",color:"#64748b",padding:48},children:"No blocks found"}):J.map(G=>t.jsxs("div",{onClick:()=>$(G),style:{padding:"14px 16px",cursor:"pointer",opacity:G.is_active?1:.4,borderBottom:"1px solid #1e3a4f",background:(d==null?void 0:d.id)===G.id?"rgba(13,126,163,0.08)":"transparent",borderLeft:(d==null?void 0:d.id)===G.id?"2px solid #0d7ea3":"2px solid transparent"},onMouseEnter:V=>{(d==null?void 0:d.id)!==G.id&&(V.currentTarget.style.background="rgba(255,255,255,0.02)")},onMouseLeave:V=>{(d==null?void 0:d.id)!==G.id&&(V.currentTarget.style.background="transparent")},children:[t.jsxs("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:8},children:[t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsx("div",{style:{color:"#e2e8f0",fontWeight:600,fontSize:13,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:G.title}),t.jsxs("div",{style:{color:"#64748b",fontSize:11,marginTop:2},children:["Order: ",G.sort_order]})]}),t.jsx("button",{onClick:V=>{V.stopPropagation(),B(G)},style:{fontSize:10,padding:"2px 8px",borderRadius:20,flexShrink:0,cursor:"pointer",background:G.
630is_active?"rgba(74,222,128,0.12)":"rgba(100,116,139,0.12)",color:G.is_active?"#4ade80":"#64748b",border:`1px solid ${G.is_active?"rgba(74,222,128,0.25)":"rgba(100,116,139,0.2)"}`},children:G.is_active?"Active":"Off"})]}),t.jsxs("p",{style:{color:"#64748b",fontSize:11,marginTop:6},children:[G.content.slice(0,100),"..."]}),t.jsxs("div",{style:{color:"#334155",fontSize:10,marginTop:4},children:["Updated ",new Date(G.updated_at).toLocaleDateString()]})]},G.id))]}),d&&t.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:"0 14px 14px 0",borderLeft:"none"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 20px",borderBottom:"1px solid #1e3a4f",background:"rgba(255,255,255,0.02)"},children:[t.jsxs("div",{children:[t.jsx("div",{style:{color:"#e2e8f0",fontWeight:700,fontSize:14},children:"Edit Block"}),t.jsxs("div",{style:{color:"#64748b",fontSize:11,marginTop:2},children:[d.applies_to," · order ",d.sort_order]})]}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[b&&t.jsx("span",{style:{fontSize:13,fontWeight:600,color:b.includes("â")?"#f87171":"#4ade80"},children:b}),t.jsx("button",{onClick:()=>c(null),style:{padding:"6px 14px",borderRadius:8,fontSize:12,color:"#64748b",cursor:"pointer",background:"rgba(255,255,255,0.04)",border:"1px solid #1e3a4f"},children:"Cancel"}),t.jsx("button",{onClick:I,disabled:y,style:{padding:"6px 16px",borderRadius:8,fontSize:12,fontWeight:700,color:"#fff",background:"linear-gradient(135deg, #3b82f6, #2563eb)",border:"none",cursor:y?"not-allowed":"pointer",opacity:y?.5:1},children:y?"Saving...":"Save Changes"})]})]}),t.jsxs("div",{style:{flex:1,overflowY:"auto",padding:20},children:[t.jsxs("div",{style:{background:"rgba(251,191,36,0.06)",border:"1px solid rgba(251,191,36,0.2)",borderRadius:10,padding:"10px 14px",marginBottom:16,display:"flex",gap:8,fontSize:12,color:"#fbbf24"},children:[t.jsx("span",{children:"â ï¸"}),t.jsxs("span",{children:[t.jsx("strong",{children:"Live content."})," Changes update the public T&C page and all new documents instantly."]})]}),t.jsxs("div",{style:{marginBottom:14},children:[t.jsx("label",{style:{display:"block",fontSize:11,color:"#64748b",marginBottom:6},children:"Section Title"}),t.jsx("input",{type:"text",value:u,onChange:G=>h(G.target.value),style:{width:"100%",boxSizing:"border-box",background:"rgba(255,255,255,0.05)",border:"1px solid #1e3a4f",borderRadius:10,padding:"9px 14px",color:"#e2e8f0",fontSize:13,outline:"none"}})]}),t.jsxs("div",{style:{marginBottom:14},children:[t.jsxs("label",{style:{display:"block",fontSize:11,color:"#64748b",marginBottom:6},children:["Content ",t.jsxs("span",{style:{color:"#334155"},children:["(",f.length," chars)"]})]}),t.jsx("textarea",{value:f,onChange:G=>p(G.target.value),rows:20,style:{width:"100%",boxSizing:"border-box",background:"rgba(255,255,255,0.05)",border:"1px solid #1e3a4f",borderRadius:10,padding:"10px 14px",color:"#e2e8f0",fontSize:12,fontFamily:"monospace",outline:"none",resize:"none",lineHeight:1.6}})]}),t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:11,color:"#64748b",marginBottom:8,fontWeight:600,textTransform:"uppercase",letterSpacing:"0.05em"},children:"Preview"}),t.jsxs("div",{style:{background:"#162232",border:"1px solid #1e3a4f",borderRadius:10,padding:"14px 16px"},children:[t.jsx("div",{style:{color:"#e2e8f0",fontWeight:700,fontSize:13,marginBottom:8},children:u}),t.jsx("div",{style:{color:"#94a3b8",fontSize:12,whiteSpace:"pre-wrap",lineHeight:1.7},children:f})]})]})]})]}),!d&&t.jsx("div",{style:{flex:1,display:"none"},className:"lg:flex items-center justify-center"})]})}const d$=[{value:"ro",label:"Reverse Osmosis"},{value:"softener",label:"Water Softener"},{value:"whole_home_filter",label:"Whole Home Filter"},{value:"iron_filter",label:"Iron Filter"},{value:"uv_system",label:"UV System"},{value:"combo_whole_home_ro",label:"Combo (Whole Home + RO)"}];function c$({items:e,onChange:n,products:r,fulfillmentType:s}){const[i,o]=g.useState(""),[a,l]=g.useState("1"),[d,c]=g.useState("0"),[f,p]=g.useState(""),u=x=>x===0?"Every cycle":`Year ${x} only`;function h(){if(!i){p("Select a product");return}const x=parseInt(a)||1,_=parseInt(d)||0;if(e.some(C=>C.product_id===i&&C.cycle_year===_)){p("This product+cycle combo already exists");return}n([...e,{product_id:i,quantity:x,cycle_year:_}]),o(""),l("1"),c("0"),p("")}function y(x){n(e.filter((_,j)=>j!==x))}function m(x,_){const j=Math.max(1,parseInt(_)||1);n(e.map((C,S)=>S===x?{...C,quantity:j}:C))}const b=s==="shipment",A=s==="tech_visit",v=b;return t.jsxs("div",{children:[t.jsxs("label",{style:{display:"block",fontSize:11,color:"#64748b",marginBottom:8,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.05em"},children:[b?"ð¦ Products to Ship":A?"ð§ Related Products":"ð Products",b&&t.jsx("span",{style:{color:"#a85
6305f7",fontWeight:400,textTransform:"none",letterSpacing:0},children:" â fulfilled per cycle by shipping cron"})]}),e.length>0&&t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6,marginBottom:10},children:e.map((x,_)=>{var C;const j=((C=r.find(S=>S.id===x.product_id))==null?void 0:C.name)||"Unknown product";return t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,background:"rgba(168,85,247,0.06)",border:"1px solid rgba(168,85,247,0.2)",borderRadius:10,padding:"8px 12px"},children:[t.jsx("span",{style:{fontSize:14},children:"ð¦"}),t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsx("div",{style:{color:"#e2e8f0",fontWeight:600,fontSize:12,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:j}),t.jsxs("div",{style:{display:"flex",gap:8,marginTop:2},children:[t.jsxs("span",{style:{fontSize:10,color:"#a855f7"},children:["Qty: ",x.quantity]}),v&&t.jsxs("span",{style:{fontSize:10,color:"#64748b"},children:["· ",u(x.cycle_year)]})]})]}),t.jsx("input",{type:"number",min:"1",value:x.quantity,onChange:S=>m(_,S.target.value),style:{width:50,background:"rgba(255,255,255,0.06)",border:"1px solid #1e3a4f",borderRadius:6,padding:"4px 8px",color:"#e2e8f0",fontSize:12,outline:"none",textAlign:"center"}}),t.jsx("button",{onClick:()=>y(_),style:{color:"#f87171",background:"none",border:"none",cursor:"pointer",fontSize:16,lineHeight:1,padding:"2px 4px"},children:"Ã"})]},_)})}),t.jsxs("div",{style:{background:"rgba(255,255,255,0.03)",border:"1px dashed #1e3a4f",borderRadius:10,padding:12},children:[t.jsx("div",{style:{fontSize:11,color:"#64748b",marginBottom:8,fontWeight:600},children:"+ Add Product"}),t.jsxs("div",{style:{display:"flex",gap:8,flexWrap:"wrap"},children:[t.jsxs("select",{value:i,onChange:x=>{o(x.target.value),p("")},style:{flex:"2 1 160px",background:"rgba(255,255,255,0.05)",border:"1px solid #1e3a4f",borderRadius:8,padding:"7px 10px",color:i?"#e2e8f0":"#64748b",fontSize:12,outline:"none"},children:[t.jsx("option",{value:"",style:{background:"#0f1923"},children:"Select product..."}),r.map(x=>t.jsx("option",{value:x.id,style:{background:"#0f1923"},children:x.name},x.id))]}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:2,flex:"0 0 70px"},children:[t.jsx("label",{style:{fontSize:9,color:"#64748b",textTransform:"uppercase",letterSpacing:"0.04em"},children:"Qty"}),t.jsx("input",{type:"number",min:"1",value:a,onChange:x=>l(x.target.value),style:{background:"rgba(255,255,255,0.05)",border:"1px solid #1e3a4f",borderRadius:8,padding:"7px 10px",color:"#e2e8f0",fontSize:12,outline:"none",textAlign:"center"}})]}),v&&t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:2,flex:"1 1 100px"},children:[t.jsx("label",{style:{fontSize:9,color:"#64748b",textTransform:"uppercase",letterSpacing:"0.04em"},children:"Ships in"}),t.jsxs("select",{value:d,onChange:x=>c(x.target.value),style:{background:"rgba(255,255,255,0.05)",border:"1px solid #1e3a4f",borderRadius:8,padding:"7px 10px",color:"#e2e8f0",fontSize:12,outline:"none"},children:[t.jsx("option",{value:"0",style:{background:"#0f1923"},children:"Every cycle"}),t.jsx("option",{value:"1",style:{background:"#0f1923"},children:"Year 1 only"}),t.jsx("option",{value:"2",style:{background:"#0f1923"},children:"Year 2 only"}),t.jsx("option",{value:"3",style:{background:"#0f1923"},children:"Year 3 only"}),t.jsx("option",{value:"4",style:{background:"#0f1923"},children:"Year 4 only"}),t.jsx("option",{value:"5",style:{background:"#0f1923"},children:"Year 5 only"})]})]}),t.jsx("button",{onClick:h,style:{flex:"0 0 auto",alignSelf:"flex-end",padding:"7px 14px",borderRadius:8,fontSize:12,fontWeight:700,cursor:"pointer",background:"linear-gradient(135deg, #a855f7, #9333ea)",color:"#fff",border:"none"},children:"Add"})]}),f&&t.jsxs("div",{style:{fontSize:11,color:"#f87171",marginTop:6},children:["â ï¸ ",f]}),v&&t.jsxs("div",{style:{fontSize:10,color:"#475569",marginTop:8,lineHeight:1.5},children:["ð¡ ",t.jsx("strong",{children:"Every cycle"})," = ships on every fulfillment date."," ",t.jsx("strong",{children:"Year N only"})," = only ships when the subscription age matches that year. Use this for multi-year filter kits (e.g., annual + 3-year membrane)."]})]}),b&&e.length===0&&t.jsx("div",{style:{fontSize:11,color:"#f59e0b",marginTop:8},children:"â ï¸ No products added â fulfillment cron will skip this plan until at least one product is linked"})]})}function u$({components:e,onChange:n,componentProducts:r,onProductsChange:s,products:i}){const[o,a]=g.useState(""),[l,d]=g.useState("annual_maintenance_visit"),[c,f]=g.useState("tech_visit"),[p,u]=g.useState("12"),[h,y]=g.useState(""),[m,b]=g.useState("");function A(){if(!o.trim()){b("Label is required");return}if(c!=="on_demand"&&(!p||parseInt(p)<=0)){b("Interval must be > 0 for non-on-demand components");return}const _=h.trim()===""?null:parseInt(h);if(_!==null&&(isNaN(_)||_<0)){b("Reminder days must be a positive number, or blank for none");return}n([...e,{label:o.trim(),component_code:l,fulfillment_type:c,interval_months:c==="on_demand"?null:parseInt(p),reminder_days_before:_}]),a(""),d("annual_maintenance_visit"),f("tech_visit"),u("12"),y(""),b("")}function v(_){n(e.filter((j,C)=>C!==_))}const x={background:"rgba(255,255,255,0.05)",border:"1px solid #1e3a4f",borderRadius:8,padding:"7px 10px",color:"#e2e8f0",fontSize:12,outline:"none"};return t.jsxs("div",{children:[t.jsxs("label",{style:{display:"block",fontSize:11,color:"#64748b",marginBottom:8,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.05em"},children:["ð Recurring Components",t.jsx("span",{style:{color:"#475569",fontWeight:400,textTransform:"none",letterSpacing:0,marginLeft:8}
630,children:"snapshotted per customer at activation â editing here does not affect existing customers"})]}),e.length>0&&t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8,marginBottom:10},children:e.map((_,j)=>{const C=r[j]||[];return t.jsxs("div",{style:{background:"rgba(56,189,248,0.06)",border:"1px solid rgba(56,189,248,0.2)",borderRadius:10,padding:"10px 12px"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[t.jsx("span",{style:{fontSize:14},children:_.fulfillment_type==="tech_visit"?"ð§":_.fulfillment_type==="shipment"?"ð¦":_.fulfillment_type==="delivery"?"ð":"ð"}),t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsx("div",{style:{color:"#e2e8f0",fontWeight:600,fontSize:12},children:_.label}),t.jsxs("div",{style:{fontSize:10,color:"#64748b",marginTop:2},children:[VW[_.fulfillment_type],_.interval_months?` · every ${_.interval_months} months`:" · no fixed schedule",_.reminder_days_before!=null?` · ð ${_.reminder_days_before}d before`:""," · ",t.jsx("span",{style:{color:"#94a3b8"},children:_.component_code})]})]}),t.jsx("button",{onClick:()=>v(j),style:{color:"#f87171",background:"none",border:"none",cursor:"pointer",fontSize:16,lineHeight:1},children:"Ã"})]}),t.jsxs("div",{style:{marginTop:10,paddingTop:10,borderTop:"1px solid rgba(56,189,248,0.15)"},children:[t.jsx("div",{style:{fontSize:10,color:"#64748b",fontWeight:700,textTransform:"uppercase",marginBottom:6},children:"ð¦ Products / Parts"}),C.length>0&&t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:4,marginBottom:6},children:C.map((S,T)=>{const L=i.find(E=>E.id===S.product_catalog_id);return t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:11,color:"#e2e8f0"},children:[t.jsx("span",{style:{color:"#38bdf8"},children:"·"}),t.jsx("span",{style:{flex:1},children:(L==null?void 0:L.name)||"Unknown"}),t.jsx("input",{type:"number",min:"1",value:S.quantity,onChange:E=>{const R=[...r[j]||[]];R[T]={...R[T],quantity:Math.max(1,parseInt(E.target.value)||1)};const N=[...r];N[j]=R,s(N)},style:{width:44,background:"rgba(255,255,255,0.05)",border:"1px solid #1e3a4f",borderRadius:4,padding:"2px 4px",color:"#e2e8f0",fontSize:11,outline:"none",textAlign:"center"}}),t.jsx("button",{onClick:()=>{const E=[...r[j]||[]];E.splice(T,1);const R=[...r];R[j]=E,s(R)},style:{color:"#f87171",background:"none",border:"none",cursor:"pointer",fontSize:13},children:"Ã"})]},T)})}),t.jsx("div",{style:{display:"flex",gap:6,alignItems:"center"},children:t.jsxs("select",{defaultValue:"",onChange:S=>{if(!S.target.value)return;const T=[...r];T[j]=[...T[j]||[],{product_catalog_id:S.target.value,quantity:1}],s(T),S.target.value=""},style:{flex:1,background:"rgba(255,255,255,0.05)",border:"1px solid #1e3a4f",borderRadius:6,padding:"5px 8px",color:"#e2e8f0",fontSize:11,outline:"none"},children:[t.jsx("option",{value:"",children:"+ Add product..."}),i.map(S=>t.jsx("option",{value:S.id,style:{background:"#0f1923"},children:S.name},S.id))]})})]})]},j)})}),t.jsxs("div",{style:{background:"rgba(255,255,255,0.03)",border:"1px dashed #1e3a4f",borderRadius:10,padding:12},children:[t.jsx("div",{style:{fontSize:11,color:"#64748b",marginBottom:8,fontWeight:600},children:"+ Add Component"}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8},children:[t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:10,color:"#64748b",marginBottom:4},children:"Label"}),t.jsx("input",{type:"text",value:o,onChange:_=>{a(_.target.value),b("")},placeholder:"e.g., Annual Tech Visit",style:{...x,width:"100%",boxSizing:"border-box"}})]}),t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:10,color:"#64748b",marginBottom:4},children:"Component Code"}),t.jsx("select",{value:l,onChange:_=>d(_.target.value),style:{...x,width:"100%",boxSizing:"border-box"},children:HW.map(_=>t.jsx("option",{value:_.value,style:{background:"#0f1923"},children:_.label},_.value))})]})]}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr auto",gap:8,alignItems:"flex-end"},children:[t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:10,
630color:"#64748b",marginBottom:4},children:"Fulfillment Type"}),t.jsxs("select",{value:c,onChange:_=>{const j=_.target.value;f(j),j==="on_demand"&&u(""),b("")},style:{...x,width:"100%",boxSizing:"border-box"},children:[t.jsx("option",{value:"tech_visit",style:{background:"#0f1923"},children:"Technician Visit"}),t.jsx("option",{value:"shipment",style:{background:"#0f1923"},children:"Shipment"}),t.jsx("option",{value:"delivery",style:{background:"#0f1923"},children:"Delivery"}),t.jsx("option",{value:"on_demand",style:{background:"#0f1923"},children:"On-Demand (no schedule)"})]})]}),c!=="on_demand"&&t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:10,color:"#64748b",marginBottom:4},children:"Interval (months)"}),t.jsx("input",{type:"number",min:"1",value:p,onChange:_=>{u(_.target.value),b("")},style:{...x,width:"100%",boxSizing:"border-box",textAlign:"center"}})]}),c!=="on_demand"&&t.jsxs("div",{title:"Default days before the due date to remind the customer. Blank = no reminder. Editable per customer afterwards.",children:[t.jsx("div",{style:{fontSize:10,color:"#64748b",marginBottom:4},children:"ð Remind (days before)"}),t.jsx("input",{type:"number",min:"0",value:h,placeholder:"none",onChange:_=>{y(_.target.value),b("")},style:{...x,width:"100%",boxSizing:"border-box",textAlign:"center"}})]}),t.jsx("button",{onClick:A,style:{padding:"7px 16px",borderRadius:8,fontSize:12,fontWeight:700,cursor:"pointer",background:"linear-gradient(135deg, #38bdf8, #0ea5e9)",color:"#fff",border:"none",alignSelf:"flex-end"},children:"Add"})]})]}),m&&t.jsxs("div",{style:{fontSize:11,color:"#f87171",marginTop:6},children:["â ï¸ ",m]})]}),e.length===0&&t.jsx("div",{style:{fontSize:11,color:"#64748b",marginTop:8,fontStyle:"italic"},children:"No components â this plan has no recurring schedule (billing only or priority access)."})]})}function p$(){const[e,n]=g.useState([]),[r,s]=g.useState({}),[i,o]=g.useState(!0),[a,l]=g.useState(!1),[d,c]=g.useState(null),[f,p]=g.useState(!1),[u,h]=g.useState(""),[y,m]=g.useState([]),[b,A]=g.useState(""),[v,x]=g.useState(""),[_,j]=g.useState(""),[C,S]=g.useState("yearly"),[T,L]=g.useState(""),[E,R]=g.useState("none"),[N,O]=g.useState(""),[z,P]=g.useState([]),[D,M]=g.useState(!0),[k,q]=g.useState(!1),[$,I]=g.useState([]),[B,J]=g.useState([]),[ae,te]=g.useState([]),[U,W]=g.useState(!1),[G,V]=g.useState(!1),[ee,re]=g.useState(!1),[Q,oe]=g.useState(!1),[ne,ge]=g.useState(!1),[be,we]=g.useState(!1);g.useEffect(()=>{F(),w.from("product_catalog").select("id, name").eq("is_active",!0).order("name").then(({data:ue})=>{m((ue||[]).map(fe=>({id:fe.id,name:fe.name})))})},[]);async function F(){o(!0);try{const ue=await b0();if(n(ue),ue.length>0)try{const fe=ue.map(xe=>xe.id),{data:le,error:ce}=await w.from("service_plan_items").select("service_plan_id, product_id, quantity, cycle_year").in("service_plan_id",fe);if(!ce&&le){const xe={};for(const ve of le)xe[ve.service_plan_id]||(xe[ve.service_plan_id]=[]),xe[ve.service_plan_id].push({product_id:ve.product_id,quantity:ve.quantity??1,cycle_year:ve.cycle_year??0});s(xe)}}catch(fe){console.warn("service_plan_items table not available yet:",fe)}}catch(ue){console.error("Failed to load plan templates:",ue)}o(!1)}function K(){A(""),x(""),j(""),S("yearly"),L(""),R("none"),O(""),P([]),M(!0),q(!1),I([]),J([]),te([]),W(!1),V(!1),re(!1),oe(!1),ge(!1),we(!1),c(null),h("")}function Z(){K(),l(!0)}function ie(ue){c(ue),A(ue.name),x(ue.description||""),j(ue.internal_notes||""),S(ue.billing_interval||ue.billing_cycle||"yearly"),L(String(ue.price_monthly??ue.price??"")),R(ue.fulfillment_type),O(ue.fulfillment_interval_months?String(ue.fulfillment_interval_months):""),P(Array.isArray(ue.applies_to_categories)?ue.applies_to_categories:[]),M(ue.requires_installed_system),q(ue.auto_activate_on_install),I(r[ue.id]||[]);const fe=ue;W(fe.includes_scheduled_maintenance??!1),V(fe.includes_unscheduled??fe.includes_unscheduled_maintenance??!1),re(fe.includes_water_test??!1),oe(fe.includes_salt_delivery??!1),ge(fe.includes_filter_shipments??!1),we(fe.includes_priority_service??!1),A0(ue.id).then(async le=>{J(le.map(xe=>({label:xe.label,component_code:xe.component_code,fulfillment_type:xe.fulfillment_type,interval_months:xe.interval_months})));const ce=await Promise.all(le.map(xe=>XW(xe.id).then(ve=>ve.map(_e=>({product_catalog_id:_e.product_catalog_id,quantity:_e.quantity}))).catch(()=>[])));te(ce)}).catch(()=>{J([]),te([])}),l(!0),h("")}async function Y(){if(!b.trim()){h("Plan name is required");return}if(!T||parseFloat(T)<0){h("Valid price is required");return}p(!0),h("");const ue={name:b.trim(),description:v.trim()||void 0,internal_notes:_.trim()||void 0,billing_interval:C,price_monthly:parseFloat(T),fulfillment_type:E,fulfillment_interval_months:N?parseInt(N):null,applies_to_categories:z,requires_installed_system:D,auto_activate_on_install:k};try{let fe;d?(await OW(d.id,ue),fe=d.id):fe=(await DW(ue)).id;try{await w.from("service_plan_items").delete().eq("service_plan_id",fe),$.length>0&&await w.from("service_plan_items").insert($.map(ce=>({service_plan_id:fe,product_id:ce.product_id,quantity:ce.quantity,cycle_year:ce.cycle_year})))}catch(ce){console.warn("service_plan_items not available:",ce)}await w.from("service_plans").update({includes_scheduled_maintenance:U,includes_unscheduled:G,includes_water_test:ee,includes_salt_delivery:Q,includes_filter_shipments:ne,includes_priority_service:be}).eq("id",fe);const le=await Ik(fe,B);await Promise.all(le.map((ce,xe)=>GW(ce.id,ae[xe]||[]))),l(!1),K(),F()}catch(fe){h(fe.message||"Failed to save")}p(!1)}async function X(ue){try{await IW(ue.id,!ue.is_active),n(fe=>fe.map(le=>le.id===ue.id?{...le,is_active:!le.is_active}:le))}catch(fe){console.error("Toggle active error:",fe)}}async function H(ue){try{await LW(ue.id,!ue.auto_activate_on_install),n(fe=>fe.map(le=>le.id===ue.id?{...le,auto_activate_on_install:!le.auto_activate_on_install}:le))}catch(fe){console.error("Toggle auto-activate error:",fe)}}async function de(ue){if(!confirm(`Delete "${ue.name}"? This cannot be undone.`))return;const{error:fe}=await w.from("service_plans").delete().eq("id",ue.id);fe||F()}async function pe(ue,fe){const le=e.findIndex(ve=>ve.id===ue.id),ce=fe==="up"?le-1:le+1;if(ce<0||ce>=e.length)return;const xe=e[ce];await w.from("service_plans").update({sort_order:xe.sort_order}).eq("id",ue.id),await w.from("service_plans").update({sort_order:ue.sort_order}).eq("id",xe.id),F()}function Ne(ue){P(fe=>fe.includes(ue)?fe.filter(le=>le!==ue):[...fe,ue])}const Ie=e.filter(ue=>ue.is_active).length,Ze=e.filter(ue=>ue.auto_activate_on_install&&ue.is_active).length,ht=ue=>{const fe=ue;return Number(fe.price_monthly??fe.price??0)},ke=ue=>{const fe=ue;return fe.billing_interval||fe.billing_cycle||""},Pe={width:"100%",boxSizing:"border-box",background:"rgba(255,255,255,0.05)",border:"1px solid #1e3a4f",borderRadius:10,padding:"9px 14px",color:"#e2e8f0",fontSize:13,outline:"none"},nt={display:"block",fontSize:11,color:"#64748b",marginBottom:6};return t.jsxs("div",{style:{height:"100%",overflowY:"auto"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:16},children:[t.jsxs("div",{children:[t.jsx("h2",{style:{color:"#e2e8f0",fontWeight:700,fontSize:16,margin:0},children:"Service Plan Templates"}),t.jsxs("p",{style:{color:"#64748b",fontSize:12,marginTop:4},children:[Ie," active · ",Ze," auto-enroll on install"]})]}),t.jsx("button",{onClick:Z,style:{padding:"8px 18px",borderRadius:10,fontSize:13,fontWeight:700,background:"linear-gradient(135deg, #f59e0b, #d97706)",color:"#fff",border:"none",cursor:"pointer"},children:"+ Add Plan Template"})]}),a&&t.jsxs("div",{style:{...vs,marginBottom:16,padding:20},children:[t.jsx("h3",{style:{color:"#e2e8f0",fontWeight:700,fontSize:14,marginBottom:16},children:d?"Edit Plan Template":"New Plan Template"}),u&&t.jsx("div",{style:{background:"rgba(248,113,113,0.08)",border:"1px solid rgba(248,113,113,0.3)",borderRadius:10,padding:"8px 14px",marginBottom:14,fontSize:12,color:"#f87171"},children:u}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:14},children:[t.jsxs("div",{children:[t.jsx("label",{style:nt,children:"Plan Name"}),t.jsx("input",{type:"text",value:b,onChange:ue=>A(ue.target.value),placeholder:"e.g., Annual Maintenance Plan",style:Pe})]}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12},children:[t.jsxs("div",{children:[t.jsx("label",{style:nt,children:"Billing Cycle"}),t.jsxs("select",{value:C,onChange:ue=>S(ue.target.value),style:Pe,children:[t.jsx("option",{value:"monthly",style:{background:"#0f1923"},children:"Monthly"}),t.jsx("option",{value:"quarterly",style:{background:"#0f1923"},children:"Quarterly"}),t.jsx("option",{value:"yearly",style:{background:"#0f1923"},children:"Yearly"}),t.jsx("option",{value:"biannual",style:{background:"#0f1923"},children:"Every 6 Months"}),t.jsx("option",{value:"one_time",style:{background:"#0f1923"},children:"One-Time"})]})]}),t.jsxs("div",{children:[t.jsx("label",{style:nt,children:"Monthly Price ($)"}),t.jsx("input",{type:"number",step:"0.01",min:"0",value:T,onChange:ue=>L(ue.target.value),placeholder:"0.00",style:Pe})]})]}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12},children:[t.jsxs("div",{children:[t.jsx("label",{style:nt,children:"Fulfillment Type"}),t.jsxs("select",{value:E,onChange:ue=>R(ue.target.value),style:Pe,children:[t.jsx("option",{value:"tech_visit",style:{background:"#0f1923"},children:"Technician Visit"}),t.jsx("option",{value:"shipment",style:{background:"#0f1923"},children:"Filter Shipment"}),t.jsx("option",{value:"on_demand",style:{background:"#0f1923"},children:"On-Demand Service"}),t.jsx("option",{value:"none",style:{background:"#0f1923"},children:"Billing Only (No Fulfillment)"})]})]}),(E==="tech_visit"||E==="shipment")&&t.jsxs("div",{children:[t.jsx("label",{style:nt,children:"Fulfillment Interval (months)"}),t.jsx("input",{type:"number",min:"1",value:N,onChange:ue=>O(ue.target.value),placeholder:"12",style:Pe})]})]}),E!=="none"&&t.jsx("div",{style:{background:"rgba(168,85,247,0.04)",border:"1px solid rgba(168,85,247,0.15)",borderRadius:12,padding:16},children:t.jsx(c$,{items:$,onChange:I,products:y,fulfillmentType:E})}),t.jsxs("div",{children:[t.jsx("label",{style:nt,children:"Customer-Facing Description"}
630),t.jsx("textarea",{value:v,onChange:ue=>x(ue.target.value),rows:2,placeholder:"Shown on quotes and customer pages",style:{...Pe,resize:"none",fontFamily:"inherit"}})]}),t.jsxs("div",{children:[t.jsx("label",{style:nt,children:"Internal Notes (admin only)"}),t.jsx("textarea",{value:_,onChange:ue=>j(ue.target.value),rows:2,placeholder:"Not shown to customers",style:{...Pe,resize:"none",fontFamily:"inherit"}})]}),t.jsxs("div",{children:[t.jsxs("label",{style:nt,children:["Applies to Product Categories ",t.jsx("span",{style:{color:"#334155"},children:"(empty = all)"})]}),t.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:8},children:d$.map(ue=>{const fe=z.includes(ue.value);return t.jsx("button",{onClick:()=>Ne(ue.value),style:{padding:"5px 12px",borderRadius:20,fontSize:12,cursor:"pointer",background:fe?"rgba(245,158,11,0.15)":"rgba(255,255,255,0.04)",color:fe?"#f59e0b":"#64748b",border:`1px solid ${fe?"rgba(245,158,11,0.4)":"#1e3a4f"}`,fontWeight:fe?700:400},children:ue.label},ue.value)})})]}),t.jsxs("div",{style:{display:"flex",gap:24},children:[t.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer"},children:[t.jsx("input",{type:"checkbox",checked:D,onChange:ue=>M(ue.target.checked),style:{width:15,height:15,accentColor:"#0d7ea3"}}),t.jsx("span",{style:{fontSize:13,color:"#e2e8f0"},children:"Requires Installed System"})]}),t.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer"},children:[t.jsx("input",{type:"checkbox",checked:k,onChange:ue=>q(ue.target.checked),style:{width:15,height:15,accentColor:"#f59e0b"}}),t.jsx("span",{style:{fontSize:13,color:"#e2e8f0"},children:"Auto-Enroll on Install"})]})]}),k&&t.jsxs("div",{style:{background:"rgba(245,158,11,0.06)",border:"1px solid rgba(245,158,11,0.2)",borderRadius:10,padding:"8px 14px",fontSize:12,color:"#f59e0b",display:"flex",gap:8},children:[t.jsx("span",{children:"â¡"}),t.jsx("span",{children:"This plan will automatically activate for every new installation matching the selected categories."})]}),t.jsxs("div",{style:{background:"rgba(56,189,248,0.04)",border:"1px solid rgba(56,189,248,0.15)",borderRadius:12,padding:16},children:[t.jsxs("div",{style:{fontSize:11,color:"#38bdf8",fontWeight:700,textTransform:"uppercase",letterSpacing:"0.05em",marginBottom:10},children:["Coverage Features ",t.jsx("span",{style:{color:"#475569",fontWeight:400,textTransform:"none",letterSpacing:0},children:"â informational only, shown on customer page"})]}),t.jsx("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:8},children:[{state:U,set:W,label:"Scheduled Maintenance"},{state:G,set:V,label:"Unscheduled Access"},{state:ee,set:re,label:"Water Tests"},{state:Q,set:oe,label:"Salt Delivery"},{state:ne,set:ge,label:"Filter Shipments"},{state:be,set:we,label:"Priority Service"}].map(({state:ue,set:fe,label:le})=>t.jsxs("label",{style:{display:"flex",alignItems:"center",gap:6,cursor:"pointer"},children:[t.jsx("input",{type:"checkbox",checked:ue,onChange:ce=>fe(ce.target.checked),style:{width:13,height:13,accentColor:"#38bdf8"}}),t.jsx("span",{style:{fontSize:11,color:"#94a3b8"},children:le})]},le))})]}),t.jsx("div",{style:{background:"rgba(56,189,248,0.04)",border:"1px solid rgba(56,189,248,0.15)",borderRadius:12,padding:16},children:t.jsx(u$,{components:B,onChange:J,componentProducts:ae,onProductsChange:te,products:y})}),t.jsxs("div",{style:{display:"flex",gap:8,paddingTop:4},children:[t.jsx("button",{onClick:()=>{l(!1),K()},style:{padding:"8px 16px",borderRadius:10,fontSize:13,color:"#64748b",cursor:"pointer",background:"rgba(255,255,255,0.04)",border:"1px solid #1e3a4f"},children:"Cancel"}),t.jsx("button",{onClick:Y,disabled:f||!b.trim(),style:{padding:"8px 20px",borderRadius:10,fontSize:13,fontWeight:700,color:"#fff",background:"linear-gradient(135deg, #f59e0b, #d97706)",border:"none",cursor:f||!b.trim()?"not-allowed":"pointer",opacity:f||!b.trim()?.5:1},children:f?"Saving...":d?"Update Template":"Create Template"})]})]})]}),i?t.jsx("div",{style:{textAlign:"center",color:"#64748b",padding:"48px 0"},children:"Loading..."}):e.length===0?t.jsxs("div",{style:{textAlign:"center",padding:"48px 0"},children:[t.jsx("div",{style:{fontSize:40,marginBottom:12},children:"ð"}),t.jsx("p",{style:{color:"#64748b"},children:"No service plan templates yet."})]}):t.jsx("div",{style:{...vs,overflowX:"auto"},children:t.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",minWidth:780},children:[t.jsx("thead",{children:t.jsxs("tr",{children:[t.jsx("th",{style:{...dt,width:36},children:"#"}),t.jsx("th",{style:dt,children:"Plan"}),t.jsx("th",{style:{...dt,width:100},children:"Billing"}),t.jsx("th",{style:{...dt,width:90,textAlign:"right"},children:"Price"}),t.jsx("th",{style:{...dt,width:160},children:"Fulfillment"}),t.jsx("th",{style:{...dt,width:80,textAlign:"center"},children:"Active"}),t.jsx("th",{style:{...dt,width:90,textAlign:"center"},children:"Auto-Enroll"}),t.jsx("th",{style:{...dt,width:70,textAlign:"center"},children:"Order"}),t.jsx("th",{style:{...dt,width:100,textAlign:"right"},children:"Actions"})]})}),t.jsx("tbody",{children:e.map((ue,fe)=>{const le=r[ue.id]||[],ce=ke(ue),xe=ht(ue);return t.jsxs("tr",{style:{opacity:ue.is_active?1:.4},children:[t.jsx("td",{style:{...ct,color:"#64748b",fontFamily:"monospace"},children:fe+1}),t.jsxs("td",{style:ct,children:[t.jsx("div",{style:{fontWeight:600},children:ue.name}),ue.description&&t.jsx("div",{style:{fontSize:11,color:"#64748b",marginTop:3},children:ue.description.length>
63080?ue.description.slice(0,80)+"...":ue.description}),Array.isArray(ue.applies_to_categories)&&ue.applies_to_categories.length>0&&t.jsx("div",{style:{display:"flex",gap:4,marginTop:4,flexWrap:"wrap"},children:ue.applies_to_categories.map(ve=>t.jsx("span",{style:{fontSize:9,padding:"1px 6px",borderRadius:10,background:"rgba(245,158,11,0.1)",color:"#f59e0b",border:"1px solid rgba(245,158,11,0.25)"},children:ve},ve))})]}),t.jsx("td",{style:ct,children:t.jsx("span",{style:{fontSize:11,padding:"3px 8px",borderRadius:20,background:"rgba(255,255,255,0.05)",color:"#94a3b8",border:"1px solid #1e3a4f"},children:ce==="one_time"?"One-Time":ce?ce.charAt(0).toUpperCase()+ce.slice(1):"â"})}),t.jsxs("td",{style:{...ct,textAlign:"right",fontFamily:"monospace",fontWeight:600},children:["$",xe.toFixed(2),t.jsx("div",{style:{fontSize:10,color:"#64748b",fontWeight:400},children:ya[ce]||"/mo"})]}),t.jsxs("td",{style:ct,children:[t.jsx("span",{style:{fontSize:11,padding:"3px 8px",borderRadius:20,background:ue.fulfillment_type==="tech_visit"?"rgba(96,165,250,0.1)":ue.fulfillment_type==="shipment"?"rgba(168,85,247,0.1)":ue.fulfillment_type==="on_demand"?"rgba(74,222,128,0.1)":"rgba(255,255,255,0.05)",color:ue.fulfillment_type==="tech_visit"?"#60a5fa":ue.fulfillment_type==="shipment"?"#a855f7":ue.fulfillment_type==="on_demand"?"#4ade80":"#94a3b8",border:"1px solid transparent"},children:td[ue.fulfillment_type]||ue.fulfillment_type}),ue.fulfillment_interval_months&&t.jsxs("div",{style:{fontSize:10,color:"#64748b",marginTop:2},children:["Every ",ue.fulfillment_interval_months," mo"]}),le.length>0?t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:2,marginTop:4},children:le.map((ve,_e)=>{var Be;const je=(Be=y.find(Je=>Je.id===ve.product_id))==null?void 0:Be.name;return je?t.jsxs("div",{style:{fontSize:10,color:"#a855f7",display:"flex",alignItems:"center",gap:4},children:[t.jsx("span",{children:"ð¦"}),t.jsxs("span",{children:[je," Ã",ve.quantity]}),ve.cycle_year>0&&t.jsxs("span",{style:{color:"#64748b"},children:["· Yr ",ve.cycle_year]})]},_e):null})}):ue.fulfillment_type==="shipment"&&t.jsx("div",{style:{fontSize:10,color:"#f59e0b",marginTop:2},children:"â ï¸ No products linked"})]}),t.jsx("td",{style:{...ct,textAlign:"center"},children:t.jsx(Yf,{active:ue.is_active,onClick:()=>X(ue)})}),t.jsx("td",{style:{...ct,textAlign:"center"},children:t.jsx("button",{onClick:()=>H(ue),style:{fontSize:11,padding:"3px 10px",borderRadius:20,fontWeight:700,cursor:"pointer",background:ue.auto_activate_on_install?"rgba(245,158,11,0.12)":"rgba(100,116,139,0.12)",color:ue.auto_activate_on_install?"#f59e0b":"#64748b",border:`1px solid ${ue.auto_activate_on_install?"rgba(245,158,11,0.4)":"rgba(100,116,139,0.2)"}`},children:ue.auto_activate_on_install?"â¡ On":"Off"})}),t.jsx("td",{style:{...ct,textAlign:"center"},children:t.jsxs("div",{style:{display:"flex",justifyContent:"center",gap:4},children:[t.jsx("button",{onClick:()=>pe(ue,"up"),disabled:fe===0,style:{color:"#64748b",background:"none",border:"none",cursor:"pointer",opacity:fe===0?.2:1},children:"â²"}),t.jsx("button",{onClick:()=>pe(ue,"down"),disabled:fe===e.length-1,style:{color:"#64748b",background:"none",border:"none",cursor:"pointer",opacity:fe===e.length-1?.2:1},children:"â¼"})]})}),t.jsx("td",{style:{...ct,textAlign:"right"},children:t.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:10},children:[t.jsx("button",{onClick:()=>ie(ue),style:{fontSize:12,color:"#60a5fa",background:"none",border:"none",cursor:"pointer",fontWeight:600},children:"Edit"}),t.jsx("button",{onClick:async()=>{try{await ZW(ue.id),F()}catch(ve){alert("Duplicate failed: "+ve.message)}},style:{fontSize:12,color:"#a855f7",background:"none",border:"none",cursor:"pointer",fontWeight:600},children:"Duplicate"}),t.jsx("button",{onClick:()=>de(ue),style:{fontSize:12,color:"#f87171",background:"none",border:"none",cursor:"pointer",fontWeight:600},children:"Delete"})]})})]},ue.id)})})]})})]})}const j_={sms:{bg:"rgba(34,197,94,0.1)",color:"#22c55e",border:"rgba(34,197,94,0.3)"},email:{bg:"rgba(96,165,250,0.1)",color:"#60a5fa",border:"rgba(96,165,250,0.3)"},task:{bg:"rgba(251,191,36,0.1)",color:"#fbbf24",border:"rgba(251,191,36,0.3)"},internal:{bg:"rgba(100,116,139,0.1)",color:"#94a3b8",border:"rgba(100,116,139,0.2)"}};function h$(){const[e,n]=g.useState([]),[r,s]=g.useState(!0),[i,o]=g.useState(null),[a,l]=g.useState(""),[d,c]=g.useState(!1),[f,p]=g.useState({});g.useEffect(()=>{u()},[]);async function u(){s(!0);const{data:_}=await w.from("automation_settings").select("id, key, label, group_name, enabled, channel, sms_template, timing_label, updated_at").order("group_name").order("key");_&&n(_),s(!1)}async function h(_){const{error:j}=await w.from("automation_settings").update({enabled:!_.enabled,updated_at:new Date().toISOString()}).eq("id",_.id);j||n(C=>C.map(S=>S.id===_.id?{...S,enabled:!S.enabled}:S))}function y(_){o(_.key),l(_.sms_template||"")}async function m(_){c(!0);const{error:j}=await w.from("automation_settings").update({sms_template:a.trim()||null,updated_at:new Date().toISOString()}).eq("id",_.id);j?p(C=>({...C,[_.key]:"â Error: "+j.message})):(n(C=>C.map(S=>S.id===_.id?{...S,sms_template:a.trim()||null}:S)),p(C=>({...C,[_.key]:"â
Saved"})),o(null),setTimeout(()=>p(C=>{const S={...C};return delete S[_.key],S}),3e3)),c(!1)}const b=e.reduce((_,j)=>(_[j.group_name]||(_[j.group_name]=[]),_[j.group_name].push(j),_),{}),A=["Lead Pipeline","Consultation","Installation","Post-Install & Retention","Billing & Contracts","Shipping & Fulfillment"],v=[...A.filter(_=>b[_]),...Object.keys(b).filter(_=>!A.includes(_))],x=e.filter(_=>_.enabled).length;return r?t.jsx("div",{style:{textAlign:"center",color:"#64748b",padding:"48px 0"},children:"Loading automations..."}):t.jsxs("div",{style:{height:"100%",overflowY:"auto"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:20},children:[t.jsxs("div",{children:[t.jsx("h2",{style:{color:"#e2e8f0",fontWeight:700,fontSize:16,margin:0},children:"Automation Settings"}),t.jsxs("p",{style:{color:"#64748b",fontSize:12,marginTop:4},children:[x," of ",e.length," automations active â toggle on/off and edit message templates"]})]}),t.jsx("div",{style:{fontSize:11,padding:"6px 14px",borderRadius:20,fontWeight:600,background:"rgba(249,115,22,0.1)",color:"#f97316",border:"1px solid rgba(249,115,22,0.3)"},children:"â¡ Changes take effect on next trigger"})]}),t.jsxs("div",{style:{background:"rgba(13,126,163,0.06)",border:"1px solid rgba(13,126,163,0.2)",borderRadius:12,padding:"12px 16px",marginBottom:20,display:"flex",gap:12,alignItems:"flex-start"},children:[t.jsx("span",{style:{fontSize:18,flexShrink:0},children:"ð¡"}),t.jsxs("div",{children:[t.jsx("div",{style:{color:"#38bdf8",fontWeight:700,fontSize:12,marginBottom:4},children:"Template Variables"}),t.jsxs("div",{style:{color:"#64748b",fontSize:11,lineHeight:1.6},children:["Use ",t.jsx("code",{style:{background:"rgba(255,255,255,0.08)",padding:"1px 5px",borderRadius:4,color:"#94a3b8"},children:"{{name}}"})," ",t.jsx("code",{style:{background:"rgba(255,255,255,0.08)",padding:"1px 5px",borderRadius:4,color:"#94a3b8"},children:"{{date}}"})," ",t.jsx("code",{style:{background:"rgba(255,255,255,0.08)",padding:"1px 5px",borderRadius:4,color:"#94a3b8"},children:"{{time}}"})," ",t.jsx("code",{style:{background:"rgba(255,255,255,0.08)",padding:"1px 5px",borderRadius:4,color:"#94a3b8"},children:"{{tracking_number}}"})," ",t.jsx("code",{style:{background:"rgba(255,255,255,0.08)",padding:"1px 5px",borderRadius:4,color:"#94a3b8"},children:"{{plan_name}}"})," â ","replaced automatically when SMS is sent."]})]})]}),v.map(_=>{const j=b[_]||[],C=j.filter(S=>S.enabled).length;return t.jsxs("div",{style:{marginBottom:20},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,marginBottom:8,paddingBottom:8,borderBottom:"1px solid #1e3a4f"},children:[t.jsx("div",{style:{color:"#e2e8f0",fontWeight:700,fontSize:13},children:_}),t.jsxs("div",{style:{fontSize:10,padding:"2px 8px",borderRadius:20,fontWeight:600,background:"rgba(249,115,22,0.08)",color:"#f97316"},children:[C,"/",j.length," active"]})]}),t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:j.map(S=>{const T=j_[S.channel]||j_.internal,L=i===S.key,E=f[S.key];return t.jsxs("div",{style:{background:"#162232",border:`1px solid ${S.enabled?"#1e3a4f":"rgba(255,255,255,0.04)"}`,borderRadius:12,overflow:"hidden",opacity:S.enabled?1:.55},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"12px 16px"},children:[t.jsx("button",{onClick:()=>h(S),style:{width:44,height:24,borderRadius:12,cursor:"pointer",flexShrink:0,background:S.enabled?"#f97316":"rgba(100,116,139,0.3)",border:"none",position:"relative",transition:"background 0.2s"},children:t.jsx("div",{style:{position:"absolute",top:3,left:S.enabled?23:3,width:18,height:18,borderRadius:"50%",background:"#fff",transition:"left 0.2s"}})}),t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsx("div",{style:{color:"#e2e8f0",fontWeight:600,fontSize:13},children:S.label}),S.timing_label&&t.jsxs("div",{style:{color:"#64748b",fontSize:11,marginTop:2},children:["â± ",S.timing_label]})]}),t.jsx("span",{style:{fontSize:10,padding:"2px 8px",borderRadius:20,fontWeight:700,flexShrink:0,background:T.bg,color:T.color,border:`1px solid ${T.border}`,textTransform:"uppercase"},children:S.channel}),S.channel==="sms"&&t.jsx("button",{onClick:()=>L?o(null):y(S),style:{fontSize:11,padding:"4px 12px",borderRadius:8,cursor:"pointer",flexShrink:0,background:L?"rgba(249,115,22,0.15)":"rgba(255,255,255,0.05)",color:L?"#f97316":"#64748b",border:`1px solid ${L?"rgba(249,115,22,0.3)":"#1e3a4f"}`,fontWeight:600},children:L?"Cancel":"âï¸ Edit Message"}),E&&t.jsx("span",{style:{fontSize:12,fontWeight:700,color:E.includes("â")?"#f87171":"#4ade80",flexShrink:0},children:E})]}),L&&t.jsx("div",{style:{padding:"0 16px 16px",borderTop:"1px solid #1e3a4f"},children:t.jsxs("div",{style:{paddingTop:12},children:[t.jsxs("label",{style:{display:"block",fontSize:11,color:"#64748b",marginBottom:6},children:["Message Template ",t.jsxs("span",{style:{color:"#334155"},children:["(",a.length," chars · recommended max 160)"]})]}),t.jsx("textarea",{value:a,onChange:R=>l(R.target.value),rows:3,style:{width:"100%",boxSizing:"border-box",background:"rgba(255,255,255,0.05)",border:"1px solid #1e3a4f",borderRadius:10,padding:"10px 14px",color:"#e2e8f0",fontSize:13,fontFamily:"inherit",outline:"none",resize:"none"}}),a&&t.jsxs("div",{style:{background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:8,padding:"8px 12px",marginTop:8,fontSize:12,color:"#94a3b8",lineHeight:1.5},children:[t.jsx("span",{style:{color:"#64748b",fontSize:10,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.05em"},children:"Preview: "}),a.replace(/{{name}}/g,"John").replace(/{{date}}/g,"Wednesday, April 2").replace(/{{time}}/g,"10:00 AM").replace(/{{tracking_number}}/g,"1234567890").replace(/{{plan_name}}/g,"Annual Filter Plan").replace(/{{review_url}}/g,"g.page/review")]}),t.jsxs("div",{style:{display:"flex",gap:8,marginTop:10},children:[t.jsx("button",{onClick:()=>o(null),style:{padding:"7px 14px",borderRadius:8,fontSize:12,color:"#64748b",cursor:"pointer",background:"rgba(255,255,255,0.04)",border:"1px solid #1e3a4f"},children:"Cancel"}),t.jsx("button",{onClick:()=>m(S),disabled:d,style:{padding:"7px 18px",borderRadius:8,fontSize:12,fontWeight:700,color:"#fff",background:"linear-gradient(135deg, #f97316, #ea580c)",border:"none",cursor:d?"not-allowed":"pointer",opacity:d?.5:1},children:d?"Saving...":"Save Template"})]})]})}),!L&&S.channel==="sms"&&S.sms_template&&t.jsx("div",{style:{padding:"6px 16px 10px",borderTop:"1px solid rgba(255,255,255,0.03)"},children:t.jsxs("div",{style:{fontSize:11,color:"#475569",lineHeight:1.5,fontStyle:"italic"},children:['"',S.sms_template.length>120?S.sms_template.slice(0,120)+"...":S.sms_template,'"']})})]},S.key)})})]},_)})]})}function f$(){const[e,n]=g.useState("branches"),[r,s]=g.useState([]),[i,o]=g.useState([]),[a,l]=g.useState([]),[d,c]=g.useState(!0),[f,p]=g.useState(!1),[u,h]=g.useState(null),[y,m]=g.useState(""),[b,A]=g.useState(""),[v,x]=g.useState(""),[_,j]=g.useState(""),[C,S]=g.useState(""),[T,L]=g.useState(""),[E,R]=g.useState(""),[N,O]=g.useState(""),[z,P]=g.useState(""),[D,M]=g.useState(!1),[k,q]=g.useState(""),[$,I]=g.useState(""),[B,J]=g.useState(""),[ae,te]=g.useState(""),[U,W]=g.useState(!1);g.useEffect(()=>{G()},[]);async function G(){c(!0);try{const[{data:K},{data:Z},{data:ie}]=await Promise.all([w.from("branches").select("*").order("name"),w.from("profiles").select("id, full_name, role, branch_id").order("full_name"),w.from("zip_territories").select("*").order("zip_code")]);K&&s(K),Z&&o(Z),ie&&l(ie)}finally{c(!1)}}function V(){h(null),m(""),A(""),x(""),j(""),S("IN"),L(""),R(""),O(""),P(""),q(""),p(!0)}function ee(K){h(K),m(K.name),A(K.code),x(K.address||""),j(K.city||""),S(K.state||""),L(K.zip||""),R(K.phone||""),O(K.email||""),P(K.stripe_account_id||""),q(""),p(!0)}async function re(){if(!y.trim()||!b.trim()){q("Name and Code are required");return}M(!0),q("");try{const K={name:y.trim(),code:b.trim().toUpperCase(),address:v.trim()||null,city:_.trim()||null,state:C.trim()||null,zip:T.trim()||null,phone:E.trim()||null,email:N.trim()||null,stripe_account_id:z.trim()||null};if(u){const{error:Z}=await w.from("branches").update(K).eq("id",u.id);if(Z)throw Z}else{const{error:Z}=await w.from("branches").insert({...K,is_active:!0});if(Z)throw Z}p(!1),h(null),G()}catch(K){q(K.message||"Failed to save")}M(!1)}async function Q(K){await w.from("branches").update({is_active:!K.is_active}).eq("id",K.id),s(Z=>Z.map(ie=>ie.id===K.id?{...ie,is_active:!ie.is_active}:ie))}async function oe(K,Z){await w.from("profiles").update({branch_id:Z}).eq("id",K),o(ie=>ie.map(Y=>Y.id===K?{...Y,branch_id:Z}:Y))}async function ne(){if(!(!$.trim()||!B)){W(!0);try{const{error:K}=await w.from("zip_territories").insert({zip_code:$.trim(),branch_id:B,assigned_rep_id:ae||null});if(K)throw K;I(""),J(""),te(""),G()}catch(K){alert("Error: "+K.message)}W(!1)}}async function ge(K){confirm("Remove this ZIP territory?")&&(await w.from("zip_territories").delete().eq("id",K),l(Z=>Z.filter(ie=>ie.id!==K)))}const be={width:"100%",boxSizing:"border-box",background:"rgba(255,255,255,0.05)",border:"1px solid #1e3a4f",borderRadius:10,padding:"9px 14px",color:"#e2e8f0",fontSize:13,outline:"none"},we={display:"block",fontSize:11,color:"#64748b",marginBottom:6},F=i.filter(K=>K.role==="salesrep"||K.role==="frontdesk"||K.role==="admin");return t.jsxs("div",{style:{height:"100%",overflowY:"auto"},children:[t.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:16},children:t.jsxs("div",{children:[t.jsx("h2",{style:{color:"#e2e8f0",fontWeight:700,fontSize:16,margin:0},children:"Branch Management"}),t.jsxs("p",{style:{color:"#64748b",fontSize:12,marginTop:4},children:[r.filter(K=>K.is_active).length," active branches · ",i.length," team members · ",a.length," ZIP territories"]})]})}),t.jsx("div",{style:{display:"flex",gap:6,marginBottom:20},children:[{key:"branches",label:"ð¢ Branches",color:"#0d7ea3"},{key:"users",label:"ð¤ Assign Users",color:"#a78bfa"},{key:"zip_territories",label:"ð® ZIP Territories",color:"#34d399"}].map(K=>t.jsx("button",{onClick:()=>n(K.key),style:{padding:"8px 18px",borderRadius:10,fontSize:13,fontWeight:600,cursor:"pointer",background:e===K.key?`${K.color}18`:"rgba(255,255,255,0.03)",border:`1px solid ${e===K.key?`${K.color}50`:"rgba(255,255,255,0.06)"}`,color:e===K.key?K.color:"#64748b"},children:K.label},K.key))}),d?t.jsx("div",{style:{textAlign:"center",color:"#64748b",padding:"48px 0"},children:"Loading..."}):t.jsxs(t.Fragment,{children:[e==="branches"&&t.jsxs("div",{children:[t.jsx("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:14},children:t.jsx("button",{onClick:V,style:{padding:"8px 18px",borderRadius:10,fontSize:13,fontWeight:700,background:"linear-gradient(135deg, #0d7ea3, #0369a1)",color:"#fff",border:"none",cursor:"pointer"},children:"+ Add Branch"})}),f&&t.jsxs("div",{style:{...vs,marginBottom:16,padding:20},children:[t.jsx("h3",{style:{color:"#e2e8f0",fontWeight:700,fontSize:14,marginBottom:16},children:u?"Edit Branch":"New
630 Branch"}),k&&t.jsx("div",{style:{background:"rgba(248,113,113,0.08)",border:"1px solid rgba(248,113,113,0.3)",borderRadius:10,padding:"8px 14px",marginBottom:14,fontSize:12,color:"#f87171"},children:k}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:14},children:[t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"2fr 1fr",gap:12},children:[t.jsxs("div",{children:[t.jsx("label",{style:we,children:"Branch Name *"}),t.jsx("input",{type:"text",value:y,onChange:K=>m(K.target.value),placeholder:"Zenith Pure â Chicago",style:be})]}),t.jsxs("div",{children:[t.jsxs("label",{style:we,children:["Code * ",t.jsx("span",{style:{color:"#334155"},children:"(2-6 letters, e.g. CHI)"})]}),t.jsx("input",{type:"text",value:b,onChange:K=>A(K.target.value.toUpperCase()),placeholder:"CHI",maxLength:6,style:be})]})]}),t.jsxs("div",{children:[t.jsx("label",{style:we,children:"Address"}),t.jsx("input",{type:"text",value:v,onChange:K=>x(K.target.value),placeholder:"123 Main St",style:be})]}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"2fr 1fr 1fr",gap:12},children:[t.jsxs("div",{children:[t.jsx("label",{style:we,children:"City"}),t.jsx("input",{type:"text",value:_,onChange:K=>j(K.target.value),style:be})]}),t.jsxs("div",{children:[t.jsx("label",{style:we,children:"State"}),t.jsx("input",{type:"text",value:C,onChange:K=>S(K.target.value),maxLength:2,style:be})]}),t.jsxs("div",{children:[t.jsx("label",{style:we,children:"ZIP"}),t.jsx("input",{type:"text",value:T,onChange:K=>L(K.target.value),style:be})]})]}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12},children:[t.jsxs("div",{children:[t.jsx("label",{style:we,children:"Phone"}),t.jsx("input",{type:"text",value:E,onChange:K=>R(K.target.value),style:be})]}),t.jsxs("div",{children:[t.jsx("label",{style:we,children:"Email"}),t.jsx("input",{type:"email",value:N,onChange:K=>O(K.target.value),style:be})]})]}),t.jsx("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12},children:t.jsxs("div",{children:[t.jsxs("label",{style:we,children:["Stripe Account ID ",t.jsx("span",{style:{color:"#334155"},children:"(optional â leave blank to use master)"})]}),t.jsx("input",{type:"text",value:z,onChange:K=>P(K.target.value),placeholder:"acct_...",style:be})]})}),t.jsxs("div",{style:{display:"flex",gap:8,paddingTop:4},children:[t.jsx("button",{onClick:()=>{p(!1),h(null)},style:{padding:"8px 16px",borderRadius:10,fontSize:13,color:"#64748b",cursor:"pointer",background:"rgba(255,255,255,0.04)",border:"1px solid #1e3a4f"},children:"Cancel"}),t.jsx("button",{onClick:re,disabled:D,style:{padding:"8px 20px",borderRadius:10,fontSize:13,fontWeight:700,color:"#fff",background:"linear-gradient(135deg, #0d7ea3, #0369a1)",border:"none",cursor:D?"not-allowed":"pointer",opacity:D?.5:1},children:D?"Saving...":u?"Update Branch":"Create Branch"})]})]})]}),t.jsx("div",{style:{...vs,overflowX:"auto"},children:t.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",minWidth:700},children:[t.jsx("thead",{children:t.jsxs("tr",{children:[t.jsx("th",{style:dt,children:"Branch"}),t.jsx("th",{style:{...dt,width:70},children:"Code"}),t.jsx("th",{style:dt,children:"Location"}),t.jsx("th",{style:{...dt,width:80,textAlign:"center"},children:"Status"}),t.jsx("th",{style:{...dt,width:110,textAlign:"right"},children:"Actions"})]})}),t.jsx("tbody",{children:r.map(K=>t.jsxs("tr",{style:{opacity:K.is_active?1:.4},children:[t.jsxs("td",{style:ct,children:[t.jsx("div",{style:{fontWeight:600},children:K.name}),K.email&&t.jsx("div",{style:{fontSize:11,color:"#64748b",marginTop:2},children:K.email})]}),t.jsx("td",{style:ct,children:t.jsx("span",{style:{fontSize:12,fontWeight:700,padding:"3px 10px",borderRadius:20,background:"rgba(13,126,163,0.12)",color:"#0d7ea3",border:"1px solid rgba(13,126,163,0.25)"},children:K.code})}),t.jsxs("td",{style:ct,children:[t.jsx("div",{style:{fontSize:13},children:[K.address,K.city,K.state,K.zip].filter(Boolean).join(", ")||"â"}),K.phone&&t.jsx("div",{style:{fontSize:11,color:"#64748b",marginTop:2},children:K.phone})]}),t.jsx("td",{style:{...ct,textAlign:"center"},children:t.jsx(Yf,{active:K.is_active,onClick:()=>Q(K)})}),t.jsx("td",{style:{...ct,textAlign:"right"},children:t.jsx("button",{onClick:()=>ee(K),style:{fontSize:12,color:"#60a5fa",background:"none",border:"none",cursor:"pointer",fontWeight:600},children:"Edit"})})]},K.id))})]})})]}),e==="users"&&t.jsxs("div",{children:[t.jsx("p",{style:{color:"#64748b",fontSize:12,marginBottom:14},children:"Assign each team member to their branch. Admin users can see all branches."}),t.jsx("div",{style:{...vs,overflowX:"auto"},children:t.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",minWidth:500},children:[t.jsx("thead",{children:t.jsxs("tr",{children:[t.jsx("th",{style:dt,children:"Team Member"}),t.jsx("th",{style:{...dt,width:120},children:"Role"}),t.jsx("th",{style:{...dt,width:240},children:"Branch Assignment"})]})}),t.jsx("tbody",{children:i.map(K=>t.jsxs("tr",{children:[t.jsx("td",{style:ct,children:t.jsx("div",{style:{fontWeight:600},children:K.full_name})}),t.jsx("td",{style:ct,children:t.jsx("span",{style:{fontSize:11,padding:"2px 8px",borderRadius:20,background:"rgba(255,255,255,0.05)",color:"#94a3b8",border:"1px solid #1e3a4f"},children:K.role})}),t.jsx("td",{style:ct,children:t.jsxs("select",{value:K.branch_id||"",onChange:Z=>oe(K.id,Z.target.value||null),style:{background:"rgba(255,255,255,0.05)",border:"1px solid #1e3a4f",borderRadius:8,padding:"6px 10px",color:"#e2e8f0",fontSize:12,outline:"none",width:"100%"},children:[t.jsx("option",{value:"",style:{background:"#0f1923"},children:"â Unassigned â"}),r.filter(Z=>Z.is_active).map(Z=>t.jsxs("option",{value:Z.id,style:{background:"#0f1923"}
630,children:[Z.name," (",Z.code,")"]},Z.id))]})})]},K.id))})]})})]}),e==="zip_territories"&&t.jsxs("div",{children:[t.jsx("p",{style:{color:"#64748b",fontSize:12,marginBottom:14},children:"Map ZIP codes to branches. New leads from these ZIPs auto-route to the matching branch."}),t.jsxs("div",{style:{...vs,marginBottom:16,padding:16},children:[t.jsx("div",{style:{fontSize:12,color:"#64748b",fontWeight:700,marginBottom:12},children:"+ Add ZIP Territory"}),t.jsxs("div",{style:{display:"flex",gap:10,alignItems:"flex-end",flexWrap:"wrap"},children:[t.jsxs("div",{style:{flex:"0 0 120px"},children:[t.jsx("label",{style:we,children:"ZIP Code"}),t.jsx("input",{type:"text",value:$,onChange:K=>I(K.target.value),placeholder:"46201",maxLength:5,style:{...be,padding:"8px 12px",fontSize:13}})]}),t.jsxs("div",{style:{flex:"1 1 200px"},children:[t.jsx("label",{style:we,children:"Branch"}),t.jsxs("select",{value:B,onChange:K=>J(K.target.value),style:{...be,padding:"8px 12px",fontSize:13},children:[t.jsx("option",{value:"",style:{background:"#0f1923"},children:"Select branch..."}),r.filter(K=>K.is_active).map(K=>t.jsxs("option",{value:K.id,style:{background:"#0f1923"},children:[K.name," (",K.code,")"]},K.id))]})]}),t.jsxs("div",{style:{flex:"1 1 200px"},children:[t.jsxs("label",{style:we,children:["Default Rep ",t.jsx("span",{style:{color:"#334155"},children:"(optional)"})]}),t.jsxs("select",{value:ae,onChange:K=>te(K.target.value),style:{...be,padding:"8px 12px",fontSize:13},children:[t.jsx("option",{value:"",style:{background:"#0f1923"},children:"Round-robin"}),F.map(K=>t.jsx("option",{value:K.id,style:{background:"#0f1923"},children:K.full_name},K.id))]})]}),t.jsx("button",{onClick:ne,disabled:U||!$.trim()||!B,style:{padding:"9px 18px",borderRadius:10,fontSize:13,fontWeight:700,color:"#fff",background:"linear-gradient(135deg, #34d399, #10b981)",border:"none",cursor:"pointer",flexShrink:0},children:U?"Adding...":"Add ZIP"})]})]}),a.length===0?t.jsxs("div",{style:{textAlign:"center",padding:"32px 0",color:"#64748b"},children:[t.jsx("div",{style:{fontSize:32,marginBottom:8},children:"ð®"}),t.jsx("p",{children:"No ZIP territories yet. Add ZIPs above to auto-route leads to the right branch."})]}):t.jsx("div",{style:{...vs,overflowX:"auto"},children:t.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",minWidth:500},children:[t.jsx("thead",{children:t.jsxs("tr",{children:[t.jsx("th",{style:{...dt,width:120},children:"ZIP Code"}),t.jsx("th",{style:dt,children:"Branch"}),t.jsx("th",{style:dt,children:"Default Rep"}),t.jsx("th",{style:{...dt,width:80,textAlign:"right"},children:"Remove"})]})}),t.jsx("tbody",{children:a.map(K=>{const Z=r.find(Y=>Y.id===K.branch_id),ie=i.find(Y=>Y.id===K.assigned_rep_id);return t.jsxs("tr",{children:[t.jsx("td",{style:ct,children:t.jsx("span",{style:{fontFamily:"monospace",fontWeight:700,fontSize:14},children:K.zip_code})}),t.jsx("td",{style:ct,children:Z?t.jsx("span",{style:{fontSize:12,fontWeight:700,padding:"3px 10px",borderRadius:20,background:"rgba(13,126,163,0.12)",color:"#0d7ea3",border:"1px solid rgba(13,126,163,0.25)"},children:Z.code}):t.jsx("span",{style:{color:"#64748b"},children:"â"})}),t.jsx("td",{style:ct,children:(ie==null?void 0:ie.full_name)||t.jsx("span",{style:{color:"#64748b"},children:"Round-robin"})}),t.jsx("td",{style:{...ct,textAlign:"right"},children:t.jsx("button",{onClick:()=>ge(K.id),style:{fontSize:12,color:"#f87171",background:"none",border:"none",cursor:"pointer",fontWeight:600},children:"Remove"})})]},K.id)})})]})})]})]})]})}function g$(){const{profile:e}=Ee(),[n,r]=g.useState("50"),[s,i]=g.useState("100"),[o,a]=g.useState("50"),[l,d]=g.useState(!0),[c,f]=g.useState(!1),[p,u]=g.useState("");g.useEffect(()=>{async function N(){if(!(e!=null&&e.tenant_id))return;const{data:O}=await w.from("tenants").select("buyout_rental_credit_pct, buyout_install_credit_pct, buyout_credit_cap_pct").eq("id",e.tenant_id).single();O&&(r(String(O.buyout_rental_credit_pct??50)),i(String(O.buyout_install_credit_pct??100)),a(String(O.buyout_credit_cap_pct??50))),d(!1)}N()},[e==null?void 0:e.tenant_id]);async function h(){if(!(e!=null&&e.tenant_id))return;const N=parseFloat(n),O=parseFloat(s),z=parseFloat(o);if(isNaN(N)||N<0||N>100){u("â Rental credit must be 0â100");return}if(isNaN(O)||O<0||O>100){u("â Install credit must be 0â100");return}if(isNaN(z)||z<0||z>100){u("â Credit cap must be 0â100");return}f(!0),u("");const{error:P}=await w.from("tenants").update({buyout_rental_credit_pct:N,buyout_install_credit_pct:O,buyout_credit_cap_pct:z}).eq("id",e.tenant_id);P?u("â Error: "+P.message):(u("â
Saved"),setTimeout(()=>u(""),3e3)),f(!1)}const y=2500,m=29.99,b=18,A=150,v=parseFloat(n)||0,x=parseFloat(s)||0,_=parseFloat(o)||0,j=b*m*(v/100),C=y*(_/100),S=Math.min(j,C),T=A*(x/100),L=Math.max(0,y-S-T),E=N=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}).format(N),R={background:"rgba(255,255,255,0.05)",border:"1px solid #1e3a4f",borderRadius:10,padding:"10px 14px",color:"#e2e8f0",fontSize:14,outline:"none",width:"100%",boxSizing:"border-box"};return l?t.jsx("div",{style:{color:"#64748b",padding:40,textAlign:"center"},children:"Loading..."}):t.jsxs("div",{style:{height:"100%",overflowY:"auto",maxWidth:720},children:[t.jsxs("div",{style:{marginBottom:20},children:[t.jsx("h2",{style:{color:"#e2e8f0",fontWeight:700,fontSize:16,margin:0},children:"Buyout Configuration"}),t.jsx("p",{style:{color:"#64748b",fontSize:12,marginTop:4},children:"Set how rental payments and install fees credit toward equipment buyout price. Each tenant controls their own formula."})]}),t.jsx("div",{style:{background:"#162232",border:"1px solid #1e3a4f",borderRadius:14,padding:24,marginBottom:20},children:t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:20},children:[t.jsxs("div",{children:[t.jsx("label",{style:{display:"block",fontSize:12,color:"#94a3b8",fontWeight:700,marginBottom:6,textTransform:"uppercase",letterSpacing:"0.06em"},children:"Rental Credit %"}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12},children:[t.jsx("input",{type:"number",min:"0",max:"100",step:"1",value:n,onChange:N=>r(N.target.value),style:{...R,maxWidth:120}}),t.jsx("span",{style:{color:"#64748b",fontSize:13},children:"% of each monthly payment counts toward buyout credit"})]}),t.jsx("p",{style:{color:"#475569",fontSize:11,marginTop:6},children:"Example: 50% means if customer paid $30/mo for 12 months, they get $180 credit (12 Ã $30 Ã 50%)."})]}),t.jsxs("div",{children:[t.jsx("label",{style:{display:"block",fontSize:12,color:"#94a3b8",fontWeight:700,marginBottom:6,textTransform:"uppercase",letterSpacing:"0.06em"},children:"Install Fee Credit %"}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12},children:[t.jsx("input",{type:"number",min:"0",max:"100",step:"1",value:s,onChange:N=>i(N.target.value),style:{...R,maxWidth:120}}),t.jsx("span",{style:{color:"#64748b",fontSize:13},children:"% of the original install fee credited back"})]}),t.jsx("p",{style:{color:"#475569",fontSize:11,marginTop:6},children:"Example: 100% means the full install fee is credited. Set to 0% to
630not credit the install fee."})]}),t.jsxs("div",{children:[t.jsx("label",{style:{display:"block",fontSize:12,color:"#94a3b8",fontWeight:700,marginBottom:6,textTransform:"uppercase",letterSpacing:"0.06em"},children:"Rental Credit Cap % of Retail"}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12},children:[t.jsx("input",{type:"number",min:"0",max:"100",step:"1",value:o,onChange:N=>a(N.target.value),style:{...R,maxWidth:120}}),t.jsx("span",{style:{color:"#64748b",fontSize:13},children:"% maximum rental credit as % of retail price"})]}),t.jsx("p",{style:{color:"#475569",fontSize:11,marginTop:6},children:"Prevents the rental credit from exceeding this % of the retail price regardless of how long customer has rented."})]}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,paddingTop:8},children:[t.jsx("button",{onClick:h,disabled:c,style:{padding:"10px 24px",borderRadius:10,fontSize:13,fontWeight:700,background:"linear-gradient(135deg, #f43f5e, #e11d48)",color:"#fff",border:"none",cursor:c?"not-allowed":"pointer",opacity:c?.6:1},children:c?"Saving...":"Save Configuration"}),p&&t.jsx("span",{style:{fontSize:13,fontWeight:700,color:p.includes("â")?"#f87171":"#4ade80"},children:p})]})]})}),t.jsxs("div",{style:{background:"rgba(14,165,233,0.06)",border:"1px solid rgba(14,165,233,0.25)",borderRadius:14,padding:20},children:[t.jsx("div",{style:{fontSize:11,fontWeight:700,color:"#0ea5e9",textTransform:"uppercase",letterSpacing:"0.08em",marginBottom:14},children:"ð Example Calculation Preview"}),t.jsxs("div",{style:{fontSize:11,color:"#64748b",marginBottom:14},children:["Using: Retail ",E(y)," · ",E(m),"/mo · ",b," months paid · ",E(A)," install fee"]}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",fontSize:13},children:[t.jsx("span",{style:{color:"#94a3b8"},children:"Current Retail Price"}),t.jsx("span",{style:{color:"#e2e8f0",fontWeight:600},children:E(y)})]}),t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",fontSize:13},children:[t.jsxs("span",{style:{color:"#94a3b8"},children:["Rental Credit (",b," à ",E(m)," à ",v,"%",S<j?`, capped at ${_}% retail`:"",")"]}),t.jsxs("span",{style:{color:"#4ade80",fontWeight:600},children:["â ",E(S)]})]}),t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",fontSize:13},children:[t.jsxs("span",{style:{color:"#94a3b8"},children:["Install Fee Credit (",E(A)," à ",x,"%)"]}),t.jsxs("span",{style:{color:"#4ade80",fontWeight:600},children:["â ",E(T)]})]}),t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",fontSize:16,fontWeight:800,borderTop:"1px solid rgba(14,165,233,0.2)",paddingTop:12,marginTop:4},children:[t.jsx("span",{style:{color:"#e2e8f0"},children:"Customer Pays"}),t.jsx("span",{style:{color:"#0ea5e9"},children:E(L)})]})]})]})]})}const w_=[{key:"payment",label:"Payment Gateway",icon:"ð³",color:"#4ade80"},{key:"financing",label:"Financing",icon:"ð¦",color:"#f472b6"},{key:"shipping",label:"Shipping",icon:"ð¦",color:"#a78bfa"},{key:"branding",label:"Branding",icon:"ð¨",color:"#22d3ee"},{key:"bank",label:"Bank / ACH",icon:"ðï¸",color:"#fbbf24"}],S_=[{value:"",label:"â None (disable financing quotes) â"},{value:"hearth",label:"Hearth"},{value:"greensky",label:"GreenSky"},{value:"service_finance",label:"Service Finance Company"},{value:"enerbank",label:"EnerBank"},{value:"other",label:"Other"}],m$=[{value:"stripe",label:"Stripe"},{value:"authorize_net",label:"Authorize.net"},{value:"manual",label:"Manual (no online payments)"}],_s={background:"#162232",border:"1px solid #1e3a4f",borderRadius:14,padding:24},Mn={width:"100%",boxSizing:"border-box",background:"rgba(255,255,255,0.05)",border:"1px solid #1e3a4f",borderRadius:10,padding:"9px 14px",color:"#e2e8f0",fontSize:13,outline:"none",fontFamily:"monospace"},jn={display:"block",fontSize:11,color:"#64748b",marginBottom:6,fontWeight:600,textTransform:"uppercase",letterSpacing:"0.05em"},Hs={color:"#e2e8f0",fontWeight:700,fontSize:14,marginBottom:16,paddingBottom:10,borderBottom:"1px solid #1e3a4f"};function x$(){const{profile:e}=Ee(),[n,r]=g.useState("payment"),[s,i]=g.useState([]),[o,a]=g.useState(null),[l,d]=g.useState(null),[c,f]=g.useState(!0),p=(e==null?void 0:e.role)==="admin"||(e==null?void 0:e.role)==="super_admin";g.useEffect(()=>{u()},[e]);async function u(){if(e!=null&&e.id){f(!0);try{const{data:h}=await w.from("profiles").select("tenant_id").eq("id",e.id).single();if(!(h!=null&&h.tenant_id))return;d(h.tenant_id);const{data:y}=await w.from("branches").select("id, name, code, is_active, is_default").eq("tenant_id",h.tenant_id).eq("is_active",!0).order("is_default",{ascending:!1}).order("name");if(y&&y.length>0){i(y);const m=y.find(b=>b.is_default)||y[0];a(m.id)}}finally{f(!1)}}}return p?c?t.jsx("div",{style:{textAlign:"center",color:"#64748b",padding:"48px 0"},children:"Loading..."}):t.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%"},children:[t.jsxs("div",{style:{flexShrink:0,marginBottom:20},children:[t.jsx("h1",{style:{color:"#e2e8f0",fontWeight:700,fontSize:22,margin:0},children:"Account Settings"}),t.jsx("p",{style:{color:"#64748b",fontSize:13,marginTop:4},children:"Configure payment, financing, branding, and banking for your account"})]}),s.length>1&&t.jsx("div",{style:{flexShrink:0,marginBottom:20},children:t.jsx("div",{style:{..._s,padding:16},children:t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12},children:[t.jsx("span",{style:{fontSize:11,color:"#64748b",fontWeight:700,textTransform:"uppercase",letterSpacing:"0.05em",flexShrink:0},children:"Configuring Branch:"}),t.jsx("div",{style:{display:"flex",gap:8,flexWrap:"wrap"},children:s.map(h=>t.jsxs("button",{onClick:()=>a(h.id),style:{padding:"6px 14px",borderRadius:20,fontSize:12,fontWeight:600,cursor:"pointer",background:o===h.id?"rgba(13,126,163,0.2)":"rgba(255,255,255,0.04)",border:`1px solid ${o===h.id?"#0d7ea3":"#1e3a4f"}`,color:o===h.id?"#38bdf8":"#64748b"},children:[h.name," ",t.jsxs("span",{style:{opacity:.6},children:["(",h.code,")"]}
630),h.is_default&&t.jsx("span",{style:{marginLeft:4,fontSize:10,color:"#4ade80"},children:"â
Default"})]},h.id))}),t.jsx("div",{style:{marginLeft:"auto",fontSize:11,color:"#334155"},children:"Contact support to add new branches"})]})})}),t.jsx("div",{style:{display:"grid",gridTemplateColumns:`repeat(${w_.length}, 1fr)`,gap:8,flexShrink:0,marginBottom:20},children:w_.map(h=>{const y=n===h.key;return t.jsxs("button",{onClick:()=>r(h.key),style:{display:"flex",alignItems:"center",gap:10,padding:"14px 20px",borderRadius:14,textAlign:"left",background:y?`${h.color}15`:"rgba(255,255,255,0.03)",border:`1px solid ${y?h.color+"50":"rgba(255,255,255,0.06)"}`,boxShadow:y?`0 0 18px ${h.color}18`:"none",cursor:"pointer"},children:[t.jsx("span",{style:{fontSize:18},children:h.icon}),t.jsx("div",{children:t.jsx("div",{style:{fontSize:12,fontWeight:700,color:y?h.color:"#64748b"},children:h.label})}),y&&t.jsx("div",{style:{marginLeft:"auto",width:8,height:8,borderRadius:"50%",backgroundColor:h.color,boxShadow:`0 0 8px ${h.color}`}})]},h.key)})}),t.jsx("div",{style:{flex:1,overflowY:"auto"},children:l&&t.jsxs(t.Fragment,{children:[n==="payment"&&t.jsx(b$,{tenantId:l,branchId:o}),n==="financing"&&t.jsx(A$,{tenantId:l,branchId:o}),n==="shipping"&&t.jsx(v$,{tenantId:l,branchId:o}),n==="branding"&&t.jsx(_$,{tenantId:l}),n==="bank"&&t.jsx(w$,{tenantId:l})]})})]}):t.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100%"},children:[t.jsx("div",{style:{fontSize:48,marginBottom:16},children:"ð"}),t.jsx("h2",{style:{color:"#e2e8f0",fontWeight:700,fontSize:20},children:"Admin Access Only"}),t.jsx("p",{style:{color:"#64748b",marginTop:8},children:"You don't have permission to view this page."})]})}async function Rr(e,n,r,s,i,o){let a=w.from("tenant_api_credentials").select("id").eq("tenant_id",e).eq("service",r).eq("credential_key",s);a=n?a.eq("branch_id",n):a.is("branch_id",null);const{data:l}=await a.maybeSingle();if(l){const{error:d}=await w.from("tenant_api_credentials").update({credential_value:i,is_active:!0,connected_at:new Date().toISOString(),...o}).eq("id",l.id);if(d)throw d}else{const{error:d}=await w.from("tenant_api_credentials").insert({tenant_id:e,branch_id:n,service:r,credential_key:s,credential_value:i,is_active:!0,connected_at:new Date().toISOString(),...o});if(d)throw d}}async function y$(e,n,r){let s=w.from("tenant_api_credentials").delete().eq("tenant_id",e).eq("service",r);s=n?s.eq("branch_id",n):s.is("branch_id",null),await s}async function Mk(e,n,r){let s=w.from("tenant_api_credentials").select("credential_key, credential_value, payment_gateway").eq("tenant_id",e).eq("service",r).eq("is_active",!0);s=n?s.eq("branch_id",n):s.is("branch_id",null);const{data:i}=await s,o={};for(const a of i||[])o[a.credential_key]=a.credential_value,a.payment_gateway&&(o._gateway=a.payment_gateway);return o}function Ld({label:e,value:n,onChange:r,placeholder:s,show:i,required:o=!1}){return t.jsxs("div",{children:[t.jsxs("label",{style:jn,children:[e," ",o&&t.jsx("span",{style:{color:"#f87171"},children:"*"})]}),t.jsx("input",{value:n,onChange:a=>r(a.target.value),placeholder:s,style:{...Mn,filter:i?"none":n?"blur(4px)":"none",transition:"filter 0.2s",userSelect:i?"auto":"none"},autoComplete:"off"})]})}function b$({tenantId:e,branchId:n}){const[r,s]=g.useState("stripe"),[i,o]=g.useState({gateway:"stripe",stripe_secret_key:"",stripe_publishable_key:"",stripe_webhook_secret:"",authorize_login_id:"",authorize_transaction_key:""}),[a,l]=g.useState(!1),[d,c]=g.useState(!1),[f,p]=g.useState(!0),[u,h]=g.useState(!1),[y,m]=g.useState(!1),[b,A]=g.useState("");g.useEffect(()=>{v()},[e,n]);async function v(){p(!0);try{const _=await Mk(e,n,"payment_config"),j=_._gateway||_.gateway||"stripe";s(j);const C=j==="authorize_net"?"authorize_net":"stripe",{count:S}=await w.from("tenant_api_credentials").select("id",{count:"exact",head:!0}).eq("tenant_id",e).eq("service",C).eq("is_active",!0);l((S||0)>0),o({gateway:j,stripe_secret_key:"",stripe_publishable_key:"",stripe_webhook_secret:"",authorize_login_id:"",authorize_transaction_key:""})}finally{p(!1)}}async function x(){h(!0),A(""),m(!1);try{if(await Rr(e,n,"payment_config","gateway",r,{payment_gateway:r,payments_enabled:r!=="manual"}),r==="stripe"){if(i.stripe_secret_key){if(!i.stripe_secret_key.startsWith("sk_"))throw new Error("Stripe secret key must start with sk_");if(!i.stripe_publishable_key.startsWith("pk_"))throw new Error("Publishable key must start with pk_");
630await Rr(e,n,"stripe","secret_key",i.stripe_secret_key),await Rr(e,n,"stripe","publishable_key",i.stripe_publishable_key),i.stripe_webhook_secret&&await Rr(e,n,"stripe","webhook_secret",i.stripe_webhook_secret),l(!0)}else if(!a)throw new Error("Stripe keys are required â enter your secret and publishable keys")}else if(r==="authorize_net"){if(i.authorize_login_id){if(!i.authorize_transaction_key)throw new Error("Transaction Key is required");await Rr(e,n,"authorize_net","login_id",i.authorize_login_id),await Rr(e,n,"authorize_net","transaction_key",i.authorize_transaction_key),l(!0)}else if(!a)throw new Error("Authorize.net credentials are required")}m(!0),setTimeout(()=>m(!1),3e3)}catch(_){A(_.message||"Failed to save")}h(!1)}return f?t.jsx("div",{style:{textAlign:"center",color:"#64748b",padding:48},children:"Loading..."}):t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:20},children:t.jsxs("div",{style:_s,children:[t.jsx("div",{style:Hs,children:"Payment Gateway"}),t.jsx("p",{style:{color:"#64748b",fontSize:12,marginBottom:20},children:"Choose how customers pay online. Credentials are stored securely and never exposed to the frontend."}),t.jsxs("div",{style:{marginBottom:20},children:[t.jsx("label",{style:jn,children:"Payment Provider"}),t.jsx("div",{style:{display:"flex",gap:10},children:m$.map(_=>t.jsx("button",{onClick:()=>s(_.value),style:{flex:1,padding:"12px 16px",borderRadius:12,cursor:"pointer",background:r===_.value?"rgba(74,222,128,0.1)":"rgba(255,255,255,0.03)",border:`2px solid ${r===_.value?"#4ade80":"#1e3a4f"}`,color:r===_.value?"#4ade80":"#64748b",fontWeight:r===_.value?700:400,fontSize:13},children:_.label},_.value))})]}),r==="stripe"&&t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:14},children:[t.jsxs("div",{style:{background:"rgba(99,102,241,0.06)",border:"1px solid rgba(99,102,241,0.2)",borderRadius:10,padding:"10px 14px",fontSize:12,color:"#818cf8"},children:["ð¡ Find your keys at ",t.jsx("strong",{children:"dashboard.stripe.com â Developers â API keys"})]}),a&&t.jsx("div",{style:{background:"rgba(74,222,128,0.08)",border:"1px solid rgba(74,222,128,0.2)",borderRadius:10,padding:"10px 14px",fontSize:12,color:"#4ade80"},children:"â
Stripe keys are configured. Leave fields empty to keep existing keys, or enter new values to update them."}),t.jsx(Ld,{label:"Secret Key",value:i.stripe_secret_key,onChange:_=>o(j=>({...j,stripe_secret_key:_})),placeholder:a?"Leave empty to keep existing key":"sk_live_...",show:d,required:!a}),t.jsx(Ld,{label:"Publishable Key",value:i.stripe_publishable_key,onChange:_=>o(j=>({...j,stripe_publishable_key:_})),placeholder:a?"Leave empty to keep existing key":"pk_live_...",show:d,required:!a}),t.jsx(Ld,{label:"Webhook Secret (optional â for payment confirmation webhooks)",value:i.stripe_webhook_secret,onChange:_=>o(j=>({...j,stripe_webhook_secret:_})),placeholder:a?"Leave empty to keep existing key":"whsec_...",show:d}),t.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer"},children:[t.jsx("input",{type:"checkbox",checked:d,onChange:_=>c(_.target.checked),style:{width:14,height:14,accentColor:"#4ade80"}}),t.jsx("span",{style:{fontSize:12,color:"#64748b"},children:"Show keys"})]})]}),r==="authorize_net"&&t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:14},children:[t.jsxs("div",{style:{background:"rgba(99,102,241,0.06)",border:"1px solid rgba(99,102,241,0.2)",borderRadius:10,padding:"10px 14px",fontSize:12,color:"#818cf8"},children:["ð¡ Find your credentials at ",t.jsx("strong",{children:"account.authorize.net â Account â Settings â API Credentials"})]}),a&&t.jsx("div",{style:{background:"rgba(74,222,128,0.08)",border:"1px solid rgba(74,222,128,0.2)",borderRadius:10,padding:"10px 14px",fontSize:12,color:"#4ade80"},children:"â
Authorize.net credentials configured. Leave fields empty to keep existing, or enter new values to update."}),t.jsx(Ld,{label:"API Login ID",value:i.authorize_login_id,onChange:_=>o(j=>({...j,authorize_login_id:_})),placeholder:a?"Leave empty to keep existing":"Your API Login ID",show:d,required:!a}),t.jsx(Ld,{label:"Transaction Key",value:i.authorize_transaction_key,onChange:_=>o(j=>({...j,authorize_transaction_key:_})),placeholder:a?"Leave empty to keep existing":"Your Transaction Key",show:d,required:!a}),t.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer"},children:[t.jsx("input",{type:"checkbox",checked:d,onChange:_=>c(_.target.checked),style:{width:14,height:14,accentColor:"#4ade80"}}),t.jsx("span",{style:{fontSize:12,color:"#64748b"},children:"Show credentials"})]})]}),r==="manual"&&t.jsx("div",{style:{background:"rgba(251,191,36,0.06)",border:"1px solid rgba(251,191,36,0.2)",borderRadius:10,padding:"14px",fontSize:13,color:"#fbbf24"},children:"â ï¸ Manual mode â no online payments. Customers will see bank/ACH details only. Configure those in the Bank / ACH tab."}),b&&t.jsxs("div",{style:{marginTop:16,background:"rgba(248,113,113,0.08)",border:"1px solid rgba(248,113,113,0.3)",borderRadius:10,padding:"8px 14px",fontSize:12,color:"#f87171"},children:["â ",b]}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,marginTop:20},children:[t.jsx("button",{onClick:x,disabled:u,style:{padding:"10px 24px",borderRadius:10,fontSize:13,fontWeight:700,color:"#fff",background:"linear-gradient(135deg, #4ade80, #22c55e)",border:"none",cursor:u?"not-allowed":"pointer",opacity:u?.5:1},children:u?"Saving...":"Save Payment Settings"}),y&&t.jsx("span",{style:{fontSize:13,color:"#4ade80",fontWeight:600},children:"â
Saved successfully"})]})]})})}function A$({tenantId:e,branchId:n}){var m;const[r,s]=g.useState({provider:"",apply_url:"",settlement_type:"direct_to_customer"}),[i,o]=g.useState(!0),[a,l]=g.useState(!1),[d,c]=g.useState(!1),[f,p]=g.useState("");g.useEffect(()=>{u()},[e,n]);async function u(){o(!0);try{const b=await Mk(e,n,"financing");s({provider:b.provider||"",apply_url:b.apply_url||"",settlement_type:b.settlement_type||"direct_to_customer"})}finally{o(!1)}}async function h(){l(!0),p(""),c(!1);try{if(!r.provider)await y$(e,n,"financing");else{if(!r.apply_url)throw new Error("Application URL is required when a provider is selected");if(!r.apply_url.startsWith("http"))throw new Error("Application URL must be a valid URL starting with http");await Rr(e,n,"financing","provider",r.provider),await Rr(e,n,"financing","apply_url",r.apply_url),await Rr(e,n,"financing","settlement_type",r.settlement_type)}c(!0),setTimeout(()=>c(!1),3e3)}catch(b){p(b.message||"Failed to save")}l(!1)}if(i)return t.jsx("div",{style:{textAlign:"center",color:"#64748b",padding:48},children:"Loading..."});const y=((m=S_.find(b=>b.value===r.provider))==null?void 0:m.label)||"";return t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:20},children:t.jsxs("div",{style:_s,children:[t.jsx("div",{style:Hs,children:"Financing Configuration"}),t.jsx("p",{style:{color:"#64748b",fontSize:12,marginBottom:20},children:'Enable financing quotes for your customers. When configured, a "Financed" quote type becomes available in the quote builder. After signing, customers are redirected to your financing partner to apply.'}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[t.jsxs("div",{children:[t.jsx("label",{style:jn,children:"Financing Provider"}
630),t.jsx("select",{value:r.provider,onChange:b=>s(A=>({...A,provider:b.target.value})),style:{...Mn,fontFamily:"inherit"},children:S_.map(b=>t.jsx("option",{value:b.value,style:{background:"#0f1923"},children:b.label},b.value))})]}),r.provider&&t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[t.jsxs("div",{children:[t.jsxs("label",{style:jn,children:["Partner Application URL ",t.jsx("span",{style:{color:"#f87171"},children:"*"})]}),t.jsx("input",{value:r.apply_url,onChange:b=>s(A=>({...A,apply_url:b.target.value})),placeholder:r.provider==="hearth"?"https://app.gethearth.com/partners/your-company/your-name/apply":r.provider==="greensky"?"https://greensky.com/apply/your-merchant-id":"https://your-financing-partner.com/apply/your-id",style:{...Mn,fontFamily:"inherit"}}),t.jsx("div",{style:{fontSize:11,color:"#64748b",marginTop:6},children:"Customer info (name, email, phone, amount) will be pre-filled in the URL automatically."})]}),t.jsxs("div",{children:[t.jsxs("label",{style:jn,children:["How Does ",y," Pay You?"]}),t.jsxs("div",{style:{display:"flex",gap:10},children:[t.jsxs("button",{onClick:()=>s(b=>({...b,settlement_type:"direct_to_customer"})),style:{flex:1,padding:"12px 16px",borderRadius:12,cursor:"pointer",textAlign:"left",background:r.settlement_type==="direct_to_customer"?"rgba(244,114,182,0.1)":"rgba(255,255,255,0.03)",border:`2px solid ${r.settlement_type==="direct_to_customer"?"#f472b6":"#1e3a4f"}`},children:[t.jsx("div",{style:{fontWeight:700,fontSize:13,color:r.settlement_type==="direct_to_customer"?"#f472b6":"#94a3b8",marginBottom:4},children:"ð¸ Direct to Customer"}),t.jsx("div",{style:{fontSize:11,color:"#64748b"},children:"Financing company deposits funds into customer's bank. You then collect payment from the customer via Stripe/Authorize.net."})]}),t.jsxs("button",{onClick:()=>s(b=>({...b,settlement_type:"direct_to_merchant"})),style:{flex:1,padding:"12px 16px",borderRadius:12,cursor:"pointer",textAlign:"left",background:r.settlement_type==="direct_to_merchant"?"rgba(74,222,128,0.1)":"rgba(255,255,255,0.03)",border:`2px solid ${r.settlement_type==="direct_to_merchant"?"#4ade80":"#1e3a4f"}`},children:[t.jsx("div",{style:{fontWeight:700,fontSize:13,color:r.settlement_type==="direct_to_merchant"?"#4ade80":"#94a3b8",marginBottom:4},children:"ð¦ Direct to Merchant"}),t.jsx("div",{style:{fontSize:11,color:"#64748b"},children:"Financing company deposits funds directly into your merchant account. No further billing of the customer required."})]})]})]}),t.jsxs("div",{style:{background:"rgba(13,126,163,0.06)",border:"1px solid rgba(13,126,163,0.2)",borderRadius:12,padding:16},children:[t.jsx("div",{style:{fontSize:11,color:"#38bdf8",fontWeight:700,textTransform:"uppercase",letterSpacing:"0.05em",marginBottom:10},children:"ð How This Flow Works"}),t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:['Rep creates a "Financed" quote and sends to customer',`Customer signs quote â redirected to ${y} to apply`,'Rep marks application "Approved" or "Declined" in CRM',r.settlement_type==="direct_to_customer"?`Approved â system auto-creates invoice + sends customer payment link (${y} deposited funds into their account)`:`Approved â payment marked as received (${y} deposited funds into your account)`,"Declined â rep clones quote as Rental or Purchase and resends"].map((b,A)=>t.jsxs("div",{style:{display:"flex",gap:10,alignItems:"flex-start"},children:[t.jsx("div",{style:{width:20,height:20,borderRadius:"50%",flexShrink:0,background:"rgba(13,126,163,0.2)",border:"1px solid rgba(13,126,163,0.4)",display:"flex",alignItems:"center",justifyContent:"center",fontSize:10,fontWeight:700,color:"#38bdf8"},children:A+1}),t.jsx("div",{style:{fontSize:12,color:"#94a3b8",lineHeight:1.5},children:b})]},A))})]})]}),!r.provider&&t.jsx("div",{style:{background:"rgba(100,116,139,0.06)",border:"1px solid rgba(100,116,139,0.15)",borderRadius:10,padding:16,fontSize:13,color:"#64748b",textAlign:"center"},children:'No financing provider selected â "Financed" quote type will be hidden from the quote builder.'})]}),f&&t.jsxs("div",{style:{marginTop:16,background:"rgba(248,113,113,0.08)",border:"1px solid rgba(248,113,113,0.3)",borderRadius:10,padding:"8px 14px",fontSize:12,color:"#f87171"},children:["â ",f]}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,marginTop:20},children:[t.jsx("button",{onClick:h,disabled:a,style:{padding:"10px 24px",borderRadius:10,fontSize:13,fontWeight:700,color:"#fff",background:"linear-gradient(135deg, #f472b6, #ec4899)",border:"none",cursor:a?"not-allowed":"pointer",opacity:a?.5:1},children:a?"Saving...":"Save Financing Settings"}),d&&t.jsx("span",{style:{fontSize:13,color:"#4ade80",fontWeight:600},children:"â
Saved successfully"})]})]})})}function v$({tenantId:e,branchId:n}){const[r,s]=g.useState({fedex_api_key:"",fedex_secret_key:"",fedex_account_number:""}),[i,o]=g.useState(!1),[a,l]=g.useState(!1),[d,c]=g.useState(!0),[f,p]=g.useState(!1),[u,h]=g.useState(!1),[y,m]=g.useState(""),[b,A]=g.useState(!1),[v,x]=g.useState(null);g.useEffect(()=>{_()},[e,n]);async function _(){c(!0);try{const{count:S}=await w.from("tenant_api_credentials").select("id",{count:"exact",head:!0}).eq("tenant_id",e).eq("service","fedex").eq("is_active",!0);o((S||0)>0),s({fedex_api_key:"",fedex_secret_key:"",fedex_account_number:""})}finally{c(!1)}}async function j(){p(!0),m(""),h(!1);try{if(r.fedex_api_key){if(!r.fedex_secret_key)throw new Error("Secret Key is required");if(!r.fedex_account_number)throw new Error("Account Number is required");await Rr(e,n,"fedex","api_key",r.fedex_api_key),await Rr(e,n,"fedex","secret_key",r.fedex_secret_key),await Rr(e,n,"fedex","account_number",r.fedex_account_number),o(!0)}else if(!i)throw new Error("FedEx credentials are required â enter your API Key, Secret Key, and Account Number");h(!0),setTimeout(()=>h(!1),3e3)}catch(S){m(S.message||"Failed to save")}p(!1)}async function C(){A(!0),x(null);try{const T=await(await fetch("/api/shipping/fedex-test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tenantId:e,branchId:n})})).json();T.ok?x({ok:!0,message:`Connected to FedEx ${T.environment==="production"?"production":"sandbox"}${T.account_number_preview?` (acct ${T.account_number_preview})`:""}`,environment:T.environment}):x({ok:!1,message:typeof T.error=="string"?T.error:"Connection failed",environment:T.environment})}catch(S){x({ok:!1,message:S.message||"Network error"})}A(!1)}return d?t.jsx("div",{style:{textAlign:"center",color:"#64748b",padding:48},children:"Loading..."}):t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:20},children:t.jsxs("div",{style:_s,children:[t.jsx("div",{style:Hs,children:"FedEx Shipping"}),t.jsx("p",{style:{color:"#64748b",fontSize:12,marginBottom:20},children:"Connect your FedEx account to print shipping labels and track packages. Credentials are stored securely and never exposed to the frontend."}),i&&t.jsx("div",{style:{background:"rgba(74,222,128,0.08)",border:"1px solid rgba(74,222,128,0.3)",borderRadius:12,padding:12,marginBottom:16,fontSize:12,color:"#4ade80"},children:"â FedEx credentials configured. Re-enter all three fields to update."}),t.jsxs("div",{style:{background:"rgba(13,126,163,0.06)",border:"1px solid rgba(13,126,163,0.2)",borderRadius:12,padding:12,marginBottom:16,fontSize:12,color:"#38bdf8"},children:["ð¡ Find your keys at ",t.jsx("strong",{children:"developer.fedex.com â My Projects"}),". You need API Key, Secret Key, and your FedEx Account Number."]}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[t.jsxs("div",{children:[t.jsx("label",{style:jn,children:"API Key"}),t.jsx("input",{type:a?"text":"password",value:r.fedex_api_key,onChange:S=>s(T=>({...T,fedex_api_key:S.target.value})),placeholder:"l7xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",style:{...Mn,fontFamily:"monospace"}})]}),t.jsxs("div",{children:[t.jsx("label",{style:jn,children:"Secret Key"}),t.jsx("input",{type:a?"text":"password",value:r.fedex_secret_key,onChange:S=>s(T=>({...T,fedex_secret_key:S.target.value})),placeholder:"â¢â¢â¢â¢â¢â¢â¢â¢â¢â¢â¢â¢â¢â¢â¢â¢â¢â¢â¢â¢â¢â¢â¢â¢â¢â¢â¢â¢â¢â¢â¢â¢",style:{...Mn,fontFamily:"monospace"}})]}),t.jsxs("div",{children:[t.jsx("label",{style:jn,children:"Account Number"}),t.jsx("input",{type:"text",value:r.fedex_account_number,onChange:S=>s(T=>({...T,fedex_account_number:S.target.value})),placeholder:"123456789",style:{...Mn,fontFamily:"monospace"}})]}),t.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,fontSize:12,color:"#94a3b8",curs
630or:"pointer"},children:[t.jsx("input",{type:"checkbox",checked:a,onChange:S=>l(S.target.checked)}),"Show secrets"]})]}),v&&t.jsxs("div",{style:{marginTop:16,background:v.ok?"rgba(74,222,128,0.08)":"rgba(248,113,113,0.08)",border:`1px solid ${v.ok?"rgba(74,222,128,0.3)":"rgba(248,113,113,0.3)"}`,borderRadius:12,padding:12,fontSize:12,color:v.ok?"#4ade80":"#f87171"},children:[v.ok?"â":"â"," ",v.message]}),y&&t.jsx("div",{style:{marginTop:16,background:"rgba(248,113,113,0.08)",border:"1px solid rgba(248,113,113,0.3)",borderRadius:12,padding:12,fontSize:12,color:"#f87171"},children:y}),t.jsxs("div",{style:{display:"flex",gap:10,marginTop:20},children:[t.jsx("button",{onClick:C,disabled:b||!i&&!r.fedex_api_key,style:{padding:"10px 18px",borderRadius:10,background:"rgba(167,139,250,0.1)",border:"1px solid rgba(167,139,250,0.3)",color:"#a78bfa",fontWeight:600,fontSize:13,cursor:b||!i&&!r.fedex_api_key?"not-allowed":"pointer",opacity:b||!i&&!r.fedex_api_key?.5:1},children:b?"Testingâ¦":"Test Connection"}),t.jsx("button",{onClick:j,disabled:f,style:{padding:"10px 18px",borderRadius:10,background:"#a78bfa",border:"none",color:"#0f1923",fontWeight:700,fontSize:13,cursor:f?"not-allowed":"pointer",opacity:f?.5:1},children:f?"Savingâ¦":u?"â Saved":"Save"})]})]})})}function _$({tenantId:e}){const[n,r]=g.useState({company_name:"",phone:"",email:"",address_line1:"",city:"",state:"",zip:"",logo_url:"",tagline:"",website:"",owner_name:"",accounts_email:"",bank_name:"",bank_routing:"",bank_account:"",bank_account_name:"",google_review_url:"",tax_rate:.07}),[s,i]=g.useState(!0),[o,a]=g.useState(!1),[l,d]=g.useState(!1),[c,f]=g.useState("");g.useEffect(()=>{p()},[e]);async function p(){i(!0);try{const{data:y}=await w.from("tenants").select("company_name, phone, email, address_line1, city, state, zip, logo_url, tagline, website, owner_name, accounts_email, bank_name, bank_routing, bank_account, bank_account_name, google_review_url, tax_rate").eq("id",e).single();y&&r({company_name:y.company_name||"",phone:y.phone||"",email:y.email||"",address_line1:y.address_line1||"",city:y.city||"",state:y.state||"",zip:y.zip||"",logo_url:y.logo_url||"",tagline:y.tagline||"",website:y.website||"",owner_name:y.owner_name||"",accounts_email:y.accounts_email||"",bank_name:y.bank_name||"",bank_routing:y.bank_routing||"",bank_account:y.bank_account||"",bank_account_name:y.bank_account_name||"",google_review_url:y.google_review_url||"",tax_rate:typeof y.tax_rate=="number"?y.tax_rate:.07})}finally{i(!1)}}async function u(){a(!0),f(""),d(!1);try{const{error:y}=await w.from("tenants").update({company_name:n.company_name,phone:n.phone,email:n.email,address_line1:n.address_line1,city:n.city,state:n.state,zip:n.zip,logo_url:n.logo_url,tagline:n.tagline,website:n.website,owner_name:n.owner_name,accounts_email:n.accounts_email,google_review_url:n.google_review_url,tax_rate:n.tax_rate}).eq("id",e);if(y)throw y;d(!0),setTimeout(()=>d(!1),3e3)}catch(y){f(y.message||"Failed to save")}a(!1)}if(s)return t.jsx("div",{style:{textAlign:"center",color:"#64748b",padding:48},children:"Loading..."});const h=(y,m,b,A="text")=>t.jsxs("div",{children:[t.jsx("label",{style:jn,children:y}),t.jsx("input",{type:A,value:String(n[m]),onChange:v=>r(x=>({...x,[m]:A==="number"?parseFloat(v.target.value)||0:v.target.value})),placeholder:b,style:{...Mn,fontFamily:"inherit"}})]});return t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:20},children:[t.jsxs("div",{style:_s,children:[t.jsx("div",{style:Hs,children:"Company Information"}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:14},children:[h("Company Name","company_name","Zenith Pure Solutions"),h("Owner / Authorized Rep Name","owner_name","John Smith"),h("Phone","phone","(555) 000-0000"),h("Email","email","[email protected]","email"),h("Accounts / Billing Email","accounts_email","[email protected]","email"),h("Website","website","https://yourcompany.com","url")]}),t.jsx("div",{style:{marginTop:14},children:h("Tagline","tagline","Pure water for every home")})]}),t.jsxs("div",{style:_s,children:[t.jsx("div",{style:Hs,children:"Address"}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:14},children:[h("Street Address","address_line1","123 Main St"),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"2fr 1fr 1fr",gap:12},children:[h("City","city","Indianapolis"),h("State","state","IN"),h("ZIP","zip","46201")]})]})]}),t.jsxs("div",{style:_s,children:[t.jsx("div",{style:Hs,children:"Logo & Reviews"}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:14},children:[h("Logo URL","logo_url","https://yourcompany.com/logo.png","url"),n.logo_url&&t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,padding:12,background:"rgba(255,255,255,0.03)",borderRadius:10,border:"1px solid #1e3a4f"},children:[t.jsx("img",{src:n.logo_url,alt:"Logo preview",style:{height:40,objectFit:"contain"},onError:y=>{y.currentTarget.style.display="none"}}),t.jsx("span",{style:{fontSize:12,color:"#64748b"},children:"Logo preview"})]}),h("Google Review URL","google_review_url","https://g.page/r/your-review-link"),t.jsx("div",{style:{fontSize:11,color:"#64748b"},children:"Google review link is sent to customers via SMS after installation."})]})]}),t.jsxs("div",{style:_s,children:[t.jsx("div",{style:Hs,children:"Tax Rate"}),t.jsxs("div",{style:{maxWidth:200},children:[t.jsx("label",{style:jn,children:"Sales Tax Rate (%)"}),t.jsx("input",{type:"number",step:"0.01",min:"0",max:"20",value:(n.tax_rate*100).toFixed(2),onChange:y=>r(m=>({...m,tax_rate:parseFloat(y.target.value)/100||0})),style:{...Mn,fontFamily:"inherit"}}),t.jsxs("div",{style:{fontSize:11,color:"#64748b",marginTop:6},children:["Applied to all charges including install fees, rentals, and service plans. Current: ",(n.tax_rate*100).toFixed(2),"%"]})]})]}),t.jsx(j$,{tenantId:e}),c&&t.jsxs("div",{style:{background:"rgba(248,113,113,0.08)",border:"1px solid rgba(248,113,113,0.3)",borderRadius:10,padding:"8px 14px",fontSize:12,color:"#f87171"},children:["â ",c]}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12},children:[t.jsx("button",{onClick:u,disabled:o,style:{padding:"10px 24px",borderRadius:10,fontSize:13,fontWeight:700,color:"#fff",background:"linear-gradient(135deg, #22d3ee, #0891b2)",border:"none",cursor:o?"not-allowed":"pointer",opacity:o?.5:1},children:o?"Saving...":"Save Branding"}),l&&t.jsx("span",{style:{fontSize:13,color:"#4ade80",fontWeight:600},children:"â
Saved successfully"})]})]})}const pm=(()=>{const e=[];for(let n=6*60;n<=22*60;n+=30)e.push(n);return e})();function wo(e){const n=Math.floor(e/60),r=String(e%60).padStart(2,"0");return n===0?`12:${r} AM`:n<12?`${n}:${r} AM`:n===12?`12:${r} PM`:`${n-12}:${r} PM`}function k_(e){return pm.includes(e)?pm:[...pm,e].sort((n,r)=>n-r)}function j$({tenantId:e}){const[n,r]=g.useState(540),[s,i]=g.useState(1020),[o,a]=g.useState(60),[l,d]=g.useState(!0),[c,f]=g.useState(!1),[p,u]=g.useState(!1),[h,y]=g.useState("");g.useEffect(()=>{m()},[e]);async function m(){d(!0);const{data:x,error:_}=await w.from("tenants").select("visit_day_start_minutes, visit_day_end_minutes, visit_duration_minutes").eq("id",e).maybeSingle();_&&y(_.message),x&&(r(Number(x.visit_day_start_minutes??540)),i(Number(x.visit_day_end_minutes??1020)),a(Number(x.visit_duration_minutes??60))),d(!1)}const b=s-o,A=b<n;async function v(){if(f(!0),y(""),u(!1),s<=n){y("The day must end after it starts."),f(!1);return}if(A){y(`A ${o}-minute visit does not fit between ${wo(n)} and ${wo(s)}, so no slots would be offered at all.`),f(!1);return}const{error:x}=await w.from("tenants").update({visit_day_start_minutes:n,visit_day_end_minutes:s,visit_duration_minutes:o}).eq("id",e);if(x){y(x.message),f(!1);return}u(!0),setTimeout(()=>u(!1),3e3),f(!1)}return l?null:t.jsxs("div",{style:_s,children:[t.jsx("div",{style:Hs,children:"Site Visit Scheduling"}),t.jsx("p",{style:{color:"#64748b",fontSize:12,marginBottom:20},children:"Controls the times offered in the Schedule Site Visit popup. Slots start every 30 minutes."}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(170px, 1fr))",gap:16},children:[t.jsxs("div",{children:[t.jsx("label",{style:jn,children:"Day starts at"}),t.jsx("select",{value:n,onChange:x=>r(+x.target.value),style:Mn,children:k_(n).map(x=>t.jsx("option",{value:x,children:wo(x)},x))})]}),t.jsxs("div",{children:[t.jsx("label",{style:jn,children:"Day ends at"}),t.jsx("select",{value:s,onChange:x=>i(+x.target.value),style:Mn,children:k_(s).map(x=>t.jsx("option",{value:x,children:wo(x)},x))})]}),t.jsxs("div",{children:[t.jsx("label",{style:jn,children:"Visit length"}),t.jsxs("select",{value:o,onChange:x=>a(+x.target.value),style:Mn,children:[t.jsx("option",{value:30,children:"30 minutes"}),t.jsx("option",{value:60,children:"1 hour"}),t.jsx("option",{value:90,children:"1 hour 30 minutes"}),t.jsx("option",{value:120,children:"2 hours"})]})]})]}),t.jsx("div",{style:{fontSize:12,marginTop:14,color:A?"#f87171":"#94a3b8"},children:A?`A ${o}-minute visit does not fit in this window, so no slots would be offered.`:`First slot ${wo(n)}, last slot ${wo(b)} â that visit finishes at ${wo(s)}. "Day ends at" is closing time, not the last appointment.`}),h&&t.jsxs("div",{style:{marginTop:12,fontSize:12,color:"#f87171"},children:["â ",h]}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,marginTop:16},children:[t.jsx("button",{onClick:v,disabled:c,style:{padding:"10px 24px",borderRadius:10,fontSize:13,fontWeight:700,color:"#fff",background:"linear-gradient(135deg, #22d3ee, #0891b2)",border:"none",cursor:c?"not-allowed":"pointer",opacity:c?.5:1},children:c?"Saving...":"Save Scheduling"}),p&&t.jsx("span",{style:{fontSize:13,color:"#4ade80",fontWeight:600},children:"â
Saved successfully"})]})]})}function w$({tenantId:e}){const[n,r]=g.useState({bank_name:"",bank_routing:"",bank_account:"",bank_account_name:""}),[s,i]=g.useState(!0),[o,a]=g.useState(!1),[l,d]=g.useState(!1),[c,f]=g.useState(""),[p,u]=g.useState(!1);g.useEffect(()=>{h()},[e]);async function h(){i(!0);try{const{data:m}=await w.from("tenants").select("bank_name, bank_routing, bank_account, bank_account_name").eq("id",e).single();m&&r({bank_name:m.bank_name||"",bank_routing:m.bank_routing||"",bank_account:m.bank_account||"",bank_account_name:m.bank_account_name||""})}finally{i(!1)}}async function y(){a(!0),f(""),d(!1);try{const{error:m}=await w.from("tenants").update(n).eq("id",e);if(m)throw m;d(!0),setTimeout(()=>d(!1),3e3)}catch(m){f(m.message||"Failed to save")}a(!1)}return s?t.jsx("div",{style:{textAlign:"center",color:"#64748b",padding:48},children:"Loading..."}):t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:20},children:t.jsxs("div",{style:_s,children:[t.jsx("div",{style:Hs,children:"Bank / ACH Details"}),t.jsx("p",{style:{color:"#64748b",fontSize:12,marginBottom:20},children:"These details appear on purchase invoices so customers can pay via bank transfer or ACH. Only shown when payment gateway is set to Manual, or as an alternative payment method."}),t.jsxs("div",{style:{background:"rgba(251,191,36,0.06)",border:"1px solid rgba(251,191,36,0.2)",borderRadius:10,padding:"10px 14px",marginBottom:20,fontSize:12,color:"#fbbf24",display:"flex",gap:8},children:[t.jsx("span",{children:"â ï¸"}),t.jsx("span",{children:"Bank details are shown on customer invoices. Double-check routing and account numbers before saving."})]}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:14},children:[t.jsxs("div",{children:[t.jsx("label",{style:jn,children:"Bank Name"}),t.jsx("input",{value:n.bank_name,onChange:m=>r(b=>({...b,bank_name:m.target.value})),placeholder:"Chase Bank",style:{...Mn,fontFamily:"inherit"}})]}),t.jsxs("div",{children:[t.jsx("label",{style:jn,children:"Account Name"}),t.jsx("input",{value:n.bank_account_name,onChange:m=>r(b=>({...b,bank_account_name:m.target.value})),placeholder:"Zenith Pure Solutions LLC",style:{...Mn,fontFamily:"inherit"}})]}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12},children:[t.jsxs("div",{children:[t.jsx("label",{style:jn,children:"ACH Routing Number"}),t.jsx("input",{value:n.bank_routing,onChange:m=>r(b=>({...b,bank_routing:m.target.value})),placeholder:"021000021",style:{...Mn,filter:p?"none":n.bank_routing?"blur(4px)":"none",transition:"filter 0.2s"}})]}),t.jsxs("div",{children:[t.jsx("label",{style:jn,children:"Account Number"}),t.jsx("input",{value:n.bank_account,onChange:m=>r(b=>({...b,bank_account:m.target.value})),placeholder:"000123456789",style:{...Mn,filter:p?"none":n.bank_account?"blur(4px)":"none",transition:"filter 0.2s"}})]})]}),t.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer"},children:[t.jsx("input",{type:"checkbox",checked:p,onChange:m=>u(m.target.checked),style:{width:14,height:14,accentColor:"#fbbf24"}}),t.jsx("span",{style:{fontSize:12,color:"#64748b"},children:"Show account details"})]})]}),(n.bank_name||n.bank_routing)&&t.jsxs("div",{style:{background:"rgba(255,255,255,0.03)",border:"1px solid #1e3a4f",borderRadius:10,padding:16,marginTop:16},children:[t.jsx("div",{style:{fontSize:11,color:"#64748b",fontWeight:700,textTransform:"uppercase",letterSpacing:"0.05em",marginBottom:10},children:"Preview â as shown on invoices"}),t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[["Bank Name",n.bank_name],["Account Name",n.bank_account_name],["ACH ABA Number",n.bank_routing],["Account Number",p?n.bank_account:n.bank_account?"â¢â¢â¢â¢"+n.bank_account.slice(-4):""]].filter(([,m])=>m).map(([m,b])=>t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",fontSize:13},children:[t.jsx("span",{style:{color:"#64748b"},children:m}),t.jsx("span",{style:{color:"#e2e8f0",fontWeight:600},children:b})]},m))})]}),c&&t.jsxs("div",{style:{marginTop:16,background:"rgba(248,113,113,0.08)",border:"1px solid rgba(248,113,113,0.3)",borderRadius:10,padding:"8px 14px",fontSize:12,color:"#f87171"},children:["â ",c]}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,marginTop:20},children:[t.jsx("button",{onClick:y,disabled:o,style:{padding:"10px 24px",borderRadius:10,fontSize:13,fontWeight:700,color:"#fff",background:"linear-gradient(135deg, #fbbf24, #f59e0b)",border:"none",cursor:o?"not-allowed":"pointer",opacity:o?.5:1},children:o?"Saving...":"Save Bank Details"}),l&&t.jsx("span",{style:{fontSize:13,color:"#4ade80",fontWeight:600},children:"â
Saved successfully"})]})]})})}function S$(){const{tenantSlug:e}=di(),{tenant:n,loading:r,error:s}
630=Ff(e),[i,o]=g.useState([]),[a,l]=g.useState(!0),[d,c]=g.useState(null);if(g.useEffect(()=>{n&&(l(!0),w.from("term_blocks").select("id, title, sort_order, content, updated_at").eq("tenant_id",n.id).eq("applies_to","terms_page").eq("is_active",!0).order("sort_order").then(({data:j})=>{j&&(o(j),j.length>0&&c(j[0].id)),l(!1)}))},[n]),r)return t.jsx("div",{className:"min-h-screen bg-white flex items-center justify-center",children:t.jsx("div",{className:"text-gray-500",children:"Loading..."})});if(s||!n)return t.jsx("div",{className:"min-h-screen bg-white flex items-center justify-center px-6",children:t.jsxs("div",{className:"max-w-md text-center",children:[t.jsx("h1",{className:"text-2xl font-bold text-gray-900 mb-2",children:"Provider Not Found"}),t.jsx("p",{className:"text-gray-600 mb-6",children:s||"Provider not found."}),t.jsx(Kb,{to:"/terms",className:"inline-block px-5 py-2 bg-blue-900 text-white rounded-lg",children:"Browse all providers"})]})});const f=i.find(j=>j.title.toLowerCase().includes("effective date")),p=i.filter(j=>!j.title.toLowerCase().includes("effective date")),u=i.length>0?new Date(Math.max.apply(null,i.map(j=>new Date(j.updated_at).getTime()))).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric"}):"",h=n.company_name||n.name,y=n.website?n.website.replace(/^https?:\/\//,"").replace(/\/$/,""):"",m=FR(n),b=MR(n.phone),A=n.accounts_email||n.email||"",v=n.primary_color||"#0a2540",x=h.split(/\s+/).map(j=>j[0]).join("").slice(0,2).toUpperCase();function _(j){return"px-3 py-2 rounded text-sm "+(j?"bg-blue-900 text-white font-medium":"text-gray-700 hover:bg-gray-100")}return t.jsxs("div",{className:"min-h-screen bg-white",children:[t.jsx("div",{style:{backgroundColor:v},className:"text-white",children:t.jsxs("div",{className:"max-w-6xl mx-auto px-6 py-8",children:[t.jsxs("div",{className:"flex items-center gap-4 mb-4",children:[n.logo_url?t.jsx("img",{src:n.logo_url,alt:h,className:"h-12 w-auto bg-white rounded p-1"}):t.jsx("div",{className:"bg-white rounded-lg px-3 py-2",children:t.jsx("span",{style:{color:v},className:"font-bold text-sm tracking-wide",children:x})}),t.jsxs("div",{children:[t.jsx("div",{className:"font-semibold text-lg",children:h}),n.tagline&&t.jsx("div",{className:"text-sm opacity-80",children:n.tagline})]})]}),t.jsx("h1",{className:"text-3xl font-bold",children:"General Terms and Conditions"}),u&&t.jsxs("p",{className:"text-sm opacity-80 mt-2",children:["Updated ",u]})]})}),t.jsx("div",{className:"bg-gray-50 border-b border-gray-200",children:t.jsxs("div",{className:"max-w-6xl mx-auto px-6 py-3 flex flex-wrap gap-6 text-sm text-gray-600",children:[m&&t.jsx("span",{children:m}),b&&t.jsx("span",{children:b}),A&&t.jsx("span",{children:A}),y&&t.jsx("span",{children:y})]})}),t.jsxs("div",{className:"max-w-6xl mx-auto px-6 py-8 grid grid-cols-1 lg:grid-cols-4 gap-8",children:[t.jsxs("aside",{className:"lg:col-span-1 lg:sticky lg:top-6 lg:self-start",children:[t.jsx("div",{className:"text-xs font-semibold text-gray-500 uppercase mb-3",children:"Table of Contents"}),t.jsx("nav",{className:"flex flex-col gap-1 mb-6",children:p.map(j=>t.jsx("a",{href:"#section-"+j.id,onClick:()=>c(j.id),className:_(d===j.id),children:j.title},j.id))}),t.jsxs("div",{className:"bg-gray-50 rounded-lg p-4 text-sm",children:[t.jsx("div",{className:"font-semibold text-gray-900 mb-2",children:"Questions?"}),b&&t.jsx("div",{className:"text-gray-600",children:b}),A&&t.jsx("div",{className:"text-gray-600 break-all",children:A})]})]}),t.jsx("main",{className:"lg:col-span-3",children:a?t.jsx("div",{className:"text-gray-500",children:"Loading terms..."}):i.length===0?t.jsx("div",{className:"text-gray-500",children:"No terms available."}):t.jsxs(t.Fragment,{children:[f&&t.jsxs("div",{className:"mb-6 p-4 bg-blue-50 border border-blue-200 rounded-lg text-sm text-blue-900",children:[t.jsxs("strong",{children:[f.title,":"]})," ",f.content]}),p.map(j=>t.jsxs("section",{id:"section-"+j.id,className:"mb-8 scroll-mt-6",children:[t.jsx("h2",{className:"text-xl font-bold text-gray-900 mb-3",children:j.title}),t.jsx("div",{className:"text-gray-700 whitespace-pre-wrap leading-relaxed",children:j.content})]},j.id)),t.jsxs("div",{className:"mt-12 pt-6 border-t border-gray-200",children:[t.jsx("div",{className:"font-semibold text-gray-900",children:h}),m&&t.jsx("div",{className:"text-sm text-gray-600 mt-1",children:m}),(b||A)&&t.jsxs("div",{className:"text-sm text-gray-600 mt-1",children:[b&&t.jsxs(t.Fragment,{children:["Phone: ",b]}),b&&A&&" | ",A&&t.jsxs(t.Fragment,{children:["Email: ",A]})]}),u&&t.jsxs("div",{className:"text-sm text-gray-500 mt-2",children:["Last updated: ",u]})]})]})})]})]})}function k$(){const[e,n]=g.useState([]),[r,s]=g.useState(!0),[i,o]=g.useState(null);return g.useEffect(()=>{w.rpc("list_public_tenants").then(({data:a,error:l})=>{l?o(l.message):a&&n(a),s(!1)})},[]),t.jsxs("div",{className:"min-h-screen bg-white",children:[t.jsx("div",{className:"bg-[#0a2540] text-white",children:t.jsxs("div",{className:"max-w-4xl mx-auto px-6 py-10",children:[t.jsx("h1",{className:"text-3xl font-bold",children:"Terms & Conditions"}),t.jsx("p",{className:"text-blue-200 mt-2",children:"Select your service provider to view their terms"})]})}),t.jsx("div",{className:"max-w-4xl mx-auto px-6 py-10",children:r?t.jsx("div",{className:"text-gray-500",children:"Loading providers..."}):i?t.jsxs("div",{className:"bg-red-50 border border-red-200 text-red-800 rounded-lg p-4",children:["Error loading providers: ",i]}):e.length===0?t.jsx("div",{className:"text-gray-500",children:"No providers available."}):t.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:e.map(a=>{const l=a.company_name||a.name,d=l.split(/\s+/).map(c=>c[0]).join("").slice(0,2).toUpperCase();return t.jsx(Kb,{to:`/t/${a.slug}/terms`,className:"block bg-white border border-gray-200 rounded-lg p-5 hover:border-[#0a2540] hover:shadow-md transition",children:t.jsxs("div",{className:"flex items-center gap-4",children:[t.jsx("div",{className:"w-12 h-12 rounded-lg bg-[#0a2540] text-white flex items-center justify-center font-bold text-sm",children:d}),t.jsxs("div",{className:"flex-1 min-w-0",children:[t.jsx("div",{className:"font-semibold text-gray-900 truncate",children:l}),t.jsx("div",{className:"text-sm text-gray-500",children:"View terms â"})]})]})},a.slug)})})})]})}async function C$(e){const{data:n,error:r}=await w.from("jobs").select("id, source_quote_id, inventory_status, tenant_id").eq("id",e).single();if(r||!n)throw new Error(`Job not found: ${e}`);if(!n.source_quote_id)throw new Error(`Job ${e} has no source_quote_id`);
630if(!n.tenant_id)throw new Error(`Job ${e} has no tenant_id`);const{data:s,error:i}=await w.from("document_line_items").select("id, product_id, quantity, description").eq("quote_id",n.source_quote_id).not("product_id","is",null);if(i)throw new Error(`Failed to load line items: ${i.message}`);if(!s||s.length===0)return await w.from("jobs").update({inventory_status:"not_required",inventory_checked_at:new Date().toISOString()}).eq("id",e),{status:"not_required",results:[]};const o=[...new Set(s.map(h=>h.product_id).filter(Boolean))],{data:a,error:l}=await w.from("product_catalog").select("id, name, track_inventory, vendor_sku").in("id",o);if(l)throw new Error(`Failed to load products: ${l.message}`);const d=new Map((a||[]).map(h=>[h.id,h])),c=s.filter(h=>{const y=d.get(h.product_id);return(y==null?void 0:y.track_inventory)===!0});if(c.length===0)return await w.from("jobs").update({inventory_status:"not_required",inventory_checked_at:new Date().toISOString()}).eq("id",e),{status:"not_required",results:[]};const f=[];let p=!1;for(const h of c){const y=d.get(h.product_id),m=h.quantity||1,b=`${e}:${h.product_id}:fulfillment_committed`,{data:A,error:v}=await w.rpc("rpc_reserve_stock",{p_product_id:h.product_id,p_job_id:e,p_quantity:m,p_reservation_key:b});if(v){console.error(`Reserve RPC failed for ${y.name}:`,v),f.push({product_id:h.product_id,product_name:y.name,result:"error"}),p=!0;continue}const x=(typeof A=="string"?JSON.parse(A):A)??{},_=x.result??"error",j=Number(x.shortfall??0);if(f.push({product_id:h.product_id,product_name:y.name,result:_}),_==="short"||_==="partial"){p=!0;const{data:C}=await w.from("reorder_requests").select("id").eq("job_id",e).eq("product_id",h.product_id).in("status",["open","grouped","ordered"]).limit(1);if(!C||C.length===0){const{error:S}=await w.from("reorder_requests").insert({tenant_id:n.tenant_id,product_id:h.product_id,job_id:e,request_type:"job_shortage",quantity_needed:j>0?j:m,vendor_sku:y.vendor_sku||null,status:"open"});S&&console.error(`Reorder request failed for ${y.name}:`,S)}}}const u=p?"short":"reserved";return await w.from("jobs").update({inventory_status:u,inventory_checked_at:new Date().toISOString(),inventory_reservation_key:`${e}:fulfillment_committed`}).eq("id",e),{status:u,results:f}}async function T$(e,n,r){if(n<=0)throw new Error("Quantity must be positive");const{data:s,error:i}=await w.rpc("rpc_receive_stock",{p_product_id:e,p_quantity:n,p_reference_type:r!=null&&r.purchaseOrderItemId?"purchase_order_item":null,p_reference_id:(r==null?void 0:r.purchaseOrderItemId)||null,p_notes:(r==null?void 0:r.notes)||null,p_created_by:(r==null?void 0:r.receivedBy)||null});if(i)throw new Error(`Receive stock failed: ${i.message}`);if(r!=null&&r.purchaseOrderItemId){const{data:l}=await w.from("purchase_order_items").select("id, quantity_ordered, quantity_received, po_id").eq("id",r.purchaseOrderItemId).single();if(l){const d=(l.quantity_received||0)+n,c=d>=l.quantity_ordered?"received":"partial";await w.from("purchase_order_items").update({quantity_received:d,status:c,received_at:c==="received"?new Date().toISOString():null}).eq("id",l.id);const{data:f}=await w.from("purchase_order_items").select("status").eq("po_id",l.po_id);f&&f.every(p=>p.status==="received")?await w.from("purchase_orders").update({status:"received",received_at:new Date().toISOString()}).eq("id",l.po_id):f&&f.some(p=>p.status==="received"||p.status==="partial")&&await w.from("purchase_orders").update({status:"partial"}).eq("id",l.po_id)}}const{data:o}=await w.from("reorder_requests").select("id, job_id, quantity_needed").eq("product_id",e).eq("request_type","job_shortage").in("status",["open","grouped","ordered"]),a=[];if(o&&o.length>0)for(const l of o){if(!l.job_id)continue;const d=`${l.job_id}:${e}:fulfillment_committed`,{data:c}=await w.from("jobs").select("source_quote_id").eq("id",l.job_id).single();let f=l.quantity_needed;if(c!=null&&c.source_quote_id){const{data:m}=await w.from("document_line_items").select("quantity").eq("quote_id",c.source_quote_id).eq("product_id",e),b=(m||[]).reduce((A,v)=>A+(v.quantity||0),0);b>0&&(f=b)}const{data:p}=await w.rpc("rpc_reserve_stock",{p_product_id:e,p_job_id:l.job_id,p_quantity:f,p_reservation_key:d}),u=(typeof p=="string"?JSON.parse(p):p)??{},h=u.result??"error",y=Number(u.shortfall??0);if(y===0&&(h==="reserved"||h==="already_reserved")){await w.from("reorder_requests").update({status:"fulfilled",fulfilled_at:new Date().toISOString()}).eq("id",l.id);const{data:m}=await w.from("reorder_requests").select("id").eq("job_id",l.job_id).eq("request_type","job_shortage").in("status",["open","grouped","ordered"]);(!m||m.length===0)&&await w.from("jobs").update({inventory_status:"reserved",inventory_checked_at:new Date().toISOString(),job_status:"ready_to_schedule"}).eq("id",l.job_id),a.push(l.job_id)}else y>0&&await w.from("reorder_requests").update({quantity_needed:y}).eq("id",l.id)}return{received:n,jobsRetried:a}}async function z$(e){var p;const{data:n,error:r}=await w.from("jobs").select("id, source_quote_id, inventory_status, inventory_checked_at").eq("id",e).single();if(r||!n)throw new Error(`Job not found: ${e}`);if(!n.source_quote_id)return{ready:!0,status:"not_required",items:[],checked_at:n.inventory_checked_at||new Date().toISOString()};const{data:s}=await w.from("document_line_items").select("product_id, quantity").eq("quote_id",n.source_quote_id).not("product_id","is",null);if(!s||s.length===0)return{ready:!0,status:"not_required",items:[],checked_at:n.inventory_checked_at||new Date().toISOString()};const i=[...new Set(s.map(u=>
630u.product_id).filter(Boolean))],{data:o}=await w.from("product_catalog").select("id, name, track_inventory").in("id",i),a=new Map((o||[]).map(u=>[u.id,u])),l=[];let d=!0,c=!1;for(const u of s){const h=a.get(u.product_id);if(!(h!=null&&h.track_inventory))continue;c=!0;const y=u.quantity||1,m=`${e}:${u.product_id}:fulfillment_committed`,{data:b}=await w.from("inventory_transactions").select("type, quantity").eq("reservation_key",m).in("type",["reserve","unreserve"]),A=(b||[]).reduce((S,T)=>S+(T.type==="reserve"?T.quantity||0:-(T.quantity||0)),0),v=A>=y,{data:x}=await w.from("inventory_items").select("quantity_available").eq("product_catalog_id",u.product_id).single(),_=(x==null?void 0:x.quantity_available)||0,{data:j}=await w.from("reorder_requests").select("id").eq("job_id",e).eq("product_id",u.product_id).eq("request_type","job_shortage").in("status",["open","grouped","ordered"]).limit(1),C=!v;C&&(d=!1),l.push({product_id:u.product_id,product_name:h.name,quantity_needed:y,quantity_available:_,reserved:v,short:C,shortage_amount:C?Math.max(0,y-A):0,reorder_request_id:((p=j==null?void 0:j[0])==null?void 0:p.id)||null})}return c?{ready:d,status:d?"reserved":"short",items:l,checked_at:new Date().toISOString()}:{ready:!0,status:"not_required",items:[],checked_at:new Date().toISOString()}}const N$={ro:"Reverse Osmosis",softener:"Water Softener",whole_home_filter:"Whole Home Filter",replacement_filter:"Replacement Filter",accessory:"Accessory",uv:"UV Sterilization",iron_filter:"Iron Filter",pfas:"PFAS Filter",salt_free:"Salt-Free",lead_filter:"Lead Filter",well_water:"Well Water"},C_={receive:"ð¦ Receive",reserve:"ð Reserve",unreserve:"ð Unreserve",fulfill:"â
Fulfill",adjustment:"âï¸ Adjust",adjust:"âï¸ Adjust",return:"â©ï¸ Return"},R$={good:["rgba(74,222,128,0.12)","#4ade80"],damaged:["rgba(248,113,113,0.12)","#f87171"],needs_refurb:["rgba(251,191,36,0.12)","#fbbf24"]},E$={none:["rgba(100,116,139,0.12)","#64748b"],in_progress:["rgba(167,139,250,0.12)","#a78bfa"],complete:["rgba(74,222,128,0.12)","#4ade80"]};function Ks(e){return e==null?"â":`$${Number(e).toFixed(2)}`}function P$(e){const n={open:["rgba(251,191,36,0.12)","#fbbf24"],ordered:["rgba(96,165,250,0.12)","#60a5fa"],received:["rgba(74,222,128,0.12)","#4ade80"],cancelled:["rgba(100,116,139,0.12)","#64748b"],draft:["rgba(100,116,139,0.12)","#94a3b8"],submitted:["rgba(96,165,250,0.12)","#60a5fa"],partial:["rgba(167,139,250,0.12)","#a78bfa"],job_shortage:["rgba(248,113,113,0.12)","#f87171"],stock_replenishment:["rgba(96,165,250,0.12)","#60a5fa"],low:["rgba(251,191,36,0.12)","#fbbf24"],out_of_stock:["rgba(248,113,113,0.12)","#f87171"],ok:["rgba(74,222,128,0.12)","#4ade80"]},[r,s]=n[e]||["rgba(100,116,139,0.12)","#64748b"];return{background:r,color:s,border:`1px solid ${s}35`,fontSize:11,fontWeight:700,padding:"2px 8px",borderRadius:20}}function io({val:e,label:n}){return t.jsx("span",{style:P$(e),children:n||e.replace(/_/g," ")})}function q$({available:e,reorderPoint:n}){return e<=0?t.jsx(io,{val:"out_of_stock",label:"Out of Stock"}):e<=n?t.jsx(io,{val:"low",label:"Low"}):t.jsx(io,{val:"ok",label:"OK"})}function v0(){return`PO-${new Date().getFullYear()}-${String(Math.floor(Math.random()*9e3)+1e3)}`}function D$({rows:e,onClose:n,onDone:r}){const s=e.filter(u=>u.inv&&u.inv.quantity_on_hand===0),[i,o]=g.useState({}),[a,l]=g.useState(!1),[d,c]=g.useState(""),f=s.filter(u=>!d||u.product.name.toLowerCase().includes(d.toLowerCase())||u.product.sku.toLowerCase().includes(d.toLowerCase()));async function p(){var h;const u=Object.entries(i).filter(([,y])=>y&&parseInt(y)>0);if(!u.length){n();return}l(!0);for(const[y,m]of u){const b=parseInt(m),A=(h=e.find(v=>v.product.id===y))==null?void 0:h.inv;A&&await w.from("inventory_items").update({quantity_on_hand:b,quantity_available:Math.max(0,b-A.quantity_reserved)}).eq("id",A.id)}l(!1),r(),n()}return t.jsx("div",{style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.75)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:60,padding:16},children:t.jsxs("div",{style:{background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:16,width:"100%",maxWidth:600,maxHeight:"85vh",display:"flex",flexDirection:"column"},children:[t.jsxs("div",{style:{padding:"20px 24px",borderBottom:"1px solid #1e3a4f",dis
630play:"flex",alignItems:"center",justifyContent:"space-between"},children:[t.jsxs("div",{children:[t.jsx("div",{style:{color:"#e2e8f0",fontWeight:800,fontSize:17},children:"Set Opening Stock"}),t.jsxs("div",{style:{color:"#475569",fontSize:12,marginTop:3},children:[s.length," products at zero â enter current quantities on hand"]})]}),t.jsx("button",{onClick:n,style:{background:"none",border:"none",color:"#64748b",fontSize:20,cursor:"pointer"},children:"Ã"})]}),t.jsx("div",{style:{padding:"14px 24px",borderBottom:"1px solid #1e3a4f"},children:t.jsx("input",{value:d,onChange:u=>c(u.target.value),placeholder:"Search productâ¦",style:{width:"100%",background:"#162232",border:"1px solid #1e3a4f",borderRadius:8,color:"#e2e8f0",padding:"8px 12px",fontSize:13,outline:"none",boxSizing:"border-box"}})}),t.jsxs("div",{style:{flex:1,overflowY:"auto",padding:"8px 0"},children:[f.map(u=>t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"10px 24px",borderBottom:"1px solid #0d1a26"},children:[t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsx("div",{style:{fontSize:13,fontWeight:600,color:"#e2e8f0",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:u.product.name}),t.jsx("div",{style:{fontSize:11,color:"#475569",fontFamily:"monospace"},children:u.product.sku})]}),t.jsxs("div",{style:{flexShrink:0,display:"flex",alignItems:"center",gap:8},children:[t.jsx("span",{style:{fontSize:11,color:"#475569"},children:"Qty on hand:"}),t.jsx("input",{type:"number",min:"0",value:i[u.product.id]||"",onChange:h=>o(y=>({...y,[u.product.id]:h.target.value})),placeholder:"0",style:{width:72,background:"#162232",border:"1px solid #1e3a4f",borderRadius:8,color:"#e2e8f0",padding:"6px 10px",fontSize:13,outline:"none",textAlign:"right"}})]})]},u.product.id)),f.length===0&&t.jsx("div",{style:{textAlign:"center",padding:40,color:"#334155"},children:"No products match your search"})]}),t.jsxs("div",{style:{padding:"16px 24px",borderTop:"1px solid #1e3a4f",display:"flex",gap:10,justifyContent:"flex-end"},children:[t.jsx("button",{onClick:n,style:{padding:"8px 16px",fontSize:13,color:"#64748b",background:"none",border:"none",cursor:"pointer"},children:"Cancel"}),t.jsx("button",{onClick:p,disabled:a,style:{padding:"10px 22px",borderRadius:8,border:"none",cursor:"pointer",background:"#0d7ea3",color:"#fff",fontWeight:700,fontSize:14,opacity:a?.5:1},children:a?"Savingâ¦":`Save ${Object.values(i).filter(u=>u&&parseInt(u)>0).length} quantities`})]})]})})}function O$({rows:e,onClose:n,onDone:r,onSwitchToPO:s}){const[i,o]=g.useState(()=>{const p={};return e.forEach(u=>{p[u.product.id]="1"}),p}),[a,l]=g.useState(""),[d,c]=g.useState(!1);async function f(){c(!0);const p=e.map(y=>({product:y.product,qty:parseInt(i[y.product.id]||"1")})).filter(y=>y.qty>0);if(!p.length){n();return}const u=v0(),{data:h}=await w.from("purchase_orders").insert({po_number:u,status:"draft",notes:a||`Quick reorder â ${p.length} product(s)`}).select().single();h&&await w.from("purchase_order_items").insert(p.map(y=>({po_id:h.id,product_catalog_id:y.product.id,quantity_ordered:y.qty,unit_cost:y.product.vendor_cost||0,subtotal:(y.product.vendor_cost||0)*y.qty}))),c(!1),r(),n(),s()}return t.jsx("div",{style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.75)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:60,padding:16},children:t.jsxs("div",{style:{background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:16,width:"100%",maxWidth:560,maxHeight:"85vh",display:"flex",flexDirection:"column"},children:[t.jsxs("div",{style:{padding:"20px 24px",borderBottom:"1px solid #1e3a4f",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[t.jsxs("div",{children:[t.jsx("div",{style:{color:"#e2e8f0",fontWeight:800,fontSize:17},children:"Quick Reorder â Draft PO"}),t.jsxs("div",{style:{color:"#475569",fontSize:12,marginTop:3},children:[e.length," product",e.length!==1?"s":""," selected · Set quantities then create"]})]}),t.jsx("button",{onClick:n,style:{background:"none",border:"none",color:"#64748b",fontSize:20,cursor:"pointer"},children:"Ã"})]}),t.jsx("div",{style:{flex:1,overflowY:"auto"},children:e.map(p=>t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"12px 24px",borderBottom:"1px solid #0d1a26"},children:[t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsx("div",{style:{fontSize:13,fontWeight:600,color:"#e2e8f0",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:p.product.name}),t.jsxs("div",{style:{fontSize:11,color:"#475569",fontFamily:"monospace",marginTop:2},children:[p.product.sku,p.product.vendor_name&&t.jsxs("span",{style:{marginLeft:8,color:"#fbbf24"},children:["· ",p.product.vendor_name]}),p.product.vendor_sku&&t.jsx("span",{style:{marginLeft:6,color:"#64748b"},children:p.product.vendor_sku})]}),p.product.vendor_cost&&t.jsxs("div",{style:{fontSize:11,color:"#4ade80",marginTop:2},children:["Cost: ",Ks(p.product.vendor_cost)," · Line: ",Ks((p.product.vendor_cost||0)*parseInt(i[p.product.id]||"1"))]})]}),t.jsxs("div",{style:{flexShrink:0,display:"flex",alignItems:"center",gap:8},children:[t.jsx("span",{style:{fontSize:11,color:"#475569"},children:"Qty:"}),t.jsx("input",{type:"number",min:"1",value:i[p.product.id]||"1",onChange:u=>o(h=>({...h,[p.product.id]:u.target.value})),style:{width:64,background:"#162232",border:"1px solid #1e3a4f",borderRadius:8,color:"#e2e8f0",padding:"6px 10px",fontSize:13,outline:"none",textAlign:"right"}})]})]},p.product.id))}),t.jsx("div",{style:{padding:"14px 24px",borderTop:"1px solid #1e3a4f"},children:t.jsx("input",{value:a,onChange:p=>l(p.target.value),placeholder:"Notes (optional)",style:{width:"100%",background:"#162232",border:"1px solid #1e3a4f",borderRadius:8,color:"#e2e8f0",padding:"8px 12px",fontSize:13,outline:"none",boxSizing:"border-box"}})}),t.jsxs("div",{style:{padding:"12px 24px",borderTop:"1px solid #1e3a4f",dis
630play:"flex",gap:10,justifyContent:"flex-end",alignItems:"center"},children:[t.jsx("span",{style:{fontSize:11,color:"#334155",marginRight:"auto"},children:"Creates a Draft PO â review before sending to vendor"}),t.jsx("button",{onClick:n,style:{padding:"8px 16px",fontSize:13,color:"#64748b",background:"none",border:"none",cursor:"pointer"},children:"Cancel"}),t.jsx("button",{onClick:f,disabled:d,style:{padding:"10px 22px",borderRadius:8,border:"none",cursor:"pointer",background:"#0d7ea3",color:"#fff",fontWeight:700,fontSize:14,opacity:d?.5:1},children:d?"Creatingâ¦":"Create Draft PO"})]})]})})}function I$({allProducts:e,onClose:n,onDone:r}){const[s,i]=g.useState(""),[o,a]=g.useState([]),[l,d]=g.useState(""),[c,f]=g.useState(!1),p=e.filter(A=>!o.find(v=>v.product.id===A.id)&&(A.name.toLowerCase().includes(s.toLowerCase())||A.sku.toLowerCase().includes(s.toLowerCase()))).slice(0,20);function u(A){a(v=>[...v,{product:A,qty:"1",cost:A.vendor_cost?String(A.vendor_cost):""}]),i("")}function h(A){a(v=>v.filter(x=>x.product.id!==A))}function y(A,v,x){a(_=>_.map(j=>j.product.id===A?{...j,[v]:x}:j))}const m=o.reduce((A,v)=>A+parseFloat(v.cost||"0")*parseInt(v.qty||"0"),0);async function b(){if(!o.length)return;f(!0);const A=v0(),{data:v}=await w.from("purchase_orders").insert({po_number:A,status:"draft",notes:l}).select().single();v&&await w.from("purchase_order_items").insert(o.map(x=>({po_id:v.id,product_catalog_id:x.product.id,quantity_ordered:parseInt(x.qty||"1"),unit_cost:parseFloat(x.cost||"0"),subtotal:parseFloat(x.cost||"0")*parseInt(x.qty||"1")}))),f(!1),r(),n()}return t.jsx("div",{style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.75)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:60,padding:16},children:t.jsxs("div",{style:{background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:16,width:"100%",maxWidth:680,maxHeight:"90vh",display:"flex",flexDirection:"column"},children:[t.jsxs("div",{style:{padding:"20px 24px",borderBottom:"1px solid #1e3a4f",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[t.jsxs("div",{children:[t.jsx("div",{style:{color:"#e2e8f0",fontWeight:800,fontSize:17},children:"Create Purchase Order"}),t.jsx("div",{style:{color:"#475569",fontSize:12,marginTop:3},children:"Search products â add lines â set quantities and costs"})]}),t.jsx("button",{onClick:n,style:{background:"none",border:"none",color:"#64748b",fontSize:20,cursor:"pointer"},children:"Ã"})]}),t.jsxs("div",{style:{padding:"14px 24px",borderBottom:"1px solid #1e3a4f",position:"relative"},children:[t.jsx("input",{value:s,onChange:A=>i(A.target.value),placeholder:"Search products to addâ¦",style:{width:"100%",background:"#162232",border:"1px solid #1e3a4f",borderRadius:8,color:"#e2e8f0",padding:"9px 12px",fontSize:13,outline:"none",boxSizing:"border-box"}}),s&&p.length>0&&t.jsx("div",{style:{position:"absolute",left:24,right:24,top:"100%",background:"#162232",border:"1px solid #1e3a4f",borderRadius:8,zIndex:10,maxHeight:220,overflowY:"auto"},children:p.map(A=>t.jsxs("div",{onClick:()=>u(A),style:{padding:"10px 14px",cursor:"pointer",borderBottom:"1px solid #0d1a26"},onMouseEnter:v=>{v.currentTarget.style.background="#1e3a4f"},onMouseLeave:v=>{v.currentTarget.style.background="transparent"},children:[t.jsx("div",{style:{fontSize:13,color:"#e2e8f0",fontWeight:600},children:A.name}),t.jsxs("div",{style:{fontSize:11,color:"#475569",fontFamily:"monospace"},children:[A.sku,A.vendor_name&&t.jsxs("span",{style:{marginLeft:8,color:"#fbbf24"},children:["· ",A.vendor_name]}),A.vendor_cost&&t.jsx("span",{style:{marginLeft:6,color:"#4ade80"},children:Ks(A.vendor_cost)})]})]},A.id))})]}),t.jsx("div",{style:{flex:1,overflowY:"auto"},children:o.length===0?t.jsx("div",{style:{textAlign:"center",padding:40,color:"#334155",fontSize:13},children:"Search and add products above"}):t.jsxs(t.Fragment,{children:[t.jsx("div",{style:{display:"grid",gridTemplateColumns:"1fr 80px 100px 36px",gap:0,padding:"8px 24px",borderBottom:"1px solid #1e3a4f"},children:["Product","Qty","Unit Cost",""].map(A=>t.jsx("div",{style:{fontSize:10,fontWeight:700,color:"#475569",textTransform:"uppercase",letterSpacing:"0.06em"},children:A},A))}),o.map(A=>t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 80px 100px 36px",gap:8,padding:"10px 24px",borderBottom:"1px solid #0d1a26",alignItems:"center"},children:[t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:13,color:"#e2e8f0",fontWeight:600,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:A.product.name}),t.jsxs("div",{style:{fontSize:11,color:"#475569",fontFamily:"monospace"},children:[A.product.sku,A.product.vendor_sku&&t.jsx("span",{style:{marginLeft:6,color:"#64748b"},children:A.product.vendor_sku})]})]}),t.jsx("input",{type:"number",min:"1",value:A.qty,onChange:v=>y(A.product.id,"qty",v.target.value),style:{background:"#162232",border:"1px solid #1e3a4f",borderRadius:6,color:"#e2e8f0",padding:"6px 8px",fontSize:13,outline:"none",textAlign:"right",width:"100%",boxSizing:"border-box"}}),t.jsx("input",{type:"number",min:"0",step:"0.01",value:A.cost,onChange:v=>y(A.product.id,"cost",v.target.value),placeholder:"0.00",style:{background:"#162232",border:"1px solid #1e3a4f",borderRadius:6,color:"#e2e8f0",padding:"6px 8px",fontSize:13,outline:"none",textAlign:"right",width:"100%",boxSizing:"border-box"}}),t.jsx("button",{onClick:()=>h(A.product.id),style:{background:"none",border:"none",color:"#f87171",cursor:"pointer",fontSize:16},children:"Ã"})]},A.product.id)),t.jsx("div",{style:{display:"flex",justifyContent:"flex-end",padding:"10px 24px",borderTop:"1px solid #1e3a4f"},children:t.jsxs("span",{style:{fontSize:13,color:"#94a3b8"},children:["Total: ",t.jsx("strong",{style:{color:"#4ade80"},children:Ks(m)})]})})]})}),t.jsx("div",{style:{padding:"12px 24px",borderTop:"1px solid #1e3a4f"}
630,children:t.jsx("input",{value:l,onChange:A=>d(A.target.value),placeholder:"Notes (optional)",style:{width:"100%",background:"#162232",border:"1px solid #1e3a4f",borderRadius:8,color:"#e2e8f0",padding:"8px 12px",fontSize:13,outline:"none",boxSizing:"border-box"}})}),t.jsxs("div",{style:{padding:"12px 24px",borderTop:"1px solid #1e3a4f",display:"flex",gap:10,justifyContent:"flex-end"},children:[t.jsx("button",{onClick:n,style:{padding:"8px 16px",fontSize:13,color:"#64748b",background:"none",border:"none",cursor:"pointer"},children:"Cancel"}),t.jsx("button",{onClick:b,disabled:c||o.length===0,style:{padding:"10px 22px",borderRadius:8,border:"none",cursor:"pointer",background:o.length?"#0d7ea3":"#334155",color:"#fff",fontWeight:700,fontSize:14,opacity:c?.5:1},children:c?"Creatingâ¦":`Create Draft PO (${o.length} line${o.length!==1?"s":""})`})]})]})})}function L$({onSwitchToPO:e}){const{profile:n}=Ee(),r=yt.manageInventory(n==null?void 0:n.role),[s,i]=g.useState([]),[o,a]=g.useState(!0),[l,d]=g.useState(""),[c,f]=g.useState("all"),[p,u]=g.useState(new Set),[h,y]=g.useState(null),[m,b]=g.useState(""),[A,v]=g.useState(""),[x,_]=g.useState(!1),[j,C]=g.useState(!1),[S,T]=g.useState(!1),[L,E]=g.useState(!1),[R,N]=g.useState([]),O=g.useCallback(async()=>{a(!0);const{data:W}=await w.from("product_catalog").select("id, name, sku, category, is_active, vendor_name, vendor_sku, vendor_cost").order("name"),{data:G}=await w.from("inventory_items").select("*"),V={};for(const re of G||[])V[re.product_catalog_id]=re;const ee=(W||[]).map(re=>({product:re,inv:V[re.id]||null}));i(ee),a(!1)},[]);g.useEffect(()=>{O()},[O]);async function z(W){await w.from("inventory_items").insert({product_catalog_id:W.id,quantity_on_hand:0,quantity_reserved:0,quantity_available:0,quantity_on_order:0,reorder_point:2}),O()}async function P(){C(!0);const W=s.filter(G=>!G.inv);for(const G of W)await w.from("inventory_items").insert({product_catalog_id:G.product.id,quantity_on_hand:0,quantity_reserved:0,quantity_available:0,quantity_on_order:0,reorder_point:2});C(!1),O()}async function D(){if(!(h!=null&&h.inv)||!m)return;_(!0);const W=parseInt(m);if(W!==0){const G=h.inv;await w.from("inventory_items").update({quantity_on_hand:Math.max(0,G.quantity_on_hand+W),quantity_available:Math.max(0,G.quantity_available+W)}).eq("id",G.id)}y(null),b(""),v(""),_(!1),O()}function M(W){u(G=>{const V=new Set(G);return V.has(W)?V.delete(W):V.add(W),V})}function k(W){N(W),E(!0)}const q=s.filter(W=>W.inv),$=s.filter(W=>!W.inv),I=q.filter(W=>W.inv.quantity_available<=0),B=q.filter(W=>W.inv.quantity_available>0&&W.inv.quantity_available<=W.inv.reorder_point),J=q.filter(W=>W.inv.quantity_on_hand===0),ae=[{id:"all",label:"All Tracked",count:q.length,color:"#60a5fa"},{id:"low",label:"Low Stock",count:B.length,color:"#fbbf24"},{id:"short",label:"Out of Stock",count:I.length,color:"#f87171"},{id:"untracked",label:"Not Tracked",count:$.length,color:"#64748b"}],te=s.filter(W=>{const G=l.toLowerCase(),V=!l||W.product.name.toLowerCase().includes(G)||W.product.sku.toLowerCase().includes(G)||W.product.vendor_name&&W.product.vendor_name.toLowerCase().includes(G)||W.product.vendor_sku&&W.product.vendor_sku.toLowerCase().includes(G);if(c==="untracked")return V&&!W.inv;if(!W.inv)return!1;const ee=c==="all"?!0:c==="short"?W.inv.quantity_available<=0:c==="low"?W.inv.quantity_available>0&&W.inv.quantity_available<=W.inv.reorder_point:!0;return V&&ee}),U=te.filter(W=>p.has(W.product.id)&&W.inv);return t.jsxs("div",{children:[t.jsx("div",{style:{display:"grid",gridTemplateColumns:`repeat(${ae.length}, 1fr)`,gap:3,marginBottom:16},children:ae.map(W=>{const G=c===W.id;return t.jsxs("button",{onClick:()=>f(W.id),style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 16px",borderRadius:12,border:`1px solid ${G?W.color+"50":"rgba(255,255,255,0.06)"}`,background:G?`${W.color}18`:"rgba(255,255,255,0.02)",cursor:"pointer",boxShadow:G?`0 0 18px ${W.color}18`:"none"},children:[t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:10,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.08em",color:G?W.color:"#64748b",marginBottom:4},children:W.label}),t.jsx("div",{style:{fontSize:22,fontWeight:800,color:G?W.color:"#94a3b8"},children:W.count})]}),G&&t.jsx("div",{style:{width:8,height:8,borderRadius:"50%",background:W.color,boxShadow:`0 0 8px ${W.color}`}})]},W.id)})}),t.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(4, 1fr)",gap:10,marginBottom:16},children:[{label:"Total On Hand",value:q.reduce((W,G)=>W+G.inv.quantity_on_hand,0),color:"#60a5fa"},{label:"Reserved for Jobs",value:q.reduce((W,G)=>W+G.inv.quantity_reserved,0),color:"#a78bfa"},{label:"Available to Sell",value:q.reduce((W,G)=>W+G.inv.quantity_available,0),color:"#4ade80"},{label:"On Order",value:q.reduce((W,G)=>W+(G.inv.quantity_on_order||0),0),color:"#fbbf24"}].map(W=>t.jsxs("div",{style:{background:"rgba(255,255,255,0.03)",border:"1px solid rgba(255,255,255,0.06)",borderRadius:12,padding:"10px 14px"},children:[t.jsx("div",{style:{fontSize:20,fontWeight:800,color:W.color},children:W.value}),t.jsx("div",{style:{fontSize:11,color:"#64748b",marginTop:2},children:W.label})]},W.label))}),t.jsxs("div",{style:{display:"flex",gap:10,marginBottom:14,flexWrap:"wrap"}
630,children:[t.jsx("input",{value:l,onChange:W=>d(W.target.value),placeholder:"Search product, vendor, SKUâ¦",style:{flex:1,minWidth:180,background:"rgba(255,255,255,0.04)",border:"1px solid rgba(255,255,255,0.08)",borderRadius:10,color:"#e2e8f0",padding:"9px 14px",fontSize:13,outline:"none"}}),J.length>0&&r&&t.jsxs("button",{onClick:()=>T(!0),style:{padding:"9px 16px",borderRadius:10,border:"1px solid rgba(167,139,250,0.3)",background:"rgba(167,139,250,0.1)",color:"#a78bfa",fontSize:13,fontWeight:600,cursor:"pointer",whiteSpace:"nowrap"},children:["ð¦ Set Opening Stock (",J.length,")"]}),$.length>0&&t.jsx("button",{onClick:P,disabled:j,style:{padding:"9px 16px",borderRadius:10,border:"1px solid rgba(96,165,250,0.3)",background:"rgba(96,165,250,0.1)",color:"#60a5fa",fontSize:13,fontWeight:600,cursor:"pointer",whiteSpace:"nowrap",opacity:j?.5:1},children:j?"Setting upâ¦":`Track All (${$.length})`})]}),U.length>0&&t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 16px",marginBottom:12,background:"rgba(13,126,163,0.1)",border:"1px solid rgba(13,126,163,0.3)",borderRadius:10},children:[t.jsxs("span",{style:{fontSize:13,color:"#38bdf8"},children:[U.length," product",U.length!==1?"s":""," selected"]}),t.jsxs("div",{style:{display:"flex",gap:8},children:[t.jsx("button",{onClick:()=>u(new Set),style:{padding:"5px 12px",borderRadius:8,border:"1px solid #1e3a4f",background:"transparent",color:"#64748b",cursor:"pointer",fontSize:12},children:"Clear"}),t.jsx("button",{onClick:()=>k(U),style:{padding:"5px 14px",borderRadius:8,border:"none",background:"#0d7ea3",color:"#fff",cursor:"pointer",fontSize:12,fontWeight:700},children:"ð Reorder Selected â Draft PO"})]})]}),t.jsx("div",{style:{background:"#162232",border:"1px solid #1e3a4f",borderRadius:14,overflow:"hidden"},children:t.jsx("div",{style:{overflowX:"auto"},children:t.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",minWidth:900},children:[t.jsx("thead",{children:t.jsxs("tr",{style:{background:"#0f1923",borderBottom:"1px solid #1e3a4f"},children:[t.jsx("th",{style:{width:36,padding:"10px 12px"}}),["Product","SKU","Category","Vendor","On Hand","Reserved","Available","Reorder At",...r?["Cost"]:[],"Status",""].map((W,G)=>t.jsx("th",{style:{textAlign:["On Hand","Reserved","Available","Reorder At","Cost"].includes(W)?"right":W==="Status"?"center":"left",padding:"10px 14px",fontSize:10,fontWeight:700,color:"#64748b",textTransform:"uppercase",letterSpacing:"0.08em"},children:W},W+G))]})}),t.jsx("tbody",{children:o?t.jsx("tr",{children:t.jsx("td",{colSpan:12,style:{textAlign:"center",padding:60,color:"#64748b"},children:"Loading inventoryâ¦"})}):te.length===0?t.jsx("tr",{children:t.jsx("td",{colSpan:12,style:{textAlign:"center",padding:60,color:"#64748b"},children:"No products found"})}):te.map(W=>t.jsxs("tr",{style:{borderBottom:"1px solid #0d1a26",background:p.has(W.product.id)?"rgba(13,126,163,0.08)":"transparent"},onMouseEnter:G=>{p.has(W.product.id)||(G.currentTarget.style.background="rgba(96,165,250,0.04)")},onMouseLeave:G=>{p.has(W.product.id)||(G.currentTarget.style.background="transparent")},children:[t.jsx("td",{style:{padding:"10px 12px",textAlign:"center"},children:W.inv&&t.jsx("input",{type:"checkbox",checked:p.has(W.product.id),onChange:()=>M(W.product.id),style:{accentColor:"#0d7ea3",width:14,height:14,cursor:"pointer"}})}),t.jsx("td",{style:{padding:"10px 14px"},children:t.jsx("div",{style:{fontSize:13,fontWeight:600,color:"#e2e8f0"},children:W.product.name})}),t.jsx("td",{style:{padding:"10px 14px",fontSize:11,color:"#94a3b8",fontFamily:"monospace"},children:W.product.sku}),t.jsx("td",{style:{padding:"10px 14px",fontSize:11,color:"#64748b"},children:N$[W.product.category]||W.product.category}),t.jsxs("td",{style:{padding:"10px 14px"},children:[W.product.vendor_name&&t.jsx("div",{style:{fontSize:12,fontWeight:600,color:"#fbbf24"},children:W.product.vendor_name}),W.product.vendor_sku&&t.jsx("div",{style:{fontSize:10,color:"#64748b",fontFamily:"monospace",marginTop:1},children:W.product.vendor_sku}),!W.product.vendor_name&&!W.product.vendor_sku&&t.jsx("span",{style:{color:"#334155"},children:"â"})]}),W.inv?t.jsxs(t.Fragment,{children:[t.jsx("td",{style:{padding:"10px 14px",textAlign:"right",fontWeight:700,color:"#e2e8f0"},children:W.inv.quantity_on_hand}),t.jsx("td",{style:{padding:"10px 14px",textAlign:"right",color:"#a78bfa"},children:W.inv.quantity_reserved}),t.jsx("td",{style:{padding:"10px 14px",textAlign:"right",fontWeight:800,color:"#e2e8f0"},children:W.inv.quantity_available}),t.jsx("td",{style:{padding:"10px 14px",textAlign:"right",color:"#64748b"},children:W.inv.reorder_point}),r&&t.jsx("td",{style:{padding:"10px 14px",textAlign:"right",fontSize:12,color:W.product.vendor_cost?"#4ade80":"#334155"},children:Ks(W.product.vendor_cost)}),t.jsx("td",{style:{padding:"10px 14px",textAlign:"center"},children:t.jsx(q$,{available:W.inv.quantity_available,reorderPoint:W.inv.reorder_point})}),t.jsx("td",{style:{padding:"10px 14px",textAlign:"right"},children:t.jsxs("div",{style:{display:"flex",gap:6,justifyContent:"flex-end"},children:[t.jsx("button",{onClick:()=>y(W),style:{fontSize:11,padding:"4px 10px",borderRadius:7,border:"1px solid rgba(96,165,250,0.3)",background:"rgba(96,165,250,0.1)",color:"#60a5fa",cursor:"pointer",fontWeight:600},children:"Adjust"}),t.jsx("button",{onClick:()=>k([W]),style:{fontSize:11,padding:"4px 10px",borderRadius:7,border:"1px solid rgba(13,126,163,0.3)",background:"rgba(13,126,163,0.1)",color:"#0d7ea3",cursor:"pointer",fontWeight:600},children:"ð Reorder"})]})})]}):t.jsxs(t.Fragment,{children:[[0,1,2,3].map(G=>t.jsx("td",{style:{padding:"10px 14px",textAlign:"right",color:"#334155"},children:"â"},G)),r&&t.jsx("td",{style:{padding:"10px 14px",textAlign:"right",fontSize:12,color:W.product.vendor_cost?"#4ade80":"#334155"},children:Ks(W.product.vendor_cost)}),t.jsx("td",{style:{padding:"10px 14px",textAlign:"center"},children:t.jsx("span",{style:{fontSize:11,color:"#334155",fontStyle:"italic"},children:"not tracked"})}),t.jsx("td",{style:{padding:"10px 14px",textAlign:"right"},children:t.jsx("button",{onClick:()=>z(W.product),style:{fontSize:11,padding:"4px 10px",borderRadius:7,border:"1px solid rgba(74,222,128,0.3)",background:"rgba(74,222,128,0.1)",color:"#4ade80",cursor:"pointer",fontWeight:600},children:"+ Track"})})]})]},W.product.id))})]})})}),(h==null?void 0:h.inv)&&t.jsx("div",{style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.7)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:60,padding:16},children:t.jsxs("div",{style:{background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:16,width:"100%",maxWidth:360,padding:24},children:[t.jsx("div",{style:{color:"#e2e8f0",fontWeight:700,fontSize:17,marginBottom:4},children:"Adjust Stock"}),t.jsxs("div",{style:{color:"#64748b",fontSize:13,marginBottom:16},children:[h.product.name,t.jsx("span",{style:{margin:"0 8px",color:"#334155"},children:"·"}),"Available: ",t.jsx("strong",{style:{color:"#e2e8f0"},children:h.inv.quantity_available})]}),t.jsx("label",{style:{display:"block",fontSize:12,color:"#64748b",marginBottom:6},children:"Quantity change (+ add · â remove)"}),t.jsx("input",{type:"number",value:m,onChange:W=>b(W.target.value),placeholder:"e.g. 10 or -2",style:{width:"100%",background:"#162232",border:"1px solid #1e3a4f",borderRadius:8,color:"#e2e8f0",padding:"9px 12px",fontSize:14,outline:"none",boxSizing:"border-box",marginBottom:12}}),t.jsx("label",{style:{display:"block",fontSize:12,color:"#64748b",marginBottom:6},children:"Note"}),t.jsx("input",{value:A,onChange:W=>
630v(W.target.value),placeholder:"Reason for adjustment",style:{width:"100%",background:"#162232",border:"1px solid #1e3a4f",borderRadius:8,color:"#e2e8f0",padding:"9px 12px",fontSize:14,outline:"none",boxSizing:"border-box",marginBottom:16}}),t.jsxs("div",{style:{display:"flex",gap:10},children:[t.jsx("button",{onClick:()=>y(null),style:{flex:1,padding:"10px 0",borderRadius:10,background:"rgba(255,255,255,0.05)",border:"1px solid rgba(255,255,255,0.08)",color:"#64748b",cursor:"pointer",fontSize:13},children:"Cancel"}),t.jsx("button",{onClick:D,disabled:x||!m,style:{flex:1,padding:"10px 0",borderRadius:10,border:"none",background:"#0d7ea3",color:"#fff",fontWeight:700,fontSize:13,cursor:"pointer",opacity:x||!m?.5:1},children:x?"Savingâ¦":"Apply"})]})]})}),S&&t.jsx(D$,{rows:s,onClose:()=>T(!1),onDone:O}),L&&t.jsx(O$,{rows:R,onClose:()=>E(!1),onDone:O,onSwitchToPO:e})]})}function W$(){const[e,n]=g.useState([]),[r,s]=g.useState(!0),[i,o]=g.useState("open"),[a,l]=g.useState(new Set),[d,c]=g.useState({}),f=g.useCallback(async()=>{s(!0);const{data:b}=await w.from("reorder_requests").select("*").order("created_at",{ascending:!1});n(b||[]);const A=[...new Set((b||[]).map(v=>v.product_id).filter(Boolean))];if(A.length){const{data:v}=await w.from("product_catalog").select("id, name, sku").in("id",A),x={};for(const _ of v||[])x[_.id]={name:_.name,sku:_.sku};c(x)}s(!1)},[]);g.useEffect(()=>{f()},[f]);const p=[{id:"open",label:"Open",color:"#fbbf24"},{id:"ordered",label:"Ordered",color:"#60a5fa"},{id:"received",label:"Received",color:"#4ade80"},{id:"cancelled",label:"Cancelled",color:"#64748b"},{id:"all",label:"All",color:"#94a3b8"}],u=e.filter(b=>i==="all"||b.status===i);async function h(b,A){await w.from("reorder_requests").update({status:A}).eq("id",b),f()}function y(b){l(A=>{const v=new Set(A);return v.has(b)?v.delete(b):v.add(b),v})}async function m(){const b=e.filter(x=>a.has(x.id));if(!b.length)return;const A=v0(),{data:v}=await w.from("purchase_orders").insert({po_number:A,status:"draft",notes:`From ${b.length} reorder request(s)`}).select().single();v&&(await w.from("purchase_order_items").insert(b.map(x=>({po_id:v.id,product_catalog_id:x.product_id,quantity_ordered:x.qty_requested,unit_cost:0,subtotal:0}))),await w.from("reorder_requests").update({status:"ordered"}).in("id",b.map(x=>x.id))),l(new Set),f()}return t.jsxs("div",{children:[t.jsx("div",{style:{display:"flex",gap:4,marginBottom:16,padding:4,background:"rgba(255,255,255,0.03)",border:"1px solid rgba(255,255,255,0.06)",borderRadius:12,overflowX:"auto"},children:p.map(b=>t.jsxs("button",{onClick:()=>o(b.id),style:{padding:"8px 16px",borderRadius:8,fontSize:13,fontWeight:500,cursor:"pointer",whiteSpace:"nowrap",flexShrink:0,border:i===b.id?`1px solid ${b.color}35`:"1px solid transparent",background:i===b.id?`${b.color}18`:"transparent",color:i===b.id?b.color:"#64748b"},children:[b.label," ",b.id!=="all"&&`(${e.filter(A=>A.status===b.id).length})`]},b.id))}),a.size>0&&t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 16px",marginBottom:12,background:"rgba(96,165,250,0.08)",border:"1px solid rgba(96,165,250,0.2)",borderRadius:10},children:[t.jsxs("span",{style:{fontSize:13,color:"#60a5fa"},children:[a.size," selected"]}),t.jsx("button",{onClick:m,style:{padding:"6px 16px",borderRadius:8,border:"none",background:"#0d7ea3",color:"#fff",fontWeight:700,fontSize:13,cursor:"pointer"},children:"Create Draft PO"})]}),t.jsx("div",{style:{background:"#162232",border:"1px solid #1e3a4f",borderRadius:14,overflow:"hidden"},children:t.jsx("div",{style:{overflowX:"auto"},children:t.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",minWidth:600},children:[t.jsx("thead",{children:t.jsx("tr",{style:{background:"#0f1923",borderBottom:"1px solid #1e3a4f"},children:["","Product","Type","Qty Needed","Status","Created","Notes",""].map(b=>t.jsx("th",{style:{padding:"10px 14px",textAlign:b==="Qty Needed"?"right":"left",fontSize:10,fontWeight:700,color:"#64748b",textTransform:"uppercase",letterSpacing:"0.08em"},children:b},b))})}),t.jsx("tbody",{children:r?t.jsx("tr",{children:t.jsx("td",{colSpan:8,style:{textAlign:"center",padding:40,color:"#64748b"},children:"Loadingâ¦"})}):u.length===0?t.jsx("tr",{children:t.jsx("td",{colSpan:8,style:{textAlign:"center",padding:40,color:"#64748b"},children:"No reorder requests"})}):u.map(b=>{var A,v,x;return t.jsxs("tr",{style:{borderBottom:"1px solid #0d1a26"},children:[t.jsx("td",{style:{padding:"10px 14px"},children:b.status==="open"&&t.jsx("input",{type:"checkbox",checked:a.has(b.id),onChange:()=>y(b.id),style:{accentColor:"#0d7ea3",cursor:"pointer"}})}),t.jsxs("td",{style:{padding:"10px 14px"},children:[t.jsx("div",{style:{fontSize:13,fontWeight:600,color:"#e2e8f0"},children:((A=d[b.product_id])==null?void 0:A.name)||((v=b.product_id)==null?void 0:v.slice(0,8))}),t.jsx("div",{style:{fontSize:11,color:"#475569",fontFamily:"monospace"},children:((x=d[b.product_id])==null?void 0:x.sku)||"â"})]}),t.jsx("td",{style:{padding:"10px 14px"},children:t.jsx(io,{val:b.request_type})}),t.jsx("td",{style:{padding:"10px 14px",textAlign:"right",fontWeight:800,color:"#e2e8f0"},children:b.qty_requested}),t.jsx("td",{style:{padding:"10px 14px"},children:t.jsx(io,{val:b.status})}),t.jsx("td",{style:{padding:"10px 14px",fontSize:12,color:"#64748b"},children:new Date(b.created_at).toLocaleDateString()}),t.jsx("td",{style:{padding:"10px 14px",fontSize:12,color:"#64748b",maxWidth:180,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:b.notes||"â"}),t.jsx("td",{style:{padding:"10px 14px",textAlign:"right"},children:b.status==="open"&&t.jsx("button",{onClick:()=>h(b.id,"cancelled"),style:{fontSize:11,padding:"3px 10px",borderRadius:6,border:"1px solid rgba(248,113,113,0.2)",background:"transparent",color:"#f87171",cursor:"pointer"},children:"Cancel"})})]},b.id)})})]})})})]})}function $$(e,n){const r=e.purchase_order_items||[],s=r.reduce((p,u)=>p+(Number(u.unit_cost)||0)*(Number(u.quantity_ordered)||0),0),i=r.map(p=>{const u=p.product,h=(u==null?void 0:u.name)||"â",y=(u==null?void 0:u.sku)||"â",m=(u==null?void 0:u.vendor_sku)||"â",b=p.quantity_ordered||0,A=Number(p.unit_cost||0).toFixed(2),v=(Number(p.unit_cost||0)*b).toFixed(2);return'<tr><td style="padding:10px 12px;border-bottom:1px solid #e2e8f0;"><div style="font-weight:600;font-size:14px;">'+h+'</div><div style="font-size:11px;color:#64748b;font-family:monospace;">Internal: '+y+" / Vendor: "+m+'</div></td><td style="padding:10px 12px;border-bottom:1px solid #e2e8f0;text-align:right;">'+b+'</td><td style="padding:10px 12px;border-bottom:1px solid #e2e8f0;text-align:right;">$'+A+'</td><td style="padding:10px 12px;border-bottom:1px solid #e2e8f0;text-align:right;font-weight:600;">$'+v+"</td></tr>"}).join(""),o=e.status==="draft"?"#475569":e.status==="submitted"?"#1d4ed8":e.status==="partial"?"#6d28d9":"#15803d",a=e.status==="draft"?"#f1f5f9":e.status==="submitted"?"#dbeafe":e.status==="partial"?"#ede9fe":"#dcfce7",l=new Date(e.created_at).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric"}
630),d=new Date().toLocaleString(),c='<!DOCTYPE html><html><head><meta charset="utf-8"><title>PO '+e.po_number+'</title><style>*{margin:0;padding:0;box-sizing:border-box}body{font-family:Arial,sans-serif;color:#1e293b;padding:40px;max-width:800px;margin:0 auto}@media print{body{padding:20px}.no-print{display:none!important}}</style></head><body><div style="display:flex;justify-content:space-between;align-items:flex-start;margin-bottom:32px;padding-bottom:24px;border-bottom:2px solid #0d7ea3;"><div><div style="font-size:22px;font-weight:800;color:#0d7ea3;">Zenith Pure Solutions</div><div style="font-size:13px;color:#64748b;margin-top:4px;">6951 E 30th St, Suite B</div><div style="font-size:13px;color:#64748b;">Indianapolis, IN 46219</div></div><div style="text-align:right;"><div style="font-size:26px;font-weight:900;">PURCHASE ORDER</div><div style="font-size:18px;font-weight:700;color:#0d7ea3;margin-top:4px;">'+e.po_number+'</div><div style="font-size:13px;color:#64748b;margin-top:6px;">Date: '+l+'</div><div style="margin-top:8px;"><span style="background:'+a+";color:"+o+';padding:4px 12px;border-radius:20px;font-size:12px;font-weight:700;text-transform:uppercase;">'+e.status+'</span></div></div></div><div class="no-print" style="margin-bottom:24px;"><button onclick="window.print()" style="background:#0d7ea3;color:#fff;border:none;padding:10px 24px;border-radius:8px;font-size:14px;font-weight:700;cursor:pointer;">Print / Save as PDF</button><span style="margin-left:12px;font-size:12px;color:#94a3b8;">In print dialog choose Save as PDF</span></div>'+(e.notes?'<div style="background:#f8fafc;border:1px solid #e2e8f0;border-radius:8px;padding:12px 16px;margin-bottom:24px;font-size:13px;color:#475569;"><strong>Notes:</strong> '+e.notes+"</div>":"")+'<table style="width:100%;border-collapse:collapse;margin-bottom:24px;"><thead><tr style="background:#f1f5f9;"><th style="padding:10px 12px;text-align:left;font-size:11px;font-weight:700;text-transform:uppercase;color:#64748b;">Product</th><th style="padding:10px 12px;text-align:right;font-size:11px;font-weight:700;text-transform:uppercase;color:#64748b;">Qty</th><th style="padding:10px 12px;text-align:right;font-size:11px;font-weight:700;text-transform:uppercase;color:#64748b;">Unit Cost</th><th style="padding:10px 12px;text-align:right;font-size:11px;font-weight:700;text-transform:uppercase;color:#64748b;">Total</th></tr></thead><tbody>'+i+'</tbody></table><div style="display:flex;justify-content:flex-end;margin-bottom:32px;"><div style="min-width:240px;"><div style="display:flex;justify-content:space-between;padding:10px 0;border-top:2px solid #1e293b;"><span style="font-size:16px;font-weight:800;">Total</span><span style="font-size:16px;font-weight:800;color:#0d7ea3;">$'+s.toFixed(2)+'</span></div></div></div><div style="border-top:1px solid #e2e8f0;padding-top:20px;font-size:12px;color:#94a3b8;text-align:center;">Zenith Pure Solutions LLC / Indianapolis, IN / Generated '+d+"</div></body></html>",f=window.open("","_blank");f&&(f.document.write(c),f.document.close())}function M$({allProducts:e}){const[n,r]=g.useState([]),[s,i]=g.useState(!0),[o,a]=g.useState(null),[l,d]=g.useState("all"),[c,f]=g.useState(!1),p=g.useCallback(async()=>{i(!0);const{data:m}=await w.from("purchase_orders").select("*, purchase_order_items(id, product_catalog_id, quantity_ordered, unit_cost, subtotal, product:product_catalog_id(name, sku, vendor_sku, vendor_name))").order("created_at",{ascending:!1});r(m||[]),i(!1)},[]);g.useEffect(()=>{p()},[p]);const u=[{id:"all",color:"#94a3b8"},{id:"draft",color:"#64748b"},{id:"submitted",color:"#60a5fa"},{id:"partial",color:"#a78bfa"},{id:"received",color:"#4ade80"}],h=n.filter(m=>l==="all"||m.status===l);async function y(m,b){try{const A={status:b};b==="received"&&(A.received_at=new Date().toISOString()),await w.from("purchase_orders").update(A).eq("id",m)}catch(A){console.error(A)}p()}return t.jsxs("div",{children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:16,flexWrap:"wrap",gap:10},children:[t.jsx("div",{style:{display:"flex",gap:4,padding:4,background:"rgba(255,255,255,0.03)",border:"1px solid rgba(255,255,255,0.06)",borderRadius:12,overflowX:"auto"},children:u.map(m=>t.jsxs("button",{onClick:()=>d(m.id),style:{padding:"8px 16px",borderRadius:8,fontSize:13,fontWeight:500,cursor:"pointer",whiteSpace:"nowrap",flexShrink:0,border:l===m.id?`1px solid ${m.color}35`:"1px solid transparent",background:l===m.id?`${m.color}18`:"transparent",color:l===m.id?m.color:"#64748b",textTransform:"capitalize"},children:[m.id," ",m.id!=="all"&&`(${n.filter(b=>b.status===m.id).length})`]},m.id))}),t.jsx("button",{onClick:()=>f(!0),style:{padding:"9px 18px",borderRadius:10,border:"none",background:"#0d7ea3",color:"#fff",fontWeight:700,fontSize:13,cursor:"pointer",whiteSpace:"nowrap"},children:"+ Create PO"})]}),t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:s?t.jsx("div",{style:{textAlign:"center",padding:40,color:"#64748b"},children:"Loadingâ¦"}):h.length===0?t.jsx("div",{style:{textAlign:"center",padding:60,color:"#64748b",background:"#162232",border:"1px solid #1e3a4f",borderRadius:14},children:"No purchase orders"}):h.map(m=>{var b;return t.jsxs("div",{style:{background:"#162232",border:`1px solid ${o===m.id?"rgba(96,165,250,0.3)":"#1e3a4f"}`,borderRadius:14,overflow:"hidden"},children:[t.jsxs("div",{onClick:()=>a(o===m.id?null:m.id),style:{display:"flex",alignItems:"center",gap:12,padding:"14px 18px",cursor:"pointer",background:o===m.id?"rgba(96,165,250,0.04)":"transparent",flexWrap:"wrap"},children:[t.jsx("span",{style:{fontFamily:"monospace",fontWeight:800,fontSize:13,color:"#60a5fa"},children:m.po_number}),t.jsx(io,{val:m.status}),t.jsx("span",{style:{marginLeft:"auto",fontSize:12,color:"#475569"},children:new Date(m.created_at).toLocaleDateString()}),m.subtotal!=null&&t.jsx("span",{style:{fontSize:13,fontWeight:700,color:"#4ade80"},children:Ks(m.subtotal)}),t.jsxs("span",{style:{fontSize:12,color:"#475569"},children:[((b=m.purchase_order_items)==null?void 0:b.length)||0," items"]}),t.jsx("span",{style:{color:"#334155"},children:o===m.id?"â²":"â¼"})]}),o===m.id&&t.jsxs("div",{style:{padding:"16px 18px",borderTop:"1px solid #1e3a4f"},children:[t.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",marginBottom:12},children:[t.jsx("thead",{children:t.jsx("tr",{style:{borderBottom:"1px solid #1e3a4f"},children:["Product","Qty","Unit Cost","Line Total"].map((A,v)=>t.jsx("th",{style:{padding:"6px 10px",textAlign:v===0?"left":"right",fontSize:10,fontWeight:700,color:"#475569",textTransform:"uppercase",letterSpacing:"0.06em"},children:A},A))})}),t.jsx("tbody",{children:(m.purchase_order_items||[]).map(A=>{var v,x,_;return t.jsxs("tr",{style:{borderBottom:"1px solid #0d1a26"},children:[t.jsxs("td",{style:{padding:"8px 10px"},children:[t.jsx("div",{style:{fontSize:13,color:"#e2e8f0"},children:((v=A.product)==null?void 0:v.name)||"â"}),t.jsxs("div",{style:{fontSize:11,color:"#475569",fontFamily:"monospace"},children:["Internal: ",((x=A.product)==null?void 0:x.sku)||"â"," / Vendor: ",((_=A.product)==null?void 0:_.vendor_sku)||"â"]}
630)]}),t.jsx("td",{style:{padding:"8px 10px",textAlign:"right",color:"#e2e8f0",fontWeight:700},children:A.quantity_ordered}),t.jsx("td",{style:{padding:"8px 10px",textAlign:"right",color:"#64748b"},children:Ks(A.unit_cost)}),t.jsx("td",{style:{padding:"8px 10px",textAlign:"right",color:"#e2e8f0"},children:Ks(A.quantity_ordered*A.unit_cost)})]},A.id)})})]}),m.notes&&t.jsx("p",{style:{fontSize:12,color:"#475569",marginBottom:12},children:m.notes}),t.jsxs("div",{style:{display:"flex",gap:8,flexWrap:"wrap"},children:[m.status==="draft"&&t.jsx("button",{onClick:()=>y(m.id,"submitted"),style:{padding:"7px 16px",borderRadius:8,border:"1px solid rgba(96,165,250,0.25)",background:"rgba(96,165,250,0.1)",color:"#60a5fa",cursor:"pointer",fontSize:13,fontWeight:600},children:"Mark Submitted"}),m.status==="submitted"&&t.jsx("button",{onClick:()=>y(m.id,"partial"),style:{padding:"7px 16px",borderRadius:8,border:"1px solid rgba(167,139,250,0.25)",background:"rgba(167,139,250,0.1)",color:"#a78bfa",cursor:"pointer",fontSize:13,fontWeight:600},children:"Mark Partial"}),(m.status==="submitted"||m.status==="partial")&&t.jsx("span",{title:"Use the Receiving tab to receive this PO and update inventory",style:{padding:"7px 16px",borderRadius:8,border:"1px solid rgba(74,222,128,0.15)",background:"rgba(74,222,128,0.04)",color:"#4ade8066",fontSize:13,fontWeight:600,cursor:"not-allowed",display:"inline-flex",alignItems:"center",gap:6},children:"â
Use Receiving Tab to receive stock"}),m.status!=="received"&&m.status!=="cancelled"&&t.jsx("button",{onClick:()=>y(m.id,"cancelled"),style:{padding:"7px 16px",borderRadius:8,border:"1px solid rgba(248,113,113,0.2)",background:"rgba(248,113,113,0.08)",color:"#f87171",cursor:"pointer",fontSize:13,fontWeight:600},children:"Cancel PO"}),t.jsx("button",{onClick:()=>$$(m),style:{padding:"7px 16px",borderRadius:8,border:"1px solid rgba(251,191,36,0.25)",background:"rgba(251,191,36,0.08)",color:"#fbbf24",cursor:"pointer",fontSize:13,fontWeight:600,marginLeft:"auto"},children:"ð¨ï¸ Print / PDF"})]})]})]},m.id)})}),c&&t.jsx(I$,{allProducts:e,onClose:()=>f(!1),onDone:p})]})}function F$(){const[e,n]=g.useState([]),[r,s]=g.useState(!0),[i,o]=g.useState(null),[a,l]=g.useState({}),[d,c]=g.useState(!1),[f,p]=g.useState(!1),[u,h]=g.useState({}),y=g.useCallback(async()=>{s(!0);const{data:A}=await w.from("purchase_orders").select("*, purchase_order_items(id, product_catalog_id, quantity_ordered, unit_cost, subtotal, product:product_catalog_id(name, sku, vendor_sku, vendor_name))").in("status",["submitted","partial"]).order("created_at",{ascending:!1});n(A||[]);const v=[...new Set((A||[]).flatMap(x=>(x.purchase_order_items||[]).map(_=>_.product_catalog_id)).filter(Boolean))];if(v.length){const{data:x}=await w.from("product_catalog").select("id, name, sku").in("id",v),_={};for(const j of x||[])_[j.id]={name:j.name,sku:j.sku};h(_)}s(!1)},[]);g.useEffect(()=>{y()},[y]);function m(A){o(A),p(!1);const v={};(A.purchase_order_items||[]).forEach(x=>{v[x.id]=String(x.quantity_ordered)}),l(v)}async function b(){if(i){c(!0);try{for(const A of i.purchase_order_items||[]){const v=parseInt(a[A.id]||"0");v>0&&await T$(A.product_catalog_id,v,{purchaseOrderItemId:A.id})}}catch(A){console.error("[Receiving] receive failed:",A),alert("Receive failed: "+((A==null?void 0:A.message)||"unknown error")),c(!1);return}try{const{data:A}=await w.from("jobs").select("id").eq("job_status","waiting_for_stock");if(A&&A.length>0)for(const v of A)await w.rpc("rpc_recheck_waiting_job",{p_job_id:v.id})}catch(A){console.error("[Receiving] Recheck waiting jobs error:",A)}c(!1),p(!0),y()}}return r?t.jsx("div",{style:{textAlign:"center",padding:40,color:"#64748b"},children:"Loadingâ¦"}):f?t.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",padding:60},children:t.jsxs("div",{style:{textAlign:"center"},children:[t.jsx("div",{style:{fontSize:48,marginBottom:16},children:"â
"}),t.jsx("div",{style:{color:"#e2e8f0",fontWeight:800,fontSize:20,marginBottom:8},children:"Stock Received"}),t.jsxs("div",{style:{color:"#475569",fontSize:13,marginBottom:24},children:[i==null?void 0:i.po_number," marked received. Inventory updated."]}),t.jsx("button",{onClick:()=>o(null),style:{padding:"10px 24px",borderRadius:10,background:"rgba(255,255,255,0.06)",border:"1px solid rgba(255,255,255,0.1)",color:"#94a3b8",curs
630or:"pointer",fontSize:13},children:"Back to List"})]})}):i?t.jsxs("div",{style:{maxWidth:500},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,marginBottom:20},children:[t.jsx("button",{onClick:()=>o(null),style:{color:"#64748b",background:"none",border:"none",cursor:"pointer",fontSize:13},children:"â Back"}),t.jsx("span",{style:{fontFamily:"monospace",fontWeight:800,color:"#60a5fa",fontSize:13},children:i.po_number}),t.jsx(io,{val:i.status})]}),t.jsxs("div",{style:{background:"#162232",border:"1px solid #1e3a4f",borderRadius:12,padding:20,marginBottom:16},children:[t.jsx("p",{style:{fontSize:11,color:"#475569",textTransform:"uppercase",fontWeight:700,letterSpacing:"0.06em",marginBottom:14},children:"Confirm quantities received"}),t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:12},children:(i.purchase_order_items||[]).map(A=>{var v,x,_;return t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12},children:[t.jsxs("div",{style:{flex:1},children:[t.jsx("div",{style:{fontSize:13,color:"#e2e8f0"},children:((v=u[A.product_catalog_id])==null?void 0:v.name)||((x=A.product_catalog_id)==null?void 0:x.slice(0,8))}),t.jsxs("div",{style:{fontSize:11,color:"#475569",fontFamily:"monospace"},children:[((_=u[A.product_catalog_id])==null?void 0:_.sku)||"â"," · Ordered: ",A.quantity_ordered]})]}),t.jsx("input",{type:"number",value:a[A.id]||"",onChange:j=>l(C=>({...C,[A.id]:j.target.value})),style:{width:72,background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:8,color:"#e2e8f0",padding:"7px 10px",fontSize:13,outline:"none",textAlign:"right"}})]},A.id)})})]}),t.jsx("button",{onClick:b,disabled:d,style:{width:"100%",padding:"12px 0",borderRadius:12,border:"none",background:"#0d7ea3",color:"#fff",fontWeight:700,fontSize:14,cursor:"pointer",opacity:d?.5:1},children:d?"Processingâ¦":"Confirm Receipt & Update Stock"})]}):t.jsxs("div",{children:[t.jsx("p",{style:{color:"#475569",fontSize:13,marginBottom:16},children:"Select a purchase order to confirm receipt and update stock levels."}),e.length===0?t.jsx("div",{style:{textAlign:"center",padding:60,color:"#475569",background:"#162232",border:"1px solid #1e3a4f",borderRadius:14},children:"No pending purchase orders to receive"}):t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:e.map(A=>{var v;return t.jsxs("div",{onClick:()=>m(A),style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 18px",background:"#162232",border:"1px solid #1e3a4f",borderRadius:12,cursor:"pointer"},onMouseEnter:x=>{x.currentTarget.style.borderColor="rgba(96,165,250,0.3)"},onMouseLeave:x=>{x.currentTarget.style.borderColor="#1e3a4f"},children:[t.jsxs("div",{children:[t.jsx("span",{style:{fontFamily:"monospace",fontWeight:800,fontSize:13,color:"#60a5fa"},children:A.po_number}),t.jsx("span",{style:{marginLeft:12},children:t.jsx(io,{val:A.status})}),t.jsxs("div",{style:{fontSize:12,color:"#475569",marginTop:4},children:[(v=A.purchase_order_items)==null?void 0:v.length," items"]})]}),t.jsx("button",{style:{padding:"8px 18px",borderRadius:10,border:"none",background:"#0d7ea3",color:"#fff",fontWeight:700,fontSize:13,cursor:"pointer"},children:"Receive"})]},A.id)})})]})}function B$(){const[e,n]=g.useState([]),[r,s]=g.useState(!0),[i,o]=g.useState(""),[a,l]=g.useState("all"),[d,c]=g.useState({});g.useEffect(()=>{(async()=>{s(!0);const{data:u}=await w.from("inventory_transactions").select("*").order("created_at",{ascending:!1}).limit(200);n(u||[]);const h=[...new Set((u||[]).map(y=>y.product_id).filter(Boolean))];if(h.length){const{data:y}=await w.from("product_catalog").select("id, name, sku").in("id",h),m={};for(const b of y||[])m[b.id]={name:b.name,sku:b.sku};c(m)}s(!1)})()},[]);const f=["all",...Array.from(new Set(e.map(u=>u.transaction_type)))],p=e.filter(u=>{var y,m,b,A;return(!i||((m=(y=d[u.product_id])==null?void 0:y.name)==null?void 0:m.toLowerCase().includes(i.toLowerCase()))||((A=(b=d[u.product_id])==null?void 0:b.sku)==null?void 0:A.toLowerCase().includes(i.toLowerCase())))&&(a==="all"||u.transaction_type===a)});return t.jsxs("div",{children:[t.jsxs("div",{style:{display:"flex",gap:10,marginBottom:16},children:[t.jsx("input",{value:i,onChange:u=>o(u.target.value),placeholder:"Search productâ¦",style:{flex:1,background:"rgba(255,255,255,0.04)",border:"1px solid rgba(255,255,255,0.08)",borderRadius:10,color:"#e2e8f0",padding:"9px 14px",fontSize:13,outline:"none"}}),t.jsx("select",{value:a,onChange:u=>l(u.target.value),style:{background:"rgba(255,255,255,0.04)",border:"1px solid rgba(255,255,255,0.08)",borderRadius:10,color:"#94a3b8",padding:"9px 14px",fontSize:13,outline:"none"},children:f.map(u=>t.jsx("option",{value:u,style:{background:"#0f1923"},children:u==="all"?"All Types":`${C_[u]||""} ${u}`},u))})]}),t.jsx("div",{style:{background:"#162232",border:"1px solid #1e3a4f",borderRadius:14,overflow:"hidden"},children:t.jsx("div",{style:{overflowX:"auto"},children:t.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",minWidth:560},children:[t.jsx("thead",{children:t.jsx("tr",{style:{background:"#0f1923",borderBottom:"1px solid #1e3a4f"},children:["Date","Product","Type","Change","Reference","Notes"].map((u,h)=>t.jsx("th",{style:{padding:"10px 14px",textAlign:h===3?"right":"left",fontSize:10,fontWeight:700,color:"#64748b",textTransform:"uppercase",letterSpacing:"0.08em"},children:u},u))})}),t.jsx("tbody",{children:r?t.jsx("tr",{children:t.jsx("td",{colSpan:6,style:{textAlign:"center",padding:40,color:"#64748b"},children:"Loadingâ¦"})}):p.length===0?t.jsx("tr",{children:t.jsx("td",{colSpan:6,style:{textAlign:"center",padding:40,color:"#64748b"}
630,children:"No transactions found"})}):p.map(u=>{var h,y,m;return t.jsxs("tr",{style:{borderBottom:"1px solid #0d1a26"},children:[t.jsxs("td",{style:{padding:"10px 14px"},children:[t.jsx("div",{style:{fontSize:12,color:"#94a3b8"},children:new Date(u.created_at).toLocaleDateString()}),t.jsx("div",{style:{fontSize:11,color:"#334155"},children:new Date(u.created_at).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}),t.jsxs("td",{style:{padding:"10px 14px"},children:[t.jsx("div",{style:{fontSize:13,color:"#e2e8f0"},children:((h=d[u.product_id])==null?void 0:h.name)||((y=u.product_id)==null?void 0:y.slice(0,8))}),t.jsx("div",{style:{fontSize:11,color:"#475569",fontFamily:"monospace"},children:((m=d[u.product_id])==null?void 0:m.sku)||"â"})]}),t.jsx("td",{style:{padding:"10px 14px",fontSize:13,color:"#94a3b8"},children:C_[u.transaction_type]||u.transaction_type}),t.jsxs("td",{style:{padding:"10px 14px",textAlign:"right",fontSize:16,fontWeight:800,color:u.qty>0?"#4ade80":"#f87171"},children:[u.qty>0?"+":"",u.qty]}),t.jsx("td",{style:{padding:"10px 14px",fontSize:12,color:"#475569",textTransform:"capitalize"},children:u.reference_type||"â"}),t.jsx("td",{style:{padding:"10px 14px",fontSize:12,color:"#475569",maxWidth:180,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:u.notes||"â"})]},u.id)})})]})})})]})}function U$({allProducts:e}){const[n,r]=g.useState([]),[s,i]=g.useState(!0),[o,a]=g.useState(!1),[l,d]=g.useState(!1),[c,f]=g.useState(null),[p,u]=g.useState("all"),[h,y]=g.useState(""),[m,b]=g.useState(""),[A,v]=g.useState(null),[x,_]=g.useState(""),[j,C]=g.useState(""),[S,T]=g.useState("good"),[L,E]=g.useState(""),[R,N]=g.useState(!1),[O,z]=g.useState([]),P=g.useCallback(async()=>{i(!0);const{data:I}=await w.from("equipment_returns").select("*, customers(full_name), product_catalog(name, sku)").order("created_at",{ascending:!1});r(I||[]),i(!1)},[]);g.useEffect(()=>{P()},[P]),g.useEffect(()=>{if(m.length<2){z([]);return}const I=setTimeout(async()=>{const{data:B}=await w.from("customers").select("id, full_name, phone").ilike("full_name",`%${m}%`).limit(6);z(B||[])},300);return()=>clearTimeout(I)},[m]);async function D(){h&&(d(!0),await w.from("equipment_returns").insert({customer_id:A||null,product_id:h,serial_number:j||null,condition:S,refurb_status:S==="needs_refurb"?"in_progress":"none",redeployable:R,restocked:!1,notes:L||null,returned_at:new Date().toISOString().split("T")[0]}),d(!1),a(!1),y(""),C(""),E(""),v(null),b(""),_(""),T("good"),N(!1),P())}async function M(I){if(!I.product_id||I.restocked)return;f(I.id);const{data:B}=await w.from("inventory_items").select("id, quantity_on_hand, quantity_available").eq("product_catalog_id",I.product_id).maybeSingle();B&&await w.from("inventory_items").update({quantity_on_hand:B.quantity_on_hand+1,quantity_available:B.quantity_available+1}).eq("id",B.id),await w.from("equipment_returns").update({restocked:!0,redeployable:!0}).eq("id",I.id),f(null),P()}async function k(I,B){const J={refurb_status:B};B==="complete"&&(J.redeployable=!0),await w.from("equipment_returns").update(J).eq("id",I),P()}const q=[{id:"all",label:"All",color:"#94a3b8"},{id:"good",label:"Good",color:"#4ade80"},{id:"needs_refurb",label:"Needs Refurb",color:"#fbbf24"},{id:"damaged",label:"Damaged",color:"#f87171"}],$=n.filter(I=>p==="all"||I.condition===p);return t.jsxs("div",{children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:16,flexWrap:"wrap",gap:10},children:[t.jsx("div",{style:{display:"flex",gap:4,padding:4,background:"rgba(255,255,255,0.03)",border:"1px solid rgba(255,255,255,0.06)",borderRadius:12,overflowX:"auto"},children:q.map(I=>t.jsxs("button",{onClick:()=>u(I.id),style:{padding:"8px 14px",borderRadius:8,fontSize:13,fontWeight:500,cursor:"pointer",whiteSpace:"nowrap",flexShrink:0,border:p===I.id?`1px solid ${I.color}35`:"1px solid transparent",background:p===I.id?`${I.color}18`:"transparent",color:p===I.id?I.color:"#64748b"},children:[I.label," ",I.id!=="all"&&`(${n.filter(B=>B.condition===I.id).length})`]},I.id))}),t.jsx("button",{onClick:()=>a(!o),style:{padding:"9px 18px",borderRadius:10,border:"none",background:"#0d7ea3",color:"#fff",fontWeight:700,fontSize:13,cursor:"pointer",whiteSpace:"nowrap"},children:"+ Log Return"})]}),t.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(4, 1fr)",gap:10,marginBottom:16},children:[{label:"Total Returns",value:n.length,color:"#60a5fa"},{label:"Redeployable",value:n.filter(I=>I.redeployable&&!I.restocked).length,color:"#4ade80"},{label:"Needs Refurb",value:n.filter(I=>I.condition==="needs_refurb").length,color:"#fbbf24"},{label:"Restocked",value:n.filter(I=>I.restocked).length,color:"#a78bfa"}].map(I=>t.jsxs("div",{style:{background:"rgba(255,255,255,0.03)",border:"1px solid rgba(255,255,255,0.06)",borderRadius:12,padding:"10px 14px"},children:[t.jsx("div",{style:{fontSize:20,fontWeight:800,color:I.color},children:I.value}),t.jsx("div",{style:{fontSize:11,color:"#64748b",marginTop:2},children:I.label})]},I.label))}),o&&t.jsxs("div",{style:{background:"#162232",border:"1px solid #1e3a4f",borderRadius:14,padding:20,marginBottom:16},children:[t.jsx("div",{style:{color:"#e2e8f0",fontWeight:700,fontSize:15,marginBottom:16},children:"Log Equipment Return"}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12,marginBottom:12},children:[t.jsxs("div",{children:[t.jsx("label",{style:{display:"block",fontSize:11,color:"#64748b",fontWeight:700,textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:6},children:"Product *"}),t.jsxs("select",{value:h,onChange:I=>y(I.target.value),style:{width:"100%",background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:8,color:h?"#e2e8f0":"#64748b",padding:"9px 12px",fontSize:13,outline:"none"},children:[t.jsx("option",{value:"",children:"Select productâ¦"}),e.map(I=>t.jsx("option",{value:I.id,style:{background:"#0f1923"},children:I.name},I.id))]})]}),t.jsxs("div",{style:{position:"relative"},children:[t.jsx("label",{style:{display:"block",fontSize:11,color:"#64748b",fontWeight:700,textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:6},children:"Customer (optional)"}),A?t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:8,padding:"9px 12px"},children:[t.jsx("span",{style:{fontSize:13,color:"#e2e8f0",flex:1},children:x}),t.jsx("button",{onClick:()=>{v(null),_(""),b("")},style:{background:"none",border:"none",color:"#64748b",cursor:"pointer",fontSize:14},children:"Ã"})]}):t.jsxs(t.Fragment,{children:[t.jsx("input",{value:m,onChange:I=>b(I.target.value),placeholder:"Search customer nameâ¦",style:{width:"100%",background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:8,color:"#e2e8f0",padding:"9px 12px",fontSize:13,outline:"none",boxSizing:"border-box"}}),O.length>0&&t.jsx("div",{style:{position:"absolute",left:0,right:0,top:"100%",background:"#162232",border:"1px solid #1e3a4f",borderRadius:8,zIndex:10},children:O.map(I=>t.jsxs("div",{onClick:()=>{v(I.id),_(I.full_name),b(""),z([])},style:{padding:"9px 14px",cursor:"pointer",borderBottom:"1px solid #0d1a26",fontSize:13,color:"#e2e8f0"},onMouseEnter:B=>{B.currentTarget.style.background="#1e3a4f"},onMouseLeave:B=>
630{B.currentTarget.style.background="transparent"},children:[I.full_name," ",t.jsx("span",{style:{color:"#64748b",fontSize:11},children:I.phone})]},I.id))})]})]})]}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:12,marginBottom:12},children:[t.jsxs("div",{children:[t.jsx("label",{style:{display:"block",fontSize:11,color:"#64748b",fontWeight:700,textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:6},children:"Serial Number"}),t.jsx("input",{value:j,onChange:I=>C(I.target.value),placeholder:"Optional",style:{width:"100%",background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:8,color:"#e2e8f0",padding:"9px 12px",fontSize:13,outline:"none",boxSizing:"border-box",fontFamily:"monospace"}})]}),t.jsxs("div",{children:[t.jsx("label",{style:{display:"block",fontSize:11,color:"#64748b",fontWeight:700,textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:6},children:"Condition *"}),t.jsxs("select",{value:S,onChange:I=>T(I.target.value),style:{width:"100%",background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:8,color:"#e2e8f0",padding:"9px 12px",fontSize:13,outline:"none"},children:[t.jsx("option",{value:"good",style:{background:"#0f1923"},children:"Good"}),t.jsx("option",{value:"needs_refurb",style:{background:"#0f1923"},children:"Needs Refurb"}),t.jsx("option",{value:"damaged",style:{background:"#0f1923"},children:"Damaged"})]})]}),t.jsx("div",{style:{display:"flex",flexDirection:"column",justifyContent:"flex-end"},children:t.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer",paddingBottom:10},children:[t.jsx("input",{type:"checkbox",checked:R,onChange:I=>N(I.target.checked),style:{accentColor:"#4ade80",width:15,height:15}}),t.jsx("span",{style:{fontSize:13,color:"#e2e8f0"},children:"Redeployable now"})]})})]}),t.jsxs("div",{style:{marginBottom:14},children:[t.jsx("label",{style:{display:"block",fontSize:11,color:"#64748b",fontWeight:700,textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:6},children:"Notes"}),t.jsx("input",{value:L,onChange:I=>E(I.target.value),placeholder:"Reason for return, condition detailsâ¦",style:{width:"100%",background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:8,color:"#e2e8f0",padding:"9px 12px",fontSize:13,outline:"none",boxSizing:"border-box"}})]}),t.jsxs("div",{style:{display:"flex",gap:10,justifyContent:"flex-end"},children:[t.jsx("button",{onClick:()=>a(!1),style:{padding:"8px 16px",fontSize:13,color:"#64748b",background:"none",border:"none",cursor:"pointer"},children:"Cancel"}),t.jsx("button",{onClick:D,disabled:l||!h,style:{padding:"10px 22px",borderRadius:8,border:"none",cursor:"pointer",background:h?"#0d7ea3":"#334155",color:"#fff",fontWeight:700,fontSize:14,opacity:l?.5:1},children:l?"Savingâ¦":"Log Return"})]})]}),t.jsx("div",{style:{background:"#162232",border:"1px solid #1e3a4f",borderRadius:14,overflow:"hidden"},children:t.jsx("div",{style:{overflowX:"auto"},children:t.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",minWidth:800},children:[t.jsx("thead",{children:t.jsx("tr",{style:{background:"#0f1923",borderBottom:"1px solid #1e3a4f"},children:["Date","Product","Customer","Serial","Condition","Refurb","Status","Actions"].map((I,B)=>t.jsx("th",{style:{padding:"10px 14px",textAlign:"left",fontSize:10,fontWeight:700,color:"#64748b",textTransform:"uppercase",letterSpacing:"0.08em"},children:I},I))})}),t.jsx("tbody",{children:s?t.jsx("tr",{children:t.jsx("td",{colSpan:8,style:{textAlign:"center",padding:40,color:"#64748b"},children:"Loadingâ¦"})}):$.length===0?t.jsx("tr",{children:t.jsx("td",{colSpan:8,style:{textAlign:"center",padding:60,color:"#64748b"},children:'No returns logged yet. Use "Log Return" to record returned equipment.'})}):$.map(I=>{var U,W,G;const[B,J]=R$[I.condition]||["rgba(100,116,139,0.12)","#64748b"],[ae,te]=E$[I.refurb_status]||["rgba(100,116,139,0.12)","#64748b"];return t.jsxs("tr",{style:{borderBottom:"1px solid #0d1a26"},children:[t.jsx("td",{style:{padding:"10px 14px",fontSize:12,color:"#64748b"},children:new Date(I.returned_at).toLocaleDateString()}),t.jsxs("td",{style:{padding:"10px 14px"},children:[t.jsx("div",{style:{fontSize:13,fontWeight:600,color:"#e2e8f0"},children:((U=I.product_catalog)==null?void 0:U.name)||"â"}),t.jsx("div",{style:{fontSize:11,color:"#475569",fontFamily:"monospace"},children:((W=I.product_catalog)==null?void 0:W.sku)||"â"})]}),t.jsx("td",{style:{padding:"10px 14px",fontSize:13,color:"#94a3b8"},children:((G=I.customers)==null?void 0:G.full_name)||t.jsx("span",{style:{color:"#334155"},children:"â"})}),t.jsx("td",{style:{padding:"10px 14px",fontSize:12,color:"#64748b",fontFamily:"monospace"},children:I.serial_number||"â"}),t.jsx("td",{style:{padding:"10px 14px"},children:t.jsx("span",{style:{background:B,color:J,border:`1px solid ${J}35`,fontSize:11,fontWeight:700,padding:"2px 8px",borderRadius:20},children:I.condition.replace(/_/g," ")})}),t.jsx("td",{style:{padding:"10px 14px"},children:I.condition==="needs_refurb"?t.jsxs("select",{value:I.refurb_status,onChange:V=>k(I.id,V.target.value),style:{background:ae,color:te,border:`1px solid ${te}35`,borderRadius:8,padding:"3px 8px",fontSize:11,fontWeight:700,outline:"none",cursor:"pointer"},children:[t.jsx("option",{value:"in_progress",style:{background:"#0f1923"},children:"In Progress"}),t.jsx("option",{value:"complete",style:{background:"#0f1923"},children:"Complete"})]}):t.jsx("span",{style:{color:"#334155",fontSize:12},children:"â"})}),t.jsx("td",{style:{padding:"10px 14px"},children:I.restocked?t.jsx("span",{style:{fontSize:11,color:"#4ade80",fontWeight:700},children:"â Restocked"}):I.redeployable?t.jsx("span",{style:{fontSize:11,color:"#22d3ee",fontWeight:700},children:"Ready"}):t.jsx("span",{style:{fontSize:11,color:"#334155"},children:"Pending"})}),t.jsxs("td",{style:{padding:"10px 14px"},children:[I.redeployable&&!I.restocked&&t.jsx("button",{onClick:()=>M(I),disabled:c===I.id,style:{fontSize:11,padding:"4px 12px",borderRadius:7,border:"1px solid rgba(74,222,128,0.3)",background:"rgba(74,222,128,0.1)",color:"#4ade80",cursor:"pointer",fontWeight:600,opacity:c===I.id?.5:1},children:c===I.id?"â¦":"+ Restock"}),I.notes&&t.jsx("div",{style:{fontSize:11,color:"#475569",marginTop:4,maxWidth:140,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:I.notes,children:I.notes})]})]},I.id)})})]})})})]})}const H$=[{id:"stock",label:"Stock Levels",icon:"ð¦"},{id:"reorder",label:"Reorder Requests",icon:"â ï¸"},{id:"purchase",label:"Purchase Orders",icon:"ð"},{id:"receiving",label:"Receiving",icon:"â
"},{id:"transactions",label:"Transactions",icon:"ð"},{id:"returns",label:"Returns",icon:"â©ï¸"}];function V$(){const[e,n]=g.useState("stock"),[r,s]=g.useState([]);return g.useEffect(()=>{w.from("product_catalog").select("id, name, sku, category, is_active, vendor_name, vendor_sku, vendor_cost").eq("is_active",!0).order("name").then(({data:i})=>s(i||[]))},[]),t.jsxs("div",{style:{minHeight:"100%"},children:[t.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:24},children:t.jsxs("div",{children:[t.jsx("h1",{style:{fontSize:22,fontWeight:800,color:"#e2e8f0",margin:0},children:"Inventory"}),t.jsx("p",{style:{fontSize:13,color:"#475569",marginTop:4,marginBottom:0},children:"Stock levels, reorder requests, purchase orders, receiving, and returns"})]})}),t.jsx("div",{style:{display:"flex",gap:4,marginBottom:24,padding:4,background:"rgba(255,255,255,0.03)",border:"1px solid rgba(255,255,255,0.06)",borderRadius:12,overflowX:"auto"},children:H$.map(i=>t.jsxs("button",{onClick:()=>n(i.id),style:{display:"flex",alignItems:"center",gap:6,padding:"8px 16px",borderRadius:8,fontSize:13,fontWeight:500,cursor:"pointer",whiteSpace:"nowrap",flexShrink:0,border:e===i.id?"1px solid rgba(96,165,250,0.3)":"1px solid transparent",background:e===i.id?"rgba(96,165,250,0.15)":"transparent",color:e===i.id?"#60a5fa":"#64748b"},children:[t.jsx("span",{children:i.icon}),t.jsx("span",{children:i.label})]},i.id))}),e==="stock"&&t.jsx(L$,{onSwitchToPO:()=>n("purchase")}),e==="reorder"&&t.jsx(W$,{}),e==="purchase"&&t.jsx(M$,{allProducts:r}),e==="receiving"&&t.jsx(F$,{}),e==="transactions"&&t.jsx(B$,{}),e==="returns"&&t.jsx(U$,{allProducts:r})]})}const ah=[{value:"admin",label:"Admin",color:"#f87171",bg:"rgba(248,113,113,0.1)"},{value:"frontdesk",label:"Front Desk",color:"#a78bfa",bg:"rgba(167,139,250,0.1)"},{value:"salesrep",label:"Sales Rep",color:"#60a5fa",bg:"rgba(96,165,250,0.1)"},{value:"technician",label:"Technician",color:"#4ade80",bg:"rgba(74,222,128,0.1)"}],T_=[{id:"all",label:"All Users",icon:"ð¥",color:"#60a5fa"},{id:"admin",label:"Admin",icon:"âï¸",color:"#f87171"},{id:"frontdesk",label:"Front Desk",icon:"ð",color:"#a78bfa"},{id:"salesrep",label:"Sales Rep",icon:"⬡",color:"#22d3ee"}
630,{id:"technician",label:"Technician",icon:"ð§",color:"#4ade80"},{id:"banned",label:"Banned",icon:"ð«",color:"#64748b"}],Z$=["Core","Sales","Operations","Finance","Analytics","Admin"],K$={Core:"#60a5fa",Sales:"#34d399",Operations:"#fbbf24",Finance:"#f87171",Analytics:"#a78bfa",Admin:"#fb923c"};function hm(e){return ah.find(n=>n.value===e)||{color:"#94a3b8",bg:"rgba(148,163,184,0.1)",label:e}}async function So(e,n){const{data:{session:r}}=await w.auth.getSession(),s=r==null?void 0:r.access_token,i=await fetch("/api/admin/users",{method:e,headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:n?JSON.stringify(n):void 0}),o=await i.json();if(!i.ok)throw new Error(o.error||"Request failed");return o}const fm={email:"",password:"",full_name:"",phone:"",role:"salesrep"};function Y$(){const[e,n]=g.useState([]),[r,s]=g.useState(!0),[i,o]=g.useState(null),[a,l]=g.useState("all"),[d,c]=g.useState(!1),[f,p]=g.useState(fm),[u,h]=g.useState(!1),[y,m]=g.useState(null),[b,A]=g.useState([]),[v,x]=g.useState(!1),[_,j]=g.useState(null),[C,S]=g.useState({full_name:"",phone:""}),[T,L]=g.useState(!1),[E,R]=g.useState(null),[N,O]=g.useState(null),z=g.useCallback(async()=>{s(!0),o(null);try{const{users:U}=await So("GET");n(U)}catch(U){o(U.message)}finally{s(!1)}},[]);g.useEffect(()=>{z()},[z]);function P(U){return U==="all"?e.length:U==="banned"?e.filter(W=>W.banned).length:e.filter(W=>W.role===U).length}const D=e.filter(U=>a==="all"?!0:a==="banned"?U.banned:U.role===a);function M(U){A([...U.pages||rh[U.role]||["/dashboard"]]),m(U)}function k(U){U!=="/dashboard"&&A(W=>W.includes(U)?W.filter(G=>G!==U):[...W,U])}async function q(){if(y){x(!0);try{await So("PATCH",{user_id:y.id,action:"set_pages",pages:b}),m(null),await z()}catch(U){o(U.message)}finally{x(!1)}}}async function $(){if(!f.email||!f.password||!f.role){o("Email, password, and role are required");return}h(!0),o(null);try{await So("POST",f),c(!1),p(fm),await z()}catch(U){o(U.message)}finally{h(!1)}}function I(U){S({full_name:U.full_name||"",phone:U.phone||""}),j(U),o(null)}async function B(){if(_){L(!0),o(null);try{await So("PATCH",{user_id:_.id,action:"set_profile",full_name:C.full_name,phone:C.phone}),j(null),await z()}catch(U){o(U.message)}finally{L(!1)}}}async function J(U){O(U.id);try{await So("PATCH",{user_id:U.id,action:U.banned?"unban":"ban"}),await z()}catch(W){o(W.message)}finally{O(null)}}async function ae(U,W){O(U.id+"_role");try{await So("PATCH",{user_id:U.id,action:"set_role",role:W}),await z()}catch(G){o(G.message)}finally{O(null)}}async function te(){if(E){O(E.id+"_delete");try{await So("DELETE",{user_id:E.id}),R(null),await z()}catch(U){o(U.message)}finally{O(null)}}}return t.jsxs("div",{className:"min-h-full",children:[t.jsxs("div",{className:"flex items-center justify-between mb-6",children:[t.jsxs("div",{children:[t.jsx("h1",{className:"text-2xl font-bold text-white",children:"Team & Users"}),t.jsx("p",{className:"text-sm text-slate-500 mt-0.5",children:"Manage team access, roles, and page permissions"})]}),t.jsx("button",{onClick:()=>{c(!0),o(null),p(fm)},className:"px-5 py-2.5 rounded-xl text-sm font-semibold text-white",style:{background:"linear-gradient(135deg, #3b82f6, #2563eb)"},children:"+ Add User"})]}),t.jsx("div",{className:"grid mb-5",style:{gridTemplateColumns:`repeat(${T_.length}, 1fr)`,gap:3},children:T_.map(U=>{const W=a===U.id,G=P(U.id);return t.jsxs("button",{onClick:()=>l(U.id),className:"relative flex items-center justify-between px-4 py-3 rounded-xl transition-all duration-150 text-left",style:{background:W?`linear-gradient(135deg, ${U.color}22, ${U.color}0a)`:"rgba(255,255,255,0.03)",border:`1px solid ${W?U.color+"50":"rgba(255,255,255,0.06)"}`,boxShadow:W?`0 0 18px ${U.color}18`:"none"},children:[t.jsxs("div",{children:[t.jsxs("div",{className:"text-xs font-semibold uppercase tracking-wider mb-1",style:{color:W?U.color:"#64748b"},children:[t.jsx("span",{className:"mr-1.5",children:U.icon}),U.label]}),t.jsx("div",{className:"text-2xl font-bold",style:{color:W?U.color:"#94a3b8"},children:G})]}),W&&t.jsx("div",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:U.color,boxShadow:`0 0 8px ${U.color}`}})]},U.id)})}),t.jsx("div",{className:"grid grid-cols-4 gap-3 mb-6",children:[{label:"Total Users",value:e.length,color:"#60a5fa"},{label:"Active",value:e.filter(U=>!U.banned).length,color:"#4ade80"},{label:"Banned",value:e.filter(U=>U.banned).length,color:"#f87171"},{label:"Custom Access",value:e.filter(U=>U.pages).length,color:"#fbbf24"}].map(U=>t.jsxs("div",{className:"rounded-xl px-4 py-3",style:{background:"rgba(255,255,255,0.03)",border:"1px solid rgba(255,255,255,0.06)"},children:[t.jsx("div",{className:"text-xl font-bold",style:{color:U.color},children:U.value}),t.jsx("div",{className:"text-xs text-slate-500 mt-0.5",children:U.label})]},U.label))}),i&&t.jsxs("div",{className:"mb-4 px-4 py-3 rounded-xl text-sm flex items-center justify-between",style:{background:"rgba(248,113,113,0.1)",border:"1px solid rgba(248,113,113,0.25)",color:"#f87171"},children:[t.jsx("span",{children:i}),t.jsx("button",{onClick:()=>o(null),className:"text-lg ml-4",children:"Ã"})]}),r?t.jsx("div",{className:"text-center py-16 text-slate-500",children:"Loading users..."}):t.jsx("div",{className:"rounded-2xl overflow-hidden",style:{border:"1px solid rgba(255,255,255,0.06)"},children:t.jsx("div",{style:{overflowX:"auto"},children:t.jsxs("table",{className:"w-full text-sm",style:{minWidth:640},children:[t.jsx("thead",{children:t.jsxs("tr",{style:{background:"rgba(255,255,255,0.03)",borderBottom:"1px solid rgba(255,255,255,0.06)"},children:[t.jsx("th",{className:"text-left px-4 py-3 text-xs font-semibold uppercase tracking-wider text-slate-500",children:"User"}),t.jsx("th",{className:"text-left px-4 py-3 text-xs font-semibold uppercase tracking-wider text-slate-500",children:"Role"}),t.jsx("th",{className:"text-left px-4 py-3 text-xs font-semibold uppercase tracking-wider text-slate-500",children:"Page Access"}),t.jsx("th",{className:"text-left px-4 py-3 text-xs font-semibold uppercase tracking-wider text-slate-500",children:"Status"}),t.jsx("th",{className:"text-left px-4 py-3 text-xs font-semibold uppercase tracking-wider text-slate-500",children:"Last Sign In"})," ",t.jsx("th",{className:"px-4 py-3 text-xs font-semibold uppercase tracking-wider text-slate-500 text-right",children:"Actions"})]})}),t.jsx("tbody",{children:D.length===0?t.jsx("tr",{children:t.jsx("td",{colSpan:6,className:"text-center py-16 text-slate-500",children:"No users in this category"})}):D.map((U,W)=>{const G=hm(U.role),V=N==null?void 0:N.startsWith(U.id),ee=U.pages||rh[U.role]||[],re=!!U.pages;return t.jsxs("tr",{style:{borderBottom:"1px solid rgba(255,255,255,0.04)",background:U.banned?"rgba(248,113,113,0.03)":W%2===0?"transparent":"rgba(255,255,255,0.01)",opacity:U.banned?.7:1},children:[t.jsxs("td",{className:"px-4 py-3",children:[t.jsx("div",{className:"font-medium text-white",children:U.full_name||U.email}),U.full_name&&t.jsx("div",{className:"text-xs text-slate-500 mt-0.5",children:U.email}),U.phone&&t.jsx("div",{className:"text-xs mt-0.5",style:{color:"#4ade80"},children:U.phone})]}),t.jsx("td",{className:"px-4 py-3",children:t.jsx("select",{value:U.role,onChange:Q=>ae(U,Q.target.value),disabled:V,className:"rounded-lg px-2 py-1 text-xs font-semibold focus:outline-none disabled:opacity-40",style:{background:G.bg,color:G.color,border:`1px solid ${G.color}35`},children:ah.map(Q=>t.jsx("option",{value:Q.value,style:{background:"#0f1923",color:"#e2e8f0"},children:Q.label},Q.value))})}),t.jsx("td",{className:"px-4 py-3",children:t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsxs("span",{className:"text-xs text-slate-300",children:[ee.length," pages"]}),t.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded font-semibold",style:re?{background:"rgba(251,191,36,0.12)",color:"#fbbf24",border:"1px solid rgba(251,191,36,0.2)"}:{background:"rgba(148,163,184,0.08)",color:"#64748b"}
630,children:re?"Custom":"Default"}),t.jsx("button",{onClick:()=>M(U),className:"text-xs px-2 py-1 rounded-lg",style:{background:"rgba(96,165,250,0.1)",color:"#60a5fa",border:"1px solid rgba(96,165,250,0.2)"},children:"Edit"})]})}),t.jsx("td",{className:"px-4 py-3",children:t.jsx("span",{className:"text-xs font-semibold px-2.5 py-1 rounded-full",style:U.banned?{background:"rgba(248,113,113,0.15)",color:"#f87171",border:"1px solid rgba(248,113,113,0.3)"}:{background:"rgba(74,222,128,0.12)",color:"#4ade80",border:"1px solid rgba(74,222,128,0.25)"},children:U.banned?"Banned":"Active"})}),t.jsx("td",{className:"px-4 py-3 text-slate-400 text-xs",children:U.last_sign_in?new Date(U.last_sign_in).toLocaleDateString():"Never"}),t.jsx("td",{className:"px-4 py-3",children:t.jsxs("div",{className:"flex items-center justify-end gap-2",children:[t.jsx("button",{onClick:()=>I(U),disabled:V,className:"text-xs px-3 py-1.5 rounded-lg font-medium disabled:opacity-40",style:{background:"rgba(96,165,250,0.1)",color:"#60a5fa",border:"1px solid rgba(96,165,250,0.2)"},children:"Edit Profile"}),t.jsx("button",{onClick:()=>J(U),disabled:V,className:"text-xs px-3 py-1.5 rounded-lg font-medium disabled:opacity-40",style:U.banned?{background:"rgba(74,222,128,0.1)",color:"#4ade80",border:"1px solid rgba(74,222,128,0.2)"}:{background:"rgba(251,191,36,0.1)",color:"#fbbf24",border:"1px solid rgba(251,191,36,0.2)"},children:V&&N===U.id?"...":U.banned?"Unban":"Ban"}),t.jsx("button",{onClick:()=>R(U),disabled:V,className:"text-xs px-3 py-1.5 rounded-lg font-medium disabled:opacity-40",style:{background:"rgba(248,113,113,0.08)",color:"#f87171",border:"1px solid rgba(248,113,113,0.2)"},children:"Delete"})]})})]},U.id)})})]})})}),y&&t.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4",style:{background:"rgba(0,0,0,0.75)",backdropFilter:"blur(6px)"},children:t.jsxs("div",{className:"w-full max-w-lg rounded-2xl flex flex-col",style:{background:"#0d1520",border:"1px solid rgba(255,255,255,0.1)",maxHeight:"85vh"},children:[t.jsxs("div",{className:"px-6 pt-5 pb-4",style:{borderBottom:"1px solid rgba(255,255,255,0.06)"},children:[t.jsxs("div",{className:"flex items-start justify-between",children:[t.jsxs("div",{children:[t.jsx("h3",{className:"text-white font-bold text-lg",children:"Page Permissions"}),t.jsxs("p",{className:"text-slate-500 text-sm mt-0.5",children:[y.full_name||y.email," · ",t.jsx("span",{style:{color:hm(y.role).color},children:hm(y.role).label})]})]}),t.jsx("button",{onClick:()=>m(null),className:"text-slate-500 hover:text-white text-xl",children:"Ã"})]}),t.jsxs("div",{className:"mt-3",children:[t.jsx("div",{className:"text-xs text-slate-500 mb-2",children:"Load role defaults:"}),t.jsxs("div",{className:"flex gap-2 flex-wrap",children:[ah.map(U=>t.jsx("button",{onClick:()=>A([...rh[U.value]||["/dashboard"]]),className:"text-xs px-3 py-1.5 rounded-lg",style:{background:U.bg,color:U.color,border:`1px solid ${U.color}30`},children:U.label},U.value)),t.jsx("button",{onClick:()=>A(nh.map(U=>U.path)),className:"text-xs px-3 py-1.5 rounded-lg",style:{background:"rgba(255,255,255,0.05)",color:"#94a3b8",border:"1px solid rgba(255,255,255,0.08)"},children:"All Pages"})]})]})]}),t.jsx("div",{className:"overflow-y-auto px-6 py-4 flex-1 space-y-5",children:Z$.map(U=>{const W=nh.filter(ee=>ee.group===U),G=K$[U],V=W.every(ee=>b.includes(ee.path));return t.jsxs("div",{children:[t.jsxs("div",{className:"flex items-center justify-between mb-2",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("div",{className:"w-2 h-2 rounded-full",style:{background:G}}),t.jsx("span",{className:"text-xs font-bold uppercase tracking-wider",style:{color:G},children:U})]}),t.jsx("button",{onClick:()=>{const ee=W.map(re=>re.path).filter(re=>re!=="/dashboard");A(V?re=>re.filter(Q=>!ee.includes(Q)):re=>[...re,...ee.filter(Q=>!re.includes(Q))])},className:"text-xs",style:{color:V?"#64748b":G},children:V?"Deselect all":"Select all"})]}),t.jsx("div",{className:"grid grid-cols-2 gap-2",children:W.map(ee=>{const re=b.includes(ee.path),Q=ee.path==="/dashboard";return t.jsxs("label",{className:"flex items-center gap-2.5 px-3 py-2.5 rounded-xl",style:{background:re?`${G}10`:"rgba(255,255,255,0.03)",border:re?`1px solid ${G}30`:"1px solid rgba(255,255,255,0.06)",cursor:Q?"default":"pointer"},children:[t.jsx("input",{type:"checkbox",checked:re,disabled:Q,onChange:()=>k(ee.path),className:"w-3.5 h-3.5 rounded",style:{accentColor:G}}),t.jsxs("span",{className:"text-xs font-medium",style:{color:re?"#e2e8f0":"#64748b"},children:[ee.icon," ",ee.label]}),Q&&t.jsx("span",{className:"text-xs text-slate-600 ml-auto",children:"always"})]},ee.path)})})]},U)})}),t.jsxs("div",{className:"px-6 py-4 flex items-center justify-between",style:{borderTop:"1px solid rgba(255,255,255,0.06)"},children:[t.jsxs("span",{className:"text-xs text-slate-500",children:[b.length," of ",nh.length," pages selected"]}),t.jsxs("div",{className:"flex gap-2",children:[t.jsx("button",{onClick:()=>m(null),className:"px-4 py-2 rounded-xl text-sm text-slate-400",style:{background:"rgba(255,255,255,0.05)",border:"1px solid rgba(255,255,255,0.08)"},children:"Cancel"}),t.jsx("button",{onClick:q,disabled:v,className:"px-5 py-2 rounded-xl text-sm font-semibold text-white disabled:opacity-40",style:{background:"linear-gradient(135deg, #3b82f6, #2563eb)"},children:v?"Saving...":"Save Permissions"})]})]})]})}),d&&t.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4",style:{background:"rgba(0,0,0,0.7)",backdropFilter:"blur(4px)"},children:t.jsxs("div",{className:"w-full max-w-md rounded-2xl p-6",style:{background:"#0f1923",border:"1px solid rgba(255,255,255,0.1)"},children:[t.jsx("h3",{className:"text-white font-bold text-lg mb-1",children:"Add New User"}),t.jsx("p",{className:"text-slate-500 text-sm mb-5",children:"Create a login for a new team member."}),t.jsxs("div",{className:"space-y-4",children:[[{label:"Full Name",key:"full_name",type:"text",placeholder:"e.g. Cody Merrill",required:!1},{label:"Email Address",key:"email",type:"email",placeholder:"[email protected]",required:!0},{label:"Mobile Phone",key:"phone",type:"tel",placeholder:"(317) 555-0123",required:!1},{label:"Password",key:"password",type:"password",placeholder:"Minimum 6 characters",required:!0}].map(U=>t.jsxs("div",{children:[t.jsxs("label",{className:"block text-xs text-slate-500 mb-1.5",children:[U.label," ",U.required&&t.jsx("span",{style:{color:"#f87171"},children:"*"})]}),t.jsx("input",{type:U.type,value:f[U.key],onChange:W=>p(G=>({...G,[U.key]:W.target.value})),placeholder:U.placeholder,className:"w-full rounded-xl px-3 py-2.5 text-white text-sm focus:outline-none",style:{background:"rgba(255,255,255,0.06)",border:"1px solid rgba(255,255,255,0.1)"}})]},U.key)),t.jsxs("div",{children:[t.jsxs("label",{className:"block text-xs text-slate-500 mb-1.5",children:["Role ",t.jsx("span",{style:{color:"#f87171"},children:"*"})]}),t.jsx("select",{value:f.role,onChange:U=>p(W=>({...W,role:U.target.value})),className:"w-full rounded-xl px-3 py-2.5 text-white text-sm focus:outline-none",style:{background:"rgba(255,255,255,0.06)",border:"1px solid rgba(255,255,255,0.1)"},children:ah.map(U=>t.jsx("option",{value:U.value,style:{background:"#0f1923"},children:U.label},U.value))})]}),t.jsx("p",{className:"text-xs text-slate-600",children:"You can customize exact page access after creating the user."}),i&&t.jsx("div",{className:"px-3 py-2.5 rounded-xl text-sm",style:{background:"rgba(248,113,113,0.1)",color:"#f87171",border:"1px solid rgba(248,113,113,0.2)"},children:i})]}),t.jsxs("div",{className:"flex gap-2 mt-5",children:[t.jsx("button",{onClick:()=>{c(!1),o(null)},className:"flex-1 py-2.5 rounded-xl text-sm text-slate-400",style:{background:"rgba(255,255,255,0.05)",border:"1px solid rgba(255,255,255,0.08)"},children:"Cancel"}),t.jsx("button",{onClick:$,disabled:u,className:"flex-1 py-2.5 rounded-xl text-sm font-semibold text-white disabled:opacity-40",style:{background:"linear-gradient(135deg, #3b82f6, #2563eb)"},children:u?"Creating...":"Create User"})]})]})}),_&&t.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4",style:{background:"rgba(0,0,0,0.7)",backdropFilter:"blur(4px)"},children:t.jsxs("div",{className:"w-full max-w-md rounded-2xl p-6",style:{background:"#0f1923",border:"1px solid rgba(255,255,255,0.1)"},children:[t.jsx("h3",{className:"text-white font-bold text-lg mb-1",children:"Edit Profile"}),t.jsx("p",{className:"text-slate-500 text-sm mb-5",children:"Update name and mobile number."}),t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{children:[t.jsx("label",{className:"block text-xs text-slate-500 mb-1.5",children:"Email Address"}),t.jsx("input",{type:"email",value:_.email,disabled:!0,className:"w-full rounded-xl px-3 py-2.5 text-sm",style:{background:"rgba(255,255,255,0.03)",border:"1px solid rgba(255,255,255,0.06)",color:"#64748b"}}),t.jsx("p",{className:"text-xs text-slate-600 mt-1.5",children:"Email is the login and cannot be changed here."})]}),t.jsxs("div",{children:[t.jsx("label",{className:"block text-xs text-slate-500 mb-1.5",children:"Full Name"}),t.jsx("input",{type:"text",value:C.full_name,onChange:U=>S(W=>({...W,full_name:U.target.value})),placeholder:"e.g. Cody Merrill",className:"w-full rounded-xl px-3 py-2.5 text-white text-sm focus:outline-none",style:{background:"rgba(255,255,255,0.06)",border:"1px solid rgba(255,255,255,0.1)"}})]}),t.jsxs("div",{children:[t.jsx("label",{className:"block text-xs text-slate-500 mb-1.5",children:"Mobile Phone"}),t.jsx("input",{type:"tel",value:C.phone,onChange:U=>S(W=>({...W,phone:U.target.value})),placeholder:"(317) 555-0123",className:"w-full rounded-xl px-3 py-2.5 text-white text-sm focus:outline-none",style:{background:"rgba(255,255,255,0.06)",border:"1px solid rgba(255,255,255,0.1)"}}),t.jsx("p",{className:"text-xs text-slate-600 mt-1.5",children:"Used for work-assignment text alerts."})]}),t.jsx("p",{className:"text-xs text-slate-600",children:"Role is changed from the dropdown in the table."}),i&&t.jsx("div",{className:"px-3 py-2.5 rounded-xl text-sm",style:{background:"rgba(248,113,113,0.1)",color:"#f87171",border:"1px solid rgba(248,113,113,0.2)"},children:i})]}),t.jsxs("div",{className:"flex gap-2 mt-5",children:[t.jsx("button",{onClick:()=>{j(null),o(null)},className:"flex-1 py-2.5 rounded-xl text-sm text-slate-400",style:{background:"rgba(255,255,255,0.05)",border:"1px solid rgba(255,255,255,0.08)"},children:"Cancel"}),t.jsx("button",{onClick:B,disabled:T,className:"flex-1 py-2.5 rounded-xl text-sm font-semibold text-white disabled:opacity-40",style:{background:"linear-gradient(135deg, #3b82f6, #2563eb)"},children:T?"Saving...":"Save Changes"})]})]})}),E&&t.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4",style:{background:"rgba(0,0,0,0.75)",backdropFilter:"blur(4px)"},children:t.jsxs("div",{className:"w-full max-w-sm rounded-2xl p-6",style:{background:"#0f1923",border:"1px solid rgba(248,113,113,0.2)"},children:[t.jsx("div",{className:"text-4xl mb-3 text-center",children:"â ï¸"}),t.jsx("h3",{className:"text-white font-bold text-lg text-center mb-2",children:"Delete User?"}),t.jsx("p",{style:{color:"#f87171"},className:"font-semibold text-center mb-4",children:E.email}),t.jsxs("p",{className:"text-slate-500 text-xs text-center mb-5",children:["This cannot be undone. Consider ",t.jsx("strong",{className:"text-slate-400",children:"banning"})," instead."]}),t.jsxs("div",{className:"flex gap-2",children:[t.jsx("button",{onClick:()=>R(null),className:"flex-1 py-2.5 rounded-xl text-sm text-slate-400",style:{background:"rgba(255,255,255,0.05)",border:"1px solid rgba(255,255,255,0.08)"},children:"Cancel"}),t.jsx("button",{onClick:te,disabled:!!N,className:"flex-1 py-2.5 rounded-xl text-sm font-semibold text-white disabled:opacity-40",style:{background:"linear-gradient(135deg, #ef4444, #dc2626)"},children:N?"Deleting...":"Yes, Delete"})]})]})})]})}function gp(e,n=0){const r=String(n||0).padStart(2,"0");return e===0?`12:${r} AM`:e<12?`${e}:${r} AM`:e===12?`12:${r} PM`:`${e-12}:${r} PM`}function mp(e){if(!e)return"";const n=new Date(e);return isNaN(n.getTime())?"":n.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})}function kr(e){const n=r=>String(r).padStart(2,"0");return`${e.getFullYear()}-${n(e.getMonth()+1)}-${n(e.getDate())}`}function Pn(e,n){const r=new Date(e);return r.setDate(r.getDate()+n),r}function z_(e){return new Date(e.getFullYear(),e.getMonth(),1)}function N_(e){return new Date(e.getFullYear(),e.getMonth()+1,0)}const gm=["January","February","March","April","May","June","July","August","September","October","November","December"],R_=["Sunday","Monday","Tuesday","Wednesday","Thursday","Frid
630ay","Saturday"],X$=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],Ts={scheduled:"#60a5fa",confirmed:"#60a5fa",in_progress:"#22d3ee",complete:"#4ade80",cancelled:"#64748b",pending:"#fbbf24"},mm={ro:"RO System",ro_install:"RO System",softener:"Water Softener",softener_only:"Water Softener",whole_home_filter:"Whole Home Filter",iron_filter:"Iron Filter",dual_tank:"Dual Tank",advanced_softener:"Advanced Softener"};function G$(){const{profile:e,role:n}=Ee(),r=gt(),[s,i]=g.useState("month"),[o,a]=g.useState(new Date),[l,d]=g.useState([]),[c,f]=g.useState(!0),[p,u]=g.useState(null),[h,y]=g.useState({}),m=yt.viewFullSchedule(n),b=n==="technician",A=n==="salesrep"||n==="frontdesk",v=m||A,x=m||b,_=kr(s==="month"?Pn(z_(o),-6):Pn(o,-o.getDay())),j=kr(s==="month"?Pn(N_(o),6):Pn(o,6-o.getDay()));g.useEffect(()=>{w.from("qualifying_questions").select("id, question_text").then(({data:I})=>{if(I){const B={};for(const J of I)B[J.id]=J.question_text;y(B)}})},[]),g.useEffect(()=>{e!=null&&e.id&&C()},[e==null?void 0:e.id,_,j,n]);async function C(){f(!0);const I=[];if(v){let B=w.from("site_visits").select("id, lead_id, assigned_rep_id, visit_date, visit_hour, visit_minute, status").gte("visit_date",_).lte("visit_date",j).not("status","eq","cancelled");m||(B=B.eq("assigned_rep_id",e.id));const{data:J}=await B;if(J!=null&&J.length){const ae=[...new Set(J.map(V=>V.lead_id).filter(Boolean))],{data:te}=await w.from("leads").select("id, full_name, phone, email, water_concern, notes, qualifying_answers").in("id",ae),U=Object.fromEntries((te||[]).map(V=>[V.id,V])),{data:W}=await w.from("addresses").select("entity_id, address_line1, city, state, zip").eq("entity_type","lead").eq("is_primary",!0).in("entity_id",ae),G=Object.fromEntries((W||[]).map(V=>[V.entity_id,V]));for(const V of J){const ee=U[V.lead_id];if(!ee)continue;const re=G[V.lead_id];I.push({kind:"visit",id:V.id,date:V.visit_date,hour:V.visit_hour,minute:Number(V.visit_minute||0),leadId:V.lead_id,leadName:ee.full_name,leadPhone:ee.phone||"",leadEmail:ee.email||"",leadAddress:(re==null?void 0:re.address_line1)??ee.address??"",leadCity:(re==null?void 0:re.city)??ee.city??"",leadState:(re==null?void 0:re.state)??ee.state??"",leadZip:(re==null?void 0:re.zip)??ee.zip??"",waterConcern:ee.water_concern||"",notes:ee.notes||"",qualifyingAnswers:ee.qualifying_answers||{},repId:V.assigned_rep_id,status:V.status})}}}if(x){const{data:B}=await w.from("jobs").select("id, customer_name_snapshot, service_address_snapshot, job_type, job_status, scheduled_at, assigned_technician_id, source_quote_id, phone_snapshot, email_snapshot").gte("scheduled_at",_).lte("scheduled_at",j);if(B!=null&&B.length){const J=[...new Set(B.map(W=>W.assigned_technician_id).filter(Boolean))];let ae={};if(J.length){const{data:W}=await w.from("user_profiles").select("id, full_name").in("id",J);ae=Object.fromEntries((W||[]).map(G=>[G.id,G.full_name]))}const te=[...new Set(B.map(W=>W.source_quote_id).filter(Boolean))];let U={};if(te.length){const{data:W}=await w.from("quote_line_items").select("quote_id, description").in("quote_id",te);if(W)for(const G of W)U[G.quote_id]||(U[G.quote_id]=[]),U[G.quote_id].push(G.description)}for(const W of B){const G=W.source_quote_id&&U[W.source_quote_id]?U[W.source_quote_id]:[mm[W.system_type]||W.system_type||"Install"].filter(Boolean);I.push({kind:"job",id:W.id,date:(W.scheduled_date||"").split("T")[0],scheduledTime:W.scheduled_date||"",customerName:W.customer_name_snapshot||"Unknown",address:W.service_address_snapshot||"",systemType:W.system_type||"",status:W.status,techName:W.assigned_technician_id&&ae[W.assigned_technician_id]||"",phone:W.phone_snapshot||"",email:W.email_snapshot||"",products:G})}}}d(I),f(!1)}function S(){const I=z_(o),B=N_(o),J=[];for(let te=0;te<I.getDay();te++)J.push(kr(Pn(I,-I.getDay()+te)));let ae=new Date(I);for(;ae<=B;)J.push(kr(ae)),ae=Pn(ae,1);for(;J.length%7!==0;)J.push(kr(ae=Pn(ae,1)));return J}function T(){const I=Pn(o,-o.getDay());return Array.from({length:7},(B,J)=>kr(Pn(I,J)))}const L=s==="month"?S():T(),E=kr(new Date);function R(I){return l.filter(B=>B.date===I)}function N(){a(s==="month"?new Date(o.getFullYear(),o.getMonth()-1,1):Pn(o,-7))}function O(){a(s==="month"?new Date(o.getFullYear(),o.getMonth()+1,
6301):Pn(o,7))}function z(){a(new Date)}const P=s==="month"?`${gm[o.getMonth()]} ${o.getFullYear()}`:(()=>{const I=Pn(o,-o.getDay()),B=Pn(I,6);return`${gm[I.getMonth()]} ${I.getDate()} â ${I.getMonth()!==B.getMonth()?gm[B.getMonth()]+" ":""}${B.getDate()}, ${B.getFullYear()}`})();function D(I){return I.kind==="visit"?"#22d3ee":"#fb923c"}function M(I){return!I||typeof I!="object"?[]:Object.entries(I).filter(([,B])=>B!=null&&B!=="").map(([B,J])=>({label:h[B]||B.replace(/_/g," ").replace(/\b\w/g,ae=>ae.toUpperCase()),value:Array.isArray(J)?J.join(", "):String(J)})).slice(0,10)}const k=kr(new Date),q=kr(Pn(new Date,14)),$=l.filter(I=>I.date>=k&&I.date<=q).sort((I,B)=>{if(I.date!==B.date)return I.date.localeCompare(B.date);const J=I.kind==="visit"?I.hour*60+(I.minute||0):0,ae=B.kind==="visit"?B.hour*60+(B.minute||0):0;return J-ae});return t.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%"},children:[t.jsxs("div",{style:{flexShrink:0,display:"flex",alignItems:"flex-start",justifyContent:"space-between",marginBottom:16,flexWrap:"wrap",gap:12},children:[t.jsxs("div",{children:[t.jsx("h1",{style:{color:"#e2e8f0",fontWeight:800,fontSize:22,margin:0,letterSpacing:"-0.01em"},children:b?"My Install Schedule":A?"My Visit Schedule":"Team Schedule"}),t.jsxs("p",{style:{color:"#475569",fontSize:13,marginTop:4,marginBottom:0},children:[c?"Loadingâ¦":`${l.length} event${l.length!==1?"s":""} in view`,v&&t.jsx("span",{style:{marginLeft:10,color:"#22d3ee",fontSize:12},children:"â site visits"}),x&&t.jsx("span",{style:{marginLeft:10,color:"#fb923c",fontSize:12},children:"â installs"})]})]}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[t.jsx("div",{style:{display:"flex",background:"#162232",border:"1px solid #1e3a4f",borderRadius:10,overflow:"hidden"},children:["month","week"].map(I=>t.jsx("button",{onClick:()=>i(I),style:{padding:"8px 18px",fontSize:12,fontWeight:700,cursor:"pointer",border:"none",background:s===I?"#0d7ea3":"transparent",color:s===I?"#fff":"#64748b",transition:"all 0.15s"},children:I==="month"?"Month":"Week"},I))}),t.jsx("button",{onClick:N,style:{width:34,height:34,borderRadius:8,border:"1px solid #1e3a4f",background:"#162232",color:"#94a3b8",cursor:"pointer",fontSize:16,display:"flex",alignItems:"center",justifyContent:"center"},children:"â¹"}),t.jsx("button",{onClick:z,style:{padding:"7px 16px",borderRadius:8,border:"1px solid #1e3a4f",background:"#162232",color:"#94a3b8",cursor:"pointer",fontSize:12,fontWeight:700},children:"Today"}),t.jsx("button",{onClick:O,style:{width:34,height:34,borderRadius:8,border:"1px solid #1e3a4f",background:"#162232",color:"#94a3b8",cursor:"pointer",fontSize:16,display:"flex",alignItems:"center",justifyContent:"center"},children:"âº"}),t.jsx("span",{style:{color:"#e2e8f0",fontWeight:700,fontSize:14,minWidth:160,textAlign:"center"},children:P})]})]}),t.jsx("div",{className:"block md:hidden",style:{flex:1,overflowY:"auto",display:"flex",flexDirection:"column",gap:8},children:c?t.jsx("div",{style:{textAlign:"center",padding:"40px 0",color:"#475569",fontSize:14},children:"Loadingâ¦"}):$.length===0?t.jsxs("div",{style:{textAlign:"center",padding:"60px 20px"},children:[t.jsx("div",{style:{fontSize:40,marginBottom:12},children:"ð
"}),t.jsx("div",{style:{color:"#475569",fontSize:15,fontWeight:600},children:"No upcoming events"}),t.jsx("div",{style:{color:"#334155",fontSize:13,marginTop:6},children:"Next 14 days are clear"})]}):(()=>{let I="";return $.map(B=>{const J=B.date!==I;I=B.date;const ae=B.date===k,te=B.date===kr(Pn(new Date,1)),U=ae?"Today":te?"Tomorrow":new Date(B.date+"T00:00:00").toLocaleDateString("en-US",{weekday:"long",month:"short",day:"numeric"}),W=D(B),G=B.kind==="visit"?gp(B.hour,B.minute):B.scheduledTime?mp(B.scheduledTime):"";return t.jsxs("div",{children:[J&&t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,marginBottom:6},children:[t.jsx("span",{style:{fontSize:12,fontWeight:800,color:ae?"#0d7ea3":"#64748b",textTransform:"uppercase",letterSpacing:"0.06em"},children:U}),t.jsx("div",{style:{flex:1,height:1,background:"#1e3a4f"}})]}),t.jsxs("button",{onClick:()=>u(B),style:{width:"100%",textAlign:"left",cursor:"pointer",background:"#0f1923",border:`1px solid ${W}30`,borderLeft:`4px solid ${W}`,borderRadius:14,padding:"14px 16px",display:"flex",alignItems:"center",gap:14},onMouseEnter:V=>{V.currentTarget.style.background="#162232"},onMouseLeave:V=>{V.currentTarget.style.background="#0f1923"},children:[t.jsx("div",{style:{width:44,height:44,borderRadius:12,flexShrink:0,background:`${W}15`,border:`1px solid ${W}25`,display:"flex",alignItems:"center",justifyContent:"center",fontSize:20},children:B.kind==="visit"?"ð":"ð§"}),t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsx("div",{style:{fontSize:15,fontWeight:700,color:"#e2e8f0",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:B.kind==="visit"?B.leadName:B.customerName}),t.jsx("div",{style:{fontSize:12,color:"#64748b",marginTop:3},children:B.kind==="visit"?`${G} · Site Visit`:`${mm[B.systemType]||B.systemType||"Install"}${G?` · ${G}`:""}${B.techName?` · ${B.techName}`:""}`}),B.kind==="visit"&&B.leadPhone&&t.jsx("div",{style:{fontSize:12,color:"#22d3ee",marginTop:2},children:B.leadPhone}),B.kind==="job"&&B.phone&&t.jsx("div",{style:{fontSize:12,color:"#fb923c",marginTop:2},children:B.phone}),B.kind==="job"&&B.address&&t.jsx("div",{style:{fontSize:11,color:"#475569",marginTop:2,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:B.address})]}),t.jsxs("div",{style:{flexShrink:0,textAlign:"right"},children:[t.jsx("span",{style:{fontSize:10,padding:"3px 9px",borderRadius:20,fontWeight:700,background:`${Ts[B.status]||"#64748b"}18`,color:Ts[B.status]||"#64748b",border:`1px solid ${Ts[B.status]||"#64748b"}30`,display:"block",whiteSpace:"nowrap"},children:B.status.replace(/_/g," ")}
630),t.jsx("div",{style:{fontSize:10,color:"#334155",marginTop:4},children:"tap to view"})]})]})]},B.id)})})()}),t.jsxs("div",{className:"hidden md:flex",style:{flex:1,overflow:"hidden",flexDirection:"column",background:"#162232",border:"1px solid #1e3a4f",borderRadius:16},children:[t.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(7, 1fr)",borderBottom:"1px solid #1e3a4f",flexShrink:0},children:X$.map(I=>t.jsx("div",{style:{padding:"10px 8px",textAlign:"center",fontSize:11,fontWeight:700,color:"#64748b",textTransform:"uppercase",letterSpacing:"0.06em"},children:I},I))}),t.jsx("div",{style:{flex:1,overflowY:"auto",display:"grid",gridTemplateColumns:"repeat(7, 1fr)",gridTemplateRows:s==="month"?`repeat(${L.length/7}, 1fr)`:"1fr"},children:L.map((I,B)=>{const J=new Date(I+"T00:00:00").getMonth()===o.getMonth(),ae=I===E,te=R(I),U=[0,6].includes(new Date(I+"T00:00:00").getDay());return t.jsxs("div",{style:{borderRight:B%7<6?"1px solid #1e3a4f":"none",borderBottom:B<L.length-7?"1px solid #1e3a4f":"none",background:U&&s==="month"?"rgba(0,0,0,0.1)":"transparent",opacity:s==="month"&&!J?.35:1,padding:"6px 6px 8px",minHeight:s==="month"?100:void 0,overflow:"hidden"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:5},children:[t.jsx("div",{style:{width:28,height:28,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",background:ae?"#0d7ea3":"transparent",color:ae?"#fff":"#94a3b8",fontSize:13,fontWeight:ae?800:500,boxShadow:ae?"0 0 10px rgba(13,126,163,0.4)":"none"},children:new Date(I+"T00:00:00").getDate()}),te.length>0&&t.jsx("span",{style:{fontSize:10,color:"#475569",fontWeight:600},children:te.length})]}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:3},children:[(s==="month"?te.slice(0,3):te).map(W=>{const G=W.kind==="visit"?gp(W.hour,W.minute):W.scheduledTime?mp(W.scheduledTime):"";return t.jsxs("button",{onClick:()=>u(W),style:{display:"flex",alignItems:"center",gap:5,padding:"4px 8px",borderRadius:6,background:`${D(W)}18`,border:`1px solid ${D(W)}35`,cursor:"pointer",textAlign:"left",width:"100%"},onMouseEnter:V=>{V.currentTarget.style.background=`${D(W)}30`},onMouseLeave:V=>{V.currentTarget.style.background=`${D(W)}18`},children:[t.jsx("span",{style:{width:6,height:6,borderRadius:"50%",background:D(W),flexShrink:0}}),t.jsx("span",{style:{fontSize:11,color:"#e2e8f0",fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1},children:W.kind==="visit"?`${G} ${W.leadName}`:`${G?G+" ":""}${W.customerName}`})]},W.id)}),s==="month"&&te.length>3&&t.jsxs("button",{onClick:()=>{a(new Date(I+"T00:00:00")),i("week")},style:{fontSize:10,color:"#64748b",background:"none",border:"none",cursor:"pointer",textAlign:"left",padding:"0 8px"},children:["+",te.length-3," more"]})]})]},I)})})]}),p&&t.jsx("div",{style:{position:"fixed",inset:0,zIndex:50,display:"flex",alignItems:"flex-end",justifyContent:"center",padding:"0",background:"rgba(0,0,0,0.7)",backdropFilter:"blur(6px)"},className:"sm:items-center sm:p-4",onClick:I=>{I.target===I.currentTarget&&u(null)},children:t.jsxs("div",{style:{width:"100%",maxWidth:560,background:"#0f1923",border:"1px solid #1e3a4f",borderTop:`3px solid ${D(p)}`,borderRadius:"20px 20px 0 0",maxHeight:"92vh",display:"flex",flexDirection:"column",overflow:"hidden"},className:"sm:rounded-[20px]",children:[t.jsx("div",{className:"flex justify-center pt-3 pb-1 sm:hidden",style:{flexShrink:0},children:t.jsx("div",{style:{width:40,height:4,borderRadius:4,background:"#1e3a4f"}})}),t.jsxs("div",{style:{flexShrink:0,display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 20px 16px",background:`linear-gradient(135deg, ${D(p)}10, transparent)`,borderBottom:"1px solid #1e3a4f"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:14},children:[t.jsx("div",{style:{width:48,height:48,borderRadius:12,flexShrink:0,background:`${D(p)}18`,border:`1px solid ${D(p)}30`,display:"flex",alignItems:"center",justifyContent:"center",fontSize:22},children:p.kind==="visit"?"ð":"ð§"}),t.jsxs("div",{children:[t.jsx("div",{style:{color:"#f1f5f9",fontWeight:800,fontSize:17,letterSpacing:"-0.01em"},children:p.kind==="visit"?p.leadName:p.customerName}),t.jsxs("div",{style:{color:"#64748b",fontSize:13,marginTop:3},children:[p.kind==="visit"?`Site Visit · ${gp(p.hour,p.minute)}`:`Install · ${mm[p.systemType]||p.systemType||"Job"}${p.scheduledTime?" · "+mp(p.scheduledTime):""}`," · ",new Date(p.date+"T00:00:00").toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric"})]})]})]}),t.jsx("button",{onClick:()=>u(null),style:{color:"#475569",background:"rgba(255,255,255,0.05)",border:"1px solid #1e3a4f",borderRadius:8,width:34,he
630ight:34,fontSize:18,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:"Ã"})]}),t.jsxs("div",{style:{flex:1,minHeight:0,overflowY:"auto",overflowX:"hidden",padding:"20px 20px",display:"flex",flexDirection:"column",gap:14,WebkitOverflowScrolling:"touch"},children:[p.kind==="visit"&&(()=>{const I=[p.leadAddress,p.leadCity,p.leadState,p.leadZip].filter(Boolean).join(", "),B=M(p.qualifyingAnswers);return t.jsxs(t.Fragment,{children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[t.jsx("span",{style:{fontSize:12,padding:"5px 14px",borderRadius:20,fontWeight:700,background:`${Ts[p.status]||"#64748b"}18`,color:Ts[p.status]||"#64748b",border:`1px solid ${Ts[p.status]||"#64748b"}35`},children:p.status.replace(/_/g," ")}),t.jsxs("span",{style:{fontSize:13,color:"#64748b"},children:["ð ",gp(p.hour,p.minute)]}),t.jsxs("span",{style:{fontSize:13,color:"#64748b"},children:["ð
",R_[new Date(p.date+"T00:00:00").getDay()],", ",new Date(p.date+"T00:00:00").toLocaleDateString("en-US",{month:"long",day:"numeric"})]})]}),t.jsxs(ko,{title:"Contact Information",icon:"ð¤",accent:"#38bdf8",children:[t.jsx(Co,{icon:"ð",label:"Phone",value:p.leadPhone||"â",href:p.leadPhone?`tel:${p.leadPhone}`:void 0,valueColor:"#38bdf8"}),p.leadEmail&&t.jsx(Co,{icon:"âï¸",label:"Email",value:p.leadEmail,href:`mailto:${p.leadEmail}`,valueColor:"#38bdf8"}),I&&t.jsx(Co,{icon:"ð",label:"Address",value:I})]}),p.waterConcern&&t.jsx(ko,{title:"Water Concern",icon:"ð§",accent:"#22d3ee",children:t.jsx("div",{style:{padding:"12px 14px",borderRadius:8,background:"rgba(34,211,238,0.06)",border:"1px solid rgba(34,211,238,0.15)"},children:t.jsx("span",{style:{fontSize:14,color:"#e2e8f0",fontWeight:500,lineHeight:1.5},children:p.waterConcern})})}),B.length>0&&t.jsx(ko,{title:"Qualifying Answers",icon:"ð",accent:"#818cf8",children:B.map((J,ae)=>t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",gap:16,padding:"10px 0",borderBottom:ae<B.length-1?"1px solid #0d1a26":"none"},children:[t.jsx("span",{style:{fontSize:13,color:"#64748b",fontWeight:500,flex:1,lineHeight:1.4},children:J.label}),t.jsx("span",{style:{fontSize:13,color:"#cbd5e1",fontWeight:700,textAlign:"right",flexShrink:0,maxWidth:"55%",lineHeight:1.4},children:J.value})]},ae))}),p.notes&&t.jsx(ko,{title:"Notes",icon:"ð",accent:"#fbbf24",children:t.jsx("div",{style:{padding:"12px 14px",borderRadius:8,background:"rgba(251,191,36,0.06)",border:"1px solid rgba(251,191,36,0.15)"},children:t.jsx("span",{style:{fontSize:14,color:"#e2e8f0",lineHeight:1.6},children:p.notes})})}),!p.leadEmail&&!I&&!p.waterConcern&&B.length===0&&!p.notes&&t.jsx("div",{style:{textAlign:"center",padding:"20px 0",color:"#334155",fontSize:14},children:"No additional info on file for this lead."})]})})(),p.kind==="job"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[t.jsx("span",{style:{fontSize:12,padding:"5px 14px",borderRadius:20,fontWeight:700,background:`${Ts[p.status]||"#64748b"}18`,color:Ts[p.status]||"#64748b",border:`1px solid ${Ts[p.status]||"#64748b"}35`},children:p.status.replace(/_/g," ")}),p.scheduledTime&&t.jsxs("span",{style:{fontSize:13,color:"#64748b"},children:["ð ",mp(p.scheduledTime)]}),t.jsxs("span",{style:{fontSize:13,color:"#64748b"},children:["ð
",R_[new Date(p.date+"T00:00:00").getDay()],", ",new Date(p.date+"T00:00:00").toLocaleDateString("en-US",{month:"long",day:"numeric"})]})]}),t.jsxs(ko,{title:"Customer",icon:"ð¤",accent:"#fb923c",children:[p.phone&&t.jsx(Co,{icon:"ð",label:"Phone",value:p.phone,href:`tel:${p.phone}`,valueColor:"#fb923c"}),p.email&&t.jsx(Co,{icon:"âï¸",label:"Email",value:p.email,href:`mailto:${p.email}`,valueColor:"#fb923c"}),p.address&&t.jsx(Co,{icon:"ð",label:"Address",value:p.address})]}),t.jsxs(ko,{title:"Job Details",icon:"ð§",accent:"#fb923c",children:[p.techName&&t.jsx(Co,{icon:"ð·",label:"Technician",value:p.techName}),!p.techName&&t.jsx("div",{style:{padding:"10px 0",fontSize:13,color:"#475569"},children:"No technician assigned yet"})]}),p.products.length>0&&t.jsx(ko,{title:"Products to Install",icon:"ð·ï¸",accent:"#fb923c",children:t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:p.products.map((I,B)=>t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"11px 14px",borderRadius:10,background:"rgba(251,146,60,0.08)",border:"1px solid rgba(251,146,60,0.2)"},children:[t.jsx("span",{style:{fontSize:16},children:"ð·ï¸"}),t.jsx("span",{style:{color:"#e2e8f0",fontSize:14,fontWeight:600},children:I})]},B))})})]})]}),t.jsxs("div",{style:{flexShrink:0,padding:"14px 20px 20px",borderTop:"1px solid #1e3a4f",dis
630play:"flex",gap:10,background:"#0d1a26"},children:[p.kind==="visit"&&t.jsx("button",{onClick:()=>{u(null),r(`/leads?lead=${p.leadId}`)},style:{flex:1,padding:"13px 0",borderRadius:12,fontSize:14,fontWeight:800,background:"linear-gradient(135deg, #0d7ea3, #0369a1)",color:"#fff",border:"none",cursor:"pointer",letterSpacing:"-0.01em"},children:"Open Lead â"}),p.kind==="job"&&t.jsx("button",{onClick:()=>{u(null),r(`/installations/${p.id}`)},style:{flex:1,padding:"13px 0",borderRadius:12,fontSize:14,fontWeight:800,background:"linear-gradient(135deg, #ea580c, #c2410c)",color:"#fff",border:"none",cursor:"pointer",letterSpacing:"-0.01em"},children:"Open Install â"}),t.jsx("button",{onClick:()=>u(null),style:{padding:"13px 20px",borderRadius:12,fontSize:14,color:"#64748b",background:"rgba(255,255,255,0.04)",border:"1px solid #1e3a4f",cursor:"pointer",fontWeight:600},children:"Close"})]})]})})]})}function ko({title:e,icon:n,accent:r,children:s}){return t.jsxs("div",{style:{background:"#162232",border:"1px solid #1e3a4f",borderRadius:12,overflow:"hidden",flexShrink:0},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"10px 14px",borderBottom:"1px solid #1e3a4f",background:`${r}08`},children:[t.jsx("span",{style:{fontSize:14},children:n}),t.jsx("span",{style:{fontSize:11,fontWeight:700,color:"#64748b",textTransform:"uppercase",letterSpacing:"0.07em"},children:e})]}),t.jsx("div",{style:{padding:"10px 14px"},children:s})]})}function Co({icon:e,label:n,value:r,href:s,valueColor:i}){const o=t.jsxs("div",{style:{display:"flex",gap:12,alignItems:"flex-start",padding:"7px 0"},children:[t.jsx("span",{style:{fontSize:16,flexShrink:0,marginTop:1,opacity:.7},children:e}),t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsx("div",{style:{fontSize:10,color:"#475569",fontWeight:700,textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:3},children:n}),t.jsx("div",{style:{fontSize:14,color:i||"#cbd5e1",fontWeight:500,wordBreak:"break-word",lineHeight:1.4},children:r})]})]});return s?t.jsx("a",{href:s,style:{textDecoration:"none",display:"block"},onMouseEnter:a=>{a.currentTarget.style.opacity="0.8"},onMouseLeave:a=>{a.currentTarget.style.opacity="1"},children:o}):o}function lh(e){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?lh=function(n){return typeof n}:lh=function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},lh(e)}var Fk="dahlia",J$=function(n){return n===3?"v3":n},Bk="https://js.stripe.com",Q$="".concat(Bk,"/").concat(Fk,"/stripe.js"),eM=/^https:\/\/js\.stripe\.com\/v3\/?(\?.*)?$/,tM=/^https:\/\/js\.stripe\.com\/(v3|[a-z]+)\/stripe\.js(\?.*)?$/;var nM=function(n){return eM.test(n)||tM.test(n)},rM=function(){for(var n=document.querySelectorAll('script[src^="'.concat(Bk,'"]')),r=0;r<n.length;r++){var s=n[r];if(nM(s.src))return s}return null},E_=function(n){var r="",s=document.createElement("script");s.src="".concat(Q$).concat(r);var i=document.head||document.body;if(!i)throw new Error("Expected document.body not to be null. Stripe.js requires a <body> element.");return i.appendChild(s),s},sM=function(n,r){!n||!n._registerWrapper||n._registerWrapper({name:"stripe-js",version:"9.0.0",startTime:r})},Wd=null,xp=null,yp=null,iM=function(n){return function(r){n(new Error("Failed to load Stripe.js",{cause:r}))}},oM=function(n,r){return function(){window.Stripe?n(window.Stripe):r(new Error("Stripe.js not available"))}},aM=function(n){return Wd!==null?Wd:(Wd=new Promise(function(r,s){if(typeof window>"u"||typeof document>"u"){r(null);return}if(window.Stripe){r(window.Stripe);return}try{var i=rM();if(!(i&&n)){if(!i)i=E_(n);else if(i&&yp!==null&&xp!==null){var o;i.removeEventListener("load",yp),i.removeEventListener("error",xp),(o=i.parentNode)===null||o===void 0||o.removeChild(i),i=E_(n)}}yp=oM(r,s),xp=iM(s),i.addEventListener("load",yp),i.addEventListener("error",xp)}catch(a){s(a);return}}),Wd.catch(function(r){return Wd=null,Promise.reject(r)}))},lM=function(n,r,s){if(n===null)return null;var i=r[0];
630if(typeof i!="string")throw new Error("Expected publishable key to be of type string, got type ".concat(lh(i)," instead."));var o=i.match(/^pk_test/),a=J$(n.version),l=Fk;o&&a!==l&&console.warn("Stripe.js@".concat(a," was loaded on the page, but @stripe/stripe-js@").concat("9.0.0"," expected Stripe.js@").concat(l,". This may result in unexpected behavior. For more information, see https://docs.stripe.com/sdks/stripejs-versioning"));var d=n.apply(void 0,r);return sM(d,s),d},$d,Uk=!1,Hk=function(){return $d||($d=aM(null).catch(function(n){return $d=null,Promise.reject(n)}),$d)};Promise.resolve().then(function(){return Hk()}).catch(function(e){Uk||console.warn(e)});var Xf=function(){for(var n=arguments.length,r=new Array(n),s=0;s<n;s++)r[s]=arguments[s];Uk=!0;var i=Date.now();return Hk().then(function(o){return lM(o,r,i)})};Xf("pk_live_51T9AsuIF6b6bnPt21JZbhmxXkXrkaE1QEppUXjhOOA8ahR2m4i5gOkYkwcUb2vfQwsd4NFBY4SKMqlr8xdQz6TgT00TQ15vzFA");async function At(){const{data:{session:e}}=await w.auth.getSession();return{"Content-Type":"application/json",Authorization:`Bearer ${(e==null?void 0:e.access_token)||""}`}}async function _0(e){const n=await fetch("/api/stripe/setup-intent",{method:"POST",headers:await At(),body:JSON.stringify(e)});if(!n.ok){const r=await n.json();throw new Error(r.error||"Failed to create setup intent")}return n.json()}async function Qc(e){e.make_default&&await w.from("payment_methods").update({is_default:!1}).eq("customer_id",e.customer_id);const{data:n,error:r}=await w.from("payment_methods").insert({customer_id:e.customer_id,stripe_payment_method_id:e.stripe_payment_method_id,card_last4:e.last_four,card_brand:e.card_brand||null,exp_month:e.exp_month,exp_year:e.exp_year,is_default:e.make_default,type:e.type||null}).select().single();if(r)throw r;return{...n,last_four:n.card_last4,external_id:n.stripe_payment_method_id}}async function eu(e,n){const{error:r}=await w.from("customers").update({stripe_customer_id:n}).eq("id",e);if(r)throw r}async function Gf(e){const n=await fetch("/api/stripe/charge",{method:"POST",headers:await At(),body:JSON.stringify({stripe_customer_id:e.stripe_customer_id,payment_method_id:e.payment_method_id,amount_cents:e.amount_cents,description:e.description,metadata:{customer_id:e.customer_id,contract_id:e.contract_id||"",invoice_id:e.invoice_id||""}})}),r=await n.json();if(!n.ok)throw new Error(r.error||"Payment failed");return{transaction:null,paymentIntent:r}}async function Vk(e){const n=await fetch("/api/stripe/payment-link",{method:"POST",headers:await At(),body:JSON.stringify({...e,metadata:{customer_id:e.customer_id,contract_id:e.contract_id||"",invoice_id:e.invoice_id||""}})});if(!n.ok){const r=await n.json();throw new Error(r.error||"Failed to create payment link")}return n.json()}async function Zk(e){const{data:n,error:r}=await w.from("payment_methods").select("*").eq("customer_id",e).order("is_default",{ascending:!1});if(r)throw r;return(n||[]).map(s=>({...s,last_four:s.card_last4,external_id:s.stripe_payment_method_id,type:s.type||"card",status:"active"}))}async function dM(e){const{data:n,error:r}=await w.from("payment_transactions").select("*").eq("customer_id",e).order("created_at",{ascending:!1}).limit(50);if(r)throw r;return n||[]}async function cM(e,n){await w.from("payment_methods").update({is_default:!1}).eq("customer_id",e);const{error:r}=await w.from("payment_methods").update({is_default:!0}).eq("id",n);if(r)throw r}async function uM(e){const{error:n}=await w.from("payment_methods").delete().eq("id",e);if(n)throw n}const yu="America/Indiana/Indianapolis";function j0(e){const n=new Intl.DateTimeFormat("en-US",{timeZone:yu,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1}).formatToParts(e),r=i=>{var o;return((o=n.find(a=>a.type===i))==null?void 0:o.value)||""};let s=parseInt(r("hour"),10);return s===24&&(s=0),{year:+r("year"),month:+r("month"),day:+r("day"),hour:s,minute:+r("minute")}}function pM(e){const n=new Date(e.toLocaleString("en-US",{timeZone:"UTC"})),r=new Date(e.toLocaleString("en-US",{timeZone:yu}));return(n.getTime()-r.getTime())/6e4}function Jf(e,n,r,s,i){const o=new Date(Date.UTC(e,n-1,r,s,i,0)),a=pM(o);return new Date(o.getTime()+a*6e4)}function Kk(e,n,r){const s=new Date(Date.UTC(e,n-1,r)).getUTCDay();return s===0||s===6}function Yk(e,n,r){let s=new Date(Date.UTC(e,n-1,r));for(;s.getUTCDay()===0||s.getUTCDay()===6;)s=new Date(s.getTime()+864e5);return{y:s.getUTCFullYear(),mo:s.getUTCMonth()+1,day:s.getUTCDate()}}function Ma(e,n){const r=new Date(e.getTime()+n*36e5),s=j0(r);let i=s.year,o=s.month,a=s.day;if(Kk(i,o,a)){const l=Yk(i,o,a);i=l.y,o=l.mo,a=l.day}return Jf(i,o,a,s.hour,s.minute).toISOString()}function hM(e){const n=j0(e);let r=n.year,s=n.month,i=n.day,o;if(n.hour<15)o=16;else{o=9;const a=new Date(Date.UTC(r,s-1,i)+864e5);r=a.getUTCFullYear(),s=a.getUTCMonth()+1,i=a.getUTCDate()}if(Kk(r,s,i)){const a=Yk(r,s,i);r=a.y,s=a.mo,i=a.day}return Jf(r,s,i,o,0).toISOString()}const fM={booking:{awaiting_call:e=>new Date(e.getTime()+30*6e4).toISOString(),chasing_1:e=>hM(e),chasing_2:e=>Ma(e,48),day7:e=>Ma(e,24*7)},quote:{q1:e=>Ma(e,24),q2:e=>Ma(e,72),q3:e=>Ma(e,24*7),q4:e=>Ma(e,24*14)}},ef={booking:["awaiting_call","chasing_1","chasing_2","day7"],quote:["q1","q2","q3","q4"]},P_={booking:["awaiting_call","chasing_1","chasing_2","day7","booked","dead"],quote:["q1","q2","q3","q4","signed","dead"]},tf={awaiting_call:"30-min call",chasing_1:"Chase 1",chasing_2:"Chase 2 (48h)",day7:"Day 7",booked:"Booked",q1:"Follow-up 1",q2:"Follow-up 2",q3:"Follow-up 3",q4:"Final follow-up",signed:"Signed",dead:"Closed"},gM={booking:"Booking Chase",quote:"Quote Chase"};function tu(e){return!e||e==="dead"?null:P_.booking.includes(e)?"booking":P_.quote.includes(e)?"quote":null}function zy(e){return e?ef.booking.includes(e)||ef.quote.includes(e):!1}const q_={booking:"awaiting_call",quote:"q1"};function Xk(e,n,r=new Date){const s=fM[e];if(!s)return null;const i=s[n];return i?i(r):null}const D_=768;function w0(){const[e,n]=g.useState(()=>window.innerWidth<D_);return g.useEffect(()=>{const r=()=>n(window.innerWidth<D_);return window.addEventListener("resize",r),()=>window.removeEventListener("resize",r)},[]),e}function Yo(e){const n=new Intl.DateTimeFormat("en-US",{timeZone:yu,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1,weekday:"short"}).formatToParts(e),r=i=>{var o;return((o=n.find(a=>a.type===i))==null?void 0:o.value)||""};let s=+r("hour");return s===24&&(s=0),{year:+r("year"),month:+r("month"),day:+r("day"),hour:s,minute:+r("minute"),weekday:r("weekday")}}const Gk={Sun:0,Mon:1,Tue:2,Wed:3,Thu:4,Fri:5,Sat:6};function nf(e){return String(e).padStart(2,"0")}function $o(e,n,r){return`${e}-${nf(n)}-${nf(r)}`}
630function Ny(e,n,r,s){const i=new Date(Date.UTC(e,n-1,r,12,0,0));return i.setUTCDate(i.getUTCDate()+s),{year:i.getUTCFullYear(),month:i.getUTCMonth()+1,day:i.getUTCDate()}}function mM(e){const n=Yo(e),r=Gk[n.weekday],s=r===0?6:r-1;return Ny(n.year,n.month,n.day,-s)}function xM(e,n,r,s){const i=Date.UTC(e,n-1,r,s,0,0),o=Yo(new Date(i));return(Date.UTC(o.year,o.month-1,o.day,o.hour,o.minute,0)-i)/6e4}function yM(e,n,r,s,i){const o=xM(e,n,r,s),a=Date.UTC(e,n-1,r,s,i,0)-o*6e4;return new Date(a).toISOString()}const rf=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],dh=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],bM=["January","February","March","April","May","June","July","August","September","October","November","December"],Qf=8,AM=18,Xo=28,vc=(AM-Qf)*2;function Jk(e,n){return((e-Qf)*2+(n>=30?1:0))*Xo}function ch(e,n){const r=e>=12?"PM":"AM";return`${e>12?e-12:e===0?12:e}${n===30?":30":""} ${r}`}function O_(e){let n=Math.floor(e/Xo);n<0&&(n=0),n>vc-1&&(n=vc-1);const r=Qf+Math.floor(n/2),s=n%2*30;return{hour:r,minute:s}}function vM(e){if(!e)return null;const n=String(e).match(/^(\d{2}):(\d{2})/);return n?{hour:parseInt(n[1],10),minute:parseInt(n[2],10)}:null}function I_(e){if(!e)return null;const n=e.match(/\b(\d{1,2}):(\d{2})\s?([AP]M)\b/i);if(!n)return null;let r=parseInt(n[1],10)%12;return n[3].toUpperCase()==="PM"&&(r+=12),{hour:r,minute:parseInt(n[2],10)}}const _M=["standard_install","service","warranty","filter_change","rental_setup"],L_={standard_install:"Install",service:"Service",warranty:"Warranty",filter_change:"Filter Change",rental_setup:"Rental Setup"},jM=["complete","cancelled"];function W_(){const e=Yo(new Date);return $o(e.year,e.month,e.day)}function wM(e){return e&&e.trim().split(/\s+/)[0]||"there"}function Ry(e,n,r){const s=+e.slice(0,4),i=+e.slice(5,7),o=+e.slice(8,10),a=new Date(Date.UTC(s,i-1,o,12)).getUTCDay();return`${rf[a===0?6:a-1]} ${dh[i-1]} ${o} at ${ch(n,r)}`}const SM={dark:{pageBg:"#0b1220",text:"#e2e8f0",textMuted:"#94a3b8",textDim:"#64748b",panelBg:"#0f172a",panelBorder:"#334155",gridLineSolid:"#24324a",gridLineDash:"#1e293b",colBorder:"#1e293b",todayHeader:"rgba(55,138,221,0.12)",todayCol:"rgba(55,138,221,0.04)",chipBg:"#1e293b",chipBorder:"#334155",chipActiveBg:"#378ADD",chipActiveBorder:"#4a97e2",chipActiveText:"#f8fafc",inputBg:"#1e293b",inputBorder:"#334155",weekendText:"#64748b",modalBg:"#0f172a",modalBorder:"#334155",overlay:"rgba(0,0,0,0.55)"},light:{pageBg:"#f1f5f9",text:"#0f172a",textMuted:"#475569",textDim:"#94a3b8",panelBg:"#ffffff",panelBorder:"#cbd5e1",gridLineSolid:"#e2e8f0",gridLineDash:"#eef2f7",colBorder:"#e2e8f0",todayHeader:"rgba(55,138,221,0.14)",todayCol:"rgba(55,138,221,0.06)",chipBg:"#e2e8f0",chipBorder:"#cbd5e1",chipActiveBg:"#378ADD",chipActiveBorder:"#2f7ac6",chipActiveText:"#ffffff",inputBg:"#ffffff",inputBorder:"#cbd5e1",weekendText:"#94a3b8",modalBg:"#ffffff",modalBorder:"#cbd5e1",overlay:"rgba(15,23,42,0.35)"}},kM={dark:{visit:{bg:"#0C447C",border:"#378ADD",title:"#E6F1FB",sub:"#B5D4F4"},call:{bg:"#27500A",border:"#639922",title:"#EAF3DE",sub:"#C0DD97"},followup:{bg:"#633806",border:"#EF9F27",title:"#FAEEDA",sub:"#FAC775"},job:{bg:"#0B4C4C",border:"#22B8B8",title:"#DDF5F5",sub:"#9FE3E3"}},light:{visit:{bg:"#DCEBFA",border:"#378ADD",title:"#0C447C",sub:"#215D96"},call:{bg:"#E4F1D2",border:"#639922",title:"#2C540C",sub:"#4A7A18"},followup:{bg:"#FCEBD1",border:"#EF9F27",title:"#7A4708",sub:"#B26E12"},job:{bg:"#D2F0F0",border:"#22B8B8",title:"#0B4C4C",sub:"#137575"}}},CM={visit:"#378ADD",call:"#639922",followup:"#EF9F27",job:"#22B8B8"};function TM(){const{profile:e}=Ee(),n=gt(),r=EM(e==null?void 0:e.role),s=w0(),[i,o]=g.useState(()=>new Date),[a,l]=g.useState(s?"day":"week"),[d,c]=g.useState("dark"),[f,p]=g.useState([]),[u,h]=g.useState(!0),[y,m]=g.useState({}),[b,A]=g.useState([]),[v,x]=g.useState(new Set),[_,j]=g.useState(""),[C,S]=g.useState(null),[T,L]=g.useState(!1),[E,R]=g.useState(null),[N,O]=g.useState(null),[z,P]=g.useState(null),D=SM[d],M=kM[d],k=g.useMemo(()=>{const Z=[],ie=W_();if(a==="day"){const Y=Yo(i),X=$o(Y.year,Y.month,Y.day),H=Gk[Y.weekday];Z.push({key:X,abbr:rf[H===0?6:H-1],dom:Y.day,isToday:X===ie,isWeekend:H===0||H===6})}else if(a==="week"){const Y=mM(i);for(let X=0;X<7;X++){const H=Ny(Y.year,Y.month,Y.day,X),de=$o(H.year,H.month,H.day);Z.push({key:de,abbr:rf[X],dom:H.day,isToday:de===ie,isWeekend:X>=5})}}return Z},[i,a]),q=g.useMemo(()=>{const Z=Yo(i),ie=new Date(Date.UTC(Z.year,Z.month-1,1,12)).getUTCDay(),Y=ne
630w Date(Date.UTC(Z.year,Z.month,0,12)).getUTCDate(),X=ie===0?6:ie-1;return{year:Z.year,month:Z.month,daysInMonth:Y,leadBlanks:X}},[i]),{rangeStart:$,rangeEnd:I}=g.useMemo(()=>a==="month"?{rangeStart:$o(q.year,q.month,1),rangeEnd:$o(q.year,q.month,q.daysInMonth)}:k.length?{rangeStart:k[0].key,rangeEnd:k[k.length-1].key}:{rangeStart:void 0,rangeEnd:void 0},[a,k,q]),B=g.useMemo(()=>{if(a==="month")return`${bM[q.month-1]} ${q.year}`;if(a==="day"){if(!k.length)return"";const Ne=k[0],Ie=+Ne.key.slice(0,4),Ze=+Ne.key.slice(5,7);return`${Ne.abbr} · ${dh[Ze-1]} ${Ne.dom}, ${Ie}`}if(!k.length)return"";const Z=k[0],ie=k[k.length-1],Y=+Z.key.slice(5,7),X=+ie.key.slice(5,7),H=+ie.key.slice(0,4),de=`${dh[Y-1]} ${Z.dom}`,pe=Y===X?`${ie.dom}`:`${dh[X-1]} ${ie.dom}`;return`${de} â ${pe}, ${H}`},[a,k,q]),J=g.useCallback(async()=>{if(!$||!I)return;h(!0);const Z=[],{data:ie}=await w.from("site_visits").select("id, lead_id, visit_date, visit_hour, visit_minute, status, customer_name_snapshot, phone_snapshot, address_snapshot, assigned_rep_id").gte("visit_date",$).lte("visit_date",I).not("status","eq","cancelled");for(const H of ie||[]){const de=H.visit_hour!==null&&H.visit_hour!==void 0,pe=H.customer_name_snapshot||"Site visit";Z.push({id:H.id,kind:"visit",dateKey:H.visit_date,hour:de?H.visit_hour:null,minute:Number(H.visit_minute||0),durationMin:60,label:pe,sub:"Site visit",repId:H.assigned_rep_id||null,navTo:H.lead_id?`/leads?lead=${H.lead_id}`:null,searchText:`${pe} ${H.phone_snapshot||""} ${H.address_snapshot||""}`.toLowerCase(),phone:H.phone_snapshot||null,customerKey:H.lead_id?`lead:${H.lead_id}`:null,draggable:de,canUnschedule:!1})}const{data:Y}=await w.from("follow_up_tasks").select("id, title, description, task_type, due_date, due_time, lead_id, customer_id, assigned_to").is("completed_at",null).gte("due_date",$).lte("due_date",I);for(const H of Y||[]){const de=H.task_type==="call_back",pe=vM(H.due_time)||(de?I_(H.title)||I_(H.description):null),Ne=H.lead_id?`/leads?lead=${H.lead_id}`:H.customer_id?`/customers/${H.customer_id}`:null,Ie=H.title||(de?"Call back":"Follow-up"),Ze=H.customer_id?`cust:${H.customer_id}`:H.lead_id?`lead:${H.lead_id}`:null;Z.push({id:H.id,kind:de?"call":"followup",dateKey:H.due_date,hour:pe?pe.hour:null,minute:pe?pe.minute:0,durationMin:30,label:Ie,sub:de?"Callback":(H.task_type||"follow-up").replace(/_/g," "),repId:H.assigned_to||null,
630navTo:Ne,searchText:`${Ie} ${H.description||""}`.toLowerCase(),phone:null,customerKey:Ze,draggable:!0,canUnschedule:!de})}const{data:X}=await w.from("jobs").select("id, lead_id, customer_id, job_type, job_status, scheduled_at, customer_name_snapshot, phone_snapshot, service_address_snapshot, assigned_technician_id").in("job_type",_M).not("job_status","in",`(${jM.join(",")})`).not("scheduled_at","is",null);for(const H of X||[]){const de=Yo(new Date(H.scheduled_at)),pe=$o(de.year,de.month,de.day);if(pe<$||pe>I)continue;const Ne=H.customer_name_snapshot||L_[H.job_type]||"Job",Ie=H.customer_id?`/customers/${H.customer_id}`:H.lead_id?`/leads?lead=${H.lead_id}`:null,Ze=H.customer_id?`cust:${H.customer_id}`:H.lead_id?`lead:${H.lead_id}`:null;Z.push({id:H.id,kind:"job",dateKey:pe,hour:de.hour,minute:de.minute>=30?30:0,durationMin:30,label:Ne,sub:L_[H.job_type]||"Job",repId:H.assigned_technician_id||null,navTo:Ie,searchText:`${Ne} ${H.phone_snapshot||""} ${H.service_address_snapshot||""}`.toLowerCase(),phone:H.phone_snapshot||null,customerKey:Ze,draggable:!0,canUnschedule:!1})}p(Z),h(!1)},[$,I]);g.useEffect(()=>{r?J():h(!1)},[r,J]),g.useEffect(()=>{let Z=!0;return w.from("profiles").select("id, full_name").then(ie=>{if(!Z)return;const Y={},X=[];for(const H of ie.data||[])Y[H.id]=H.full_name,X.push({id:H.id,name:H.full_name});X.sort((H,de)=>(H.name||"").localeCompare(de.name||"")),m(Y),A(X)}),()=>{Z=!1}},[]);const ae=_.trim().toLowerCase(),te=g.useCallback(Z=>!(v.size>0&&Z.repId&&!v.has(Z.repId)||ae&&!Z.searchText.includes(ae)),[v,ae]),U=g.useCallback(Z=>!te(Z),[te]),W=g.useMemo(()=>{const Z={};for(const ie of k)Z[ie.key]=[];for(const ie of f)ie.hour!==null&&Z[ie.dateKey]&&Z[ie.dateKey].push(ie);return Z},[f,k]),G=g.useMemo(()=>f.filter(Z=>Z.hour===null&&(Z.kind==="call"||Z.kind==="followup")).sort((Z,ie)=>Z.dateKey.localeCompare(ie.dateKey)),[f]),V=g.useMemo(()=>{const Z={};if(a!=="month")return Z;for(const ie of f){const Y=+ie.dateKey.slice(8,10);Z[Y]||(Z[Y]=[]),Z[Y].push(ie)}return Z},[f,a]);function ee(Z,ie,Y,X){const H=[];if(Z.repId){const de=f.find(pe=>pe.id!==Z.id&&pe.repId===Z.repId&&pe.dateKey===ie&&pe.hour!==null&&pe.hour===Y&&pe.minute===X);if(de){const pe=y[Z.repId]||"This rep";H.push(`${pe} already has "${de.label}" at ${ch(Y,X)}.`)}}if(Z.customerKey){const de=f.find(pe=>pe.id!==Z.id&&pe.customerKey===Z.customerKey&&pe.dateKey===ie&&(pe.kind==="call"||pe.kind==="visit"||pe.kind==="job"));de&&H.push(`This customer already has "${de.label}" on ${Ry(ie,Y,X).split(" at ")[0]}.`)}return H}function re(Z,ie,Y){const X=f.find(Ie=>Ie.id===Y.id);if(!X||!X.draggable)return;const{hour:H,minute:de}=O_(ie);if(!Y.fromRail&&X.dateKey===Z&&X.hour===H&&X.minute===de)return;const pe=ee(X,Z,H,de),Ne=X.kind==="visit"||X.kind==="call"||X.kind==="job";S({ev:X,toDateKey:Z,toHour:H,toMinute:de,toRail:!1,warnings:pe,willNotify:Ne})}function Q(Z){const ie=f.find(Y=>Y.id===Z.id);!ie||!ie.canUnschedule||ie.hour!==null&&S({ev:ie,toDateKey:ie.dateKey,toHour:0,toMinute:0,toRail:!0,warnings:[],willNotify:!1})}async function oe(){if(!C)return;L(!0);const{ev:Z,toDateKey:ie,toHour:Y,toMinute:X,toRail:H}=C;try{if(Z.kind==="visit"){const{error:de}=await w.from("site_visits").update({visit_date:ie,visit_hour:Y,visit_minute:X}).eq("id",Z.id);if(de)throw de}else if(Z.kind==="call"||Z.kind==="followup"){const de=H?{due_time:null}:{due_date:ie,due_time:`${nf(Y)}:${nf(X)}:00`},{error:pe}=await w.from("follow_up_tasks").update(de).eq("id",Z.id);if(pe)throw pe}else if(Z.kind==="job"){const de=+ie.slice(0,4),pe=+ie.slice(5,7),Ne=+ie.slice(8,10),Ie=yM(de,pe,Ne,Y,X),{error:Ze}=await w.from("jobs").update({scheduled_at:Ie}).eq("id",Z.id);if(Ze)throw Ze}!H&&C.willNotify&&Z.phone&&await ne(Z,ie,Y,X),S(null),P(H?"Task unscheduled.":"Rescheduled."),await J()}catch(de){P(`Failed: ${(de==null?void 0:de.message)||"update error"}`)}finally{L(!1),setTimeout(()=>P(null),3e3)}}async function ne(Z,ie,Y,X){const H=(e==null?void 0:e.tenant_id)??null,de=Z.kind==="visit"?"reschedule_visit":Z.kind==="call"?"reschedule_call":"reschedule_install",[{data:pe},Ne]=await Promise.all([w.from("message_templates").select("body").eq("key",de).eq("channel","sms").eq("tenant_id",H).maybeSingle(),H?w.from("tenants").select("company_name").eq("id",H).maybeSingle():Promise.resolve({data:null})]),Ie=(Ne==null?void 0:Ne.data)||null;if(!(pe!=null&&pe.body)||!Z.phone)return;const Ze=Z.kind==="job"?"job":"lead";await fetch("/api/openphone/send-sms",{method:"POST",headers:await At(),body:JSON.stringify({to:Z.phone,body:pe.body,entity_type:Ze,entity_id:Z.id,sent_by:(e==null?void 0:e.id)??null,tenant_id:H,variables:{first_name:wM(Z.label),company_name:(Ie==null?void 0:Ie.company_name)||"our team",new_time:Ry(ie,Y,X)}})}).catch(()=>{})}function ge(Z){const ie=Yo(i);
630if(a==="month")o(new Date(Date.UTC(ie.year,ie.month-1+Z,1,12)));else{const Y=a==="day"?1:7,X=Ny(ie.year,ie.month,ie.day,Z*Y);o(new Date(Date.UTC(X.year,X.month-1,X.day,12,0,0)))}}function be(){o(new Date)}function we(Z){o(new Date(Date.UTC(q.year,q.month-1,Z,12))),l(s?"day":"week")}function F(Z){x(ie=>{const Y=new Set(ie);return Y.has(Z)?Y.delete(Z):Y.add(Z),Y})}if(!r)return t.jsx("div",{style:{padding:24,color:D.textMuted,background:D.pageBg},children:"You don't have access to the calendar."});const K=vc*Xo;return t.jsxs("div",{style:{padding:"16px 20px",color:D.text,background:D.pageBg,minHeight:"100%"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,marginBottom:12,flexWrap:"wrap"},children:[t.jsx("h1",{style:{fontSize:22,fontWeight:700,margin:0},children:"Calendar"}),t.jsx("div",{style:{display:"inline-flex",border:`0.5px solid ${D.panelBorder}`,borderRadius:8,overflow:"hidden"},children:["day","week","month"].map(Z=>t.jsx("button",{onClick:()=>l(Z),style:{padding:"6px 14px",fontSize:13,fontWeight:600,textTransform:"capitalize",border:"none",cursor:"pointer",background:a===Z?D.chipActiveBg:D.chipBg,color:a===Z?D.chipActiveText:D.textMuted},children:Z},Z))}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[t.jsx("button",{onClick:()=>ge(-1),style:bp(D),children:"â¹"}),t.jsx("button",{onClick:be,style:{...bp(D),padding:"6px 14px"},children:"Today"}),t.jsx("button",{onClick:()=>ge(1),style:bp(D),children:"âº"})]}),t.jsx("span",{style:{fontSize:15,fontWeight:600},children:B}),t.jsx("span",{style:{flex:1}}),t.jsx("input",{value:_,onChange:Z=>j(Z.target.value),placeholder:"Search customerâ¦",style:{padding:"6px 10px",fontSize:13,width:170,borderRadius:6,background:D.inputBg,color:D.text,border:`0.5px solid ${D.inputBorder}`}}),t.jsx("button",{onClick:()=>c(Z=>Z==="dark"?"light":"dark"),style:bp(D),title:d==="dark"?"Switch to light":"Switch to dark",children:d==="dark"?"â":"â¾"}),t.jsxs("span",{style:Ap(D),children:[t.jsx("span",{style:{...vp,background:"#378ADD"}}),"Visit"]}),t.jsxs("span",{style:Ap(D),children:[t.jsx("span",{style:{...vp,background:"#639922"}}),"Call"]}),t.jsxs("span",{style:Ap(D),children:[t.jsx("span",{style:{...vp,background:"#EF9F27"}}),"Task"]}),t.jsxs("span",{style:Ap(D),children:[t.jsx("span",{style:{...vp,background:"#22B8B8"}}),"Install/Svc"]})]}),b.length>0&&t.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:6,marginBottom:12,alignItems:"center"},children:[t.jsx("span",{style:{fontSize:11,color:D.textDim,marginRight:2},children:"Reps:"}),b.map(Z=>{const ie=v.has(Z.id);return t.jsx("button",{onClick:()=>F(Z.id),style:{padding:"3px 10px",fontSize:11,borderRadius:999,cursor:"pointer",background:ie?D.chipActiveBg:D.chipBg,color:ie?D.chipActiveText:D.textMuted,border:`0.5px solid ${ie?D.chipActiveBorder:D.chipBorder}`},children:Z.name||"Unnamed"},Z.id)}),v.size>0&&t.jsx("button",{onClick:()=>x(new Set),style:{padding:"3px 8px",fontSize:11,borderRadius:999,cursor:"pointer",background:"transparent",color:D.textDim,border:`0.5px solid ${D.chipBorder}`},children:"Clear"})]}),u&&t.jsx("div",{style:{color:D.textMuted,padding:12},children:"Loadingâ¦"}),a==="month"?t.jsx(NM,{meta:q,byDom:V,theme:D,matches:te,today:W_(),onOpenDay:we}):t.jsxs("div",{style:{display:"grid",gridTemplateColumns:s?"1fr":"1fr 210px",gap:10,alignItems:"start"},children:[t.jsxs("div",{style:{border:`0.5px solid ${D.panelBorder}`,borderRadius:12,overflow:"hidden",background:D.panelBg},children:[t.jsxs("div",{style:{display:"grid",gridTemplateColumns:`${s?44:64}px repeat(${k.length}, 1fr)`},children:[t.jsx("div",{style:{borderBottom:`0.5px solid ${D.panelBorder}`}}),k.map(Z=>t.jsxs("div",{style:{textAlign:"center",padding:"8px 0",borderBottom:`0.5px solid ${D.panelBorder}`,borderLeft:`0.5px solid ${D.colBorder}`,background:Z.isToday?D.todayHeader:"transparent",color:Z.isWeekend?D.weekendText:D.text},children:[t.jsx("div",{style:{fontSize:12,fontWeight:500},children:Z.abbr}),t.jsx("div",{style:{fontSize:16,fontWeight:600},children:Z.dom})]},Z.key))]}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:`${s?44:64}px repeat(${k.length}, 1fr)`},children:[t.jsx("div",{style:{position:"relative",height:K},children:Array.from({length:vc}).map((Z,ie)=>{const Y=Qf+Math.floor(ie/2),X=ie%2*30;return t.jsx("div",{style:{height:Xo,fontSize:10,textAlign:"right",paddingRight:7,color:X===0?D.textMuted:D.textDim,transform:"translateY(-5px)",lineHeight:1},children:ch(Y,X)},ie)})}),k.map(Z=>t.jsxs("div",{onDragOver:E?ie=>{ie.preventDefault();const Y=ie.currentTarget.getBoundingClientRect(),{hour:X,minute:H}=O_(ie.clientY-Y.top);O(de=>de&&de.dateKey===Z.key&&de.hour===X&&de.minute===H?de:{dateKey:Z.key,hour:X,minute:H})}:void 0,onDrop:ie=>{ie.preventDefault(),R(null),O(null);let Y=null;try{Y=JSON.parse(ie.dataTransfer.getData("text/plain"))}catch{Y=null}if(!Y)return;const X=ie.currentTarget.getBoundingClientRect();re(Z.key,ie.clientY-X.top,Y)},style:{position:"relative",height:K,borderLeft:`0.5px solid ${D.colBorder}`,background:Z.isToday?D.todayCol:"transparent",outline:E?`1px dashed ${D.chipActiveBorder}`:"none",outlineOffset:-1},children:[Array.from({length:vc}).map((ie,Y)=>t.jsx("div",{style:{height:Xo,boxSizing:"border-box",borderBottom:Y%2===1?`0.5px dashed ${D.gridLineDash}`:`0.5px solid ${D.gridLineSolid}`}},Y)),E&&N&&N.dateKey===Z.key&&t.jsx("div",{style:{position:"absolute",left:0,right:0,zIndex:5,top:Jk(N.hour,N.minute),height:Xo,background:"rgba(59,130,246,0.18)",borderTop:`2px solid ${D.chipActiveBorder}`,pointerEvents:"none",display:"flex",alignItems:"center",justifyContent:"center"},children:t.jsx("span",{style:{fontSize:11,fontWeight:700,color:D.text,background:D.panelBg,padding:"1px 8px",borderRadius:6,border:`1px solid ${D.chipActiveBorder}`,whiteSpace:"nowrap"},children:ch(N.hour,N.minute)})}),(W[Z.key]||[]).map(ie=>t.jsx(RM,{e:ie,repNames:y,kc:M,dim:U(ie),onDragStart:Y=>{if(!ie.draggable){Y.preventDefault();return}R(ie.kind),Y.dataTransfer.setData("text/plain",JSON.stringify({id:ie.id,kind:ie.kind,fromRail:!1}))},onDragEnd:()=>{R(null),O(null)},onClick:()=>{ie.navTo&&n(ie.navTo)}},ie.id))]},Z.key))]})]}),t.jsxs("div",{onDragOver:E?Z=>{Z.preventDefault(),O(null)}:void 0,onDrop:Z=>{Z.preventDefault(),R(null),O(null);let ie=null;try{ie=JSON.parse(Z.dataTransfer.getData("text/plain"))}catch{ie=null}ie&&Q(ie)},style:{border:`0.5px solid ${E?D.chipActiveBorder:D.panelBorder}`,borderRadius:12,overflow:"hidden",background:D.panelBg},children:[t.jsxs("div",{style:{padding:"8px 11px",borderBottom:`0.5px solid ${D.panelBorder}`,display:"flex",alignItems:"center",gap:6},children:[t.jsx("span",{style:{fontSize:13,fontWeight:600,color:D.text},children:"Unscheduled"}),t.jsxs("span",{style:{marginLeft:"auto",fontSize:11,color:D.textDim},children:[a==="day"?"this day":"this week"," · ",G.length]})]}),t.jsx("div",{style:{maxHeight:K,overflowY:"auto",minHeight:60},children:G.length===0?t.jsx("div",{style:{padding:14,fontSize:12,color:D.textDim},children:E?"Drop a task here to unschedule.":"No unscheduled tasks."}):G.map(Z=>{var H;const ie=Z.repId?y[Z.repId]:null,Y=((H=k.find(de=>de.key===Z.dateKey))==null?void 0:H.abbr)||Z.dateKey.slice(5),X=U(Z);return t.jsxs("div",{draggable:!0,onDragStart:de=>{R(Z.kind),de.dataTransfer.setData("text/plain",JSON.stringify({id:Z.id,kind:Z.kind,fromRail:!0}))},onDragEnd:()=>{R(null),O(null)},onClick:()=>{Z.navTo&&n(Z.navTo)},style:{padding:"7px 11px",borderBottom:`0.5px solid ${D.colBorder}`,cursor:"grab",display:"flex",gap:7,alignItems:"flex-start",opacity:X?.28:1},children:[t.jsx("span",{style:{width:7,height:7,borderRadius:"50%",marginTop:4,flexShrink:0,background:Z.kind==="call"?"#639922":"#EF9F27"}}),t.jsxs("span",{style:{minWidth:0},children:[t.jsx("span",{style:{fontSize:11,color:D.text,display:"block",lineHeight:1.3},children:Z.label}),t.jsxs("span",{style:{fontSize:9,color:D.textDim},children:[Y,ie?` · ${ie}`:""]})]})]}
630,Z.id)})})]})]}),C&&t.jsx(zM,{theme:D,pending:C,saving:T,onCancel:()=>S(null),onConfirm:oe}),z&&t.jsx("div",{style:{position:"fixed",bottom:20,left:"50%",transform:"translateX(-50%)",background:D.modalBg,color:D.text,border:`0.5px solid ${D.modalBorder}`,padding:"10px 18px",borderRadius:8,fontSize:13,zIndex:60,boxShadow:"0 4px 16px rgba(0,0,0,0.3)"},children:z})]})}function zM({theme:e,pending:n,saving:r,onCancel:s,onConfirm:i}){const{ev:o,toDateKey:a,toHour:l,toMinute:d,toRail:c,warnings:f,willNotify:p}=n,u=c?"Unschedule task?":"Confirm reschedule";return t.jsx("div",{onClick:s,style:{position:"fixed",inset:0,background:e.overlay,zIndex:50,display:"flex",alignItems:"center",justifyContent:"center"},children:t.jsxs("div",{onClick:h=>h.stopPropagation(),style:{width:420,maxWidth:"90vw",background:e.modalBg,color:e.text,border:`0.5px solid ${e.modalBorder}`,borderRadius:12,padding:20,boxShadow:"0 12px 40px rgba(0,0,0,0.4)"},children:[t.jsx("div",{style:{fontSize:16,fontWeight:700,marginBottom:10},children:u}),t.jsxs("div",{style:{fontSize:13,color:e.textMuted,marginBottom:6},children:[t.jsx("strong",{style:{color:e.text},children:o.label})," · ",o.sub]}),c?t.jsx("div",{style:{fontSize:13,marginBottom:14},children:"This task's time will be cleared and it will return to the Unscheduled rail."}):t.jsxs("div",{style:{fontSize:13,marginBottom:14},children:["New time: ",t.jsx("strong",{children:Ry(a,l,d)})]}),f.length>0&&t.jsx("div",{style:{border:"0.5px solid #b45309",background:"rgba(180,83,9,0.12)",borderRadius:8,padding:"8px 11px",marginBottom:14},children:f.map((h,y)=>t.jsxs("div",{style:{fontSize:12,color:"#f59e0b",lineHeight:1.4},children:["â ",h]},y))}),!c&&p&&t.jsx("div",{style:{fontSize:12,color:e.textDim,marginBottom:14},children:o.phone?"The customer will be texted the new time.":"No phone on file â no text will be sent."}),t.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:8},children:[t.jsx("button",{onClick:s,disabled:r,style:{padding:"7px 14px",fontSize:13,borderRadius:6,cursor:"pointer",background:"transparent",color:e.textMuted,border:`0.5px solid ${e.chipBorder}`},children:"Cancel"}),t.jsx("button",{onClick:i,disabled:r,style:{padding:"7px 16px",fontSize:13,fontWeight:600,borderRadius:6,cursor:"pointer",background:e.chipActiveBg,color:e.chipActiveText,border:"none",opacity:r?.6:1},children:r?"Savingâ¦":c?"Unschedule":"Confirm"})]})]})})}function NM({meta:e,byDom:n,theme:r,matches:s,today:i,onOpenDay:o}){const a=[];for(let l=0;l<e.leadBlanks;l++)a.push(null);for(let l=1;l<=e.daysInMonth;l++)a.push(l);for(;a.length%7!==0;)a.push(null);return t.jsxs("div",{style:{border:`0.5px solid ${r.panelBorder}`,borderRadius:12,overflow:"hidden",background:r.panelBg},children:[t.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(7, 1fr)"},children:rf.map((l,d)=>t.jsx("div",{style:{textAlign:"center",padding:"8px 0",fontSize:12,fontWeight:600,color:d>=5?r.weekendText:r.textMuted,borderBottom:`0.5px solid ${r.panelBorder}`,borderLeft:d===0?"none":`0.5px solid ${r.colBorder}`},children:l},l))}),t.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(7, 1fr)"},children:a.map((l,d)=>{if(l===null)return t.jsx("div",{style:{minHeight:92,borderTop:`0.5px solid ${r.colBorder}`,borderLeft:d%7===0?"none":`0.5px solid ${r.colBorder}`}},d);const f=$o(e.year,e.month,l)===i,p=(n[l]||[]).filter(s),u={visit:0,call:0,followup:0,job:0};for(const h of p)u[h.kind]++;return t.jsxs("div",{onClick:()=>o(l),style:{minHeight:92,padding:6,cursor:"pointer",boxSizing:"border-box",borderTop:`0.5px solid ${r.colBorder}`,borderLeft:d%7===0?"none":`0.5px solid ${r.colBorder}`,background:f?r.todayCol:"transparent"},children:[t.jsxs("div",{style:{fontSize:13,fontWeight:f?700:500,marginBottom:4,color:f?r.chipActiveBg:r.text,display:"flex",alignItems:"center",justifyContent:"space-between"},children:[t.jsx("span",{children:l}),p.length>0&&t.jsx("span",{style:{fontSize:10,color:r.textDim},children:p.length})]}),t.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:3},children:["visit","call","followup","job"].map(h=>u[h]>0?t.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:2,fontSize:9,color:r.textMuted},children:[t.jsx("span",{style:{width:6,height:6,borderRadius:"50%",background:CM[h]}}),u[h]]},h):null)})]},d)})})]})}function RM({e,repNames:n,kc:r,dim:s,onClick:i,onDragStart:o,onDragEnd:a}){const l=e.repId?n[e.repId]:null,d=l?`${e.sub} · ${l}`:e.sub,c=r[e.kind],f=Jk(e.hour,e.minute)+1,u=(e.kind==="visit"?2:1)*Xo-2;return t.jsxs("div",{draggable:e.draggable,onDragStart:o,onDragEnd:a,onClick:i,title:`${e.label} â ${d}`,style:{position:"absolute",top:f,left:3,right:3,height:u,background:c.bg,borderLeft:`3px solid ${c.border}`,borderRadius:5,padding:"2px 6px",fontSize:10,lineHeight:1.2,cursor:e.draggable?"grab":e.navTo?"pointer":"default",overflow:"hidden",color:c.sub,boxSizing:"border-box",zIndex:2,opacity:s?.28:1},children:[t.jsx("div",{style:{fontWeight:600,color:c.title,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:e.label}),t.jsx("div",{style:{whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:d})]})}function EM(e){return e==="admin"||e==="super_admin"||e==="frontdesk"}function bp(e){return{padding:"6px 10px",fontSize:14,background:e.chipBg,color:e.text,border:`0.5px solid ${e.panelBorder}`,borderRadius:6,cursor:"pointer"}}function Ap(e){return{display:"inline-flex",alignItems:"center",gap:5,fontSize:12,color:e.textMuted}}const vp={width:10,height:10,borderRadius:2,display:"inline-block"},zs="11111111-1111-1111-1111-111111111111",PM=["admin","super_admin"],qM={name:"",company_name:"",slug:"",tagline:"",logo_url:"",primary_color:"#0d7ea3",phone:"",email:"",email_from:"",website:"",address:"",address_line1:"",address_line2:"",city:"",state:"",zip:"",country:"US",domain:"",resend_domain:"",resend_from_email:"",resend_domain_verified:!1,openphone_api_key:"",openphone_number:"",sms_enabled:!1,stripe_customer_id:"",stripe_connect_id:"",stripe_connect_status:"not_connected",stripe_subscription_id:"",platform_fee_percent:2.5,fedex_api_key:"",fedex_secret_key:"",fedex_connected:!1,google_review_url:"",governing_law_state:"Indiana",governing_law_county:"Marion County",cancellation_fee:250,rental_min_months:12,service_response_hours:48,business_hours:"MonâFri 8AMâ6PM EST",plan_tier:"starter",subscription_status:"trialing",trial_ends_at:null,is_active:!0,seats_included:3,seats_used:1,max_branches:1,max_users_per_branch:null,features:{shipping:!0,service_plans:!0,automations:!0,inventory:!0,reports:!0}},Fa={payment_gateway:"stripe",payments_enabled:!0,gateway_public_key:"",gateway_secret_key:"",gateway_webhook_secret:"",gateway_login_id:""},DM=["AL","AK","AZ","AR","CA","CO","CT","DE","FL","GA","HI","ID","IL","IN","IA","KS","KY","LA","ME","MD","MA","MI","MN","MS","MO","MT","NE","NV","NH","NJ","NM","NY","NC","ND","OH","OK","OR","PA","RI","SC","SD","TN","TX","UT","VT","VA","WA","WV","WI","WY","DC"],$_=[{v:"starter",l:"Starter â $199/mo",s:3,b:1},{v:"growth",l:"Growth â $299/mo",s:5,b:2},{v:"professional",l:"Professional â $399/mo",s:10,b:5},{v:"enterprise",l:"Enterprise â $799/mo",s:999,b:999}],OM=["trialing","active","past_due","cancelled"],Xn={background:"#162232",borderRadius:"12px",border:"1px solid #1e3a4f",padding:"24px",marginBottom:"20px"},$r={fontSize:"13px",fontWeight:700,color:"#0d7ea3",textTransform:"uppercase",letterSpacing:"0.08em",marginBottom:"16
630px",display:"flex",alignItems:"center",gap:"8px"},Ke={display:"block",fontSize:"12px",fontWeight:600,color:"#94a3b8",marginBottom:"4px",textTransform:"uppercase",letterSpacing:"0.04em"},tt={width:"100%",padding:"10px 12px",background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:"8px",color:"#e2e8f0",fontSize:"14px",outline:"none",boxSizing:"border-box"};({...tt});const Md={...tt,cursor:"pointer"},uh={padding:"10px 24px",background:"#0d7ea3",color:"#fff",border:"none",borderRadius:"8px",fontWeight:700,fontSize:"14px",cursor:"pointer"},_p={...uh,background:"transparent",border:"1px solid #1e3a4f",color:"#94a3b8"},cs={display:"grid",gridTemplateColumns:"1fr 1fr",gap:"12px"},fi={display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:"12px"},IM={display:"grid",gridTemplateColumns:"1fr 1fr 1fr 1fr",gap:"12px"},xm=e=>({display:"inline-block",padding:"2px 10px",borderRadius:"999px",fontSize:"11px",fontWeight:700,background:`${e}22`,color:e,border:`1px solid ${e}44`}),LM=e=>e==="active"?"#22c55e":e==="trialing"?"#3b82f6":e==="past_due"?"#f59e0b":e==="cancelled"?"#ef4444":"#64748b";function WM(){const[e,n]=g.useState([]),[r,s]=g.useState({}),[i,o]=g.useState(!0),[a,l]=g.useState(null),[d,c]=g.useState({...Fa}),[f,p]=g.useState(!1),[u,h]=g.useState(!1),[y,m]=g.useState(""),[b,A]=g.useState(""),[v,x]=g.useState(""),[_,j]=g.useState({}),[C,S]=g.useState(null),[T,L]=g.useState({}),[E,R]=g.useState(""),[N,O]=g.useState(""),[z,P]=g.useState("Main Office"),D=g.useCallback(async()=>{try{const{data:F}=await w.from("profiles").select("tenant_id, role"),K={};for(const Z of F||[])Z.tenant_id&&!PM.includes(Z.role)&&(K[Z.tenant_id]=(K[Z.tenant_id]||0)+1);s(K)}catch(F){console.warn("loadSeatCounts error:",F)}},[]),M=g.useCallback(async()=>{o(!0);try{const{data:F,error:K}=await w.from("tenants").select("*").order("created_at",{ascending:!1});if(K)throw K;n(F||[])}catch(F){m(F.message)}await D(),o(!1)},[D]);g.useEffect(()=>{M()},[M]);const k=async F=>{try{const{data:K}=await w.from("tenant_api_credentials").select("service, credential_key, credential_value, payment_gateway, payments_enabled").eq("tenant_id",F).eq("is_active",!0).in("service",["payment_config","stripe","authorize_net","square"]);if(!K||K.length===0){c({...Fa});return}const Z={...Fa},ie=K.find(Y=>Y.service==="payment_config");ie&&(Z.payment_gateway=ie.payment_gateway||ie.credential_value||"stripe",Z.payments_enabled=ie.payments_enabled??!0);for(const Y of K)Y.service==="stripe"&&(Y.credential_key==="publishable_key"&&(Z.gateway_public_key=Y.credential_value||""),Y.credential_key==="secret_key"&&(Z.gateway_secret_key=Y.credential_value||""),Y.credential_key==="webhook_secret"&&(Z.gateway_webhook_secret=Y.credential_value||"")),Y.service==="authorize_net"&&(Y.credential_key==="login_id"&&(Z.gateway_login_id=Y.credential_value||""),Y.credential_key==="transaction_key"&&(Z.gateway_secret_key=Y.credential_value||"")),Y.service==="square"&&(Y.credential_key==="access_token"&&(Z.gateway_secret_key=Y.credential_value||""),Y.credential_key==="location_id"&&(Z.gateway_public_key=Y.credential_value||""));c(Z)}catch(K){console.warn("loadGatewayConfig error:",K),c({...Fa})}},q=()=>{const F=new Date;F.setDate(F.getDate()+14),l({...qM,trial_ends_at:F.toISOString()}),c({...Fa}),p(!0),m(""),A("")},$=F=>{l({...F}),p(!1),m(""),A(""),k(F.id)},I=()=>{l(null),p(!1),m(""),A(""),c({...Fa})},B=(F,K)=>l(Z=>Z&&{...Z,[F]:K}),J=(F,K)=>c(Z=>({...Z,[F]:K})),ae=(F,K)=>l(Z=>Z&&{...Z,features:{...Z.features||{},[F]:K}}),te=F=>F.company_name||F.name||"Unnamed",U=async F=>{const K=d.payment_gateway||"stripe";if(await w.from("tenant_api_credentials").upsert({tenant_id:F,service:"payment_config",credential_key:"gateway",credential_value:K,payment_gateway:K,payments_enabled:d.payments_enabled,is_active:!0},{onConflict:"tenant_id,service,credential_key"}).then(()=>{}).catch(console.warn),K==="stripe"){const Z=[{key:"publishable_key",val:d.gateway_public_key},{key:"secret_key",val:d.gateway_secret_key},{key:"webhook_secret",val:d.gateway_webhook_secret}].filter(ie=>{var Y;return(Y=ie.val)==null?void 0:Y.trim()});for(const ie of Z)await w.from("tenant_api_credentials").upsert({tenant_id:F,service:"stripe",credential_key:ie.key,credential_value:ie.val,payment_gateway:"stripe",payments_enabled:d.payments_enabled,is_active:!0},{onConflict:"tenant_id,service,credential_key"}).then(()=>{}).catch(console.warn)}if(K==="authorize_net"){const Z=[{key:"login_id",val:d.gateway_login_id},{key:"transaction_key",val:d.gateway_secret_key}].filter(ie=>{var Y;return(Y=ie.val)==null?void 0:Y.trim()});for(const ie of Z)await w.from("tenant_api_credentials").upsert({tenant_id:F,service:"authorize_net",credential_key:ie.key,credential_value:ie.val,payment_gateway:"authorize_net",payments_enabled:d.payments_enabled,is_active:!0},{onConflict:"tenant_id,service,credential_key"}).then(()=>{}).catch(console.warn)}if(K==="square"){const Z=[{key:"access_token",val:d.gateway_secret_key},{key:"location_id",val:d.gateway_public_key}].filter(ie=>{var Y;return(Y=ie.val)==null?void 0:Y.trim()});for(const ie of Z)await w.from("tenant_api_credentials").upsert({tenant_id:F,service:"square",credential_key:ie.key,credential_value:ie.val,payment_gateway:"square",payments_enabled:d.payments_enabled,is_active:!0},{onConflict:"tenant_id,service,credential_key"}).then(()=>{}).catch(console.warn)}},W=async()=>{var F;if(!((F=a==null?void 0:a.company_name)!=null&&F.trim())){m("Company name is required");return}h(!0),m("");try{const K={...a};if(delete K.created_at,delete K.updated_at,delete K.seats_used,!K.slug&&K.company_name&&(K.slug=K.company_name.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")),!K.name&&K.company_name&&(K.name=K.company_name),!K.email_from&&K.email&&(K.email_from=K.email),f){if(!N.trim()){m("Admin email is required to provision a tenant"),h(!1);return}delete K.id;const{data:{session:Z}}=await w.auth.getSession(),ie=Z==null?void 0:Z.access_token,Y=await fetch("/api/onboard",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${ie}`},body:JSON.stringify({tenantName:K.company_name,slug:K.slug,adminEmail
630:N.trim(),branchName:z.trim()||"Main Office",planTier:K.plan_tier||"starter",maxBranches:K.max_branches||1,seatsIncluded:K.seats_included||3})}),X=await Y.json();if(!Y.ok)throw new Error(X.error||"Provisioning failed");const H=X.tenant_id,de={...K};delete de.id;const{error:pe}=await w.from("tenants").update(de).eq("id",H);pe&&console.warn("tenant detail update after provision:",pe.message);try{await w.rpc("seed_tenant_automations",{p_tenant_id:H})}catch{console.warn("seed_tenant_automations RPC not found")}await U(H),A(`Tenant "${K.company_name}" provisioned! Invite ${X.inviteSent?"sent":"NOT sent â check email config"} to ${N}. Login: ${X.loginUrl}`)}else{const{error:Z}=await w.from("tenants").update(K).eq("id",a.id);if(Z)throw Z;await U(a.id),A(`Tenant "${a.company_name}" updated!`)}await M(),setTimeout(()=>I(),1500)}catch(K){m(K.message)}h(!1)},G=async F=>{try{const{error:K}=await w.rpc("seed_tenant_automations",{p_tenant_id:F});if(K)throw K;A("Automations seeded!")}catch(K){m(K.message)}},V=async F=>{const{data:K}=await w.from("branches").select("id, tenant_id, name, code, is_active, is_default").eq("tenant_id",F).order("name");L(Z=>({...Z,[F]:K||[]}))},ee=async F=>{if(C===F){S(null);return}S(F),T[F]||await V(F)},re=async F=>{const K=!F.is_active;R("");const{error:Z}=await w.from("branches").update({is_active:K}).eq("id",F.id);if(Z){R("Error: "+Z.message),setTimeout(()=>R(""),5e3);return}await V(F.tenant_id)},Q=async F=>{var Z,ie;if(F.id===zs)return;const K=window.prompt(`This permanently deletes tenant "${te(F)}" â all branches, users, and data. This cannot be undone. 631 632Type the slug to confirm: ${F.slug}`);if(K!==null){if(K.trim()!==F.slug){R("Slug did not match â teardown cancelled"),setTimeout(()=>R(""),4e3);return}R("");try{const{data:{session:Y}}=await w.auth.getSession(),X=Y==null?void 0:Y.access_token,H=await fetch("/api/onboard?action=teardown",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${X}`},body:JSON.stringify({tenant_id:F.id})}),de=await H.json();if(!H.ok)throw new Error(de.error||"Teardown failed");R(`Tenant "${te(F)}" removed (${((Z=de.deleted)==null?void 0:Z.authUsers)||0} users, ${((ie=de.deleted)==null?void 0:ie.branches)||0} branches).`),await M(),setTimeout(()=>R(""),5e3)}catch(Y){R("Error: "+Y.message),setTimeout(()=>R(""),6e3)}}},oe=async F=>{if(F.id===zs)return;const K=!F.is_active,Z=K?"reactivate":"SUSPEND";if(!window.confirm(`${Z} tenant "${te(F)}"? Their team's access will be ${K?"restored":"restricted"} (pending RLS enforcement rollout).`))return;R("");const{error:ie}=await w.from("tenants").update({is_active:K}).eq("id",F.id);if(ie){R("Error: "+ie.message),setTimeout(()=>R(""),4e3);return}await M()},ne=({field:F,ph:K,gwField:Z})=>t.jsxs("div",{style:{position:"relative"},children:[t.jsx("input",{type:_[F||Z||""]?"text":"password",style:tt,placeholder:K,value:Z?d[Z]||"":(a==null?void 0:a[F])||"",onChange:ie=>Z?J(Z,ie.target.value):B(F,ie.target.value)}),t.jsx("button",{type:"button",onClick:()=>j(ie=>({...ie,[F||Z||""]:!ie[F||Z||""]})),style:{position:"absolute",right:"8px",top:"50%",transform:"translateY(-50%)",background:"none",border:"none",color:"#64748b",cursor:"pointer",fontSize:"12px"},children:_[F||Z||""]?"Hide":"Show"})]}),ge=e.filter(F=>te(F).toLowerCase().includes(v.toLowerCase())||(F.slug||"").toLowerCase().includes(v.toLowerCase())||(F.email||"").toLowerCase().includes(v.toLowerCase())),be=()=>t.jsxs(t.Fragment,{children:[y&&t.jsx("div",{style:{background:"#dc262622",border:"1px solid #dc262644",borderRadius:"8px",padding:"12px",color:"#fca5a5",marginBottom:"16px",fontSize:"13px"},children:y}),b&&t.jsx("div",{style:{background:"#22c55e22",border:"1px solid #22c55e44",borderRadius:"8px",padding:"12px",color:"#86efac",marginBottom:"16px",fontSize:"13px"},children:b}),E&&t.jsx("div",{style:{background:"#dc262622",border:"1px solid #dc262644",borderRadius:"8px",padding:"12px",color:"#fca5a5",marginBottom:"16px",fontSize:"13px"},children:E})]});if(!a)return t.jsxs("div",{style:{padding:"24px",maxWidth:"1200px",margin:"0 auto",height:"100%",overflowY:"auto"},children:[t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"24px"},children:[t.jsxs("div",{children:[t.jsx("h1",{style:{margin:0,fontSize:"24px",fontWeight:800,color:"#e2e8f0"},children:"Tenant Management"}),t.jsxs("p",{style:{margin:"4px 0 0",fontSize:"13px",color:"#64748b"},children:[e.length," tenant",e.length!==1?"s":""," · ",e.filter(F=>F.subscription_status==="active").length," active · ",e.filter(F=>F.subscription_status==="trialing").length," trialing"]})]}),t.jsx("button",{style:uh,onClick:q,children:"+ New Tenant"})]}
632),t.jsx("input",{style:{...tt,marginBottom:"16px",maxWidth:"400px"},placeholder:"Search by name, slug, or email...",value:v,onChange:F=>x(F.target.value)}),t.jsx(be,{}),i?t.jsx("p",{style:{color:"#64748b"},children:"Loading..."}):ge.length===0?t.jsx("div",{style:{...Xn,textAlign:"center",padding:"48px"},children:t.jsx("p",{style:{color:"#64748b",margin:0},children:'No tenants found. Click "+ New Tenant" to onboard.'})}):t.jsx("div",{style:{display:"grid",gap:"12px"},children:ge.map(F=>{const K=r[F.id]??0,Z=T[F.id];return t.jsxs(g.Fragment,{children:[t.jsxs("div",{style:{...Xn,padding:"16px 20px",display:"flex",justifyContent:"space-between",alignItems:"center"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"16px",cursor:"pointer",flex:1},onClick:()=>$(F),children:[t.jsx("div",{style:{width:"44px",height:"44px",borderRadius:"10px",background:F.primary_color||"#0d7ea3",display:"flex",alignItems:"center",justifyContent:"center",fontWeight:800,fontSize:"18px",color:"#fff",flexShrink:0},children:te(F)[0].toUpperCase()}),t.jsxs("div",{children:[t.jsx("div",{style:{fontWeight:700,fontSize:"15px",color:"#e2e8f0"},children:te(F)}),t.jsxs("div",{style:{fontSize:"12px",color:"#64748b",marginTop:"2px"},children:[F.slug&&t.jsxs("span",{children:[F.slug,".getcevora.com"]}),F.email&&t.jsxs("span",{children:[" · ",F.email]})]})]})]}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[t.jsx("span",{style:xm(LM(F.subscription_status)),children:F.subscription_status}),t.jsx("span",{style:xm("#64748b"),children:F.plan_tier}),t.jsxs("span",{style:{fontSize:"12px",color:"#64748b"},title:"Live non-admin seats / included",children:[K,"/",F.seats_included," seats"]}),t.jsxs("span",{style:{fontSize:"12px",color:"#64748b"},title:"Max branches",children:[F.max_branches??"â"," br"]}),!F.is_active&&t.jsx("span",{style:xm("#ef4444"),children:"OFF"}),t.jsx("button",{onClick:()=>ee(F.id),style:{..._p,padding:"5px 10px",fontSize:"11px",color:"#0d7ea3"},children:C===F.id?"â¾ Branches":"⸠Branches"}),t.jsx("button",{onClick:()=>oe(F),disabled:F.id===zs,title:F.id===zs?"Cannot suspend your own tenant":"",style:{padding:"5px 10px",borderRadius:"6px",fontSize:"11px",fontWeight:600,background:F.id===zs?"#162232":F.is_active?"rgba(239,68,68,0.12)":"rgba(34,197,94,0.12)",border:`1px solid ${F.id===zs?"#1e3a4f":F.is_active?"#ef444440":"#22c55e40"}`,color:F.id===zs?"#3a4a5c":F.is_active?"#ef4444":"#22c55e",cursor:F.id===zs?"not-allowed":"pointer"},children:F.is_active?"Suspend":"Activate"}),F.id!==zs&&t.jsx("button",{onClick:()=>Q(F),title:"Permanently delete this tenant",style:{padding:"5px 10px",borderRadius:"6px",fontSize:"11px",fontWeight:600,background:"rgba(239,68,68,0.12)",border:"1px solid #ef444440",color:"#ef4444",cursor:"pointer"},children:"Delete"})]})]}),C===F.id&&t.jsxs("div",{style:{...Xn,marginTop:"-12px",padding:"12px 20px 16px 40px",background:"#0f1923"},children:[t.jsx("div",{style:{color:"#64748b",fontSize:"11px",fontWeight:600,textTransform:"uppercase",letterSpacing:"0.05em",marginBottom:"8px"},children:"Branches"}),Z?Z.length===0?t.jsx("div",{style:{color:"#64748b",fontSize:"12px"},children:"No branches"}):t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:Z.map(ie=>t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",background:"#162232",border:"1px solid #1e3a4f",borderRadius:"8px",padding:"8px 14px"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[t.jsx("span",{style:{color:"#e2e8f0",fontSize:"13px",fontWeight:600},children:ie.name}),ie.code&&t.jsxs("span",{style:{color:"#64748b",fontSize:"11px"},children:["(",ie.code,")"]}),ie.is_default&&t.jsx("span",{style:{color:"#0d7ea3",fontSize:"10px",border:"1px solid #0d7ea340",borderRadius:"10px",padding:"1px 8px"},children:"default"}),!ie.is_active&&t.jsx("span",{style:{color:"#ef4444",fontSize:"10px",border:"1px solid #ef444440",borderRadius:"10px",padding:"1px 8px"},children:"suspended"})]}),t.jsx("button",{onClick:()=>re(ie),style:{padding:"5px 10px",borderRadius:"6px",fontSize:"11px",fontWeight:600,background:ie.is_active?"rgba(239,68,68,0.12)":"rgba(34,197,94,0.12)",border:`1px solid ${ie.is_active?"#ef444440":"#22c55e40"}`,color:ie.is_active?"#ef4444":"#22c55e",cursor:"pointer"},children:ie.is_active?"Suspend":"Activate"})]},ie.id))}):t.jsx("div",{style:{color:"#64748b",fontSize:"12px"},children:"Loading..."})]})]},F.id)})})]});const we=a.id?r[a.id]??0:0;return t.jsxs("div",{style:{padding:"24px",maxWidth:"900px",margin:"0 auto",height:"100%",overflowY:"auto"},children:[t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"24px"},children:[t.jsxs("div",{children:[t.jsx("button",{onClick:I,style:{..._p,padding:"6px 16px",fontSize:"12px",marginBottom:"8px"},children:"â Back"}),t.jsx("h1",{style:{margin:0,fontSize:"22px",fontWeight:800,color:"#e2e8f0"},children:f?"Onboard New Tenant":`Edit: ${a.company_name||a.name||""}`})]}),t.jsxs("div",{style:{display:"flex",gap:"10px"},children:[!f&&t.jsx("button",{style:_p,onClick:()=>G(a.id),children:"Seed Automations"}),t.jsx("button",{style:uh,onClick:W,disabled:u,children:u?"Saving...":f?"Create Tenant":"Save Changes"})]})]}),t.jsx(be,{}),!f&&a.id&&t.jsxs("div",{style:{background:"#0f192344",border:"1px solid #1e3a4f",borderRadius:"8px",padding:"10px 16px",marginBottom:"16
632px",fontSize:"12px",color:"#64748b",fontFamily:"monospace"},children:["ID: ",a.id," · Created: ",a.created_at?new Date(a.created_at).toLocaleDateString():"â"]}),t.jsxs("div",{style:Xn,children:[t.jsx("div",{style:$r,children:"ð¢ Company Identity"}),t.jsxs("div",{style:cs,children:[t.jsxs("div",{children:[t.jsx("label",{style:Ke,children:"Company Name *"}),t.jsx("input",{style:tt,value:a.company_name||"",onChange:F=>B("company_name",F.target.value),placeholder:"Acme Water Treatment"})]}),t.jsxs("div",{children:[t.jsx("label",{style:Ke,children:"Slug"}),t.jsxs("div",{style:{display:"flex"},children:[t.jsx("input",{style:{...tt,borderTopRightRadius:0,borderBottomRightRadius:0},value:a.slug||"",onChange:F=>B("slug",F.target.value.toLowerCase().replace(/[^a-z0-9-]/g,"")),placeholder:"acme-water"}),t.jsx("span",{style:{padding:"10px 12px",background:"#1e3a4f",border:"1px solid #1e3a4f",borderTopRightRadius:"8px",borderBottomRightRadius:"8px",color:"#64748b",fontSize:"12px",whiteSpace:"nowrap"},children:".getcevora.com"})]})]})]}),f&&t.jsxs("div",{style:{...cs,marginTop:"12px"},children:[t.jsxs("div",{children:[t.jsx("label",{style:Ke,children:"Admin Email *"}),t.jsx("input",{style:tt,value:N,onChange:F=>O(F.target.value),placeholder:"[email protected]"}),t.jsx("div",{style:{fontSize:"11px",color:"#64748b",marginTop:"4px"},children:"Gets an invite to set a password and sign in."})]}),t.jsxs("div",{children:[t.jsx("label",{style:Ke,children:"First Branch Name *"}),t.jsx("input",{style:tt,value:z,onChange:F=>P(F.target.value),placeholder:"Main Office"}),t.jsx("div",{style:{fontSize:"11px",color:"#64748b",marginTop:"4px"},children:"The tenant's primary location (set as default)."})]})]}),t.jsxs("div",{style:{...cs,marginTop:"12px"},children:[t.jsxs("div",{children:[t.jsx("label",{style:Ke,children:"Tagline"}),t.jsx("input",{style:tt,value:a.tagline||"",onChange:F=>B("tagline",F.target.value),placeholder:"Clean Water. Pure Simple."})]}),t.jsxs("div",{children:[t.jsx("label",{style:Ke,children:"Brand Color"}),t.jsxs("div",{style:{display:"flex",gap:"8px",alignItems:"center"},children:[t.jsx("input",{type:"color",value:a.primary_color||"#0d7ea3",onChange:F=>B("primary_color",F.target.value),style:{width:"40px",height:"38px",border:"none",background:"none",cursor:"pointer"}}),t.jsx("input",{style:tt,value:a.primary_color||"",onChange:F=>B("primary_color",F.target.value)})]})]})]}),t.jsxs("div",{style:{...cs,marginTop:"12px"},children:[t.jsxs("div",{children:[t.jsx("label",{style:Ke,children:"Logo URL"}),t.jsx("input",{style:tt,value:a.logo_url||"",onChange:F=>B("logo_url",F.target.value),placeholder:"https://example.com/logo.png"})]}),t.jsxs("div",{children:[t.jsx("label",{style:Ke,children:"Active"}),t.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"8px",cursor:"pointer",padding:"10px 0",color:"#e2e8f0",fontSize:"14px"},children:[t.jsx("input",{type:"checkbox",checked:a.is_active!==!1,onChange:F=>B("is_active",F.target.checked)})," Tenant is active"]})]})]})]}),t.jsxs("div",{style:Xn,children:[t.jsx("div",{style:$r,children:"ð Contact & Address"}),t.jsxs("div",{style:fi,children:[t.jsxs("div",{children:[t.jsx("label",{style:Ke,children:"Phone"}),t.jsx("input",{style:tt,value:a.phone||"",onChange:F=>B("phone",F.target.value),placeholder:"(555) 123-4567"})]}),t.jsxs("div",{children:[t.jsx("label",{style:Ke,children:"Email"}),t.jsx("input",{style:tt,value:a.email||"",onChange:F=>B("email",F.target.value),placeholder:"[email protected]"})]}),t.jsxs("div",{children:[t.jsx("label",{style:Ke,children:"Website"}),t.jsx("input",{style:tt,value:a.website||"",onChange:F=>B("website",F.target.value),placeholder:"https://acmewater.com"})]})]}),t.jsxs("div",{style:{marginTop:"12px"},children:[t.jsx("label",{style:Ke,children:"Address Line 1"}),t.jsx("input",{style:tt,value:a.address_line1||"",onChange:F=>B("address_line1",F.target.value),placeholder:"123 Main St, Suite B"})]}),t.jsxs("div",{style:{...IM,marginTop:"12px"},children:[t.jsxs("div",{children:[t.jsx("label",{style:Ke,children:"City"}),t.jsx("input",{style:tt,value:a.city||"",onChange:F=>B("city",F.target.value)})]}),t.jsxs("div",{children:[t.jsx("label",{style:Ke,children:"State"}),t.jsxs("select",{style:Md,value:a.state||"",onChange:F=>B("state",F.target.value),children:[t.jsx("option",{value:"",children:"â"}),DM.map(F=>t.jsx("option",{children:F},F))]})]}),t.jsxs("div",{children:[t.jsx("label",{style:Ke,children:"ZIP"}),t.jsx("input",{style:tt,value:a.zip||"",onChange:F=>B("zip",F.target.value)})]}),t.jsxs("div",{children:[t.jsx("label",{style:Ke,children:"Country"}),t.jsx("input",{style:tt,value:a.country||"US",onChange:F=>B("country",F.target.value)})]})]})]}),t.jsxs("div",{style:Xn,children:[t.jsx("div",{style:$r,children:"âï¸ Email (Resend)"}),t.jsxs("div",{style:fi,children:[t.jsxs("div",{children:[t.jsx("label",{style:Ke,children:"Sending Domain"}),t.jsx("input",{style:tt,value:a.resend_domain||"",onChange:F=>B("resend_domain",F.target.value),placeholder:"acmewater.com"})]}),t.jsxs("div",{children:[t.jsx("label",{style:Ke,children:"From Email Override"}),t.jsx("input",{style:tt,value:a.resend_from_email||"",onChange:F=>B("resend_from_email",F.target.value),placeholder:"[email protected]"})]}),t.jsxs("div",{children:[t.jsx("label",{style:Ke,children:"Custom Domain"}),t.jsx("input",{style:tt,value:a.domain||"",onChange:F=>B("domain",F.target.value),placeholder:"acmewater.com"})]})]}),t.jsx("div",{style:{marginTop:"12px"},children:t.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"8px",cursor:"pointer",color:"#e2e8f0",fontSize:"13px"},children:[t.jsx("input",{type:"checkbox",checked:a.resend_domain_verified||!1,onChange:F=>B("resend_domain_verified",F.target.checked)})," Domain Verified"]})})]}),t.jsxs("div",{style:Xn,children:[t.jsx("div",{style:$r,children:"ð¬ SMS (OpenPhone)"}),t.jsxs("div",{style:cs,children:[t.jsxs("div",{children:[t.jsx("label",{style:Ke,children:"API Key"}),t.jsx(ne,{field:"openphone_api_key",ph:"sk_..."})]}),t.jsxs("div",{children:[t.jsx("label",{style:Ke,children:"Phone Number"}),t.jsx("input",{style:tt,value:a.openphone_number||"",onChange:F=>B("openphone_number",F.target.value),placeholder:"+14551234567"})]})]}),t.jsx("div",{style:{marginTop:"12px"},children:t.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"8px",cursor:"pointer",color:"#e2e8f0",fontSize:"13px"},children:[t.jsx("input",{type:"checkbox",checked:a.sms_enabled||!1,onChange:F=>B("sms_enabled",F.target.checked)})," SMS Enabled"]})})]}),t.jsxs("div",{style:Xn,children:[t.jsxs("div",{style:$r,children:["ð³ Payments (Stripe) ",t.jsx("span",{style:{fontSize:"11px",color:"#64748b",fontWeight:400,textTransform:"none",letterSpacing:0},children:"â Cevora bills this tenant"})]}),t.jsxs("div",{style:cs,children:[t.jsxs("div",{children:[t.jsx("label",{style:Ke,children:"Stripe Customer ID (Cevora bills tenant)"}),t.jsx("input",{style:tt,value:a.stripe_customer_id||"",onChange:F=>
632B("stripe_customer_id",F.target.value),placeholder:"cus_..."})]}),t.jsxs("div",{children:[t.jsx("label",{style:Ke,children:"Cevora Subscription ID"}),t.jsx("input",{style:tt,value:a.stripe_subscription_id||"",onChange:F=>B("stripe_subscription_id",F.target.value),placeholder:"sub_..."})]})]}),t.jsxs("div",{style:{...fi,marginTop:"12px"},children:[t.jsxs("div",{children:[t.jsx("label",{style:Ke,children:"Connect ID (tenant payments)"}),t.jsx("input",{style:tt,value:a.stripe_connect_id||"",onChange:F=>B("stripe_connect_id",F.target.value),placeholder:"acct_..."})]}),t.jsxs("div",{children:[t.jsx("label",{style:Ke,children:"Connect Status"}),t.jsxs("select",{style:Md,value:a.stripe_connect_status||"not_connected",onChange:F=>B("stripe_connect_status",F.target.value),children:[t.jsx("option",{value:"not_connected",children:"Not Connected"}),t.jsx("option",{value:"pending",children:"Pending"}),t.jsx("option",{value:"active",children:"Active"})]})]}),t.jsxs("div",{children:[t.jsx("label",{style:Ke,children:"Platform Fee %"}),t.jsx("input",{type:"number",step:"0.1",style:tt,value:a.platform_fee_percent??2.5,onChange:F=>B("platform_fee_percent",parseFloat(F.target.value)||0)})]})]})]}),t.jsxs("div",{style:Xn,children:[t.jsxs("div",{style:$r,children:["ð¦ Tenant Payment Gateway ",t.jsx("span",{style:{fontSize:"11px",color:"#64748b",fontWeight:400,textTransform:"none",letterSpacing:0},children:"â tenant bills their customers"})]}),t.jsxs("div",{style:{marginBottom:"16px"},children:[t.jsx("label",{style:Ke,children:"Payment Gateway"}),t.jsxs("select",{style:Md,value:d.payment_gateway,onChange:F=>{J("payment_gateway",F.target.value),J("gateway_secret_key",""),J("gateway_public_key",""),J("gateway_webhook_secret",""),J("gateway_login_id","")},children:[t.jsx("option",{value:"stripe",children:"Stripe"}),t.jsx("option",{value:"authorize_net",children:"Authorize.net"}),t.jsx("option",{value:"square",children:"Square"}),t.jsx("option",{value:"manual",children:"Manual (checks / ACH / cash only)"})]})]}),(d.payment_gateway==="stripe"||!d.payment_gateway)&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{style:cs,children:[t.jsxs("div",{children:[t.jsx("label",{style:Ke,children:"Publishable Key"}),t.jsx("input",{style:tt,value:d.gateway_public_key||"",onChange:F=>J("gateway_public_key",F.target.value),placeholder:"pk_live_..."})]}),t.jsxs("div",{children:[t.jsx("label",{style:Ke,children:"Secret Key"}),t.jsx(ne,{gwField:"gateway_secret_key",ph:"sk_live_..."})]})]}),t.jsxs("div",{style:{marginTop:"12px"},children:[t.jsx("label",{style:Ke,children:"Webhook Secret"}),t.jsx(ne,{gwField:"gateway_webhook_secret",ph:"whsec_..."}),t.jsxs("div",{style:{marginTop:"8px",background:"#0f192366",border:"1px solid #1e3a4f",borderRadius:"8px",padding:"12px 14px"},children:[t.jsx("p",{style:{fontSize:"11px",color:"#64748b",margin:"0 0 6px",fontWeight:600,textTransform:"uppercase",letterSpacing:"0.04em"},children:"Setup Instructions"}),t.jsx("p",{style:{fontSize:"12px",color:"#94a3b8",margin:"0 0 4px"},children:"1. In Stripe â Developers â Webhooks â Add destination"}),t.jsx("p",{style:{fontSize:"12px",color:"#94a3b8",margin:"0 0 4px"},children:"2. Endpoint URL:"}),t.jsx("code",{style:{display:"block",background:"#0f1923",padding:"6px 10px",borderRadius:"6px",color:"#0d7ea3",fontSize:"12px",margin:"0 0 8px",wordBreak:"break-all"},children:"https://cevora-app.vercel.app/api/stripe/webhook"}),t.jsxs("p",{style:{fontSize:"12px",color:"#94a3b8",margin:"0 0 4px"},children:["3. Select events: ",t.jsx("code",{style:{background:"#0f1923",padding:"2px 6px",borderRadius:"4px",color:"#94a3b8",fontSize:"11px"},children:"setup_intent.succeeded · payment_intent.succeeded · payment_intent.payment_failed"})]}),t.jsxs("p",{style:{fontSize:"12px",color:"#94a3b8",margin:"0"},children:["4. Copy the ",t.jsx("code",{style:{background:"#0f1923",padding:"2px 6px",borderRadius:"4px",color:"#94a3b8",fontSize:"11px"},children:"whsec_..."})," signing secret and paste it above"]})]})]})]}),d.payment_gateway==="authorize_net"&&t.jsx(t.Fragment,{children:t.jsxs("div",{style:cs,children:[t.jsxs("div",{children:[t.jsx("label",{style:Ke,children:"Login ID"}),t.jsx("input",{style:tt,value:d.gateway_login_id||"",onChange:F=>J("gateway_login_id",F.target.value),placeholder:"Authorize.net Login ID"})]}),t.jsxs("div",{children:[t.jsx("label",{style:Ke,children:"Transaction Key"}),t.jsx(ne,{gwField:"gateway_secret_key",ph:"Authorize.net Transaction Key"})]})]})}),d.payment_gateway==="square"&&t.jsxs("div",{style:cs,children:[t.jsxs("div",{children:[t.jsx("label",{style:Ke,children:"Access Token"}),t.jsx(ne,{gwField:"gateway_secret_key",ph:"sq0atp-..."})]}),t.jsxs("div",{children:[t.jsx("label",{style:Ke,children:"Location ID"}),t.jsx("input",{style:tt,value:d.gateway_public_key||"",onChange:F=>J("gateway_public_key",F.target.value),placeholder:"Square Location ID"})]})]}),d.payment_gateway==="manual"&&t.jsx("div",{style:{background:"#0f192366",border:"1px solid #1e3a4f",borderRadius:"8px",padding:"14px 16px",fontSize:"13px",color:"#94a3b8"},children:"No payment processing. Staff records payments manually. No gateway credentials needed."}),t.jsx("div",{style:{marginTop:"14px"},children:t.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"8px",cursor:"pointer",color:"#e2e8f0",fontSize:"13px"},children:[t.jsx("input",{type:"checkbox",checked:d.payments_enabled,onChange:F=>J("payments_enabled",F.target.checked)}),"Payments Enabled"]})})]}),t.jsxs("div",{style:Xn,children:[t.jsx("div",{style:$r,children:"ð¦ Shipping (FedEx)"}),t.jsxs("div",{style:fi,children:[t.jsxs("div",{children:[t.jsx("label",{style:Ke,children:"API Key"}),t.jsx(ne,{field:"fedex_api_key",ph:"l7..."})]}),t.jsxs("div",{children:[t.jsx("label",{style:Ke,children:"Secret Key"}),t.jsx(ne,{field:"fedex_secret_key",ph:"..."})]})]}),t.jsx("div",{style:{marginTop:"12px"},children:t.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"8px",cursor:"pointer",color:"#e2e8f0",fontSize:"13px"},children:[t.jsx("input",{type:"checkbox",checked:a.fedex_connected||!1,onChange:F=>B("fedex_connected",F.target.checked)})," FedEx Connected"]})})]}),t.jsxs("div",{style:Xn,children:[t.jsx("div",{style:$r,children:"ð Google"}),t.jsx("div",{style:cs,children:t.jsxs("div",{children:[t.jsx("label",{style:Ke,children:"Review URL"}),t.jsx("input",{style:tt,value:a.google_review_url||"",onChange:F=>B("google_review_url",F.target.value),placeholder:"https://g.page/r/acmewater/review"})]})})]}),t.jsxs("div",{style:Xn,children:[t.jsx("div",{style:$r,children:"âï¸ Contract & Legal"}),t.jsxs("div",{style:fi,children:[t.jsxs("div",{children:[t.jsx("label",{style:Ke,children:"Governing State"}),t.jsx("input",{style:tt,value:a.governing_law_state||"",onChange:F=>B("governing_law_state",F.target.value),placeholder:"Indiana"})]}),t.jsxs("div",{children:[t.jsx("label",{style:Ke,children:"Governing County"}),t.jsx("input",{style:tt,value:a.governing_law_county||"",onChange:F=>B("governing_law_county",F.target.value),placeholder:"Marion County"})]}),t.jsxs("div",{children:[t.jsx("label",{style:Ke,children:"Cancel Fee ($)"}),t.jsx("input",{type:"number",style:tt,value:a.cancellation_fee??250,onChange:F=>B("cancellation_fee",parseFloat(F.target.value)||0)})]})]}),t.jsxs("div",{style:{...fi,marginTop:"12px"},children:[t.jsxs("div",{children:[t.jsx("label",{style:Ke,children:"Min Rental Months"}),t.jsx("input",{type:"number",style:tt,value:a.rental_min_months??12,onChange:F=>B("rental_min_months",parseInt(F.target.value)||12)})]}),t.jsxs("div",{children:[t.jsx("label",{style:Ke,children:"Response Hours"}),t.jsx("input",{type:"number",style:tt,value:a.service_response_hours??48,onChange:F=>B("service_response_hours",parseInt(F.target.value)||48)})]}),t.jsxs("div",{children:[t.jsx("label",{style:Ke,children:"Business Hours"}),t.jsx("input",{style:tt,value:a.business_hours||"",onChange:F=>B("business_hours",F.target.value)})]})]})]}),t.jsxs("div",{style:Xn,children:[t.jsx("div",{style:$r,children:"ð° Subscription & Limits"}),t.jsxs("div",{style:fi,children:[t.jsxs("div",{children:[t.jsx("label",{style:Ke,children:"Plan"}),t.jsx("select",{style:Md,value:a.plan_tier||"starter",onChange:F=>{const K=$_.find(Z=>Z.v===F.target.value);B("plan_tier",F.target.value),K&&(B("seats_included",K.s),B("max_branches",K.b))},children:$_.map(F=>t.jsx("option",{value:F.v,children:F.l},F.v))})]}),t.jsxs("div",{children:[t.jsx("label",{style:Ke,children:"Status"}),t.jsx("select",{style:Md,value:a.subscription_status||"trialing",onCh
632ange:F=>B("subscription_status",F.target.value),children:OM.map(F=>t.jsx("option",{children:F},F))})]}),t.jsxs("div",{children:[t.jsx("label",{style:Ke,children:"Trial Ends"}),t.jsx("input",{type:"date",style:tt,value:(a.trial_ends_at||"").split("T")[0],onChange:F=>B("trial_ends_at",F.target.value?new Date(F.target.value).toISOString():null)})]})]}),t.jsx("div",{style:{fontSize:"11px",color:"#64748b",margin:"16px 0 8px",fontWeight:600,textTransform:"uppercase",letterSpacing:"0.04em"},children:"Capacity Limits (enforced)"}),t.jsxs("div",{style:fi,children:[t.jsxs("div",{children:[t.jsx("label",{style:Ke,children:"Seats Included"}),t.jsx("input",{type:"number",min:"1",style:tt,value:a.seats_included??3,onChange:F=>B("seats_included",parseInt(F.target.value)||1)}),t.jsxs("div",{style:{fontSize:"11px",color:"#64748b",marginTop:"4px"},children:["Live non-admin seats: ",t.jsx("strong",{style:{color:a.seats_included!=null&&we>=a.seats_included?"#f87171":"#4ade80"},children:f?"â":we}),!f&&a.seats_included!=null?` / ${a.seats_included}`:""]})]}),t.jsxs("div",{children:[t.jsx("label",{style:Ke,children:"Max Branches"}),t.jsx("input",{type:"number",min:"1",style:tt,value:a.max_branches??"",placeholder:"â unlimited",onChange:F=>B("max_branches",F.target.value===""?null:parseInt(F.target.value)||1)}),t.jsx("div",{style:{fontSize:"11px",color:"#64748b",marginTop:"4px"},children:"Blank = unlimited. Enforced by DB trigger on branch create."})]}),t.jsxs("div",{children:[t.jsx("label",{style:Ke,children:"Max Users / Branch"}),t.jsx("input",{type:"number",min:"1",style:tt,value:a.max_users_per_branch??"",placeholder:"â unlimited",onChange:F=>B("max_users_per_branch",F.target.value===""?null:parseInt(F.target.value)||1)}),t.jsx("div",{style:{fontSize:"11px",color:"#64748b",marginTop:"4px"},children:"Blank = unlimited. Enforced on user create."})]})]})]}),t.jsxs("div",{style:Xn,children:[t.jsx("div",{style:$r,children:"ðï¸ Feature Flags"}),t.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"20px"},children:["shipping","service_plans","automations","inventory","reports"].map(F=>{var K;return t.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"8px",cursor:"pointer",fontSize:"13px",color:"#e2e8f0"},children:[t.jsx("input",{type:"checkbox",checked:((K=a.features)==null?void 0:K[F])??!0,onChange:Z=>ae(F,Z.target.checked)}),F.replace(/_/g," ").replace(/\b\w/g,Z=>Z.toUpperCase())]},F)})})]}),t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginTop:"8px",paddingBottom:"40px"},children:[t.jsx("button",{style:_p,onClick:I,children:"Cancel"}),t.jsx("button",{style:uh,onClick:W,disabled:u,children:u?"Saving...":f?"Create Tenant":"Save Changes"})]})]})}function $M(){const e=gt(),n=Qb(),{tenant:r}=Ff(n??void 0),s=(r==null?void 0:r.primary_color)||"#0d7ea3",i=(r==null?void 0:r.name)||"Cevora",o=i.charAt(0).toUpperCase(),[a,l]=g.useState(""),[d,c]=g.useState(!1),[f,p]=g.useState(null),[u,h]=g.useState(!1);async function y(m){m.preventDefault(),c(!0),p(null);const{error:b}=await w.auth.resetPasswordForEmail(a,{redirectTo:`${window.location.origin}/update-password`});if(c(!1),b){p(b.message);return}h(!0)}return t.jsx("div",{style:{minHeight:"100vh",backgroundColor:"#0f1923",display:"flex",alignItems:"center",justifyContent:"center",fontFamily:"system-ui, -apple-system, sans-serif",padding:"16px"},children:t.jsxs("div",{style:{width:"100%",maxWidth:"400px"},children:[t.jsxs("div",{style:{textAlign:"center",marginBottom:"32px"},children:[r!=null&&r.logo_url?t.jsx("img",{src:r.logo_url,alt:i,style:{height:"56px",margin:"0 auto 16px",display:"block",objectFit:"contain"}}):t.jsx("div",{style:{width:"56px",height:"56px",borderRadius:"14px",background:`linear-gradient(135deg, ${s}, ${s}cc)`,display:"flex",alignItems:"center",justifyContent:"center",margin:"0 auto 16px",fontSize:"24px",fontWeight:"800",color:"#ffffff",letterSpacing:"-0.5px"},children:o}),t.jsx("h1",{style:{fontSize:"24px",fontWeight:"700",color:"#e2e8f0",margin:"0 0 4px 0"},children:"Reset your password"}),t.jsx("p",{style:{color:"#64748b",fontSize:"14px",margin:"0"},children:u?"Check your email":"Weâll email you a reset link"})]}),t.jsx("div",{style:{backgroundColor:"#162232",border:"1px solid #1e3a4f",borderRadius:"12px",padding:"28px"},children:u?t.jsxs(t.Fragment,{children:[t.jsxs("div",{style:{backgroundColor:"#22c55e18",border:"1px solid #22c55e40",borderRadius:"8px",padding:"12px 16px",marginBottom:"20px",color:"#22c55e",fontSize:"13px",lineHeight:"1.5"},children:["If an account exists for ",t.jsx("strong",{children:a}),", a password reset link is on its way. The link expires in 1 hour."]}),t.jsx("button",{onClick:()=>e("/"),style:{width:"100%",backgroundColor:s,color:"#ffffff",border:"none",borderRadius:"8px",padding:"11px",fontSize:"14px",fontWeight:"600",cursor:"pointer"},children:"Back to sign in"})]}):t.jsxs(t.Fragment,{children:[f&&t.jsx("div",{style:{backgroundColor:"#ef444418",border:"1px solid #ef444440",borderRadius:"8px",padding:"12px 16px",marginBottom:"16
632px",color:"#ef4444",fontSize:"13px",lineHeight:"1.5"},children:f}),t.jsxs("form",{onSubmit:y,children:[t.jsxs("div",{style:{marginBottom:"20px"},children:[t.jsx("label",{style:{display:"block",fontSize:"11px",fontWeight:"600",color:"#64748b",textTransform:"uppercase",letterSpacing:"0.05em",marginBottom:"6px"},children:"Email"}),t.jsx("input",{type:"email",value:a,onChange:m=>l(m.target.value),placeholder:"[email protected]",required:!0,style:{width:"100%",backgroundColor:"#0f1923",border:"1px solid #1e3a4f",borderRadius:"8px",padding:"10px 14px",color:"#e2e8f0",fontSize:"14px",outline:"none",boxSizing:"border-box",transition:"border-color 0.15s"},onFocus:m=>m.currentTarget.style.borderColor="#0d7ea3",onBlur:m=>m.currentTarget.style.borderColor="#1e3a4f"})]}),t.jsx("button",{type:"submit",disabled:d,style:{width:"100%",backgroundColor:d?"#0a5f7a":"#0d7ea3",color:"#ffffff",border:"none",borderRadius:"8px",padding:"11px",fontSize:"14px",fontWeight:"600",cursor:d?"not-allowed":"pointer",opacity:d?.7:1,transition:"background-color 0.15s, opacity 0.15s"},onMouseEnter:m=>{d||(m.currentTarget.style.backgroundColor="#0b8db5")},onMouseLeave:m=>{d||(m.currentTarget.style.backgroundColor="#0d7ea3")},children:d?"Sending...":"Send reset link"})]}),t.jsx("div",{style:{marginTop:"20px",paddingTop:"20px",borderTop:"1px solid #1e3a4f",textAlign:"center"},children:t.jsx("button",{onClick:()=>e("/"),style:{background:"none",border:"none",color:"#0d7ea3",fontSize:"13px",fontWeight:"600",cursor:"pointer",padding:"0"},children:"â Back to sign in"})})]})}),t.jsx("p",{style:{textAlign:"center",color:"#475569",fontSize:"12px",marginTop:"24px"},children:"Cevora â CRM for Water Treatment Companies"})]})})}function MM(){const e=gt(),n=Qb(),{tenant:r}=Ff(n??void 0),s=(r==null?void 0:r.primary_color)||"#0d7ea3",i=(r==null?void 0:r.name)||"Cevora",o=i.charAt(0).toUpperCase(),[a,l]=g.useState(null),[d,c]=g.useState(""),[f,p]=g.useState(""),[u,h]=g.useState(!1),[y,m]=g.useState(null),[b,A]=g.useState(!1);g.useEffect(()=>{const{data:j}=w.auth.onAuthStateChange(C=>{C==="PASSWORD_RECOVERY"&&l(!0)});return w.auth.getSession().then(({data:C})=>{C.session?l(!0):setTimeout(()=>{w.auth.getSession().then(({data:S})=>{l(T=>T===null?!!S.session:T)})},1200)}),()=>{j.subscription.unsubscribe()}},[]);async function v(j){if(j.preventDefault(),m(null),d.length<8){m("Password must be at least 8 characters.");return}if(d!==f){m("Passwords do not match.");return}h(!0);const{error:C}=await w.auth.updateUser({password:d});if(h(!1),C){m(C.message);return}A(!0),await w.auth.signOut(),setTimeout(()=>e("/"),2500)}const x={width:"100%",backgroundColor:"#0f1923",border:"1px solid #1e3a4f",borderRadius:"8px",padding:"10px 14px",color:"#e2e8f0",fontSize:"14px",outline:"none",boxSizing:"border-box",transition:"border-color 0.15s"},_={display:"block",fontSize:"11px",fontWeight:"600",color:"#64748b",textTransform:"uppercase",letterSpacing:"0.05em",marginBottom:"6px"};return t.jsx("div",{style:{minHeight:"100vh",backgroundColor:"#0f1923",display:"flex",alignItems:"center",justifyContent:"center",fontFamily:"system-ui, -apple-system, sans-serif",padding:"16px"},children:t.jsxs("div",{style:{width:"100%",maxWidth:"400px"},children:[t.jsxs("div",{style:{textAlign:"center",marginBottom:"32px"},children:[r!=null&&r.logo_url?t.jsx("img",{src:r.logo_url,alt:i,style:{height:"56px",margin:"0 auto 16px",display:"block",objectFit:"contain"}}):t.jsx("div",{style:{width:"56px",height:"56px",borderRadius:"14px",background:`linear-gradient(135deg, ${s}, ${s}cc)`,display:"flex",alignItems:"center",justifyContent:"center",margin:"0 auto 16px",fontSize:"24px",fontWeight:"800",color:"#ffffff",letterSpacing:"-0.5px"},children:o}),t.jsx("h1",{style:{fontSize:"24px",fontWeight:"700",color:"#e2e8f0",margin:"0 0 4px 0"},children:"Set a new password"}),t.jsx("p",{style:{color:"#64748b",fontSize:"14px",margin:"0"},children:"Choose a password for your account"})]}),t.jsxs("div",{style:{backgroundColor:"#162232",border:"1px solid #1e3a4f",borderRadius:"12px",padding:"28px"},children:[a===null&&t.jsx("p",{style:{color:"#64748b",fontSize:"14px",textAlign:"center",margin:0},children:"Verifying reset linkâ¦"}),a===!1&&t.jsxs(t.Fragment,{children:[t.jsx("div",{style:{backgroundColor:"#ef444418",border:"1px solid #ef444440",borderRadius:"8px",padding:"12px 16px",marginBottom:"20px",color:"#ef4444",fontSize:"13px",lineHeight:"1.5"}
632,children:"This reset link is invalid or has expired. Reset links are valid for 1 hour and can only be used once."}),t.jsx("button",{onClick:()=>e("/forgot-password"),style:{width:"100%",backgroundColor:s,color:"#ffffff",border:"none",borderRadius:"8px",padding:"11px",fontSize:"14px",fontWeight:"600",cursor:"pointer"},children:"Request a new link"})]}),a===!0&&b&&t.jsx("div",{style:{backgroundColor:"#22c55e18",border:"1px solid #22c55e40",borderRadius:"8px",padding:"12px 16px",color:"#22c55e",fontSize:"13px",lineHeight:"1.5"},children:"Password updated. Redirecting you to sign inâ¦"}),a===!0&&!b&&t.jsxs(t.Fragment,{children:[y&&t.jsx("div",{style:{backgroundColor:"#ef444418",border:"1px solid #ef444440",borderRadius:"8px",padding:"12px 16px",marginBottom:"16px",color:"#ef4444",fontSize:"13px",lineHeight:"1.5"},children:y}),t.jsxs("form",{onSubmit:v,children:[t.jsxs("div",{style:{marginBottom:"16px"},children:[t.jsx("label",{style:_,children:"New password"}),t.jsx("input",{type:"password",value:d,onChange:j=>c(j.target.value),placeholder:"At least 8 characters",required:!0,style:x,onFocus:j=>j.currentTarget.style.borderColor="#0d7ea3",onBlur:j=>j.currentTarget.style.borderColor="#1e3a4f"})]}),t.jsxs("div",{style:{marginBottom:"20px"},children:[t.jsx("label",{style:_,children:"Confirm password"}),t.jsx("input",{type:"password",value:f,onChange:j=>p(j.target.value),placeholder:"Re-enter password",required:!0,style:x,onFocus:j=>j.currentTarget.style.borderColor="#0d7ea3",onBlur:j=>j.currentTarget.style.borderColor="#1e3a4f"})]}),t.jsx("button",{type:"submit",disabled:u,style:{width:"100%",backgroundColor:u?"#0a5f7a":"#0d7ea3",color:"#ffffff",border:"none",borderRadius:"8px",padding:"11px",fontSize:"14px",fontWeight:"600",cursor:u?"not-allowed":"pointer",opacity:u?.7:1,transition:"background-color 0.15s, opacity 0.15s"},onMouseEnter:j=>{u||(j.currentTarget.style.backgroundColor="#0b8db5")},onMouseLeave:j=>{u||(j.currentTarget.style.backgroundColor="#0d7ea3")},children:u?"Updating...":"Update password"})]})]})]}),t.jsx("p",{style:{textAlign:"center",color:"#475569",fontSize:"12px",marginTop:"24px"},children:"Cevora â CRM for Water Treatment Companies"})]})})}function FM(e){return e.lead_id?`lead:${e.lead_id}`:e.customer_id?`customer:${e.customer_id}`:null}function BM(){const e=gt(),[n,r]=g.useState([]),[s,i]=g.useState([]),[o,a]=g.useState({}),[l,d]=g.useState(!0),c=g.useCallback(async()=>{d(!0);try{const[h,y]=await Promise.all([AE(),vE()]);r(h),i(y);const m=[...h,...y],b=[...new Set(m.map(x=>x.lead_id).filter(Boolean))],A=[...new Set(m.map(x=>x.customer_id).filter(Boolean))],v={};if(b.length){const{data:x}=await w.from("leads").select("id, full_name").in("id",b);(x||[]).forEach(_=>{v[`lead:${_.id}`]=_.full_name})}if(A.length){const{data:x}=await w.from("customers").select("id, full_name").in("id",A);(x||[]).forEach(_=>{v[`customer:${_.id}`]=_.full_name})}a(v)}catch{r([]),i([])}finally{d(!1)}},[]);g.useEffect(()=>{c()},[c]);async function f(h){try{await fd(h),await c()}catch{}}const p=n.length+s.length;function u(h,y){const m=FM(h),b=m?o[m]:null;return t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"8px 12px",borderBottom:"1px solid #1a2a3a"},children:[t.jsx("button",{onClick:()=>f(h.id),title:"Mark complete",style:{width:18,height:18,borderRadius:4,flexShrink:0,border:"2px solid #475569",background:"transparent",cursor:"pointer"},onMouseEnter:A=>{A.currentTarget.style.borderColor="#4ade80",A.currentTarget.style.background="rgba(74,222,128,0.15)"},onMouseLeave:A=>{A.currentTarget.style.borderColor="#475569",A.currentTarget.style.background="transparent"}}),t.jsx("span",{style:{fontSize:13,flexShrink:0},children:Xl[h.task_type]||"ð"}),t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsx("div",{style:{fontSize:13,color:"#e2e8f0",fontWeight:600,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:h.title}),b&&t.jsx("div",{style:{fontSize:11,color:"#64748b"},children:b})]}),t.jsx("span",{style:{fontSize:11,fontWeight:700,flexShrink:0,color:y==="overdue"?"#f87171":"#fbbf24"},children:y==="overdue"?"Overdue":"Today"})]}
632,h.id)}return t.jsxs("div",{style:{background:"#162232",border:"1px solid #1e3a4f",borderRadius:14,overflow:"hidden"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 16px",borderBottom:"1px solid #1e3a4f"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[t.jsx("span",{style:{fontSize:14},children:"ð"}),t.jsx("span",{style:{color:"#e2e8f0",fontWeight:700,fontSize:13},children:"Follow-Ups"}),p>0&&t.jsx("span",{style:{background:n.length>0?"rgba(248,113,113,0.15)":"rgba(251,191,36,0.15)",color:n.length>0?"#f87171":"#fbbf24",borderRadius:20,padding:"1px 8px",fontSize:11,fontWeight:700},children:p})]}),t.jsx("button",{onClick:()=>e("/follow-ups"),style:{background:"none",border:"none",color:"#0d7ea3",fontSize:12,fontWeight:600,cursor:"pointer"},children:"View all â"})]}),t.jsx("div",{style:{maxHeight:260,overflowY:"auto"},children:l?t.jsx("div",{style:{padding:20,textAlign:"center",color:"#64748b",fontSize:12},children:"Loadingâ¦"}):p===0?t.jsxs("div",{style:{padding:24,textAlign:"center"},children:[t.jsx("div",{style:{fontSize:24,marginBottom:6},children:"â"}),t.jsx("div",{style:{color:"#64748b",fontSize:12},children:"No follow-ups due. All caught up."})]}):t.jsxs(t.Fragment,{children:[n.map(h=>u(h,"overdue")),s.map(h=>u(h,"today"))]})})]})}function Wt(e,n){return n?e.eq("branch_id",n):e}function bu(e){return e?e.split("T")[0]:""}function UM({tenantId:e,branchId:n}){return Ae({queryKey:["dashboard","new_leads_today",e,n],queryFn:async()=>{const r=new Date().toISOString().split("T")[0];let s=w.from("leads").select("id, full_name, phone, source, created_at").eq("tenant_id",e).eq("stage","new_lead").gte("created_at",r+"T00:00:00").order("created_at",{ascending:!1});s=Wt(s,n);const{data:i,error:o}=await s;if(o)throw o;return i||[]},enabled:!!e,refetchInterval:3e4})}function HM({tenantId:e,branchId:n}){return Ae({queryKey:["dashboard","overdue_lead_followups",e,n],queryFn:async()=>{let r=w.from("leads").select("id, full_name, phone, stage, followup_date, assigned_rep_id").eq("tenant_id",e).eq("stage","future_follow_up").lt("followup_date",new Date().toISOString()).order("followup_date",{ascending:!0});r=Wt(r,n);const{data:s,error:i}=await r;if(i)throw i;return s||[]},enabled:!!e,refetchInterval:3e4})}function VM({tenantId:e,branchId:n}){return Ae({queryKey:["dashboard","uncontacted_leads",e,n],queryFn:async()=>{let r=w.from("leads").select("id, full_name, phone, source, created_at, stage").eq("tenant_id",e).in("stage",["new_lead","qualifying"]).order("created_at",{ascending:!0}).limit(10);r=Wt(r,n);const{data:s,error:i}=await r;if(i)throw i;return s||[]},enabled:!!e,refetchInterval:3e4})}function ZM({tenantId:e,branchId:n}){return Ae({queryKey:["dashboard","todays_jobs",e,n],queryFn:async()=>{const r=new Date,s=d=>String(d).padStart(2,"0"),i=`${r.getFullYear()}-${s(r.getMonth()+1)}-${s(r.getDate())}`;let o=w.from("jobs").select("id, customer_name_snapshot, service_address_snapshot, job_type, job_status, scheduled_at, assigned_technician_id").eq("tenant_id",e).gte("scheduled_at",i+"T00:00:00").lte("scheduled_at",i+"T23:59:59").order("job_status",{ascending:!0});o=Wt(o,n);const{data:a,error:l}=await o;if(l)throw l;return a||[]},enabled:!!e,refetchInterval:3e4})}function KM({tenantId:e,branchId:n}){return Ae({queryKey:["dashboard","lead_counts",e,n],queryFn:async()=>{let r=w.from("leads").select("stage",{count:"exact",head:!1}).eq("tenant_id",e).not("stage","in","(won,lost,dnd)");r=Wt(r,n);const{data:s,error:i}=await r;if(i)throw i;return(s||[]).length},enabled:!!e,refetchInterval:6e4})}function YM({tenantId:e,branchId:n}){return Ae({queryKey:["dashboard","jobs_this_week",e,n],queryFn:async()=>{const r=new Date,s=p=>String(p).padStart(2,"0"),i=new Date(r);i.setDate(r.getDate()-r.getDay());const o=new Date(i);o.setDate(i.getDate()+6);const a=`${i.getFullYear()}-${s(i.getMonth()+1)}-${s(i.getDate())}`,l=`${o.getFullYear()}-${s(o.getMonth()+1)}-${s(o.getDate())}T23:59:59`;let d=w.from("jobs").select("id, job_status, scheduled_at").eq("tenant_id",e).gte("scheduled_at",a).lte("scheduled_at",l);d=Wt(d,n);const{data:c,error:f}=await d;if(f)throw f;return(c||[]).map(p=>({...p,status:p.job_status,scheduled_date:bu(p.scheduled_at)}))},enabled:!!e,refetchInterval:6e4})}function XM({tenantId:e,branchId:n}){return Ae({queryKey:["dashboard","overdue_services",e,n],queryFn:async()=>{let r=w.from("service_schedule_items").select("id, customer_id, due_date, status").eq("tenant_id",e).eq("status","overdue").order("due_date",{ascending:!0}).limit(10);r=Wt(r,n);const{data:s,error:i}=await r;if(i)throw i;return s||[]},enabled:!!e,refetchInterval:6e4})}function GM({tenantId:e,branchId:n}){return Ae({queryKey:["dashboard","recent_customers",e,n],queryFn:async()=>{let r=w.from("customers").select("id, full_name, lifecycle_stage, created_at").eq("tenant_id",e).order("created_at",{ascending:!1}).limit(5);r=Wt(r,n);const{data:s,error:i}=await r;if(i)throw i;return s||[]},enabled:!!e,refetchInterval:6e4})}function JM({tenantId:e,branchId:n}){return Ae({queryKey:["dashboard","failed_payments",e,n],queryFn:async()=>{const r=new Date(Date.now()-1728e5).toISOString();let s=w.from("payment_transactions").select("id, amount, failure_reason, created_at, customer_id").eq("tenant_id",e).eq("status","failed").gte("created_at",r).order("amount",{ascending:!1}).limit(10);s=Wt(s,n);const{data:i,error:o}=await s;if(o)throw o;if(!(i!=null&&i.length))return[];const a=[...new Set(i.map(c=>
632c.customer_id).filter(Boolean))],{data:l}=await w.from("customers").select("id, full_name, phone").in("id",a),d=Object.fromEntries((l||[]).map(c=>[c.id,c]));return i.map(c=>({...c,customers:d[c.customer_id]||null}))},enabled:!!e,refetchInterval:3e4})}function QM({tenantId:e,branchId:n},r,s){return Ae({queryKey:["dashboard","my_upcoming_visits",e,n,r],queryFn:async()=>{if(!r)return[];const i=new Date().toISOString().split("T")[0],o=new Date(Date.now()+7*864e5).toISOString().split("T")[0];let a=w.from("site_visits").select("id, lead_id, assigned_rep_id, visit_date, visit_hour, visit_minute, status").eq("tenant_id",e).gte("visit_date",i).lte("visit_date",o).order("visit_date",{ascending:!0}).order("visit_hour",{ascending:!0}).order("visit_minute",{ascending:!0}).limit(10);s||(a=a.eq("assigned_rep_id",r)),a=Wt(a,n);const{data:l,error:d}=await a;if(d)throw d;if(!(l!=null&&l.length))return[];const c=[...new Set(l.map(u=>u.lead_id).filter(Boolean))],{data:f}=await w.from("leads").select("id, full_name, phone").in("id",c),p=Object.fromEntries((f||[]).map(u=>[u.id,u]));return l.map(u=>({...u,lead:p[u.lead_id]||null})).filter(u=>u.lead)},enabled:!!e&&!!r,refetchInterval:6e4})}function eF({tenantId:e,branchId:n}){return Ae({queryKey:["dashboard","upcoming_renewals",e,n],queryFn:async()=>{const r=new Date().toISOString().split("T")[0],s=new Date(Date.now()+30*864e5).toISOString().split("T")[0];let i=w.from("contracts").select("id, contract_number, status, end_date, monthly_amount, commercial_type, customer_id, customers(full_name, phone)").eq("tenant_id",e).eq("status","active").gte("end_date",r).lte("end_date",s).order("end_date",{ascending:!0}).limit(10);i=Wt(i,n);const{data:o,error:a}=await i;if(a)throw a;return o||[]},enabled:!!e,refetchInterval:6e4})}function tF({tenantId:e,branchId:n}){return Ae({queryKey:["dashboard","pending_proof_review",e,n],queryFn:async()=>{let r=w.from("jobs").select("id, customer_name_snapshot, service_address_snapshot, job_type, job_status, scheduled_at").eq("tenant_id",e).eq("job_status","complete").eq("proof_approved",!1).order("scheduled_at",{ascending:!1}).limit(10);r=Wt(r,n);const{data:s,error:i}=await r;if(i)throw i;return(s||[]).map(o=>({...o,status:o.job_status,scheduled_date:bu(o.scheduled_at)}))},enabled:!!e,refetchInterval:3e4})}function nF({tenantId:e,branchId:n}){return Ae({queryKey:["dashboard","unsigned_agreements",e,n],queryFn:async()=>{let r=w.from("agreements").select("id, agreement_number, created_at, lead_id, leads(full_name, phone)").eq("tenant_id",e).eq("status","pending_signature").order("created_at",{ascending:!0}).limit(10);r=Wt(r,n);const{data:s,error:i}=await r;if(i)throw i;return s||[]},enabled:!!e,refetchInterval:6e4})}function rF({tenantId:e,branchId:n}){return Ae({queryKey:["dashboard","cold_leads",e,n],queryFn:async()=>{const r=new Date(Date.now()-6048e5).toISOString();let s=w.from("leads").select("id, full_name, phone, stage, updated_at").eq("tenant_id",e).not("stage","in","(won,lost,dnd,agreement_signed)").lt("updated_at",r).order("updated_at",{ascending:!0}).limit(10);s=Wt(s,n);const{data:i,error:o}=await s;if(o)throw o;return i||[]},enabled:!!e,refetchInterval:6e4})}function sF({tenantId:e,branchId:n}){return Ae({queryKey:["dashboard","unassigned_jobs",e,n],queryFn:async()=>{let r=w.from("jobs").select("id, customer_name_snapshot, scheduled_at, job_type, job_status").eq("tenant_id",e).in("job_status",["scheduled","in_progress"]).is("assigned_technician_id",null).order("scheduled_at",{ascending:!0}).limit(10);r=Wt(r,n);const{data:s,error:i}=await r;if(i)throw i;return(s||[]).map(o=>({...o,status:o.job_status,scheduled_date:bu(o.scheduled_at)}))},enabled:!!e,refetchInterval:6e4})}function iF({tenantId:e,branchId:n}){return Ae({queryKey:["dashboard","expiring_quotes",e,n],queryFn:async()=>{const r=new Date,s=u=>String(u).padStart(2,"0"),i=`${r.getFullYear()}-${s(r.getMonth()+1)}-${s(r.getDate())}`,o=new Date(Date.now()+7*864e5),a=`${o.getFullYear()}-${s(o.getMonth()+1)}-${s(o.getDate())}T23:59:59`;let l=w.from("quotes").select("id, quote_number, expires_at, monthly_rental_price, total, customer_id").eq("tenant_id",e).in("status",["sent","viewed"]).gte("expires_at",i).lte("expires_at",a).order("expires_at",{ascending:!0}).limit(10);l=Wt(l,n);const{data:d,error:c}=await l;if(c)throw c;if(!(d!=null&&d.length))return[];const f=[...new Set(d.map(u=>
632u.customer_id).filter(Boolean))];let p={};if(f.length){const{data:u}=await w.from("customers").select("id, full_name").in("id",f);p=Object.fromEntries((u||[]).map(h=>[h.id,h.full_name]))}return d.map(u=>({...u,customer_name:p[u.customer_id]||"Unknown"}))},enabled:!!e,refetchInterval:6e4})}function oF({tenantId:e}){return Ae({queryKey:["dashboard","low_inventory",e],queryFn:async()=>{const{data:n,error:r}=await w.from("inventory_items").select("id, quantity_on_hand, reorder_point, product_catalog_id, product_catalog(name)").eq("tenant_id",e).not("reorder_point","is",null).order("quantity_on_hand",{ascending:!0}).limit(10);if(r)throw r;return(n||[]).filter(s=>s.quantity_on_hand<=s.reorder_point)},enabled:!!e,refetchInterval:12e4})}function aF({tenantId:e,branchId:n}){return Ae({queryKey:["dashboard","shipments_due",e,n],queryFn:async()=>{const r=new Date(Date.now()+6048e5).toISOString().split("T")[0];let s=w.from("shipments").select("id, customer_id, status, due_date, customers(full_name)").eq("tenant_id",e).eq("status","pending").lte("due_date",r).order("due_date",{ascending:!0}).limit(10);s=Wt(s,n);const{data:i,error:o}=await s;if(o)throw o;return i||[]},enabled:!!e,refetchInterval:6e4})}function lF({tenantId:e,branchId:n}){return Ae({queryKey:["dashboard","pipeline_funnel",e,n],queryFn:async()=>{let r=w.from("leads").select("stage").eq("tenant_id",e).not("stage","in","(lost,dnd)");r=Wt(r,n);const{data:s,error:i}=await r;if(i)throw i;const o={};for(const l of s||[])o[l.stage]=(o[l.stage]||0)+1;return[{key:"new_lead",label:"New Leads",color:"#38bdf8"},{key:"qualifying",label:"Qualifying",color:"#818cf8"},{key:"site_visit_scheduled",label:"Site Visit",color:"#22d3ee"},{key:"proposal_in_progress",label:"Proposal",color:"#f59e0b"},{key:"quote_sent",label:"Quote Sent",color:"#fb923c"},{key:"agreement_signed",label:"Signed",color:"#4ade80"},{key:"won",label:"Won",color:"#34d399"}].map(l=>({...l,count:o[l.key]||0}))},enabled:!!e,refetchInterval:12e4})}function dF({tenantId:e,branchId:n},r,s){return Ae({queryKey:["dashboard","week_calendar",e,n,r,s],queryFn:async()=>{const i=new Date,o=c=>String(c).padStart(2,"0"),a=new Date(i);a.setDate(i.getDate()-i.getDay());const l=Array.from({length:7},(c,f)=>{const p=new Date(a);return p.setDate(a.getDate()+f),`${p.getFullYear()}-${o(p.getMonth()+1)}-${o(p.getDate())}`}),d={};for(const c of l)d[c]={visits:[],jobs:[]};if(s==="admin"||s==="super_admin"||s==="salesrep"||s==="frontdesk"){let c=w.from("site_visits").select("id, lead_id, assigned_rep_id, visit_date, visit_hour, visit_minute, status").eq("tenant_id",e).gte("visit_date",l[0]).lte("visit_date",l[6]);s!=="admin"&&s!=="super_admin"&&(c=c.eq("assigned_rep_id",r)),c=Wt(c,n);const{data:f}=await c,p=[...new Set((f||[]).map(h=>h.lead_id).filter(Boolean))];let u={};if(p.length){const{data:h}=await w.from("leads").select("id, full_name").in("id",p);u=Object.fromEntries((h||[]).map(y=>[y.id,y]))}for(const h of f||[])d[h.visit_date]&&d[h.visit_date].visits.push({...h,lead:u[h.lead_id]||null})}if(s==="admin"||s==="super_admin"||s==="technician"){let c=w.from("jobs").select("id, customer_name_snapshot, job_status, scheduled_at, job_type").eq("tenant_id",e).gte("scheduled_at",l[0]).lte("scheduled_at",l[6]+"T23:59:59");c=Wt(c,n);const{data:f}=await c;for(const p of f||[]){const u=bu(p.scheduled_at);d[u]&&d[u].jobs.push({...p,status:p.job_status})}}return{days:l,events:d}},enabled:!!e&&!!r,refetchInterval:6e4})}function cF({tenantId:e,branchId:n}){return Ae({queryKey:["dashboard","awaiting_schedule",e,n],queryFn:async()=>{let r=w.from("fulfillment_requests").select(`id, customer_id, due_date, created_at, fulfillment_type, 633 customers(full_name, phone)`).eq("tenant_id",e).eq("status","paid_awaiting_schedule");r=Wt(r,n);const{data:s,error:i}=await r;if(i)throw i;return s||[]},enabled:!!e,refetchInterval:3e4})}function uF({tenantId:e,branchId:n}){return Ae({queryKey:["dashboard","scheduled_this_week",e,n],queryFn:async()=>{const r=new Date,s=new Date(r);s.setDate(r.getDate()-r.getDay());const i=new Date(s);i.setDate(s.getDate()+6);let o=w.from("fulfillment_requests").select(`id, customer_id, scheduled_at, fulfillment_type, 634 customers(full_name)`).eq("tenant_id",e).eq("status","scheduled").gte("scheduled_at",s.toISOString().split("T")[0]).lte("scheduled_at",i.toISOString().split("T")[0]).order("scheduled_at",{ascending:!0});o=Wt(o,n);const{data:a,error:l}=await o;
634if(l)throw l;return a||[]},enabled:!!e,refetchInterval:3e4})}function pF({tenantId:e,branchId:n}){return Ae({queryKey:["dashboard","overdue_fulfillment",e,n],queryFn:async()=>{const r=new Date;r.setDate(r.getDate()-7);let s=w.from("fulfillment_requests").select(`id, customer_id, due_date, created_at, fulfillment_type, 635 customers(full_name, phone)`).eq("tenant_id",e).eq("status","paid_awaiting_schedule").lte("due_date",r.toISOString().split("T")[0]).order("due_date",{ascending:!0});s=Wt(s,n);const{data:i,error:o}=await s;if(o)throw o;return i||[]},enabled:!!e,refetchInterval:3e4})}const M_=e=>String(e).padStart(2,"0");function S0(e=new Date){return`${e.getFullYear()}-${M_(e.getMonth()+1)}-${M_(e.getDate())}`}function jp(e){const n=Math.floor((Date.now()-new Date(e).getTime())/6e4);if(n<1)return"just now";if(n<60)return`${n}m ago`;const r=Math.floor(n/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}function ym(e){return Math.floor((Date.now()-new Date(e).getTime())/864e5)}function bm(e){return Math.ceil((new Date(e).getTime()-Date.now())/864e5)}function Mo(e){return new Date(e+"T00:00:00").toLocaleDateString("en-US",{month:"short",day:"numeric"})}function Qk(e,n=0){const r=String(n||0).padStart(2,"0");return e===0?`12:${r} AM`:e<12?`${e}:${r} AM`:e===12?`12:${r} PM`:`${e-12}:${r} PM`}function nu(e){return e===S0()}function e8(e){return e===S0(new Date(Date.now()+864e5))}function hF(e){return nu(e)?"Today":e8(e)?"Tomorrow":Mo(e)}const t8=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],ph={scheduled:"#60a5fa",in_progress:"#22d3ee",complete:"#4ade80",cancelled:"#64748b"};function fF({opts:e}){const{data:n=[]}=lF(e),r=gt(),s=Math.max(...n.map(o=>o.count),1),i=n.reduce((o,a)=>o+a.count,0);return t.jsxs("div",{style:{background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:12,overflow:"hidden"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 18px",background:"linear-gradient(135deg,#162232 0%,#0d1a26 100%)",borderBottom:"1px solid #1e3a4f"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[t.jsx("div",{style:{width:32,height:32,borderRadius:8,background:"rgba(99,102,241,0.2)",border:"1px solid rgba(99,102,241,0.3)",display:"flex",alignItems:"center",justifyContent:"center",fontSize:15},children:"⬡"}),t.jsxs("div",{children:[t.jsx("div",{style:{color:"#e2e8f0",fontWeight:700,fontSize:13},children:"Pipeline Funnel"}),t.jsxs("div",{style:{color:"#475569",fontSize:11,marginTop:1},children:[i," active leads across all stages"]})]})]}),t.jsx("button",{onClick:()=>r("/leads"),style:{fontSize:11,color:"#0d7ea3",background:"rgba(13,126,163,0.1)",border:"1px solid rgba(13,126,163,0.25)",borderRadius:6,padding:"5px 12px",cursor:"pointer",fontWeight:600},children:"View Pipeline â"})]}),t.jsx("div",{style:{padding:"18px 18px 14px"},children:n.map((o,a)=>{const l=s>0?o.count/s*100:0;return t.jsxs("div",{style:{marginBottom:a<n.length-1?10:0},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:5},children:[t.jsx("span",{style:{fontSize:12,color:"#94a3b8",fontWeight:500,minWidth:110},children:o.label}),t.jsx("span",{style:{fontSize:12,fontWeight:800,color:o.count>0?o.color:"#334155",minWidth:28,textAlign:"right"},children:o.count})]}),t.jsx("div",{style:{height:8,background:"#0d1a26",borderRadius:4,overflow:"hidden"},children:t.jsx("div",{style:{height:"100%",borderRadius:4,width:`${l}%`,background:o.count>0?`linear-gradient(90deg, ${o.color}cc, ${o.color})`:"transparent",transition:"width 0.6s ease",boxShadow:o.count>0?`0 0 8px ${o.color}50`:"none"}})})]},o.key)})})]})}function gF({jobsThisWeek:e}){const n=new Date,r=new Date(n);r.setDate(n.getDate()-n.getDay());const i=Array.from({length:7},(l,d)=>{const c=new Date(r);return c.setDate(r.getDate()+d),S0(c)}).map(l=>{const d=e.filter(c=>(c.scheduled_date||bu(c.scheduled_at))===l);return{day:l,label:t8[new Date(l+"T00:00:00").getDay()],total:d.length,scheduled:d.filter(c=>(c.status||c.job_status)==="scheduled").length,in_progress:d.filter(c=>(c.status||c.job_status)==="in_progress").length,complete:d.filter(c=>(c.status||c.job_status)==="complete").length}}),o=Math.max(...i.map(l=>l.total),1),a=80;return t.jsxs("div",{style:{background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:12,overflow:"hidden"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 18px",background:"linear-gradient(135deg,#162232 0%,#0d1a26 100%)",borderBottom:"1px solid #1e3a4f"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[t.jsx("div",{style:{width:32,height:32,borderRadius:8,background:"rgba(167,139,250,0.2)",border:"1px solid rgba(167,139,250,0.3)",display:"flex",alignItems:"center",justifyContent:"center",fontSize:15},children:"ð"}),t.jsxs("div",{children:[t.jsx("div",{style:{color:"#e2e8f0",fontWeight:700,fontSize:13},children:"Jobs This Week"}),t.jsxs("div",{style:{color:"#475569",fontSize:11,marginTop:1},children:[e.length," total · ",e.filter(l=>(l.status||l.job_status)==="complete").length," completed"]})]})]}),t.jsx("div",{style:{display:"flex",gap:12},children:[["#60a5fa","Scheduled"],["#22d3ee","In Progress"],["#4ade80","Complete"]].map(([l,d])=>t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[t.jsx("span",{style:{width:8,height:8,borderRadius:2,background:l,dis
635play:"inline-block"}}),t.jsx("span",{style:{fontSize:10,color:"#475569"},children:d})]},d))})]}),t.jsx("div",{style:{padding:"20px 18px 14px"},children:t.jsx("div",{style:{display:"flex",alignItems:"flex-end",gap:6,height:a+24},children:i.map(l=>{const d=nu(l.day),c=l.total>0?Math.max(l.total/o*a,8):0,f=l.total>0?l.scheduled/l.total*100:0,p=l.total>0?l.in_progress/l.total*100:0,u=l.total>0?l.complete/l.total*100:0;return t.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",alignItems:"center",gap:6},children:[t.jsx("div",{style:{fontSize:11,fontWeight:700,color:l.total>0?"#94a3b8":"#1e3a4f",height:16},children:l.total>0?l.total:""}),t.jsx("div",{style:{width:"100%",height:a,display:"flex",alignItems:"flex-end"},children:l.total>0?t.jsxs("div",{style:{width:"100%",height:c,borderRadius:"4px 4px 2px 2px",overflow:"hidden",display:"flex",flexDirection:"column"},children:[u>0&&t.jsx("div",{style:{flex:u,background:"#4ade80",minHeight:2}}),p>0&&t.jsx("div",{style:{flex:p,background:"#22d3ee",minHeight:2}}),f>0&&t.jsx("div",{style:{flex:f,background:"#60a5fa",minHeight:2}})]}):t.jsx("div",{style:{width:"100%",height:3,borderRadius:2,background:"#0d1a26"}})}),t.jsx("div",{style:{fontSize:10,fontWeight:d?800:600,color:d?"#0d7ea3":"#475569",textTransform:"uppercase",letterSpacing:"0.05em"},children:l.label})]},l.day)})})})]})}function mF({opts:e,userId:n,role:r}){const s=gt(),{data:i}=dF(e,n,r),[o,a]=g.useState(null);if(!i)return null;const{days:l,events:d}=i,c=r==="admin"||r==="super_admin"||r==="salesrep"||r==="frontdesk",f=r==="admin"||r==="super_admin"||r==="technician",p=o?d[o]:null;return t.jsxs("div",{style:{background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:12,overflow:"hidden"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 18px",background:"linear-gradient(135deg,#162232 0%,#0d1a26 100%)",borderBottom:"1px solid #1e3a4f"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[t.jsx("div",{style:{width:32,height:32,borderRadius:8,background:"rgba(13,126,163,0.2)",border:"1px solid rgba(13,126,163,0.3)",display:"flex",alignItems:"center",justifyContent:"center",fontSize:15},children:"ð"}),t.jsxs("div",{children:[t.jsx("div",{style:{color:"#e2e8f0",fontWeight:700,fontSize:13},children:r==="technician"?"My Install Schedule":r==="salesrep"?"My Visit Schedule":"This Week"}),t.jsx("div",{style:{color:"#475569",fontSize:11,marginTop:1},children:new Date().toLocaleDateString("en-US",{month:"long",year:"numeric"})})]})]}),t.jsxs("div",{style:{display:"flex",gap:14},children:[c&&t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:5},children:[t.jsx("span",{style:{width:8,height:8,borderRadius:"50%",background:"#22d3ee",display:"inline-block"}}),t.jsx("span",{style:{fontSize:11,color:"#475569"},children:"Site Visits"})]}),f&&t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:5},children:[t.jsx("span",{style:{width:8,height:8,borderRadius:"50%",background:"#fb923c",display:"inline-block"}}),t.jsx("span",{style:{fontSize:11,color:"#475569"},children:"Installs"})]})]})]}),t.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(7, 1fr)"},children:l.map((u,h)=>{var x,_;const y=((x=d[u])==null?void 0:x.visits)||[],m=((_=d[u])==null?void 0:_.jobs)||[],b=(c?y.length:0)+(f?m.length:0),A=nu(u),v=o===u;return t.jsxs("button",{onClick:()=>a(v?null:u),style:{padding:"12px 4px 10px",borderRight:h<6?"1px solid #1e3a4f":"none",borderBottom:v?"2px solid #0d7ea3":"1px solid #0d1a26",background:v?"rgba(13,126,163,0.12)":A?"rgba(255,255,255,0.02)":"transparent",cursor:"pointer",textAlign:"center",border:"none",borderLeft:"none",borderTop:"none"},children:[t.jsx("div",{style:{fontSize:9,color:"#334155",fontWeight:700,textTransform:"uppercase",letterSpacing:"0.08em",marginBottom:5},children:t8[new Date(u+"T00:00:00").getDay()]}),t.jsx("div",{style:{width:30,height:30,borderRadius:"50%",margin:"0 auto 7px",display:"flex",alignItems:"center",justifyContent:"center",background:A?"#0d7ea3":"transparent",color:A?"#fff":"#94a3b8",fontWeight:A?800:500,fontSize:14,boxShadow:A?"0 0 12px rgba(13,126,163,0.4)":"none"},children:new Date(u+"T00:00:00").getDate()}),t.jsxs("div",{style:{display:"flex",justifyContent:"center",gap:3,minHeight:7},children:[c&&y.length>0&&t.jsx("span",{style:{width:6,height:6,borderRadius:"50%",background:"#22d3ee",display:"inline-block"}}),f&&m.length>0&&t.jsx("span",{style:{width:6,height:6,borderRadius:"50%",background:"#fb923c",display:"inline-block"}})]}),b>
6350&&t.jsx("div",{style:{fontSize:10,color:"#475569",marginTop:3,fontWeight:600},children:b})]},u)})}),o&&p?t.jsxs("div",{style:{padding:"14px 18px",borderTop:"1px solid #1e3a4f",background:"rgba(13,126,163,0.04)"},children:[t.jsxs("div",{style:{color:"#64748b",fontSize:11,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:10},children:[nu(o)?"Today":e8(o)?"Tomorrow":Mo(o)," · ",(c?p.visits.length:0)+(f?p.jobs.length:0)," event(s)"]}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[c&&p.visits.map(u=>{var h;return t.jsxs("div",{onClick:()=>s(`/leads?lead=${u.lead_id}`),style:{display:"flex",alignItems:"center",gap:10,padding:"9px 12px",borderRadius:8,background:"rgba(34,211,238,0.06)",border:"1px solid rgba(34,211,238,0.15)",cursor:"pointer"},children:[t.jsx("span",{style:{width:8,height:8,borderRadius:"50%",background:"#22d3ee",flexShrink:0}}),t.jsxs("div",{children:[t.jsx("div",{style:{color:"#e2e8f0",fontSize:13,fontWeight:600},children:((h=u.lead)==null?void 0:h.full_name)||"Unknown"}),t.jsxs("div",{style:{color:"#64748b",fontSize:11},children:[Qk(u.visit_hour,u.visit_minute)," · Site Visit"]})]})]},u.id)}),f&&p.jobs.map(u=>t.jsxs("div",{onClick:()=>s(`/installations/${u.id}`),style:{display:"flex",alignItems:"center",gap:10,padding:"9px 12px",borderRadius:8,background:"rgba(251,146,60,0.06)",border:"1px solid rgba(251,146,60,0.15)",cursor:"pointer"},children:[t.jsx("span",{style:{width:8,height:8,borderRadius:"50%",background:"#fb923c",flexShrink:0}}),t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsx("div",{style:{color:"#e2e8f0",fontSize:13,fontWeight:600,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:u.customer_name_snapshot}),t.jsxs("div",{style:{color:"#64748b",fontSize:11},children:[u.job_type||"Install"," · ",t.jsx("span",{style:{color:ph[u.status||u.job_status]||"#64748b"},children:u.status||u.job_status})]})]})]},u.id)),(c?p.visits.length:0)+(f?p.jobs.length:0)===0&&t.jsx("div",{style:{color:"#1e3a4f",fontSize:13,textAlign:"center",padding:"12px 0"},children:"Nothing scheduled"})]})]}):t.jsx("div",{style:{padding:"10px 18px",color:"#1e293b",fontSize:12,textAlign:"center"},children:"Tap a day to see details"})]})}function xF(){var te;const{profile:e,role:n}=Jb(),r=gt(),{userBranch:s,selectedBranchId:i,allBranches:o}=mu(),a=(e==null?void 0:e.tenant_id)??"",l=i??(e==null?void 0:e.branch_id)??null,d={tenantId:a,branchId:l},c=n==="admin"||n==="super_admin",f=n==="frontdesk",p=c||n==="salesrep"||n==="frontdesk",u=c||n==="technician",h=c||f,{data:y=[]}=UM(d),{data:m=[]}=HM(d),{data:b=[]}=VM(d),{data:A=[]}=ZM(d),{data:v=0}=KM(d),{data:x=[]}=YM(d),{data:_=[]}=XM(d),{data:j=[]}=GM(d),{data:C=[]}=JM(d),{data:S=[]}=QM(d,e==null?void 0:e.id,c),{data:T=[]}=eF(d),{data:L=[]}=tF(d),{data:E=[]}=nF(d),{data:R=[]}=rF(d),{data:N=[]}=sF(d),{data:O=[]}=iF(d),{data:z=[]}=oF(d),{data:P=[]}=aF(d),{data:D=[]}=cF(d),{data:M=[]}=uF(d),{data:k=[]}=pF(d),q=new Date().getHours(),$=e?`Good ${q<12?"morning":q<17?"afternoon":"evening"}, ${(e.full_name||"").split(" ")[0]||"there"}.`:"Welcome.",I=x.filter(U=>(U.status||U.job_status)==="complete").length,B=A.filter(U=>U.job_status==="scheduled").length,J=A.filter(U=>U.job_status==="in_progress").length,ae=m.length+_.length+C.length+L.length+E.length+N.length+P.length+k.length;return t.jsxs("div",{style:{width:"100%",display:"flex",flexDirection:"column",gap:20},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",flexWrap:"wrap",gap:12},children:[t.jsxs("div",{children:[t.jsx("h1",{style:{color:"#f1f5f9",fontWeight:800,fontSize:24,margin:0,letterSpacing:"-0.02em"},children:$}),t.jsx("p",{style:{color:"#475569",fontSize:13,marginTop:4,marginBottom:0},children:new Date().toLocaleDateString("en-US",{weekday:"long",month:"long",day:"numeric",year:"numeric"})})]}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[c&&t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"6px 14px",borderRadius:10,fontSize:12,fontWeight:600,background:"rgba(13,126,163,0.1)",border:"1px solid rgba(13,126,163,0.25)",color:"#0d7ea3"},children:[t.jsx("span",{children:"ð¢"}),t.jsx("span",{children:i?((te=o.find(U=>U.id===i))==null?void 0:te.name)||"Branch":"All Branches"})]}),ae>0&&t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"8px 16px",borderRadius:10,fontSize:13,fontWeight:600,background:"rgba(239,68,68,0.1)",border:"1px solid rgba(239,68,68,0.25)",color:"#f87171"},children:[t.jsx("span",{style:{width:8,height:8,borderRadius:"50%",background:"#ef4444",dis
635play:"inline-block"}}),ae," item",ae!==1?"s":""," need attention"]})]})]}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(4, 1fr)",gap:14},children:[t.jsx(wp,{label:"Active Leads",value:String(v),sub:y.length>0?`+${y.length} new today`:"No new today",icon:"⬡",bg:"linear-gradient(135deg, #0c2a4a 0%, #0f3460 100%)",border:"#1d4ed8",accent:"#38bdf8",onClick:()=>r("/leads")}),t.jsx(wp,{label:"Today's Installs",value:String(A.length),sub:J>0?`${J} in progress`:B>0?`${B} scheduled`:"None today",icon:"ð§",bg:"linear-gradient(135deg, #2d1a00 0%, #3d2200 100%)",border:"#92400e",accent:"#f59e0b",onClick:()=>r("/installations")}),t.jsx(wp,{label:"Jobs This Week",value:String(x.length),sub:`${I} completed`,icon:"ð
",bg:"linear-gradient(135deg, #1e1040 0%, #251355 100%)",border:"#6d28d9",accent:"#a78bfa",onClick:()=>r("/dispatch")}),t.jsx(wp,{label:"Failed Payments",value:String(C.length),sub:C.length>0?"Needs immediate action":"All clear",icon:"ð³",bg:C.length>0?"linear-gradient(135deg, #3b0a0a 0%, #450c0c 100%)":"linear-gradient(135deg, #0a2010 0%, #0c2a14 100%)",border:C.length>0?"#7f1d1d":"#b91c1c",accent:C.length>0?"#ef4444":"#4ade80",urgent:C.length>0,onClick:()=>r("/customers")})]}),t.jsx(BM,{}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:14},children:[t.jsx(gF,{jobsThisWeek:x}),t.jsx(fF,{opts:d})]}),t.jsx(mF,{opts:d,userId:e==null?void 0:e.id,role:n}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(2, 1fr)",gap:14},children:[h&&k.length>0&&t.jsxs(un,{title:"Overdue Fulfillment",icon:"ð¨",count:k.length,accent:"#ef4444",urgent:!0,onClick:()=>r("/fulfillment"),children:[k.slice(0,5).map(U=>{var G;const W=Math.floor((Date.now()-new Date(U.due_date).getTime())/864e5);return t.jsxs(pn,{onClick:()=>r("/fulfillment"),children:[t.jsx(hn,{primary:((G=U.customers)==null?void 0:G.full_name)||"Unknown",secondary:`${U.fulfillment_type||"Service"} · Paid ${W}d ago`}),t.jsx(fn,{children:t.jsxs("span",{style:{fontSize:11,fontWeight:700,color:"#f87171"},children:[W,"d overdue"]})})]},U.id)}),t.jsx(Fd,{count:k.length,limit:5,onClick:()=>r("/fulfillment")})]}),h&&D.length>0&&t.jsxs(un,{title:"Paid â Awaiting Schedule",icon:"ð",count:D.length,accent:"#fbbf24",urgent:!0,onClick:()=>r("/fulfillment"),children:[D.slice(0,5).map(U=>{var W,G;return t.jsxs(pn,{onClick:()=>r("/fulfillment"),children:[t.jsx(hn,{primary:((W=U.customers)==null?void 0:W.full_name)||"Unknown",secondary:U.fulfillment_type||"Service"}),t.jsx(fn,{children:(G=U.customers)!=null&&G.phone?t.jsx("a",{href:`tel:${U.customers.phone}`,onClick:V=>V.stopPropagation(),style:{fontSize:11,color:"#0d7ea3",textDecoration:"none"},children:"ð Call"}):null})]},U.id)}),t.jsx(Fd,{count:D.length,limit:5,onClick:()=>r("/fulfillment")})]}),(h||n==="technician")&&M.length>0&&t.jsxs(un,{title:"Scheduled Visits This Week",icon:"ð
",count:M.length,accent:"#60a5fa",onClick:()=>r("/fulfillment"),children:[M.slice(0,5).map(U=>{var W;return t.jsxs(pn,{onClick:()=>r("/fulfillment"),children:[t.jsx(hn,{primary:((W=U.customers)==null?void 0:W.full_name)||"Unknown",secondary:U.fulfillment_type||"Service"}),t.jsx(fn,{children:t.jsx("span",{style:{fontSize:11,color:"#60a5fa",fontWeight:600},children:U.scheduled_at?new Date(U.scheduled_at).toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric"}):"â"})})]},U.id)}),t.jsx(Fd,{count:M.length,limit:5,onClick:()=>r("/fulfillment")})]}),c&&C.length>0&&t.jsxs(un,{title:"Failed Payments",icon:"ð³",count:C.length,accent:"#ef4444",urgent:!0,onClick:()=>r("/customers"),children:[C.slice(0,5).map(U=>{var W;return t.jsxs(pn,{onClick:()=>r(`/customers/${U.customer_id}`),children:[t.jsx(hn,{primary:((W=U.customers)==null?void 0:W.full_name)||"Unknown",secondary:`${U.failure_reason||"Payment failed"} · ${jp(U.created_at)}`}),t.jsx(fn,{children:t.jsxs("span",{style:{fontSize:13,fontWeight:800,color:"#f87171"},children:["$",Number(U.amount).toFixed(2)]})})]},U.id)}),t.jsx(Fd,{count:C.length,limit:5,onClick:()=>r("/customers")})]}),u&&L.length>0&&t.jsxs(un,{title:"Pending Proof Review",icon:"ð¸",count:L.length,accent:"#fbbf24",urgent:!0,onClick:()=>r("/installations"),children:[L.slice(0,5).map(U=>t.jsxs(pn,{onClick:()=>r(`/installations/${U.id}`),children:[t.jsx(hn,{primary:U.customer_name_snapshot,secondary:U.service_address_snapshot}),t.jsx(fn,{children:t.jsx(Sp,{label:"Review",color:"#fbbf24"})})]},U.id)),t.jsx(Fd,{count:L.length,limit:5,onClick:()=>r("/installations")})]}),c&&t.jsxs(un,{title:"Unsigned Agreements",icon:"âï¸",count:E.length,accent:"#f87171",urgent:E.length>0,onClick:()=>r("/leads"),children:[E.slice(0,5).map(U=>{var W;return t.jsxs(pn,{onClick:()=>r(`/leads?lead=${U.lead_id}`),children:[t.jsx(hn,{primary:((W=U.leads)==null?void 0:W.full_name)||"Unknown",secondary:`${U.agreement_number} · ${jp(U.created_at)}`}),t.jsx(fn,{children:t.jsx(Sp,{label:"Awaiting",color:"#f87171"})})]},U.id)}),E.length===0&&t.jsx(Mr,{text:"No pending signatures"})]}),c&&t.jsxs(un,{title:"Unassigned Jobs",icon:"â ï¸",count:N.length,accent:"#fb923c",urgent:N.length>0,onClick:()=>r("/dispatch"),children:[N.slice(0,5).map(U=>t.jsxs(pn,{onClick:()=>r("/dispatch"),children:[t.jsx(hn,{primary:U.customer_name_snapshot,secondary:`${U.scheduled_date?Mo(U.scheduled_date):"No date"} · ${U.job_type||"Install"}`}),t.jsx(fn,{children:t.jsx(Sp,{label:"Unassigned",color:"#fb923c"})})]},U.id)),N.length===0&&t.jsx(Mr,{text:"All jobs assigned"})]}),p&&t.jsxs(un,{title:"Quotes Expiring Soon",icon:"â°",count:O.length,accent:"#fbbf24",urgent:O.length>0,onClick:()=>r("/quotes"),children:[O.slice(0,5).map(U=>{const W=bm(U.expires_at);return t.jsxs(pn,{onClick:()=>r("/quotes"),children:[t.jsx(hn,{primary:U.customer_name||"Unknown",secondary:`${U.quote_number} · ${U.monthly_rental_price?`$${Number(U.monthly_rental_price).toFixed(2)}/mo`:U.total?`$${Number(U.total).toFixed(2)}`:""}`}),t.jsx(fn,{children:t.jsxs("div",{style:{textAlign:"right"},children:[t.jsx("div",{style:{fontSize:13,fontWeight:800,color:W<=2?"#f87171":"#fbbf24"},children:W===0?"Today":`${W}d`}
635),t.jsx("div",{style:{fontSize:10,color:"#475569"},children:Mo(U.expires_at)})]})})]},U.id)}),O.length===0&&t.jsx(Mr,{text:"No quotes expiring this week"})]}),c&&t.jsxs(un,{title:"Upcoming Renewals",icon:"â»",count:T.length,accent:"#818cf8",onClick:()=>r("/customers"),children:[T.slice(0,5).map(U=>{var W;return t.jsxs(pn,{onClick:()=>r(`/customers/${U.customer_id}`),children:[t.jsx(hn,{primary:((W=U.customers)==null?void 0:W.full_name)||"Unknown",secondary:`${U.contract_number} · $${Number(U.monthly_amount||0).toFixed(2)}/mo`}),t.jsx(fn,{children:t.jsxs("div",{style:{textAlign:"right"},children:[t.jsxs("div",{style:{fontSize:13,fontWeight:800,color:bm(U.end_date)<=7?"#f87171":"#fbbf24"},children:[bm(U.end_date),"d"]}),t.jsx("div",{style:{fontSize:10,color:"#475569"},children:Mo(U.end_date)})]})})]},U.id)}),T.length===0&&t.jsx(Mr,{text:"No renewals in next 30 days"})]}),p&&t.jsxs(un,{title:c?"Upcoming Site Visits":"My Upcoming Visits",icon:"ð",count:S.length,accent:"#22d3ee",onClick:()=>r("/leads"),children:[S.slice(0,6).map(U=>{var W,G;return t.jsxs(pn,{onClick:()=>r(`/leads?lead=${U.lead_id}`),children:[t.jsx(hn,{primary:((W=U.lead)==null?void 0:W.full_name)||"Unknown",secondary:((G=U.lead)==null?void 0:G.phone)||""}),t.jsx(fn,{children:t.jsxs("div",{style:{textAlign:"right"},children:[t.jsx("div",{style:{fontSize:11,fontWeight:600,color:nu(U.visit_date)?"#34d399":"#94a3b8"},children:hF(U.visit_date)}),t.jsx("div",{style:{fontSize:10,color:"#475569",marginTop:2},children:Qk(U.visit_hour,U.visit_minute)})]})})]},U.id)}),S.length===0&&t.jsx(Mr,{text:"No site visits this week"})]}),p&&t.jsxs(un,{title:"Overdue Follow-Ups",icon:"ð¥",count:m.length,accent:"#f87171",urgent:m.length>0,onClick:()=>r("/leads"),children:[m.slice(0,5).map(U=>t.jsxs(pn,{onClick:()=>r("/leads"),children:[t.jsx(hn,{primary:U.full_name,secondary:U.phone}),t.jsx(fn,{children:t.jsxs("span",{style:{fontSize:11,fontWeight:700,color:"#f87171"},children:[ym(U.followup_date),"d overdue"]})})]},U.id)),m.length===0&&t.jsx(Mr,{text:"No overdue follow-ups"})]}),p&&t.jsxs(un,{title:"Leads Going Cold",icon:"ð§",count:R.length,accent:"#94a3b8",onClick:()=>r("/leads"),children:[R.slice(0,5).map(U=>{var W;return t.jsxs(pn,{onClick:()=>r("/leads"),children:[t.jsx(hn,{primary:U.full_name,secondary:`${U.phone} · ${(W=U.stage)==null?void 0:W.replace(/_/g," ")}`}),t.jsx(fn,{children:t.jsxs("span",{style:{fontSize:11,fontWeight:600,color:"#64748b"},children:[ym(U.updated_at),"d idle"]})})]},U.id)}),R.length===0&&t.jsx(Mr,{text:"No leads going cold"})]}),p&&t.jsxs(un,{title:"Leads to Contact",icon:"ð",count:b.length,accent:"#38bdf8",onClick:()=>r("/leads"),children:[b.slice(0,5).map(U=>t.jsxs(pn,{onClick:()=>r("/leads"),children:[t.jsx(hn,{primary:U.full_name,secondary:U.phone}),t.jsx(fn,{children:t.jsx("span",{style:{fontSize:11,color:"#475569"},children:jp(U.created_at)})})]},U.id)),b.length===0&&t.jsx(Mr,{text:"No leads waiting"})]}),t.jsxs(un,{title:"Today's Installations",icon:"ð§",count:A.length,accent:"#f59e0b",onClick:()=>r("/installations"),children:[A.slice(0,5).map(U=>t.jsxs(pn,{onClick:()=>r(`/installations/${U.id}`),children:[t.jsx(hn,{primary:U.customer_name_snapshot||"Unknown",secondary:U.service_address_snapshot||""}),t.jsx(fn,{children:t.jsx("span",{style:{fontSize:10,padding:"3px 9px",borderRadius:20,fontWeight:700,whiteSpace:"nowrap",background:`${ph[U.job_status]||"#64748b"}18`,color:ph[U.job_status]||"#64748b",border:`1px solid ${ph[U.job_status]||"#64748b"}30`},children:U.job_status})})]},U.id)),A.length===0&&t.jsx(Mr,{text:"No installs today"})]}),c&&t.jsxs(un,{title:"Low Inventory",icon:"ð¦",count:z.length,accent:"#2dd4bf",urgent:z.length>0,onClick:()=>r("/inventory"),children:[z.slice(0,5).map(U=>{var W;return t.jsxs(pn,{onClick:()=>r("/inventory"),children:[t.jsx(hn,{primary:((W=U.product_catalog)==null?void 0:W.name)||"Unknown item",secondary:`Reorder at ${U.reorder_point}`}),t.jsx(fn,{children:t.jsxs("div",{style:{textAlign:"right"},children:[t.jsx("div",{style:{fontSize:16,fontWeight:800,color:U.quantity_on_hand===0?"#f87171":"#fbbf24",lineHeight:1},children:U.quantity_on_hand}
635),t.jsx("div",{style:{fontSize:10,color:"#475569"},children:"in stock"})]})})]},U.id)}),z.length===0&&t.jsx(Mr,{text:"All stock levels OK"})]}),c&&t.jsxs(un,{title:"Shipments Due",icon:"ð",count:P.length,accent:"#06b6d4",urgent:P.length>0,onClick:()=>r("/shipping"),children:[P.slice(0,5).map(U=>{var W;return t.jsxs(pn,{onClick:()=>r("/shipping"),children:[t.jsx(hn,{primary:((W=U.customers)==null?void 0:W.full_name)||"Unknown",secondary:"Shipment"}),t.jsx(fn,{children:t.jsx("div",{style:{fontSize:11,fontWeight:600,color:"#06b6d4"},children:U.due_date?Mo(U.due_date):"No date"})})]},U.id)}),P.length===0&&t.jsx(Mr,{text:"No shipments due this week"})]}),c&&t.jsx(un,{title:"Recent Customers",icon:"ð¥",count:j.length,accent:"#4ade80",onClick:()=>r("/customers"),children:j.map(U=>{const W=U.lifecycle_stage||"unknown",G=W==="active"?"#4ade80":W==="at_risk"?"#f87171":"#94a3b8";return t.jsxs(pn,{onClick:()=>r(`/customers/${U.id}`),children:[t.jsx(hn,{primary:U.full_name,secondary:jp(U.created_at)}),t.jsx(fn,{children:t.jsx(Sp,{label:W,color:G})})]},U.id)})}),c&&_.length>0&&t.jsx(un,{title:"Overdue Service Items",icon:"â ï¸",count:_.length,accent:"#ef4444",urgent:!0,onClick:()=>r("/customers"),children:_.slice(0,5).map(U=>{var W;return t.jsxs(pn,{onClick:()=>U.customer_id?r(`/customers/${U.customer_id}`):void 0,children:[t.jsx(hn,{primary:`Service due ${Mo(U.due_date)}`,secondary:`Customer: ${(W=U.customer_id)==null?void 0:W.slice(0,8)}...`}),t.jsx(fn,{children:t.jsxs("span",{style:{fontSize:11,fontWeight:700,color:"#f87171"},children:[ym(U.due_date),"d overdue"]})})]},U.id)})})]}),p&&t.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:8},children:[{label:"+ New Lead",path:"/leads"},{label:"View Pipeline",path:"/leads"},{label:"Dispatch Board",path:"/dispatch"},{label:"All Customers",path:"/customers"},...h?[{label:"Fulfillment Queue",path:"/fulfillment"}]:[],...c?[{label:"Product Catalog",path:"/products"}]:[]].map(U=>t.jsx("button",{onClick:()=>r(U.path),style:{fontSize:12,padding:"8px 16px",borderRadius:8,cursor:"pointer",background:"#0f1923",border:"1px solid #1e3a4f",color:"#64748b",fontWeight:500},onMouseEnter:W=>{const G=W.currentTarget;G.style.borderColor="#0d7ea3",G.style.color="#e2e8f0"},onMouseLeave:W=>{const G=W.currentTarget;G.style.borderColor="#1e3a4f",G.style.color="#64748b"},children:U.label},U.label))})]})}function wp({label:e,value:n,sub:r,icon:s,bg:i,border:o,accent:a,urgent:l,onClick:d}){return t.jsxs("button",{onClick:d,style:{background:i,border:`1px solid ${o}`,borderRadius:14,padding:"20px 20px 18px",textAlign:"left",cursor:"pointer",width:"100%",position:"relative",overflow:"hidden",boxShadow:l?`0 0 20px ${a}20`:"none"},onMouseEnter:c=>{const f=c.currentTarget;f.style.transform="translateY(-2px)",f.style.boxShadow=`0 8px 24px ${a}20`},onMouseLeave:c=>{const f=c.currentTarget;f.style.transform="translateY(0)",f.style.boxShadow=l?`0 0 20px ${a}20`:"none"},children:[t.jsx("div",{style:{position:"absolute",top:-20,right:-20,width:80,height:80,borderRadius:"50%",background:`${a}15`,pointerEvents:"none"}}),t.jsx("div",{style:{position:"absolute",top:16,right:16,fontSize:22,opacity:.7},children:s}),t.jsx("div",{style:{fontSize:10,fontWeight:700,color:`${a}99`,textTransform:"uppercase",letterSpacing:"0.09em",marginBottom:12},children:e}),t.jsx("div",{style:{fontSize:38,fontWeight:900,color:a,lineHeight:1,letterSpacing:"-0.03em"},children:n}),t.jsx("div",{style:{fontSize:11,color:`${a}70`,marginTop:10,fontWeight:500},children:r})]})}function un({title:e,icon:n,count:r,accent:s,urgent:i,children:o,onClick:a}){return t.jsxs("div",{style:{background:"#0f1923",border:`1px solid ${i&&r>0?`${s}35`:"#1e3a4f"}`,borderLeft:`3px solid ${i&&r>0?s:"#1e3a4f"}`,borderRadius:12,overflow:"hidden"},children:[t.jsxs("div",{onClick:a,style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"13px 16px",background:"linear-gradient(135deg,#162232 0%,#0d1a26 100%)",borderBottom:"1px solid #0d1a26",cursor:"pointer"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[t.jsx("div",{style:{width:32,height:32,borderRadius:8,flexShrink:0,background:`${s}12`,border:`1px solid ${s}20`,display:"flex",alignItems:"center",justifyContent:"center",fontSize:15},children:n}),t.jsx("span",{style:{fontSize:13,fontWeight:700,color:"#cbd5e1"},children:e})]}),t.jsx("span",{style:{minWidth:26,height:22,borderRadius:20,padding:"0 8px",display:"inline-flex",alignItems:"center",justifyContent:"center",fontSize:11,fontWeight:800,background:r===0?"#1e293b":`${s}18`,color:r===0?"#334155":s,border:`1px solid ${r===0?"#1e3a4f":`${s}25`}`},children:r})]}),t.jsx("div",{children:o})]})}function pn({onClick:e,children:n}){return t.jsx("div",{onClick:e,style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"11px 16px",cursor:"pointer",borderBottom:"1px solid #0d1a26"},onMouseEnter:r=>{r.currentTarget.style.background="rgba(255,255,255,0.02)"},onMouseLeave:r=>{r.currentTarget.style.background="transparent"},children:n})}function hn({primary:e,secondary:n}
635){return t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsx("div",{style:{fontSize:13,fontWeight:600,color:"#cbd5e1",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e}),n&&t.jsx("div",{style:{fontSize:11,color:"#475569",marginTop:2,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:n})]})}function fn({children:e}){return t.jsx("div",{style:{flexShrink:0,marginLeft:8},children:e})}function Sp({label:e,color:n}){return t.jsx("span",{style:{fontSize:10,padding:"3px 9px",borderRadius:20,fontWeight:700,whiteSpace:"nowrap",background:`${n}12`,color:n,border:`1px solid ${n}25`},children:e})}function Mr({text:e}){return t.jsx("div",{style:{padding:"20px 16px",textAlign:"center",fontSize:12,color:"#1e3a4f"},children:e})}function Fd({count:e,limit:n,onClick:r}){return e<=n?null:t.jsxs("button",{onClick:r,style:{width:"100%",padding:"9px 16px",fontSize:11,color:"#0d7ea3",background:"rgba(13,126,163,0.05)",borderTop:"1px solid #0d1a26",cursor:"pointer",textAlign:"center",fontWeight:600,border:"none"},onMouseEnter:s=>{s.currentTarget.style.background="rgba(13,126,163,0.1)"},onMouseLeave:s=>{s.currentTarget.style.background="rgba(13,126,163,0.05)"},children:["View all ",e," â"]})}const Lr=` 636 id, tenant_id, branch_id, customer_id, assigned_rep_id, 637 first_name, last_name, full_name, email, phone, 638 stage, commercial_type, source, 639 notes, followup_date, followup_notes, water_concern, qualifying_answers, 640 lost_reason, lost_at, dnd_at, re_engage_date, stage_entered_at, stage_changed_at, 641 created_at, updated_at, opened_at, 642 preferred_slot_at, slot_available, booking_stage, booking_due_at, 643 is_returning, returned_at, prior_opt_out 644`,F_=["new_lead","qualifying","qualified","site_visit_scheduled","proposal_in_progress","quote_sent","agreement_signed"],n8=["won","lost","future_follow_up","dnd"],yF=["phone_call","web_form","referral","google_ad","facebook_ad","door_knock","event","other","email","text_message","referral_realtor","referral_friend","home_show","nextdoor","walk_in"];async function r8(){const e=Yt();if(!e){const a={};for(const l of F_)a[l]=[];return a}let n=w.from("leads").select(Lr).eq("tenant_id",e).not("stage","in",`(${n8.join(",")})`).order("created_at",{ascending:!1});const r=Kt();r&&(n=n.eq("branch_id",r));const{data:s,error:i}=await n;if(i)throw console.error("[leads.api] fetchLeadsByStage error:",i.message),i;const o={};for(const a of F_)o[a]=[];for(const a of s||[])o[a.stage]||(o[a.stage]=[]),o[a.stage].push(a);return o}async function s8(e){const n=Yt();if(!n)return[];const r=(e||"").replace(/[,()%*\\]/g,"").trim();if(r.length<2)return[];let s=w.from("leads").select(Lr).eq("tenant_id",n).in("stage",n8).or("full_name.ilike.%"+r+"%,email.ilike.%"+r+"%,phone.ilike.%"+r+"%").order("created_at",{ascending:!1}).limit(50);const i=Kt();i&&(s=s.eq("branch_id",i));const{data:o,error:a}=await s;if(a)throw console.error("[leads.api] searchTerminalLeads error:",a.message),a;return o||[]}async function i8(e={}){const n=Yt();if(!n)return[];let r=w.from("leads").select(Lr).eq("tenant_id",n).order("created_at",{ascending:!1});const s=Kt();if(s&&(r=r.eq("branch_id",s)),e.stage&&(r=r.eq("stage",e.stage)),e.rep_id&&(r=r.eq("assigned_rep_id",e.rep_id)),e.search){const a=`%${e.search}%`;r=r.or(`first_name.ilike.${a},last_name.ilike.${a},full_name.ilike.${a},phone.ilike.${a},email.ilike.${a}`)}const{data:i,error:o}=await r;if(o)throw o;return i||[]}async function k0(e){const n=Yt();if(!n)throw new Error("Not authenticated");const{data:r,error:s}=await w.from("leads").select(Lr).eq("id",e).eq("tenant_id",n).single();if(s)throw s;return r}async function bF(e){const n=Yt();n&&await w.from("leads").update({opened_at:new Date().toISOString()}).eq("id",e).eq("tenant_id",n).is("opened_at",null)}async function o8(e,n){const r=Yt();if(!r)throw new Error("Not authenticated");const{full_name:s,zip_code:i,urgent:o,...a}=e,l=(s||a.first_name||"").trim().split(" "),d=a.first_name||l[0]||"",c=a.last_name||l.slice(1).join(" ")||"",f=yF.includes(a.source)?a.source:"other",p={first_name:d,last_name:c,tenant_id:r,stage:"new_lead",source:f},u={phone:"phone",email:"email",water_concern:"water_concern",notes:"notes",assigned_rep_id:"assigned_rep_id",commercial_type:"commercial_type"};for(const[x,_]of Object.entries(u)){const j=a[x];j!=null&&j!==""&&(p[_]=j)}const h=a.address||null,y=a.city||null,m=a.state||null,b=i??a.zip??null,{data:A,error:v}=await w.from("leads").insert(p).select(Lr).single();if(v)throw console.error("[leads.api] createLead error:",v.message,p),v;if(h||y||m||b){const{error:x}=await w.from("addresses").insert({tenant_id:r,entity_type:"lead",entity_id:A.id,is_primary:!0,label:"Primary",address_line1:h,city:y,state:m,zip:b});x&&console.error("[L1 dual-write] lead addresses insert failed:",x)}return ii(A.id,"lead_created","Lead created",{actor_id:n}),A}async function AF(e,n,r){const s=Yt();if(!s)throw new Error("Not authenticated");const{data:i,error:o}=await w.from("leads").update({...n,updated_at:new Date().toISOString()}).eq("id",e).eq("tenant_id",s).select(Lr).single();if(o)throw o;return ii(e,"lead_updated","Lead updated",{actor_id:r}),i}
644async function C0(e,n,r,s){const i=Yt();if(!i)throw new Error("Not authenticated");const o={stage:n,stage_entered_at:new Date().toISOString(),stage_changed_at:new Date().toISOString(),updated_at:new Date().toISOString()};s!=null&&s.lost_reason&&(o.lost_reason=s.lost_reason),s!=null&&s.re_engage_date&&(o.re_engage_date=s.re_engage_date),s!=null&&s.followup_date&&(o.followup_date=s.followup_date),s!=null&&s.followup_notes&&(o.followup_notes=s.followup_notes),n==="lost"&&(o.lost_at=new Date().toISOString()),n==="dnd"&&(o.dnd_at=new Date().toISOString());const{data:a,error:l}=await w.from("leads").update(o).eq("id",e).eq("tenant_id",i).select(Lr).single();if(l)throw l;return ii(e,"stage_changed",`Stage â ${n}`,{actor_id:r},{stage:n}),a}async function a8(e,n,r){const s=Yt();if(!s)throw new Error("Not authenticated");const{data:i,error:o}=await w.from("leads").update({assigned_rep_id:n,updated_at:new Date().toISOString()}).eq("id",e).eq("tenant_id",s).select(Lr).single();if(o)throw o;return ii(e,"rep_assigned","Rep assigned",{actor_id:r},{rep_id:n}),i}async function l8(e,n,r,s){const i=Yt();if(!i)throw new Error("Not authenticated");const{data:o,error:a}=await w.from("call_attempts").insert({tenant_id:i,lead_id:e,made_by:n,outcome:r,notes:s??null}).select().single();if(a)throw a;return o}async function d8(e){const n=Yt();if(!n)return[];const{data:r}=await w.from("call_attempts").select("id, outcome, notes, made_by, created_at, profiles!made_by(full_name)").eq("lead_id",e).eq("tenant_id",n).order("created_at",{ascending:!1});return r||[]}async function vF(e){const n=Yt();if(!n)return[];const{data:r}=await w.from("lead_activity_log").select("id, event_type, description, metadata, actor_name, created_at").eq("lead_id",e).eq("tenant_id",n).order("created_at",{ascending:!1}).limit(50);return r||[]}async function T0(){const e=Yt();if(!e)return[];const{data:n,error:r}=await w.from("profiles").select("id, full_name, email, role, is_active, phone").eq("tenant_id",e).in("role",["salesrep","admin","super_admin","frontdesk"]).eq("is_active",!0).order("full_name");if(r)throw r;return n||[]}async function c8(){const e=Yt();if(!e)return{};let n=w.from("leads").select("stage").eq("tenant_id",e);const r=Kt();r&&(n=n.eq("branch_id",r));const{data:s,error:i}=await n;if(i)throw i;const o={};for(const a of s||[])o[a.stage]=(o[a.stage]||0)+1;return o}async function u8(){const e=Yt();if(!e)return{};let n=w.from("jobs").select("lead_id, inventory_status").eq("tenant_id",e).eq("job_status","ready_to_schedule").is("scheduled_at",null).not("lead_id","is",null);const r=Kt();r&&(n=n.eq("branch_id",r));const{data:s,error:i}=await n;if(i)throw i;const o={};for(const a of s||[])a.lead_id&&(o[a.lead_id]=a.inventory_status||"unknown");return o}function z0(e,n=new Date){return Xk("booking",e,n)}const _F=["awaiting_call","chasing_1","chasing_2","day7","booked","dead"];async function p8(e,n){const r=Yt();if(!r)throw new Error("Not authenticated");const{data:s}=await w.from("leads").select("booking_stage").eq("id",e).eq("tenant_id",r).single();if(s!=null&&s.booking_stage)return k0(e);const{data:i,error:o}=await w.from("leads").update({booking_stage:"awaiting_call",booking_due_at:z0("awaiting_call"),updated_at:new Date().toISOString()}).eq("id",e).eq("tenant_id",r).select(Lr).single();if(o)throw o;return ii(e,"booking_advanced","Chase started â 30-min call window",{actor_id:n},{booking_stage:"awaiting_call"}),i}async function jF(e,n,r){const s=Yt();if(!s)throw new Error("Not authenticated");if(n){const{data:o}=await w.from("leads").select("stage").eq("id",e).eq("tenant_id",s).single();(o==null?void 0:o.stage)==="new_lead"&&await C0(e,"qualifying",r);const{data:a,error:l}=await w.from("leads").update({slot_available:!0,booking_stage:"booked",updated_at:new Date().toISOString()}).eq("id",e).eq("tenant_id",s).select(Lr).single();if(l)throw l;return ii(e,"slot_available",(o==null?void 0:o.stage)==="new_lead"?"Slot available â moved to qualifying":"Slot available â accepted",{actor_id:r}),a}const{error:i}=await w.from("leads").update({slot_available:!1,updated_at:new Date().toISOString()}).eq("id",e).eq("tenant_id",s);if(i)throw i;return ii(e,"slot_unavailable","Slot unavailable â chase started",{actor_id:r}),p8(e,r)}async function wF(e,n,r,s,i){const o=Yt();if(!o)throw new Error("Not authenticated");const a=(r||"").trim();let l=!1;i.stage==="new_lead"&&(await C0(e,"qualifying",s,a?{followup_notes:a}:void 0),l=!!a);const{data:d}=await w.from("leads").select("id").eq("tenant_id",o).eq("booking_stage","booked").eq("preferred_slot_at",n).neq("id",e).limit(1);if(d&&d.length)throw new Error("That time was just taken. Please pick another.");const c={preferred_slot_at:n,booking_stage:"booked",updated_at:new Date().toISOString()};a&&!l&&(c.followup_notes=a);const{data:f,error:p}=await w.from("leads").update(c).eq("id",e).eq("tenant_id",o).select(Lr).single();if(p)throw p;const u="America/Indiana/Indianapolis",h=n.split("T")[0],y=new Intl.DateTimeFormat("en-US",{timeZone:u,hour:"numeric",minute:"2-digit",hour12:!0}).format(new Date(n)),m=new Intl.DateTimeFormat("en-US",{timeZone:u,weekday:"long",month:"long",day:"numeric",hour:"numeric",minute:"2-digit",hour12:!0}).format(new Date(n)),b=a?`Callback booked for ${m}. ${a}`:`Callback booked for ${m} (front desk).`;w.from("follow_up_tasks").insert({lead_id:e,task_type:"call_back",title:`Booked call ${y}: ${i.name}`,notes:b,description:b,due_date:h,status:"open",priority:"high",assigned_to:null}).then(()=>{}).catch(()=>{});const A=(f==null?void 0:f.phone)||null;if(A){const v=await At();fetch("/api/openphone/send-sms",{method:"POST",headers:v,body:JSON.stringify({tenant_id:o,to:A,entity_type:"lead",entity_id:e,lead_id:e,message:"Hi {{first_name}}, this confirms we'll call you {{when}}. Reply STOP to opt out.",variables:{first_name:i.name.split(" ")[0]||"there",when:m}})}).catch(()=>{})}return ii(e,"booking_advanced",`Callback booked for ${m}${a?" â "+a:""}`,{actor_id:s},{booking_stage:"booked",preferred_slot_at:n}),f}async function SF(e,n,r){const s=Yt();if(!s)throw new Error("Not authenticated");if(!_F.includes(n))throw new Error(`Invalid booking stage: ${n}`);const{data:i,error:o}
644=await w.from("leads").update({booking_stage:n,booking_due_at:z0(n),updated_at:new Date().toISOString()}).eq("id",e).eq("tenant_id",s).select(Lr).single();if(o)throw o;return ii(e,"booking_advanced",`Moved to ${n}`,{actor_id:r},{booking_stage:n}),i}const kp=Object.freeze(Object.defineProperty({__proto__:null,advanceBooking:SF,assignRep:a8,bookCallSlot:wF,computeBookingDueAt:z0,createLead:o8,fetchCallAttempts:d8,fetchInstallFlags:u8,fetchLead:k0,fetchLeadActivity:vF,fetchLeads:i8,fetchLeadsByStage:r8,fetchPipelineCounts:c8,fetchReps:T0,logCallAttempt:l8,markLeadOpened:bF,searchTerminalLeads:s8,setSlotAvailability:jF,startChase:p8,updateLead:AF,updateLeadStage:C0},Symbol.toStringTag,{value:"Module"}));async function ba(e,n){if(!n)return null;const{data:r,error:s}=await w.from("addresses").select("*").eq("entity_type",e).eq("entity_id",n).eq("is_primary",!0).maybeSingle();if(s)throw console.error("[addressService] fetchPrimaryAddress error",s),s;return r}async function B_(e,n,r){if(!n)throw new Error("upsertPrimaryAddress: entityId is required");const s=await ba(e,n);if(s){const{data:a,error:l}=await w.from("addresses").update({address_line1:r.address_line1??null,address_line2:r.address_line2??null,city:r.city??null,state:r.state??null,zip:r.zip??null,
644notes:r.notes??s.notes??null}).eq("id",s.id).select("*").single();if(l)throw console.error("[addressService] upsertPrimaryAddress UPDATE error",l),l;return a}const{data:i,error:o}=await w.from("addresses").insert({entity_type:e,entity_id:n,label:"Primary",is_primary:!0,address_line1:r.address_line1??null,address_line2:r.address_line2??null,city:r.city??null,state:r.state??null,zip:r.zip??null,notes:r.notes??null}).select("*").single();if(o)throw console.error("[addressService] upsertPrimaryAddress INSERT error",o),o;return i}const it={all:e=>["leads",e],lists:e=>[...it.all(e),"list",Kt()],list:(e,n)=>[...it.lists(e),n],kanban:e=>[...it.all(e),"kanban",Kt()],detail:(e,n)=>[...it.all(e),"detail",n],activity:(e,n)=>[...it.all(e),"activity",n],calls:(e,n)=>[...it.all(e),"calls",n],reps:e=>["reps",e],counts:e=>["pipeline_counts",e,Kt()],primaryAddr:(e,n)=>[...it.all(e),"primary_address",n],installFlags:e=>["install_flags",e,Kt()]};function kF(e){const{profile:n}=Ee(),r=(n==null?void 0:n.tenant_id)??null;return Ae({queryKey:it.list(r,{stage:e??void 0}),queryFn:()=>i8({stage:e}),enabled:!!r&&!!e,staleTime:2e4})}function CF(){const{profile:e}=Ee(),n=(e==null?void 0:e.tenant_id)??null;return Ae({queryKey:it.kanban(n),queryFn:r8,enabled:!!n,staleTime:2e4,refetchInterval:6e4})}function TF(e){const{profile:n}=Ee(),r=(n==null?void 0:n.tenant_id)??null;return Ae({queryKey:it.primaryAddr(r,e),queryFn:()=>ba("lead",e),enabled:!!r&&!!e})}function zF(e){const{profile:n}=Ee(),r=(n==null?void 0:n.tenant_id)??null;return Ae({queryKey:it.calls(r,e),queryFn:()=>d8(e),enabled:!!r&&!!e})}function h8(){const{profile:e}=Ee(),n=(e==null?void 0:e.tenant_id)??null;return Ae({queryKey:it.reps(n),queryFn:T0,enabled:!!n,staleTime:3e5})}function NF(){const{profile:e}=Ee(),n=(e==null?void 0:e.tenant_id)??null;return Ae({queryKey:it.counts(n),queryFn:c8,enabled:!!n,staleTime:3e4})}function RF(){const{profile:e}=Ee(),n=(e==null?void 0:e.tenant_id)??null;return Ae({queryKey:it.installFlags(n),queryFn:u8,enabled:!!n,staleTime:6e4,refetchInterval:12e4})}function EF(){const e=rt(),{user:n,profile:r}=Ee(),s=(r==null?void 0:r.tenant_id)??null;return _n({mutationFn:i=>o8(i,n.id),onSuccess:()=>{e.invalidateQueries({queryKey:it.all(s)}),e.invalidateQueries({queryKey:it.counts(s)})}})}function PF(){const e=rt(),{user:n,profile:r}=Ee(),s=(r==null?void 0:r.tenant_id)??null;return _n({mutationFn:({leadId:i,repId:o})=>a8(i,o,n.id),onSuccess:i=>{e.invalidateQueries({queryKey:it.kanban(s)}),e.setQueryData(it.detail(s,i.id),i)}})}function qF(){const e=rt(),{user:n,profile:r}=Ee(),s=(r==null?void 0:r.tenant_id)??null;return _n({mutationFn:({leadId:i,outcome:o,notes:a})=>l8(i,n.id,o,a),onSuccess:(i,o)=>{e.invalidateQueries({queryKey:it.calls(s,o.leadId)}),e.invalidateQueries({queryKey:it.activity(s,o.leadId)})}})}function DF(e){const{profile:n}=Ee(),r=(n==null?void 0:n.tenant_id)??null;return Ae({queryKey:["lead_activity_log",r,e],queryFn:()=>qW(e),enabled:!!r&&!!e,staleTime:1e4})}const OF={phone_call:"Phone Call",web_form:"Web Form",referral:"Referral",google_ad:"Google Ad",facebook_ad:"Facebook Ad",door_knock:"Door Knock",event:"Event",other:"Other",email:"Email",text_message:"Text",referral_realtor:"Realtor Referral",referral_friend:"Friend Referral",home_show:"Home Show",nextdoor:"Nextdoor",walk_in:"Walk-In"},IF={hard_water:"Hard Water",iron_rust:"Iron / Rust",sulfur_odor:"Sulfur / Odor",taste_chlorine:"Taste / Chlorine",tds:"TDS",bacteria:"Bacteria",other:"Other",hard_water_scale:"Hard Water / Scale",lead_heavy_metals:"Lead / Heavy Metals",pfas_chemicals:"PFAS / Chemicals",well_water:"Well Water",general_filtration:"General Filtration"};function LF(e){return e?Math.floor((Date.now()-new Date(e).getTime())/864e5):0}function WF(e){return(e||"?").split(" ").map(n=>n[0]).join("").slice(0,2).toUpperCase()}const U_=["#3b82f6","#22c55e","#8b5cf6","#f97316","#14b8a6","#06b6d4","#f43f5e"],$F={reserved:{label:"Schedule",hex:"#22c55e"},not_required:{label:"Schedule",hex:"#22c55e"},short:{label:"Backorder",hex:"#f59e0b"}},MF={quote:"#a78bfa",booking:"#f59e0b"};function FF(e){return e?$F[e]||{label:e,hex:"#64748b"}:null}function BF(e){if(!e)return"";const n=new Date(e);return isNaN(n.getTime())?"":n.toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric"})+", "+n.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit"})}
644function UF(e,n){if(!e)return null;const r=new Date(e).getTime();if(isNaN(r))return null;const s=r-n,i=s<0,o=Math.floor(Math.abs(s)/6e4),a=Math.floor(o/60),l=o%60;let d;if(o<60?d=`${o}m`:a<24?d=l?`${a}h ${l}m`:`${a}h`:d=`${Math.floor(a/24)}d`,i)return{text:`${d} overdue`,color:"#ef4444",overdue:!0,hoursPast:a};const c=s<2*36e5;return{text:`${d} left`,color:c?"#f59e0b":"#64748b",overdue:!1,hoursPast:0}}function Bd({lead:e,onClick:n,now:r,installFlag:s}){const i=e.full_name||`${e.first_name||""} ${e.last_name||""}`.trim()||"Unknown",o=LF(e.updated_at),a=o>=3,l=U_[i.charCodeAt(0)%U_.length],d=e.booking_stage,c=!!d&&zy(d)&&!!e.booking_due_at,f=c?UF(e.booking_due_at,r??Date.now()):null,p=d==="day7"&&!!(f!=null&&f.overdue)&&f.hoursPast>=168,u=d&&MF[tu(d)||"booking"]||"#f59e0b",h=!!e.preferred_slot_at&&!!d&&tu(d)==="booking"&&zy(d),y=FF(s);return t.jsxs(t.Fragment,{children:[t.jsx("style",{children:"@keyframes zenBookingFlash { 0%,100% { opacity: 1 } 50% { opacity: 0.45 } }"}),t.jsxs("div",{onClick:()=>n(e),style:{background:"#1e3448",border:f!=null&&f.overdue?"1px solid #7f1d1d":"1px solid #345570",borderRadius:10,padding:"10px 12px",cursor:"pointer",transition:"all 0.12s",marginBottom:2,boxShadow:"0 1px 3px rgba(0,0,0,0.25)"},onMouseEnter:m=>{const b=m.currentTarget;b.style.borderColor="#0d7ea3",b.style.background="#243d52",b.style.boxShadow="0 2px 8px rgba(13,126,163,0.2)"},onMouseLeave:m=>{const b=m.currentTarget;b.style.borderColor="#345570",b.style.background="#1e3448",b.style.boxShadow="0 1px 3px rgba(0,0,0,0.25)"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:8,marginBottom:6},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[t.jsx("div",{style:{width:28,height:28,borderRadius:"50%",flexShrink:0,background:`${l}25`,border:`1px solid ${l}50`,color:l,fontSize:11,fontWeight:800,display:"flex",alignItems:"center",justifyContent:"center"},children:WF(i)}),t.jsxs("div",{style:{minWidth:0},children:[t.jsx("div",{style:{fontSize:13,fontWeight:600,lineHeight:1.2,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",color:c?"#f59e0b":"#e2e8f0",animation:c?"zenBookingFlash 1.1s ease-in-out infinite":void 0},children:i}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:5,marginTop:1,flexWrap:"wrap"},children:[t.jsx("span",{style:{fontSize:11,color:"#64748b"},children:e.phone}),d==="booked"&&t.jsx("span",{style:{fontSize:9,fontWeight:700,letterSpacing:"0.03em",padding:"2px 6px",borderRadius:4,background:"#22c55e22",color:"#22c55e",border:"1px solid #22c55e55",textTransform:"uppercase"},children:"Booked"}),!e.opened_at&&t.jsx("span",{style:{fontSize:9,fontWeight:800,letterSpacing:"0.05em",padding:"2px 6px",borderRadius:4,background:"#22c55e",color:"#052e16",textTransform:"uppercase",boxShadow:"0 0 6px rgba(34,197,94,0.6)"},children:"New"}),e.is_returning&&t.jsx("span",{title:"Re-inquired via a form â reopened as a new lead",style:{fontSize:9,fontWeight:800,letterSpacing:"0.05em",padding:"2px 6px",borderRadius:4,background:"#f59e0b",color:"#451a03",textTransform:"uppercase",boxShadow:"0 0 6px rgba(245,158,11,0.6)"},children:"Returned"}),e.prior_opt_out&&t.jsx("span",{title:"This number previously opted out of texts â call, do not text",style:{fontSize:9,fontWeight:800,letterSpacing:"0.05em",padding:"2px 6px",borderRadius:4,background:"#ef4444",color:"#450a0a",textTransform:"uppercase",boxShadow:"0 0 6px rgba(239,68,68,0.6)"},children:"DND Prior"})]}),h&&t.jsxs("div",{style:{fontSize:11,color:"#38bdf8",marginTop:2,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:["ð
",BF(e.preferred_slot_at)]}),f&&t.jsxs("div",{style:{fontSize:11,color:f.color,fontWeight:500,marginTop:2,lineHeight:1.3,wordBreak:"break-word"},children:[f.overdue?"â ":"â± ",f.text,p?" - time to move":""]})]})]}),t.jsx("div",{style:{display:"flex",alignItems:"center",gap:4,flexShrink:0},children:a&&t.jsx("span",{style:{fontSize:12},title:`${o} days since last update`,children:"â°"})})]}),c&&t.jsxs("div",{style:{marginBottom:6},children:[t.jsx("span",{style:{fontSize:9,fontWeight:700,letterSpacing:"0.03em",padding:"2px 6px",borderRadius:4,background:u+"22",color:u,border:"1px solid "+u+"55",textTransform:"uppercase"},children:tf[d]||d}
644),p&&t.jsx("span",{title:"7+ days past the Day 7 deadline - decide: work it or mark Cold Lead",style:{marginLeft:5,fontSize:9,fontWeight:800,letterSpacing:"0.03em",padding:"2px 6px",borderRadius:4,background:"#ef4444",color:"#450a0a",textTransform:"uppercase",boxShadow:"0 0 6px rgba(239,68,68,0.6)"},children:"Cold?"})]}),y&&t.jsx("div",{style:{marginBottom:6},children:t.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4,fontSize:9,fontWeight:700,letterSpacing:"0.03em",padding:"2px 6px",borderRadius:4,background:y.hex+"22",color:y.hex,border:"1px solid "+y.hex+"55",textTransform:"uppercase"},title:"Job ready to schedule",children:[t.jsx("span",{style:{fontSize:8},children:"ð§"}),y.label]})}),e.water_concern&&t.jsx("div",{style:{marginBottom:6},children:t.jsx("span",{style:{fontSize:10,background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:4,padding:"2px 6px",color:"#64748b"},children:IF[e.water_concern]||e.water_concern})}),t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[t.jsx("span",{style:{fontSize:11,color:"#475569"},children:OF[e.source]||e.source||""}),t.jsx("span",{style:{fontSize:11,color:a?"#f59e0b":"#475569"},children:o===0?"Today":`${o}d`})]})]})]})}const sf={website_form:"Website Form",phone_call:"Phone Call",email:"Email",walk_in:"Walk-In",referral_realtor:"Referral â Realtor",referral_partner:"Referral â Partner",google_ad:"Google Ad",meta_ad:"Meta Ad",trade_show:"Trade Show",event:"Event"},of={hard_water:"Hard Water / Scale",iron_rust:"Iron / Rust",sulfur_odor:"Sulfur / Odor",taste_chlorine:"Taste / Chlorine",pfas_chemicals:"PFAS / Chemicals",lead_heavy_metals:"Lead / Heavy Metals",well_water:"Well Water Issues",general_filtration:"General Filtration",unknown:"Unknown"},N0={new_lead:"New Lead",qualifying:"Qualifying",qualified:"Qualified",site_visit_scheduled:"Site Visit Scheduled",proposal_in_progress:"Proposal in Progress",quote_sent:"Quote Sent",agreement_signed:"Agreement Signed",won:"Won",lost:"Lost",future_follow_up:"Cold Lead",dnd:"DND",new:"New",site_visit:"Site Visit",negotiating:"Negotiating",agreed:"Agreed",signed:"Signed",install_scheduled:"Install Scheduled",installed:"Installed"},HF={new_lead:"bg-muted/20 text-muted border-muted/30",qualifying:"bg-purple/20 text-purple border-purple/30",qualified:"bg-accent/20 text-accent border-accent/30",site_visit_scheduled:"bg-cyan/20 text-cyan border-cyan/30",proposal_in_progress:"bg-cyan/20 text-cyan border-cyan/30",quote_sent:"bg-amber/20 text-amber border-amber/30",agreement_signed:"bg-green/20 text-green border-green/30",won:"bg-green/20 text-green border-green/30",lost:"bg-red/20 text-red border-red/30",future_follow_up:"bg-purple/20 text-purple border-purple/30",dnd:"bg-muted/20 text-muted border-muted/30",new:"bg-muted/20 text-muted border-muted/30",site_visit:"bg-cyan/20 text-cyan border-cyan/30",negotiating:"bg-cyan/20 text-cyan border-cyan/30",agreed:"bg-green/20 text-green border-green/30",signed:"bg-green/20 text-green border-green/30",install_scheduled:"bg-green/20 text-green border-green/30",installed:"bg-green/20 text-green border-green/30"},VF=Object.entries(sf),ZF=Object.entries(of),Fr=e=>({width:"100%",boxSizing:"border-box",background:"#162232",border:`1px solid ${e?"#ef4444":"#1e3a4f"}`,borderRadius:8,padding:"10px 14px",fontSize:13,color:"#e2e8f0",outline:"none"}),Br={display:"block",fontSize:10,fontWeight:700,color:"#64748b",textTransform:"uppercase",letterSpacing:"0.07em",marginBottom:6};function KF({onClose:e,onCreated:n}){const{role:r}=Ee();rs(r);const{mutateAsync:s,isPending:i}=EF(),{data:o}=h8(),[a,l]=g.useState({full_name:"",phone:"",email:"",address:"",city:"",state:"IN",zip_code:"",source:"phone_call",water_concern:"",assigned_rep_id:"",notes:"",urgent:!1}),[d,c]=g.useState({}),[f,p]=g.useState("");function u(m,b){l(A=>({...A,[m]:b})),d[m]&&c(A=>({...A,[m]:""}))}function h(){const m={};return a.full_name.trim()||(m.full_name="Name is required"),a.phone.trim()?/^\+?[\d\s\-().]{7,}$/.test(a.phone)||(m.phone="Enter a valid phone number"):m.phone="Phone is required",a.source||(m.source="Lead source is required"),
644c(m),Object.keys(m).length===0}async function y(){if(!h())return;p("");const m={full_name:a.full_name,phone:a.phone,source:a.source,...a.email&&{email:a.email},...a.address&&{address:a.address},...a.city&&{city:a.city},...a.state&&{state:a.state},...a.zip_code&&{zip_code:a.zip_code},...a.water_concern&&{water_concern:a.water_concern},...a.assigned_rep_id&&{assigned_rep_id:a.assigned_rep_id},...a.notes&&{notes:a.notes},urgent:a.urgent};try{await s(m),n==null||n(),e()}catch(b){p(b instanceof Error?b.message:"Failed to create lead")}}return t.jsxs("div",{style:{position:"fixed",inset:0,zIndex:50,display:"flex",alignItems:"center",justifyContent:"center",padding:16},children:[t.jsx("div",{style:{position:"absolute",inset:0,background:"rgba(0,0,0,0.65)",backdropFilter:"blur(4px)"},onClick:e}),t.jsxs("div",{style:{position:"relative",background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:20,width:"100%",maxWidth:520,maxHeight:"90vh",display:"flex",flexDirection:"column",boxShadow:"0 24px 64px rgba(0,0,0,0.5)"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"18px 20px",borderBottom:"1px solid #1e3a4f",flexShrink:0},children:[t.jsxs("div",{children:[t.jsx("h2",{style:{color:"#f1f5f9",fontWeight:800,fontSize:17,margin:0},children:"New Lead"}),t.jsx("p",{style:{color:"#64748b",fontSize:12,marginTop:3,marginBottom:0},children:"Fill in the details to add to the pipeline"})]}),t.jsx("button",{onClick:e,style:{color:"#475569",background:"rgba(255,255,255,0.05)",border:"1px solid #1e3a4f",borderRadius:8,width:32,height:32,fontSize:18,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:m=>m.currentTarget.style.color="#f1f5f9",onMouseLeave:m=>m.currentTarget.style.color="#475569",children:"â"})]}),t.jsxs("div",{style:{flex:1,overflowY:"auto",padding:"20px",display:"flex",flexDirection:"column",gap:16},children:[t.jsxs("div",{children:[t.jsxs("label",{style:Br,children:["Full Name ",t.jsx("span",{style:{color:"#f87171"},children:"*"})]}),t.jsx("input",{type:"text",value:a.full_name,onChange:m=>u("full_name",m.target.value),placeholder:"John Smith",style:Fr(!!d.full_name)}),d.full_name&&t.jsx("p",{style:{color:"#f87171",fontSize:11,marginTop:4},children:d.full_name})]}),t.jsxs("div",{children:[t.jsxs("label",{style:Br,children:["Phone ",t.jsx("span",{style:{color:"#f87171"},children:"*"})]}),t.jsx("input",{type:"tel",value:a.phone,onChange:m=>u("phone",m.target.value),placeholder:"(317) 555-0100",style:Fr(!!d.phone)}),d.phone&&t.jsx("p",{style:{color:"#f87171",fontSize:11,marginTop:4},children:d.phone})]}),t.jsxs("div",{children:[t.jsx("label",{style:Br,children:"Email"}),t.jsx("input",{type:"email",value:a.email,onChange:m=>u("email",m.target.value),placeholder:"[email protected]",style:Fr()})]}),t.jsxs("div",{children:[t.jsx("label",{style:Br,children:"Street Address"}),t.jsx("input",{type:"text",value:a.address,onChange:m=>u("address",m.target.value),placeholder:"123 Main St",style:Fr()})]}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 80px 100px",gap:10},children:[t.jsxs("div",{children:[t.jsx("label",{style:Br,children:"City"}),t.jsx("input",{type:"text",value:a.city,onChange:m=>u("city",m.target.value),placeholder:"Indianapolis",style:Fr()})]}),t.jsxs("div",{children:[t.jsx("label",{style:Br,children:"State"}),t.jsx("input",{type:"text",value:a.state,onChange:m=>u("state",m.target.value.toUpperCase()),placeholder:"IN",maxLength:2,style:Fr()})]}),t.jsxs("div",{children:[t.jsx("label",{style:Br,children:"ZIP"}),t.jsx("input",{type:"text",value:a.zip_code,onChange:m=>u("zip_code",m.target.value),placeholder:"46032",maxLength:10,style:Fr()})]})]}),t.jsxs("div",{children:[t.jsxs("label",{style:Br,children:["Lead Source ",t.jsx("span",{style:{color:"#f87171"},children:"*"})]}),t.jsx("select",{value:a.source,onChange:m=>u("source",m.target.value),style:Fr(!!d.source),children:VF.map(([m,b])=>t.jsx("option",{value:m,children:b},m))})]}),t.jsxs("div",{children:[t.jsx("label",{style:Br,children:"Water Concern"}),t.jsxs("select",{value:a.water_concern,onChange:m=>u("water_concern",m.target.value),style:Fr(),children:[t.jsx("option",{value:"",children:"â Select concern â"}),ZF.map(([m,b])=>t.jsx("option",{value:m,children:b},m))]})]}),o&&o.length>0&&t.jsxs("div",{children:[t.jsx("label",{style:Br,children:"Assign Rep"}),t.jsxs("select",{value:a.assigned_rep_id,onChange:m=>u("assigned_rep_id",m.target.value),style:Fr(),children:[t.jsx("option",{value:"",children:"â Unassigned â"}),o.map(m=>t.jsx("option",{value:m.id,children:m.full_name},m.id))]})]}),t.jsxs("div",{children:[t.jsx("label",{style:Br,children:"Notes"}),t.jsx("textarea",{value:a.notes,onChange:m=>u("notes",m.target.value),placeholder:"Any additional context...",rows:3,style:{...Fr(),resize:"vertical"}})]}),t.jsxs("label",{style:{display:"flex",alignItems:"center",gap:12,cursor:"pointer"},children:[t.jsx("div",{onClick:()=>u("urgent",!a.urgent),style:{width:40,height:22,borderRadius:20,background:a.urgent?"#f97316":"#334155",position:"relative",curs
644or:"pointer",transition:"background 0.2s",flexShrink:0},children:t.jsx("div",{style:{position:"absolute",top:3,left:a.urgent?21:3,width:16,height:16,borderRadius:"50%",background:"#fff",transition:"left 0.2s"}})}),t.jsx("span",{style:{fontSize:13,color:"#cbd5e1"},children:"Mark as Urgent"})]}),f&&t.jsx("div",{style:{background:"rgba(239,68,68,0.1)",border:"1px solid rgba(239,68,68,0.3)",borderRadius:8,padding:"10px 14px",fontSize:13,color:"#f87171"},children:f})]}),t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",gap:10,padding:"16px 20px",borderTop:"1px solid #1e3a4f",flexShrink:0},children:[t.jsx("button",{onClick:e,style:{padding:"9px 18px",fontSize:13,color:"#64748b",background:"none",border:"none",cursor:"pointer",fontWeight:500},onMouseEnter:m=>m.currentTarget.style.color="#e2e8f0",onMouseLeave:m=>m.currentTarget.style.color="#64748b",children:"Cancel"}),t.jsx("button",{onClick:y,disabled:i,style:{padding:"9px 22px",fontSize:13,fontWeight:700,background:i?"#0a5a7a":"#0d7ea3",color:"#fff",border:"none",borderRadius:10,cursor:i?"not-allowed":"pointer",opacity:i?.7:1,transition:"background 0.15s"},onMouseEnter:m=>{i||(m.currentTarget.style.background="#0e8fb8")},onMouseLeave:m=>{i||(m.currentTarget.style.background="#0d7ea3")},children:i?"Creating...":"Create Lead"})]})]})]})}const YF="modulepreload",XF=function(e){return"/"+e},H_={},Fo=function(n,r,s){let i=Promise.resolve();if(r&&r.length>0){document.getElementsByTagName("link");const a=document.querySelector("meta[property=csp-nonce]"),l=(a==null?void 0:a.nonce)||(a==null?void 0:a.getAttribute("nonce"));i=Promise.allSettled(r.map(d=>{if(d=XF(d),d in H_)return;H_[d]=!0;const c=d.endsWith(".css"),f=c?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${f}`))return;const p=document.createElement("link");if(p.rel=c?"stylesheet":YF,c||(p.as="script"),p.crossOrigin="",p.href=d,l&&p.setAttribute("nonce",l),document.head.appendChild(p),c)return new Promise((u,h)=>{p.addEventListener("load",u),p.addEventListener("error",()=>h(new Error(`Unable to preload CSS for ${d}`)))})}))}function o(a){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=a,window.dispatchEvent(l),!l.defaultPrevented)throw a}return i.then(a=>{for(const l of a||[])l.status==="rejected"&&o(l.reason);return n().catch(o)})};async function GF(){let e=w.from("customers").select("*").order("created_at",{ascending:!1});const n=Kt();n&&(e=e.eq("branch_id",n));const{data:r,error:s}=await e;if(s)throw new Error(s.message);return r||[]}async function JF(e){const{data:n,error:r}=await w.from("customers").select("*").eq("id",e).single();if(r)throw new Error(r.message);return n}async function f8(e){const{data:n,error:r}=await w.from("installed_systems").select("*, product_catalog!left(category)").eq("customer_id",e).order("install_date",{ascending:!1});if(r)throw new Error(r.message);return n||[]}async function QF(e,n){const{data:r,error:s}=await w.from("installed_systems").update({salt_reminders_enabled:n}).eq("id",e).select().single();if(s)throw new Error(s.message);return r}async function eB(e){return[]}async function tB(e){const{data:n,error:r}=await w.from("contracts").select("*").eq("customer_id",e).order("created_at",{ascending:!1});if(r)throw new Error(r.message);return n||[]}async function nB(e){const{data:n}=await w.from("contracts").select("customer_id").eq("id",e).single();if(!(n!=null&&n.customer_id))return[];const{data:r,error:s}=await w.from("payment_transactions").select("id, amount, status, payment_type, processed_at, created_at").eq("customer_id",n.customer_id).order("created_at",{ascending:!1});return s?[]:(r||[]).map(i=>({...i,payment_date:i.processed_at||i.created_at}))}async function rB(e){const{data:n,error:r}=await w.from("customer_service_plans").select("id, status, price_monthly, plan_id, created_at").eq("customer_id",e).order("created_at",{ascending:!1});return r?[]:n||[]}async function sB(e){return[]}const g8=30;function af(e=0){const n=new Date;n.setDate(n.getDate()+e);const r=String(n.getMonth()+1).padStart(2,"0"),s=String(n.getDate()).padStart(2,"0");return`${n.getFullYear()}-${r}-${s}`}async function iB(e){const{data:n,error:r}=await w.from("customer_service_plans").select("id").eq("customer_id",e).in("status",["active","pending_payment_method"]);if(r)return console.error("fetchServiceScheduleItems: plan lookup failed",r),[];if(!n||n.length===0)return[];const{data:s,error:i}=await w.from("customer_service_plan_components").select("*").in("customer_plan_id",n.map(l=>l.id)).eq("status","active").order("next_due_date",{ascending:!0});if(i)return console.error("fetchServiceScheduleItems: component lookup failed",i),[];const o=af(),a=af(g8);
644return(s||[]).map(l=>{let d="upcoming";return l.next_due_date&&(l.next_due_date<o?d="overdue":l.next_due_date<=a&&(d="due_soon")),{...l,lifecycle_status:l.status,status:d}})}async function oB(e){return[]}async function aB(e){return[]}async function lB(e,n){const r=[w.from("activity_log").select("*, title:description").eq("entity_type","customer").eq("entity_id",e).order("created_at",{ascending:!1}).limit(100)];return n&&r.push(w.from("activity_log").select("*, title:description").eq("entity_type","lead").eq("entity_id",n).order("created_at",{ascending:!1}).limit(100)),(await Promise.all(r)).flatMap(o=>o.error?[]:o.data||[]).sort((o,a)=>new Date(a.created_at).getTime()-new Date(o.created_at).getTime())}async function m8(e){const n=String(e.body||"").trim();if(!n)throw new Error("Message text is required");if(!e.entityId)throw new Error("entityId is required");const s=(e.direction==="outbound"?"SMS sent: ":"SMS received: ")+'"'+n.slice(0,80)+(n.length>80?"...":"")+'"',{data:i,error:o}=await w.from("communications_log").insert({entity_type:e.entityType,entity_id:e.entityId,direction:e.direction,channel:"sms",message:n,created_at:e.occurredAt}).select("id").single();if(o)throw new Error(o.message);try{await EW({entity_type:e.entityType,entity_id:e.entityId,event_type:e.direction==="outbound"?"sms_sent":"sms_received",description:s,actor_id:e.actorId||void 0,actor_name:e.actorName||null,metadata:{channel:"sms",direction:e.direction,body:n,logged_manually:!0},created_at:e.occurredAt})}catch(a){throw i!=null&&i.id&&await w.from("communications_log").delete().eq("id",i.id),new Error((a==null?void 0:a.message)||"Could not save to the activity timeline")}}async function dB(){const{data:e,error:n}=await w.from("customer_service_plans").select("id, customer_id").in("status",["active","pending_payment_method"]);if(n)return console.error("fetchDueServiceItems: plan lookup failed",n),[];if(!e||e.length===0)return[];const{data:r,error:s}=await w.from("customer_service_plan_components").select("*").in("customer_plan_id",e.map(p=>p.id)).eq("status","active").order("next_due_date",{ascending:!0});if(s)return console.error("fetchDueServiceItems: component lookup failed",s),[];if(!r||r.length===0)return[];const i=new Map(e.map(p=>[p.id,p.customer_id])),o=[...new Set(e.map(p=>p.customer_id).filter(Boolean))],{data:a,error:l}=await w.from("customers").select("id, first_name, last_name").in("id",o);l&&console.error("fetchDueServiceItems: customer lookup failed",l);const d=new Map((a||[]).map(p=>[p.id,[p.first_name,p.last_name].filter(Boolean).join(" ")])),c=af(),f=af(g8);return r.map(p=>{let u="upcoming";p.next_due_date&&(p.next_due_date<c?u="overdue":p.next_due_date<=f&&(u="due_soon"));const h=i.get(p.customer_plan_id)??null;return{id:p.id,customer_id:h,customer_name:h&&d.get(h)||null,component_name:p.component_name??null,next_due_date:p.next_due_date??null,fulfillment_type:p.fulfillment_type??null,urgency:u}})}const eg="America/Indiana/Indianapolis";function cB(e){return new Intl.DateTimeFormat("en-CA",{timeZone:eg,year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date(e))}function uB(e){return new Intl.DateTimeFormat("en-US",{timeZone:eg,weekday:"short",month:"short",day:"numeric"}).format(new Date(e))}function V_(e){return new Intl.DateTimeFormat("en-US",{timeZone:eg,hour:"numeric",minute:"2-digit",hour12:!0}).format(new Date(e))}function pB(e){return new Intl.DateTimeFormat("en-US",{timeZone:eg,weekday:"long",month:"long",day:"numeric",hour:"numeric",minute:"2-digit",hour12:!0}).format(new Date(e))}function hB(e,n){const r=new Map,s=(i,o)=>{const a=cB(i);r.has(a)||r.set(a,{key:a,label:uB(i),slots:[]}),r.get(a).slots.push({iso:i,taken:o})};for(const i of e)s(i,!1);for(const i of n)s(i,!0);for(const i of r.values())i.slots.sort((o,a)=>o.iso.localeCompare(a.iso));return Array.from(r.values())}function fB(e){if(!e)return 0;const n=new Date(e);if(isNaN(n.getTime()))return 0;const r=new Date,s=l=>{const d=new Date(l),c=(d.getDay()+6)%7;return d.setDate(d.getDate()-c),d.setHours(0,0,0,0),d},i=s(r).getTime(),o=s(n).getTime(),a=Math.round((o-i)/(7*24*60*60*1e3));return Math.max(0,a)}function gB({leadName:e,currentSlotAt:n,onPicked:r,onCancel:s}){const[i,o]=g.useState(()=>fB(n)),[a,l]=g.useState(!1),[d,c]=g.useState([]),[f,p]=g.useState([]),[u,h]=g.useState(!0),[y,m]=g.useState(null),[b,A]=g.useState(n??null),[v,x]=g.useState("");g.useEffect(()=>{let S=!1;async function T(){h(!0),m(null);try{const{data:{session:L}}=await w.auth.getSession(),E=L==null?void 0:L.access_token;if(!E){m("Not signed in."),h(!1);return}const R=await fetch(`/api/booking/slots?weekOffset=${i}`,{headers:{Authorization:`Bearer ${E}`}}),N=await R.json();if(S)return;if(!R.ok){m(N.error||"Could not load times."),c([]),p([]),h(!1);return}const O=Array.isArray(N.slots)?N.slots:[],z=Array.isArray(N.taken)?N.taken:[];if(O.length===0&&z.length===0&&i===0&&!a&&!n){l(!0),o(1);return}c(O),p(z)}
644catch{S||(m("Could not load times."),c([]),p([]))}finally{S||h(!1)}}return T(),()=>{S=!0}},[i]);const _=g.useMemo(()=>hB(d,f),[d,f]),j=!!b,C=()=>{b&&r(b,v.trim())};return t.jsx("div",{style:{position:"fixed",inset:0,zIndex:1e3,background:"rgba(0,0,0,0.6)",display:"flex",alignItems:"center",justifyContent:"center",padding:16},onClick:s,children:t.jsxs("div",{onClick:S=>S.stopPropagation(),style:{width:"100%",maxWidth:680,maxHeight:"88vh",display:"flex",flexDirection:"column",background:"#0f172a",borderRadius:16,border:"1px solid #334155",overflow:"hidden"},children:[t.jsxs("div",{style:{padding:"16px 20px",borderBottom:"1px solid #1e293b"},children:[t.jsx("div",{style:{fontSize:16,fontWeight:800,color:"#fff"},children:"ð Book a callback"}),t.jsxs("div",{style:{fontSize:13,color:"#94a3b8",marginTop:2},children:[e," · pick a time to call them back",n&&t.jsx("span",{style:{color:"#fbbf24"},children:" · overriding current slot"})]})]}),t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 20px"},children:[t.jsx("button",{onClick:()=>o(S=>Math.max(0,S-1)),disabled:i===0||u,style:{fontSize:13,padding:"4px 12px",borderRadius:8,background:"#1e293b",color:i===0||u?"#475569":"#e2e8f0",border:"1px solid #334155",cursor:i===0||u?"not-allowed":"pointer"},children:"â Prev"}),t.jsx("div",{style:{fontSize:12,color:"#64748b"},children:i===0?"This week":i===1?"Next week":`${i} weeks out`}),t.jsx("button",{onClick:()=>o(S=>S+1),disabled:u,style:{fontSize:13,padding:"4px 12px",borderRadius:8,background:"#1e293b",color:u?"#475569":"#e2e8f0",border:"1px solid #334155",cursor:u?"not-allowed":"pointer"},children:"Next â"})]}),t.jsxs("div",{style:{flex:1,overflowY:"auto",padding:"4px 20px 12px",minHeight:200},children:[u&&t.jsx("div",{style:{textAlign:"center",color:"#64748b",fontSize:13,padding:"40px 0"},children:"Loading open timesâ¦"}),!u&&y&&t.jsx("div",{style:{textAlign:"center",color:"#f87171",fontSize:13,padding:"40px 0"},children:y}),!u&&!y&&_.length===0&&t.jsxs("div",{style:{textAlign:"center",color:"#64748b",fontSize:13,padding:"40px 0"},children:[i===0?"This week is fully booked or already past.":"No open times this week.",t.jsx("div",{style:{marginTop:8},children:t.jsx("button",{onClick:()=>o(S=>S+1),style:{fontSize:13,fontWeight:700,padding:"6px 14px",borderRadius:8,background:"rgba(34,197,94,0.12)",color:"#4ade80",border:"1px solid rgba(34,197,94,0.35)",cursor:"pointer"},children:"Next week â"})})]}),!u&&!y&&_.map(S=>t.jsxs("div",{style:{marginBottom:12},children:[t.jsx("div",{style:{fontSize:12,fontWeight:700,color:"#cbd5e1",marginBottom:6},children:S.label}),t.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(4, 1fr)",gap:6},children:S.slots.map(T=>{const{iso:L,taken:E}=T,R=b===L;return E?t.jsxs("div",{title:"Already booked",style:{fontSize:11,padding:"8px 4px",borderRadius:8,background:"#111827",color:"#475569",border:"1px solid #1f2937",textAlign:"center",cursor:"not-allowed",textDecoration:"line-through"},children:[V_(L),t.jsx("div",{style:{fontSize:9,marginTop:2,textDecoration:"none"},children:"Booked"})]},L):t.jsxs("button",{onClick:()=>A(L),style:{fontSize:11,padding:"8px 4px",borderRadius:8,cursor:"pointer",background:R?"#166534":"#0f2a1a",color:R?"#4ade80":"#86efac",border:`1px solid ${R?"#22c55e":"#1a3a2a"}`,fontWeight:R?700:500,boxShadow:R?"0 0 10px rgba(34,197,94,0.25)":"none"},children:[V_(L),R&&t.jsx("div",{style:{fontSize:9,marginTop:2},children:"â"})]},L)})})]},S.key))]}),t.jsx("div",{style:{padding:"0 20px 12px"},children:t.jsx("input",{type:"text",value:v,onChange:S=>x(S.target.value),placeholder:"Why the callback? (optional â shows on the task)",style:{width:"100%",padding:"8px 12px",borderRadius:8,fontSize:13,background:"#1e293b",color:"#fff",border:"1px solid #334155",outline:"none"}})}),t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 20px",borderTop:"1px solid #1e293b",background:"#0b1324"},children:[t.jsx("div",{style:{fontSize:13},children:b?t.jsxs("span",{style:{color:"#4ade80",fontWeight:700},children:["â ",pB(b)]}):t.jsx("span",{style:{color:"#475569"},children:"Pick a time slot"})}),t.jsxs("div",{style:{display:"flex",gap:10},children:[t.jsx("button",{onClick:s,style:{fontSize:13,padding:"8px 14px",color:"#64748b",background:"none",border:"none",cursor:"pointer"},children:"Cancel"}),t.jsx("button",{onClick:C,disabled:!j,style:{fontSize:13,fontWeight:800,padding:"8px 18px",borderRadius:8,color:"#fff",background:j?"linear-gradient(135deg,#22c55e,#15803d)":"#334155",border:"none",cursor:j?"pointer":"not-allowed",opacity:j?1:.4},children:"Book callback"})]})]})]})})}function Ns({label:e,value:n,onChange:r,placeholder:s,maxLength:i}){return t.jsxs("div",{children:[t.jsx("label",{style:{display:"block",fontSize:11,color:"#64748b",textTransform:"uppercase",letterSpacing:"0.05em",marginBottom:4,fontWeight:600},children:e}),t.jsx("input",{type:"text",value:n,onChange:o=>r(o.target.value),placeholder:s,maxLength:i,style:{width:"100%",background:"#162232",border:"1px solid #1e3a4f",borderRadius:8,color:"#e2e8f0",padding:"8px 12px",fontSize:14,outline:"none",boxSizing:"border-box"}})]})}const Z_={lead:"leads",customer:"customers"};async function mB(e,n){if(e==="customer"){const{data:i,error:o}=await w.from("customers").select("lead_id").eq("id",n).maybeSingle();if(o)throw o;return i!=null&&i.lead_id?{kind:"one",entityType:"lead",entityId:i.lead_id}:{kind:"none"}}const{data:r,error:s}=await w.from("customers").select("id").eq("lead_id",n);if(s)throw s;return!r||r.length===0?{kind:"none"}:r.length>1?{kind:"ambiguous",count:r.length}:{kind:"one",entityType:"customer",entityId:r[0].id}}function x8({entityType:e,entityId:n,initial:r,displayName:s,onClose:i,onSaved:o}){const[a,l]=g.useState(!1),[d,c]=g.useState(null),[f,p]=g.useState(!0),[u,h]=g.useState({first_name:r.first_name??"",last_name:r.last_name??"",phone:r.phone??"",email:r.email??""}),[y,m]=g.useState({address_line1:"",address_line2:"",city:"",state:"",zip:""});g.useEffect(()=>{let _=!1;return p(!0),ba(e,n).then(j=>{_||j&&m({address_line1:j.address_line1??"",address_line2:j.address_line2??"",city:j.city??"",state:j.state??"",zip:j.zip??""})}).catch(j=>{_||c((j==null?void 0:j.message)||"Failed to load address")}).finally(()=>{_||p(!1)}),()=>{_=!0}},[e,n]);const b=u.first_name.trim(),A=u.last_name.trim(),v=b.length>0&&A.length>0;async function x(){if(!v){c("First and last name are required");return}l(!0),c(null);const{error:_}=await w.from(Z_[e]).update({first_name:b,last_name:A,phone:u.phone.trim()||null,email:u.email.trim()||null}).eq("id",n);if(_){c(`Failed to save contact: ${_.message}`),l(!1);return}const j=y.address_line1.trim()||y.address_line2.trim()||y.city.trim()||y.state.trim()||y.zip.trim();if(j)try{await B_(e,n,{address_line1:y.address_line1.trim()||null,address_line2:y.address_line2.trim()||null,city:y.city.trim()||null,state:y.state.trim()||null,zip:y.zip.trim()||null})}catch(S){c(`Contact saved. Address failed: ${(S==null?void 0:S.message)||"unknown error"}`),l(!1),o();return}let C;try{C=await mB(e,n)}catch(S){c(`Saved here. Could not reach the linked record: ${(S==null?void 0:S.message)||"lookup failed"}`),l(!1),o();return}if(C.kind==="ambiguous"){c(`Saved here. ${C.count}
644 linked records found â none updated. Resolve the duplicates first.`),l(!1),o();return}if(C.kind==="one"){const{error:S}=await w.from(Z_[C.entityType]).update({first_name:b,last_name:A,phone:u.phone.trim()||null,email:u.email.trim()||null}).eq("id",C.entityId);if(S){c(`Saved here. The linked ${C.entityType} record was not updated: ${S.message}`),l(!1),o();return}if(j)try{await B_(C.entityType,C.entityId,{address_line1:y.address_line1.trim()||null,address_line2:y.address_line2.trim()||null,city:y.city.trim()||null,state:y.state.trim()||null,zip:y.zip.trim()||null})}catch(T){c(`Saved here. The linked ${C.entityType} address was not updated: ${(T==null?void 0:T.message)||"unknown error"}`),l(!1),o();return}}l(!1),o(),i()}return t.jsx("div",{style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.75)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:60,padding:16},children:t.jsxs("div",{style:{background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:16,width:"100%",maxWidth:500,maxHeight:"90vh",overflowY:"auto"},children:[t.jsxs("div",{style:{padding:"18px 24px",borderBottom:"1px solid #1e3a4f",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[t.jsxs("div",{children:[t.jsx("div",{style:{color:"#e2e8f0",fontWeight:800,fontSize:16},children:"Edit Contact Details"}),s&&t.jsx("div",{style:{color:"#475569",fontSize:12,marginTop:2},children:s})]}),t.jsx("button",{onClick:i,style:{background:"none",border:"none",color:"#64748b",fontSize:20,cursor:"pointer"},children:"Ã"})]}),t.jsxs("div",{style:{padding:"18px 24px",display:"flex",flexDirection:"column",gap:12},children:[t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[t.jsx(Ns,{label:"First Name",value:u.first_name,onChange:_=>h(j=>({...j,first_name:_})),placeholder:"Jane"}),t.jsx(Ns,{label:"Last Name",value:u.last_name,onChange:_=>h(j=>({...j,last_name:_})),placeholder:"Doe"})]}),t.jsx(Ns,{label:"Phone",value:u.phone,onChange:_=>h(j=>({...j,phone:_})),placeholder:"(317) 555-0142"}),t.jsx(Ns,{label:"Email",value:u.email,onChange:_=>h(j=>({...j,email:_})),placeholder:"[email protected]"}),t.jsx("div",{style:{borderTop:"1px solid #1e3a4f",margin:"4px 0 0"}}),t.jsx("div",{style:{fontSize:11,color:"#64748b",textTransform:"uppercase",letterSpacing:"0.05em",fontWeight:700},children:"Service Address"}),f?t.jsx("div",{style:{color:"#475569",fontSize:13,padding:"8px 0"},children:"Loading addressâ¦"}):t.jsxs(t.Fragment,{children:[t.jsx(Ns,{label:"Address Line 1",value:y.address_line1,onChange:_=>m(j=>({...j,address_line1:_})),placeholder:"123 Main St"}),t.jsx(Ns,{label:"Address Line 2",value:y.address_line2,onChange:_=>m(j=>({...j,address_line2:_})),placeholder:"Apt, Suite, etc. (optional)"}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"2fr 1fr 1fr",gap:10},children:[t.jsx(Ns,{label:"City",value:y.city,onChange:_=>m(j=>({...j,city:_})),placeholder:"Indianapolis"}),t.jsx(Ns,{label:"State",value:y.state,onChange:_=>m(j=>({...j,state:_.toUpperCase()})),placeholder:"IN",maxLength:2}),t.jsx(Ns,{label:"ZIP",value:y.zip,onChange:_=>m(j=>({...j,zip:_})),placeholder:"46201"})]})]}),d&&t.jsx("div",{style:{padding:"8px 14px",borderRadius:8,background:"rgba(239,68,68,0.1)",border:"1px solid rgba(239,68,68,0.25)",color:"#f87171",fontSize:13},children:d})]}),t.jsxs("div",{style:{padding:"14px 24px",borderTop:"1px solid #1e3a4f",display:"flex",gap:10,justifyContent:"flex-end"},children:[t.jsx("button",{onClick:i,style:{padding:"8px 16px",fontSize:13,color:"#64748b",background:"none",border:"none",cursor:"pointer"},children:"Cancel"}),t.jsx("button",{onClick:x,disabled:a||f||!v,style:{padding:"9px 22px",borderRadius:8,border:"none",background:a||!v?"#334155":"#0d7ea3",color:"#fff",fontWeight:700,fontSize:14,cursor:a||f||!v?"not-allowed":"pointer",opacity:a||f||!v?.6:1},children:a?"Savingâ¦":"Save Changes"})]})]})})}const K_={company_name:"Water Treatment Company",phone:"",email:"",email_from:"",website:"",address:"",address_line1:"",address_line2:"",city:"",state:"",zip:"",country:"US",tagline:"",logo_url:null,primary_color:"#0d7ea3",slug:"",authorized_signer_name:"",bank_name:"",bank_routing:"",bank_account:"",bank_account_name:"",accounts_email:"",owner_name:"",hearth_apply_url:"",tax_label:"",governing_law_state:"",fullAddress:"",address_line:"",ph
644oneFormatted:"",accountName:""};let Cp=null,Y_=null;function y8(){const{profile:e}=Ee(),n=(e==null?void 0:e.tenant_id)??null,[r,s]=g.useState(Cp??K_);return g.useEffect(()=>{if(n){if(Cp&&Y_===n){s(Cp);return}w.from("tenants").select("company_name, name, phone, email, email_from, website, address_line1, address_line2, city, state, zip, country, tagline, logo_url, primary_color, slug, authorized_signer_name, bank_name, bank_routing, bank_account, bank_account_name, accounts_email, owner_name, hearth_apply_url, tax_label, governing_law_state").eq("id",n).maybeSingle().then(({data:i})=>{if(!i)return;const o=i.company_name||i.name||K_.company_name,a=i.address_line1||i.address||"",l=i.address_line2||"",d=[a,l,i.city,i.state,i.zip].filter(Boolean),c=[a,[i.city,i.state].filter(Boolean).join(", "),i.zip].filter(Boolean).join(", "),f={company_name:o,phone:i.phone||"",email:i.email||"",email_from:i.email_from||i.email||"",website:i.website||"",address:i.address||a,address_line1:a,address_line2:l,city:i.city||"",state:i.state||"",zip:i.zip||"",country:i.country||"US",tagline:i.tagline||"",logo_url:i.logo_url||null,primary_color:i.primary_color||"#0d7ea3",slug:i.slug||"",authorized_signer_name:i.authorized_signer_name||i.owner_name||"",bank_name:i.bank_name||"",bank_routing:i.bank_routing||"",bank_account:i.bank_account||"",bank_account_name:i.bank_account_name||"",accounts_email:i.accounts_email||i.email||"",owner_name:i.owner_name||"",hearth_apply_url:i.hearth_apply_url||"",tax_label:i.tax_label||"",governing_law_state:i.governing_law_state||i.state||"",fullAddress:d.join(", "),address_line:c,phoneFormatted:i.phone||"",accountName:o.toUpperCase()};Cp=f,Y_=n,s(f)})}},[n]),r}const go=` 645 *, 646 assigned_rep:user_profiles!leads_assigned_rep_id_fkey(id, full_name, role) 647`;function xB(e){return N0[e]||e}async function mo(e,n,r){let s=null,i=null;switch(n){case"site_visit_scheduled":s="booking",i="booked";break;case"proposal_in_progress":case"quote_sent":s="quote",i=q_.quote;break;case"agreement_signed":s="quote",i="signed";break;case"lost":case"dnd":case"future_follow_up":s=null,i="dead";break;case"new_lead":case"qualifying":s="booking",i=q_.booking;break;default:return}const o={booking_stage:i,booking_due_at:s?Xk(s,i):null,updated_at:new Date().toISOString()};s&&(o.chase_kind=s);const{error:a}=await w.from("leads").update(o).eq("id",e);if(a){console.error("[syncChase] failed",{leadId:e,toStage:n,error:a.message});return}await Tt({lead_id:e,event_type:"chase_synced",title:`Chase â ${i}`,metadata:{chase_kind:s,chase_stage:i,trigger_stage:n},...r}).catch(()=>{})}async function xl(e,n,r,s){const{data:i,error:o}=await w.from("leads").update({stage:r,stage_entered_at:new Date().toISOString(),stage_changed_at:new Date().toISOString()}).eq("id",e).select(go).single();if(o)throw new Error(o.message);return await Tt({lead_id:e,event_type:"stage_changed",title:`Moved to ${xB(r)}`,metadata:{from_stage:n,to_stage:r},...s,from_stage:n,to_stage:r}),await mo(e,r,s),i}async function yB(e,n,r,s,i){const o=s.trim();if(!o||o.length<5)throw new Error("Lost reason must be at least 5 characters");const{data:a,error:l}=await w.from("leads").update({stage:"lost",stage_entered_at:new Date().toISOString(),stage_changed_at:new Date().toISOString(),lost_reason:o,lost_at:new Date().toISOString(),...(i==null?void 0:i.lost_reason_code)&&{lost_reason_code:i.lost_reason_code},...(i==null?void 0:i.lost_reengage_date)&&{lost_reengage_date:i.lost_reengage_date}}).eq("id",e).select(go).single();if(l)throw new Error(l.message);return await Tt({lead_id:e,event_type:"lead_lost",title:"Marked as Lost",metadata:{from_stage:n,reason:o,...(i==null?void 0:i.lost_reason_code)&&{reason_code:i.lost_reason_code},...(i==null?void 0:i.lost_reengage_date)&&{reengage_date:i.lost_reengage_date}},...r,from_stage:n,to_stage:"lost"}),await mo(e,"lost",r),a}async function X_(e,n,r,s,i){if(!s)throw new Error("Follow-up date is required");const o=new Date(s);if(isNaN(o.getTime()))throw new Error("Invalid follow-up date");const a=j0(new Date),l=Jf(a.year,a.month,a.day,0,0);if(o<l)throw new Error("Follow-up date must be today or later");const{data:d,error:c}=await w.from("leads").update({stage:"future_follow_up",stage_entered_at:new Date().toISOString(),stage_changed_at:new Date().toISOString(),followup_date:s,followup_notes:(i==null?void 0:i.trim())||null}).eq("id",e).select(go).single();if(c)throw new Error(c.message);return await Tt({lead_id:e,event_type:"lead_followup",title:`Scheduled follow-up: ${s}`,metadata:{from_stage:n,followup_date:s,followup_notes:(i==null?void 0:i.trim())||null},...r,from_stage:n,to_stage:"future_follow_up"}),await mo(e,"future_follow_up",r),d}
647async function bB(e,n,r){const{data:s,error:i}=await w.from("leads").update({stage:"dnd",stage_entered_at:new Date().toISOString(),stage_changed_at:new Date().toISOString(),dnd_at:new Date().toISOString()}).eq("id",e).select(go).single();if(i)throw new Error(i.message);return await Tt({lead_id:e,event_type:"lead_dnd",title:"Marked as Do Not Disturb",metadata:{previous_stage:n},...r,from_stage:n,to_stage:"dnd"}),await mo(e,"dnd",r),s}async function AB(e,n,r,s){var a,l,d;if(!s.quote_total||s.quote_total<=0)throw new Error("Quote total must be greater than 0");if(!((a=s.signed_by)!=null&&a.trim()))throw new Error("Signed by name is required");if(s.payment_method==="financing"&&!((l=s.financing_provider)!=null&&l.trim()))throw new Error("Financing provider is required when payment method is financing");if(s.payment_method==="rental"){if(!s.rental_monthly_amount||s.rental_monthly_amount<=0)throw new Error("Monthly rental amount is required");if(!s.rental_term_months||s.rental_term_months<=0)throw new Error("Rental term (months) is required")}const{data:i,error:o}=await w.from("leads").update({stage:"agreement_signed",stage_entered_at:new Date().toISOString(),stage_changed_at:new Date().toISOString(),quote_total:s.quote_total,signed_at:new Date().toISOString(),signed_by:s.signed_by.trim(),deposit_amount:s.deposit_amount||null,payment_method:s.payment_method,financing_provider:((d=s.financing_provider)==null?void 0:d.trim())||null,agreement_file_url:s.agreement_file_url||null,has_signature:!0,rental_monthly_amount:s.rental_monthly_amount||null,rental_term_months:s.rental_term_months||null,install_preference:s.install_preference||null,install_preferred_date:s.install_preferred_date||null}).eq("id",e).select(go).single();if(o)throw new Error(o.message);return await Tt({lead_id:e,event_type:"agreement_signed",title:s.payment_method==="rental"?`Rental agreement signed â $${s.rental_monthly_amount}/mo à ${s.rental_term_months} months`:`Agreement signed â $${s.quote_total.toLocaleString()}`,metadata:{quote_total:s.quote_total,deposit_amount:s.deposit_amount||null,payment_method:s.payment_method,financing_provider:s.financing_provider||null,rental_monthly_amount:s.rental_monthly_amount||null,rental_term_months:s.rental_term_months||null,signed_by:s.signed_by.trim()},...r,from_stage:n,to_stage:"agreement_signed"}),await mo(e,"agreement_signed",r),i}async function vB(e,n,r){const{data:s,error:i}=await w.from("leads").update({stage:"new_lead",stage_entered_at:new Date().toISOString(),stage_changed_at:new Date().toISOString(),lost_reason:null,lost_at:null,lost_reason_code:null,lost_reengage_date:null}).eq("id",e).select(go).single();if(i)throw new Error(i.message);return await Tt({lead_id:e,event_type:"stage_changed",title:"Reopened from Lost",metadata:{from_stage:"lost",to_stage:"new_lead",cleared_fields:["lost_reason","lost_at","lost_reason_code","lost_reengage_date"],previous_lost_reason:n.lost_reason||void 0},...r,from_stage:"lost",to_stage:"new_lead"}),await mo(e,"new_lead",r),s}async function _B(e,n){const{data:r,error:s}=await w.from("leads").update({stage:"new_lead",stage_entered_at:new Date().toISOString(),stage_changed_at:new Date().toISOString(),dnd_at:null}).eq("id",e).select(go).single();if(s)throw new Error(s.message);return await Tt({lead_id:e,event_type:"stage_changed",title:"Reopened from DND",metadata:{from_stage:"dnd",to_stage:"new_lead",cleared_fields:["dnd_at"]},...n,from_stage:"dnd",to_stage:"new_lead"}),await mo(e,"new_lead",n),r}async function G_(e,n,r){const{data:s,error:i}=await w.from("leads").update({stage:"qualifying",stage_entered_at:new Date().toISOString(),stage_changed_at:new Date().toISOString(),followup_date:null,followup_notes:null}).eq("id",e).select(go).single();if(i)throw new Error(i.message);return await Tt({lead_id:e,event_type:"stage_changed",title:"Reopened from Follow-Up",metadata:{from_stage:"future_follow_up",to_stage:"qualifying",cleared_fields:["followup_date","followup_notes"],previous_followup_date:n.followup_date||void 0,previous_followup_notes:n.followup_notes||void 0}
647,...r,from_stage:"future_follow_up",to_stage:"qualifying"}),await mo(e,"qualifying",r),s}const J_=[{value:"price_too_high",label:"Price Too High",description:"Customer indicated the quoted price was beyond their budget or expectations.",requiresText:!1,requiresDate:!1,optionalText:!0,optionalTextPlaceholder:"Any additional context? (optional)",autoMove:!1,note:null},{value:"went_with_competitor",label:"Went With Competitor",description:"Customer has chosen an alternative supplier or product.",requiresText:!1,requiresDate:!1,optionalText:!0,optionalTextPlaceholder:"Competitor name if known (optional â helps competitive analysis)",autoMove:!1,note:null},{value:"finance_declined",label:"Finance Declined",description:"Hearth finance application was declined and customer cannot proceed.",requiresText:!1,requiresDate:!1,optionalText:!1,optionalTextPlaceholder:null,autoMove:!1,note:"Admin may present alternative payment options (buy outright / rental)."},{value:"no_response",label:"No Response After Follow-ups",description:"Customer did not respond after full contact sequence and follow-up emails.",requiresText:!1,requiresDate:!1,optionalText:!1,optionalTextPlaceholder:null,autoMove:!0,note:"Lead will be moved to Future Follow-Up automatically for re-engagement."},{value:"deferred",label:"Deferred / Timing Not Right",description:"Customer is interested but not ready to proceed at this time.",requiresText:!1,requiresDate:!0,optionalText:!1,optionalTextPlaceholder:null,autoMove:!0,note:"Lead will be auto-moved to Future Follow-Up on the re-engage date you set."},{value:"other",label:"Other",description:"Reason does not fit any of the above categories.",requiresText:!0,requiresDate:!1,optionalText:!1,optionalTextPlaceholder:"Required â describe the reason clearly",autoMove:!1,note:"Admin will review periodically."}];function jB({onSubmit:e,onCancel:n,isPending:r=!1}){const[s,i]=g.useState(""),[o,a]=g.useState(""),[l,d]=g.useState(""),[c,f]=g.useState({}),p=J_.find(v=>v.value===s)??null,u=new Date;u.setDate(u.getDate()+1);const h=u.toISOString().split("T")[0];function y(){const v={};return s||(v.code="Please select a reason"),p!=null&&p.requiresText&&o.trim().length<5&&(v.text="Required â please describe the reason (at least 5 characters)"),p!=null&&p.requiresDate&&!l&&(v.date="Re-engage date is required for this reason code"),p!=null&&p.requiresDate&&l&&l<h&&(v.date="Re-engage date must be in the future"),f(v),Object.keys(v).length===0}function m(){!y()||!p||e({reasonCode:p.value,reasonLabel:p.label,freeText:o.trim()||null,reEngageDate:l||null,autoMoveToFutureFollowUp:p.autoMove})}const b={width:"100%",boxSizing:"border-box",background:"rgba(255,255,255,0.05)",border:"1px solid #1e3a4f",borderRadius:10,padding:"9px 14px",color:"#e2e8f0",fontSize:13,outline:"none",fontFamily:"inherit"},A={...b,border:"1px solid rgba(248,113,113,0.6)"};return t.jsxs("div",{style:{position:"fixed",inset:0,zIndex:50,display:"flex",alignItems:"center",justifyContent:"center",padding:16},children:[t.jsx("div",{style:{position:"absolute",inset:0,background:"rgba(0,0,0,0.65)"},onClick:n}),t.jsxs("div",{style:{position:"relative",width:"100%",maxWidth:440,background:"#162232",border:"1px solid #1e3a4f",borderRadius:20,padding:"24px 24px 20px",boxShadow:"0 24px 60px rgba(0,0,0,0.5)"},children:[t.jsxs("div",{style:{marginBottom:20},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,marginBottom:4},children:[t.jsx("span",{style:{fontSize:20},children:"â"}),t.jsx("h3",{style:{color:"#e2e8f0",fontWeight:800,fontSize:16,margin:0},children:"Mark as Lost"})]}),t.jsx("p",{style:{color:"#64748b",fontSize:12,margin:0},children:"Select the reason this lead is being lost. This feeds directly into pipeline reporting."})]}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:14},children:[t.jsxs("div",{children:[t.jsxs("label",{style:{display:"block",fontSize:11,fontWeight:700,color:"#64748b",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:8},children:["Lost Reason ",t.jsx("span",{style:{color:"#f87171"},children:"*"})]}),t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:J_.map(v=>{const x=s===v.value;return t.jsx("button",{onClick:()=>{i(v.value),a(""),d(""),f({})},style:{width:"100%",textAlign:"left",cursor:"pointer",padding:"10px 14px",borderRadius:10,background:x?"rgba(248,113,113,0.1)":"rgba(255,255,255,0.03)",border:`1px solid ${x?"rgba(248,113,113,0.4)":"rgba(255,255,255,0.06)"}`,transition:"all 0.12s"},children:t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[t.jsx("div",{style:{width:16,height:16,borderRadius:"50%",flexShrink:0,border:`2px solid ${x?"#f87171":"#334155"}`,background:x?"#f87171":"transparent",display:"flex",alignItems:"center",justifyContent:"center",transition:"all 0.12s"},children:x&&t.jsx("div",{style:{width:6,height:6,borderRadius:"50%",background:"#fff"}})}),t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexWrap:"wrap"},children:[t.jsx("span",{style:{fontSize:13,fontWeight:600,color:x?"#f87171":"#e2e8f0"},children:v.label}),v.requiresText&&t.jsx("span",{style:{fontSize:9,padding:"1px 6px",borderRadius:8,background:"rgba(248,113,113,0.15)",color:"#f87171",fontWeight:700,textTransform:"uppercase",letterSpacing:"0.05em"},children:"Requires note"}),v.requiresDate&&t.jsx("span",{style:{fontSize:9,padding:"1px 6px",borderRadius:8,background:"rgba(251,191,36,0.15)",color:"#fbbf24",fontWeight:700,textTransform:"uppercase",letterSpacing:"0.05em"},children:"Requires date"}),v.autoMove&&t.jsx("span",{style:{fontSize:9,padding:"1px 6px",borderRadius:8,background:"rgba(167,139,250,0.15)",color:"#a78bfa",fontWeight:700,textTransform:"uppercase",letterSpacing:"0.05em"},children:"Auto-moves"})]}),t.jsx("div",{style:{fontSize:11,color:"#475569",marginTop:2,lineHeight:1.4},children:v.description})]})]})},v.value)})}),c.code&&t.jsx("p",{style:{fontSize:11,color:"#f87171",marginTop:6},children:c.code})]}),p&&(p.optionalText&&!p.requiresText?t.jsxs("div",{children:[t.jsxs("label",{style:{display:"block",fontSize:11,fontWeight:700,color:"#64748b",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:6},children:["Additional Context ",t.jsx("span",{style:{color:"#334155"},children:"(optional)"})]}),t.jsx("input",{type:"text",value:o,onChange:v=>a(v.target.value),placeholder:p.optionalTextPlaceholder??"",style:b})]}):p.requiresText?t.jsxs("div",{children:[t.jsxs("label",{style:{display:"block",fontSize:11,fontWeight:700,color:"#64748b",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:6},children:["Reason Description ",t.jsx("span",{style:{color:"#f87171"},children:"* Required"})]}),t.jsx("textarea",{value:o,onChange:v=>{a(v.target.value),f(x=>({...x,text:""}))},placeholder:p.optionalTextPlaceholder??"Describe the reason clearly...",rows:3,style:{...c.text?A:b,resize:"none"},autoFocus:!0}),c.text?t.jsx("p",{style:{fontSize:11,color:"#f87171",marginTop:4},children:c.text}):t.jsxs("p",{style:{fontSize:11,color:"#64748b",marginTop:4},children:[o.trim().length,"/5 minimum characters"]})]}):null),(p==null?void 0:p.requiresDate)&&t.jsxs("div",{children:[t.jsxs("label",{style:{display:"block",fontSize:11,fontWeight:700,color:"#64748b",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:6},children:["Re-Engage Date ",t.jsx("span",{style:{color:"#f87171"},children:"* Required"})]}),t.jsx("input",{type:"date",value:l,min:h,onChange:v=>{d(v.target.value),f(x=>({...x,date:""}))},style:c.date?A:b}),c.date?t.jsx("p",{style:{fontSize:11,color:"#f87171",marginTop:4},children:c.date}):t.jsx("p",{style:{fontSize:11,color:"#64748b",marginTop:4},children:"Lead will be auto-moved to Future Follow-Up on this date and a reminder task will be created for the rep."})]}),(p==null?void 0:p.note)&&t.jsxs("div",{style:{background:p.autoMove?"rgba(167,139,250,0.08)":"rgba(13,126,163,0.08)",border:`1px solid ${p.autoMove?"rgba(167,139,250,0.2)":"rgba(13,126,163,0.2)"}`,borderRadius:10,padding:"8px 12px",display:"flex",gap:8,alignItems:"flex-start"},children:[t.jsx("span",{style:{fontSize:14,flexShrink:0},children:p.autoMove?"â¹ï¸":"ð¡"}),t.jsx("p",{style:{fontSize:12,color:"#94a3b8",margin:0,lineHeight:1.5},children:p.note})]})]}),t.jsxs("div",{style:{display:"flex",gap:10,marginTop:20},children:[t.jsx("button",{onClick:n,style:{flex:1,padding:"10px 0",borderRadius:10,fontSize:13,color:"#64748b",background:"rgba(255,255,255,0.04)",border:"1px solid #1e3a4f",cursor:"pointer"},children:"Cancel"}),t.jsx("button",{onClick:m,disabled:r||!s,style:{flex:1,padding:"10px 0",borderRadius:10,fontSize:13,fontWeight:700,color:"#fff",background:r||!s?"rgba(248,113,113,0.3)":"linear-gradient(135deg, #ef4444, #dc2626)",border:"none",cursor:r||!s?"not-allowed":"pointer",opacity:r?.7:1},children:r?"Saving...":"Mark Lost"})]})]})]})}const wB=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],SB=["January","February","March","April","May","June","July","August","September","October","November","December"];function kB(e,n){return new Date(e,n+1,0).getDate()}function CB(e,n){return new Date(e,n,1).getDay()}function Am(e,n,r){return`${e}-${String(n+1).padStart(2,"0")}-${String(r).padStart(2,"0")}`}function TB(e){if(!e)return"";const[n,r,s]=e.split("-").map(Number);return new Date(n,r-1,s).toLocaleDateString("en-US",{weekday:"long",month:"long",day:"numeric",year:"numeric"})}function zB({onSubmit:e,onCancel:n,isPending:r}){const s=new Date,i=Am(s.getFullYear(),s.getMonth(),s.getDate()),[o,a]=g.useState(s.getFullYear()),[l,d]=g.useState(s.getMonth()),[c,f]=g.useState(""),[p,u]=g.useState("09:00"),[h,y]=g.useState("");function m(){l===0?(d(11),a(C=>C-1)):d(C=>C-1)}function b(){l===11?(d(0),a(C=>C+1)):d(C=>C+1)}const A=kB(o,l),v=CB(o,l),x=[...Array(v).fill(null),...Array.from({length:A},(C,S)=>S+1)];for(;x.length%7!==0;)x.push(null);function _(){if(!c||!p)return;const[C,S,T]=c.split("-").map(Number),[L,E]=p.split(":").map(Number);
647e(Jf(C,S,T,L,E).toISOString(),h.trim()||void 0)}function j(C){const S=new Date;S.setDate(S.getDate()+C);const T=Am(S.getFullYear(),S.getMonth(),S.getDate());f(T),a(S.getFullYear()),d(S.getMonth())}return t.jsx("div",{className:"absolute inset-0 bg-black/60 flex items-center justify-center p-4 z-20",children:t.jsxs("div",{className:"bg-card border border-border rounded-2xl w-full max-w-sm shadow-2xl overflow-hidden",children:[t.jsxs("div",{style:{background:"#162232",padding:"16px 20px",borderBottom:"1px solid #1e3a4f"},children:[t.jsx("div",{style:{color:"#e2e8f0",fontWeight:700,fontSize:15},children:"ð
Mark as Cold Lead"}),t.jsx("div",{style:{color:"#64748b",fontSize:12,marginTop:2},children:"Pick a date to revisit this lead"})]}),t.jsxs("div",{style:{padding:"16px 20px"},children:[t.jsx("div",{style:{display:"flex",gap:6,marginBottom:14,flexWrap:"wrap"},children:[{label:"Tomorrow",days:1},{label:"3 Days",days:3},{label:"1 Week",days:7},{label:"2 Weeks",days:14},{label:"1 Month",days:30}].map(C=>t.jsx("button",{onClick:()=>j(C.days),style:{padding:"4px 10px",borderRadius:8,fontSize:11,fontWeight:600,cursor:"pointer",border:"1px solid rgba(96,165,250,0.3)",background:"rgba(96,165,250,0.08)",color:"#60a5fa",transition:"all 0.15s"},children:C.label},C.label))}),t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:10},children:[t.jsx("button",{onClick:m,style:{background:"none",border:"none",color:"#64748b",cursor:"pointer",fontSize:18,padding:"0 4px",lineHeight:1},children:"â¹"}),t.jsxs("div",{style:{color:"#e2e8f0",fontWeight:700,fontSize:13},children:[SB[l]," ",o]}),t.jsx("button",{onClick:b,style:{background:"none",border:"none",color:"#64748b",cursor:"pointer",fontSize:18,padding:"0 4px",lineHeight:1},children:"âº"})]}),t.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(7, 1fr)",marginBottom:4},children:wB.map(C=>t.jsx("div",{style:{textAlign:"center",fontSize:10,fontWeight:700,color:"#475569",padding:"2px 0"},children:C},C))}),t.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(7, 1fr)",gap:2},children:x.map((C,S)=>{if(!C)return t.jsx("div",{},S);const T=Am(o,l,C),L=T<i,E=T===i,R=T===c;return t.jsx("button",{onClick:()=>!L&&f(T),disabled:L,style:{padding:"6px 2px",borderRadius:7,fontSize:12,fontWeight:R?700:400,cursor:L?"not-allowed":"pointer",border:"none",background:R?"#0d7ea3":E?"rgba(96,165,250,0.15)":"transparent",color:R?"#fff":L?"#334155":E?"#60a5fa":"#e2e8f0",outline:E&&!R?"1px solid rgba(96,165,250,0.4)":"none",transition:"all 0.1s"},onMouseEnter:N=>{!L&&!R&&(N.currentTarget.style.background="rgba(255,255,255,0.07)")},onMouseLeave:N=>{R||(N.currentTarget.style.background=E?"rgba(96,165,250,0.15)":"transparent")},children:C},S)})}),c&&t.jsxs("div",{style:{marginTop:12,padding:"8px 12px",background:"rgba(13,126,163,0.12)",border:"1px solid rgba(13,126,163,0.3)",borderRadius:8,fontSize:12,color:"#38bdf8",fontWeight:600},children:["â ",TB(c)]}),t.jsxs("div",{style:{marginTop:12},children:[t.jsx("label",{style:{display:"block",fontSize:11,fontWeight:700,color:"#64748b",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:6},children:"Time (Indiana)"}),t.jsx("input",{type:"time",value:p,onChange:C=>u(C.target.value),style:{colorScheme:"dark",width:"100%",background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:8,color:"#e2e8f0",padding:"8px 10px",fontSize:12,outline:"none",boxSizing:"border-box",fontFamily:"inherit"}})]}),t.jsxs("div",{style:{marginTop:12},children:[t.jsx("label",{style:{display:"block",fontSize:11,fontWeight:700,color:"#64748b",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:6},children:"Notes (optional)"}),t.jsx("textarea",{value:h,onChange:C=>y(C.target.value),placeholder:"Why are we following up? Any context...",rows:2,style:{width:"100%",background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:8,color:"#e2e8f0",padding:"8px 10px",fontSize:12,outline:"none",resize:"none",boxSizing:"border-box",fontFamily:"inherit"}})]}),t.jsxs("div",{style:{display:"flex",gap:10,marginTop:14},children:[t.jsx("button",{onClick:n,style:{flex:1,padding:"9px 0",borderRadius:9,border:"1px solid #1e3a4f",background:"transparent",color:"#64748b",fontSize:13,cursor:"pointer"},children:"Cancel"}),t.jsx("button",{onClick:_,disabled:!c||!p||r,style:{flex:1,padding:"9px 0",borderRadius:9,border:"none",background:c?"#0d7ea3":"#334155",color:"#fff",fontWeight:700,fontSize:13,cursor:c?"pointer":"not-allowed",opacity:r?.6:1},children:r?"Savingâ¦":"Mark Cold"})]})]})]})})}const NB=[{value:"cash",label:"Cash"},{value:"check",label:"Check"},{value:"card",label:"Card"},{value:"financing",label:"Financing"},{value:"rental",label:"Rental"}],RB=[{value:"asap",label:"ASAP"},{value:"specific_date",label:"Specific Date"},{value:"flexible",label:"Flexible"}];function EB({onSubmit:e,onCancel:n,isPending:r=!1}){const[s,i]=g.useState({quote_total:"",signed_by:"",deposit_amount:"",payment_method:"",financing_provider:"",rental_monthly_amount:"",rental_term_months:"60",install_preference:"",install_preferred_date:""}),[o,a]=g.useState({});function l(u,h){i(y=>({...y,[u]:h})),o[u]&&a(y=>({...y,[u]:""}))}const d=s.payment_method==="rental";function c(){const u={};if(d){const h=parseFloat(s.rental_monthly_amount);(!s.rental_monthly_amount||isNaN(h)||h<=0)&&(u.rental_monthly_amount="Must be a positive number");const y=parseInt(s.rental_term_months);(!s.rental_term_months||isNaN(y)||y<=0)&&(u.rental_term_months="Must be a positive number")}else{const h=parseFloat(s.quote_total);(!s.quote_total||isNaN(h)||h<=0)&&(u.quote_total="Must be a positive number")}return s.signed_by.trim()||(u.signed_by="Required"),s.payment_method||(u.payment_method="Select a payment method"),s.payment_method==="financing"&&!s.financing_provider.trim()&&(u.financing_provider="Required when financing"),s.install_preference==="specific_date"&&!s.install_preferred_date&&(u.install_preferred_date="Select a date"),a(u),Object.keys(u).length===0}function f(){if(!c())return;let u;d?u=parseFloat(s.rental_monthly_amount)*parseInt(s.rental_term_months):u=parseFloat(s.quote_total),e({quote_total:u,signed_by:s.signed_by.trim(),deposit_amount:s.deposit_amount?parseFloat(s.deposit_amount):void 0,payment_method:s.payment_method,financing_provider:s.financing_provider.trim()||void 0,rental_monthly_amount:d?parseFloat(s.rental_monthly_amount):void 0,rental_term_months:d?parseInt(s.rental_term_months):void 0,install_preference:s.install_preference||void 0,install_preferred_date:s.install_preferred_date||void 0})}const p=u=>`w-full bg-surface border rounded-lg px-3 py-2.5 text-sm text-slate-200 placeholder-muted focus:outline-none focus:border-accent transition-colors ${o[u]?"border-red-500":"border-border"}`;return t.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4",children:[t.jsx("div",{className:"absolute inset-0 bg-black/60",onClick:n}),t.jsxs("div",{className:"relative bg-card border border-border rounded-2xl w-full max-w-md max-h-[90vh] overflow-y-auto p-5 shadow-2xl",children:[t.jsx("h3",{className:"font-bold text-white mb-1",children:"Mark Agreement Signed"}),t.jsx("p",{className:"text-xs text-muted mb-4",children:"Enter agreement details to move this lead forward."}),t.jsxs("div",{className:"space-y-3",children:[t.jsxs("div",{children:[t.jsxs("label",{className:"block text-xs font-semibold text-muted uppercase tracking-wide mb-1.5",children:["Payment Method ",t.jsx("span",{className:"text-red-400",children:"*"})]}
647),t.jsx("div",{className:"grid grid-cols-5 gap-1.5",children:NB.map(u=>t.jsx("button",{type:"button",onClick:()=>l("payment_method",u.value),className:`py-2 text-xs font-semibold rounded-lg border transition-colors ${s.payment_method===u.value?u.value==="rental"?"bg-amber-500/20 text-amber-400 border-amber-500/50":"bg-accent/20 text-accent border-accent/50":"bg-surface text-muted border-border hover:border-muted"}`,children:u.label},u.value))}),o.payment_method&&t.jsx("p",{className:"text-xs text-red-400 mt-1",children:o.payment_method})]}),d&&t.jsxs("div",{className:"rounded-lg p-3 space-y-3",style:{backgroundColor:"rgba(245,158,11,0.06)",border:"1px solid rgba(245,158,11,0.2)"},children:[t.jsx("div",{className:"text-xs font-bold uppercase tracking-wide",style:{color:"#fbbf24"},children:"Rental Terms"}),t.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[t.jsxs("div",{children:[t.jsxs("label",{className:"block text-xs font-semibold text-muted uppercase tracking-wide mb-1",children:["Monthly Amount ",t.jsx("span",{className:"text-red-400",children:"*"})]}),t.jsxs("div",{className:"relative",children:[t.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted text-sm",children:"$"}),t.jsx("input",{type:"number",step:"0.01",min:"0",value:s.rental_monthly_amount,onChange:u=>l("rental_monthly_amount",u.target.value),placeholder:"49.99",className:`${p("rental_monthly_amount")} pl-7`})]}),o.rental_monthly_amount&&t.jsx("p",{className:"text-xs text-red-400 mt-1",children:o.rental_monthly_amount})]}),t.jsxs("div",{children:[t.jsxs("label",{className:"block text-xs font-semibold text-muted uppercase tracking-wide mb-1",children:["Term (months) ",t.jsx("span",{className:"text-red-400",children:"*"})]}),t.jsx("input",{type:"number",min:"1",value:s.rental_term_months,onChange:u=>l("rental_term_months",u.target.value),placeholder:"60",className:p("rental_term_months")}),o.rental_term_months&&t.jsx("p",{className:"text-xs text-red-400 mt-1",children:o.rental_term_months})]})]}),s.rental_monthly_amount&&s.rental_term_months&&t.jsxs("div",{className:"text-xs text-muted",children:["Total contract value: ",t.jsxs("span",{className:"text-white font-semibold",children:["$",(parseFloat(s.rental_monthly_amount||"0")*parseInt(s.rental_term_months||"0")).toLocaleString("en-US",{minimumFractionDigits:2})]})]})]}),!d&&t.jsxs("div",{children:[t.jsxs("label",{className:"block text-xs font-semibold text-muted uppercase tracking-wide mb-1.5",children:["Quote Total ",t.jsx("span",{className:"text-red-400",children:"*"})]}),t.jsxs("div",{className:"relative",children:[t.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted text-sm",children:"$"}),t.jsx("input",{type:"number",step:"0.01",min:"0",value:s.quote_total,onChange:u=>l("quote_total",u.target.value),placeholder:"0.00",className:`${p("quote_total")} pl-7`,autoFocus:!0})]}),o.quote_total&&t.jsx("p",{className:"text-xs text-red-400 mt-1",children:o.quote_total})]}),t.jsxs("div",{children:[t.jsxs("label",{className:"block text-xs font-semibold text-muted uppercase tracking-wide mb-1.5",children:["Signed By ",t.jsx("span",{className:"text-red-400",children:"*"})]}),t.jsx("input",{type:"text",value:s.signed_by,onChange:u=>l("signed_by",u.target.value),placeholder:"Customer name",className:p("signed_by")}),o.signed_by&&t.jsx("p",{className:"text-xs text-red-400 mt-1",children:o.signed_by})]}),!d&&t.jsxs("div",{children:[t.jsx("label",{className:"block text-xs font-semibold text-muted uppercase tracking-wide mb-1.5",children:"Deposit Amount"}),t.jsxs("div",{className:"relative",children:[t.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted text-sm",children:"$"}),t.jsx("input",{type:"number",step:"0.01",min:"0",value:s.deposit_amount,onChange:u=>l("deposit_amount",u.target.value),placeholder:"0.00",className:`${p("deposit_amount")} pl-7`})]})]}),s.payment_method==="financing"&&t.jsxs("div",{children:[t.jsxs("label",{className:"block text-xs font-semibold text-muted uppercase tracking-wide mb-1.5",children:["Financing Provider ",t.jsx("span",{className:"text-red-400",children:"*"})]}
647),t.jsx("input",{type:"text",value:s.financing_provider,onChange:u=>l("financing_provider",u.target.value),placeholder:"e.g., GreenSky, Synchrony...",className:p("financing_provider")}),o.financing_provider&&t.jsx("p",{className:"text-xs text-red-400 mt-1",children:o.financing_provider})]}),t.jsxs("div",{children:[t.jsx("label",{className:"block text-xs font-semibold text-muted uppercase tracking-wide mb-1.5",children:"Install Preference"}),t.jsx("div",{className:"grid grid-cols-3 gap-2",children:RB.map(u=>t.jsx("button",{type:"button",onClick:()=>l("install_preference",u.value),className:`py-2 text-xs font-semibold rounded-lg border transition-colors ${s.install_preference===u.value?"bg-green/20 text-green border-green/50":"bg-surface text-muted border-border hover:border-muted"}`,children:u.label},u.value))})]}),s.install_preference==="specific_date"&&t.jsxs("div",{children:[t.jsxs("label",{className:"block text-xs font-semibold text-muted uppercase tracking-wide mb-1.5",children:["Preferred Install Date ",t.jsx("span",{className:"text-red-400",children:"*"})]}),t.jsx("input",{type:"date",value:s.install_preferred_date,min:new Date().toISOString().split("T")[0],onChange:u=>l("install_preferred_date",u.target.value),className:p("install_preferred_date")}),o.install_preferred_date&&t.jsx("p",{className:"text-xs text-red-400 mt-1",children:o.install_preferred_date})]})]}),t.jsxs("div",{className:"flex gap-3 mt-5",children:[t.jsx("button",{onClick:n,className:"flex-1 py-2 text-sm text-muted hover:text-white transition-colors",children:"Cancel"}),t.jsx("button",{onClick:f,disabled:r,className:"flex-1 py-2 bg-green-500 hover:bg-green-400 disabled:opacity-50 text-white font-semibold rounded-lg text-sm transition-colors",children:r?"Saving...":"Sign Agreement"})]})]})]})}const PB={danger:"bg-red-500 hover:bg-red-400",warning:"bg-amber-500 hover:bg-amber-400",primary:"bg-accent hover:bg-sky-400"};function Q_({title:e,message:n,confirmLabel:r="Confirm",confirmVariant:s="primary",onConfirm:i,onCancel:o,isPending:a=!1}){return t.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4",children:[t.jsx("div",{className:"absolute inset-0 bg-black/60",onClick:o}),t.jsxs("div",{className:"relative bg-card border border-border rounded-2xl w-full max-w-sm p-5 shadow-2xl",children:[t.jsx("h3",{className:"font-bold text-white mb-2",children:e}),t.jsx("p",{className:"text-sm text-muted mb-5",children:n}),t.jsxs("div",{className:"flex gap-3",children:[t.jsx("button",{onClick:o,className:"flex-1 py-2 text-sm text-muted hover:text-white transition-colors",children:"Cancel"}),t.jsx("button",{onClick:i,disabled:a,className:`flex-1 py-2 ${PB[s]} disabled:opacity-50 text-white font-semibold rounded-lg text-sm transition-colors`,children:a?"Processing...":r})]})]})]})}const qB=["new_lead","qualifying","qualified","site_visit_scheduled","quote_sent","proposal_in_progress","agreement_signed"],DB={new_lead:[{label:"Mark Qualifying",action:"move",variant:"primary",targetStage:"qualifying",adminOnly:!0},{label:"Lost",action:"lost",variant:"danger",modal:"lost",adminOnly:!0,contactGated:!0},{label:"DND",action:"dnd",variant:"warning",modal:"confirm_dnd",adminOnly:!0,contactGated:!0}],qualifying:[{label:"Mark Qualified",action:"move",variant:"primary",targetStage:"qualified",adminOnly:!0},{label:"Schedule Site Visit",action:"schedule_visit",variant:"primary",adminOnly:!0},{label:"Lost",action:"lost",variant:"danger",modal:"lost",adminOnly:!0,contactGated:!0},{label:"Cold Lead",action:"followup",variant:"secondary",modal:"followup"},{label:"DND",action:"dnd",variant:"warning",modal:"confirm_dnd",adminOnly:!0,contactGated:!0}],qualified:[{label:"Build Quote",action:"create_quote",variant:"primary"},{label:"Schedule Site Visit",action:"schedule_visit",variant:"primary",adminOnly:!0},{label:"Lost",action:"lost",variant:"danger",modal:"lost",adminOnly:!0,contactGated:!0},{label:"Cold Lead",action:"followup",variant:"secondary",modal:"followup"},{label:"DND",action:"dnd",variant:"warning",modal:"confirm_dnd",adminOnly:!0,contactGated:!0}],site_visit_scheduled:[{label:"Build Quote",action:"create_quote",variant:"primary"},{label:"Lost",action:"lost",variant:"danger",modal:"lost",adminOnly:!0,contactGated:!0},{label:"Cold Lead",action:"followup",variant:"secondary",modal:"followup"},{label:"DND",action:"dnd",variant:"warning",modal:"confirm_dnd",adminOnly:!0,contactGated:!0}],proposal_in_progress:[{label:"Build & Send Quote",action:"create_quote",variant:"success"},{label:"Lost",action:"lost",variant:"danger",modal:"lost",adminOnly:!0,contactGated:!0},{label:"Cold Lead",action:"followup",variant:"secondary",modal:"followup"}],quote_sent:[{label:"ð Build Another Quote",action:"create_quote",variant:"primary"},{label:"Mark Signed (Manual)",action:"agreement",variant:"success",modal:"agreement",adminOnly:!0},{label:"Lost",action:"lost",variant:"danger",modal:"lost",adminOnly:!0,contactGated:!0},{label:"Cold Lead",action:"followup",variant:"secondary",modal:"followup"}],agreement_signed:[{label:"Lost",action:"lost",variant:"danger",modal:"lost",adminOnly:!0}],won:[{label:"View Customer",action:"view_customer",variant:"primary"}],lost:[{label:"Reopen as New Lead",action:"reopen_lost",variant:"secondary",modal:"confirm_reopen",adminOnly:!0}],future_follow_up:[{label:"Reopen as Qualifying",action:"reopen_followup",variant:"secondary",modal:"confirm_reopen",adminOnly:!0}],dnd:[{label:"Reopen as New Lead",action:"reopen_dnd",variant:"secondary",modal:"confirm_reopen",adminOnly:!0}]},ej={primary:{bg:"rgba(96,165,250,0.15)",color:"#60a5fa",border:"rgba(96,165,250,0.3)",hoverBg:"rgba(96,165,250,0.25)"},success:{bg:"rgba(74,222,128,0.15)",color:"#4ade80",border:"rgba(74,222,128,0.3)",hoverBg:"rgba(74,222,128,0.25)"},danger:{bg:"rgba(239,68,68,0.15)",color:"#f87171",border:"rgba(239,68,68,0.3)",hoverBg:"rgba(239,68,68,0.25)"},warning:{bg:"rgba(245,158,11,0.15)",color:"#fbbf24",border:"rgba(245,158,11,0.3)",hoverBg:"rgba(245,158,11,0.25)"},secondary:{bg:"rgba(100,116,139,0.15)",color:"#cbd5e1",border:"rgba(100,116,139,0.3)",hoverBg:"rgba(100,116,139,0.25)"}};function OB({lead:e,onLeadUpdated:n,onCreateQuote:r,creatingQuote:s=!1,qual
647ifyingComplete:i,onScheduleVisit:o,siteVisitComplete:a,callAttemptCount:l=0,hasNoContactRequest:d=!1}){const{user:c,profile:f,role:p}=Ee(),[u,h]=g.useState(null),[y,m]=g.useState(null),[b,A]=g.useState(""),v=p==="salesrep",x=DB[e.stage]||[],_=v?x.filter(k=>!k.adminOnly):x,j=qB.includes(e.stage),C=!!e.booking_stage,S=e.chase_kind||tu(e.booking_stage),T=gM[S]||"Chase",L=C?tf[e.booking_stage]||e.booking_stage:null,E=!1;if(!c)return null;if(v&&_.length===0)return t.jsx("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"8px 12px",borderRadius:8,backgroundColor:"rgba(100,116,139,0.1)",border:"1px solid rgba(100,116,139,0.2)"},children:t.jsx("span",{style:{fontSize:12,color:"#94a3b8"},children:"View only â stage actions managed by admin"})});const R={actor_id:c.id,actor_name:f==null?void 0:f.full_name};async function N(k){if(A(""),k.action==="create_quote"){if(e.stage==="site_visit_scheduled"&&!a){A("Complete all required site visit checklist items before building a quote.");return}r==null||r();return}if(k.action==="schedule_visit"){o==null||o();return}if(k.modal){h(k.modal);return}if(k.action==="move"&&k.targetStage){if(e.stage==="qualifying"&&k.targetStage==="qualified"&&!i){A("Complete all required qualifying questions before moving to Qualified.");return}m(k.action);try{const q=await xl(e.id,e.stage,k.targetStage,R);n(q)}catch(q){A(q.message)}finally{m(null)}}}async function O(k){m("lost");try{const q=k.freeText?`${k.reasonLabel}: ${k.freeText}`:k.reasonLabel,$=await yB(e.id,e.stage,R,q,{lost_reason_code:k.reasonCode,lost_reengage_date:k.reEngageDate??void 0});if(n($),k.autoMoveToFutureFollowUp&&k.reEngageDate)try{await X_(e.id,"lost",R,k.reEngageDate,`Auto-scheduled from Lost reason: ${k.reasonLabel}`)}catch{}h(null)}catch(q){A(q.message)}finally{m(null)}}async function z(k,q){m("followup");try{const $=await X_(e.id,e.stage,R,k,q);n($),h(null)}catch($){A($.message)}finally{m(null)}}async function P(){m("dnd");try{const k=await bB(e.id,e.stage,R);n(k),h(null)}catch(k){A(k.message)}finally{m(null)}}async function D(k){m("agreement");try{const q=await AB(e.id,e.stage,R,k);n(q),h(null)}catch(q){A(q.message)}finally{m(null)}}async function M(){m("reopen");try{let k;e.stage==="lost"?k=await vB(e.id,e,R):e.stage==="dnd"?k=await _B(e.id,R):e.stage==="future_follow_up"?k=await G_(e.id,e,R):k=await G_(e.id,e,R),n(k),h(null)}catch(k){A(k.message)}finally{m(null)}}return t.jsxs(t.Fragment,{children:[e.stage==="qualifying"&&!i&&!v&&t.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8,borderRadius:12,padding:"12px 16px",backgroundColor:"#854d0e",border:"2px solid #eab308"},children:[t.jsx("span",{style:{fontSize:18,lineHeight:1},children:"â ï¸"}),t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:13,fontWeight:700,color:"#fde047"},children:"Checklist Incomplete"}),t.jsx("div",{style:{fontSize:11,marginTop:2,color:"#fef08a"},children:"Answer all required questions below before moving to Qualified."})]})]}),e.stage==="site_visit_scheduled"&&!a&&t.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8,borderRadius:12,padding:"12px 16px",backgroundColor:"#581c87",border:"2px solid #a855f7"},children:[t.jsx("span",{style:{fontSize:18,lineHeight:1},children:"ð"}),t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:13,fontWeight:700,color:"#d8b4fe"},children:"Site Visit Checklist Incomplete"}),t.jsx("div",{style:{fontSize:11,marginTop:2,color:"#e9d5ff"},children:"Complete all required items below before building a quote."})]})]}),d&&j&&!v&&t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,borderRadius:12,padding:"12px 16px",backgroundColor:"rgba(239,68,68,0.08)",border:"1px solid rgba(239,68,68,0.3)"},children:[t.jsx("span",{style:{fontSize:14},children:"â"}),t.jsxs("div",{children:[t.jsx("span",{style:{fontSize:12,fontWeight:700,color:"#f87171"},children:"No Contact Requested"}),t.jsx("span",{style:{fontSize:12,marginLeft:8,color:"#94a3b8"},children:"Lead asked not to be contacted â Lost/DND unlocked immediately"})]})]}),C&&j&&!v&&t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,borderRadius:12,padding:"12px 16px",backgroundColor:"rgba(56,189,248,0.08)",border:"1px solid rgba(56,189,248,0.25)"},children:[t.jsx("span",{style:{fontSize:14},children:"ð
"}),t.jsxs("div",{children:[t.jsxs("span",{style:{fontSize:12,fontWeight:700,color:"#38bdf8"},children:[T," Active",L?` â ${L}`:""]}),t.jsx("span",{style:{fontSize:12,marginLeft:8,color:"#94a3b8"},children:"Chase is the contact process â Lost/DND unlocked"})]})]}),t.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:_.map(k=>{var B;const q=(B=k.disabled)==null?void 0:B.call(k,e),$=k.contactGated&&E,I=ej[k.variant]||ej.secondary;return t.jsx("button",{onClick:()=>!q&&!$&&N(k),disabled:!!y||q||$||s&&k.action==="create_quote",title:void 0,style:{backgroundColor:q?"rgba(74,222,128,0.1)":I.bg,color:q?"rgba(74,222,128,0.6)":I.color,border:`1px solid ${q?"rgba(74,222,128,0.2)":I.border}`,fontSize:12,padding:"6px 10px",borderRadius:8,fontWeight:500,cursor:y||$?"not-allowed":"pointer",opacity:y?.5:1,transition:"all 0.12s"},children:q?k.disabledLabel:k.label},k.action+(k.targetStage||""))})}),b&&t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,borderRadius:12,padding:"12px 16px",marginTop:8,backgroundColor:"#dc2626",border:"2px s
647olid #f87171"},children:[t.jsx("span",{style:{fontSize:18,lineHeight:1},children:"ð«"}),t.jsx("div",{style:{fontSize:13,fontWeight:700,color:"#ffffff"},children:b})]}),u==="lost"&&t.jsx(jB,{onSubmit:O,onCancel:()=>h(null),isPending:y==="lost"}),u==="followup"&&t.jsx(zB,{onSubmit:z,onCancel:()=>h(null),isPending:y==="followup"}),u==="agreement"&&t.jsx(EB,{onSubmit:D,onCancel:()=>h(null),isPending:y==="agreement"}),u==="confirm_dnd"&&t.jsx(Q_,{title:"Mark as Do Not Disturb",message:"This lead will be moved to DND. No further contact will be made. Continue?",confirmLabel:"Mark DND",confirmVariant:"warning",onConfirm:P,onCancel:()=>h(null),isPending:y==="dnd"}),u==="confirm_reopen"&&t.jsx(Q_,{title:"Reopen Lead",message:e.stage==="lost"?"This will reopen the lead as New Lead and clear the lost reason.":e.stage==="dnd"?"This will reopen the lead as New Lead and remove the DND status.":"This will reopen the lead as Qualifying and clear the follow-up schedule.",confirmLabel:"Reopen",confirmVariant:"primary",onConfirm:M,onCancel:()=>h(null),isPending:y==="reopen"})]})}const Ur=e=>e==null?"â":"$"+e.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g,",");function IB(){const e=new Date;return e.setDate(e.getDate()+7),e.toISOString().slice(0,10)}function LB(){const e=new Date;e.setDate(e.getDate()+1);const n=new Date;return n.setDate(n.getDate()+30),{min:e.toISOString().slice(0,10),max:n.toISOString().slice(0,10)}}const WB=[{value:"purchase",label:"Buy"},{value:"rental",label:"Rent"},{value:"both",label:"Both"}];function $B({leadId:e,leadName:n,existing:r,onDone:s,onCancel:i}){const[o,a]=g.useState([]),[l,d]=g.useState(new Map),[c,f]=g.useState(!0),[p,u]=g.useState(""),[h,y]=g.useState([]),[m,b]=g.useState(""),[A,v]=g.useState(""),[x,_]=g.useState(""),[j,C]=g.useState(""),[S,T]=g.useState(IB()),[L,E]=g.useState(!1),[R,N]=g.useState(""),[O,z]=g.useState(""),[P,D]=g.useState(!1),M=g.useMemo(LB,[]);g.useEffect(()=>{let Q=!1;return hE().then(oe=>{Q||d(oe)}),tP().then(oe=>{Q||a(oe)}).catch(oe=>{Q||N(oe.message)}).finally(()=>{Q||f(!1)}),()=>{Q=!0}},[]),g.useEffect(()=>{r&&(b(r.headline||""),v(r.message||""),_(r.bundle_discount_type||""),C(r.bundle_discount_value==null?"":String(r.bundle_discount_value)),T(r.expires_at.slice(0,10)),y(r.items.map((Q,oe)=>({key:`${Q.id}-${oe}`,product_catalog_id:Q.product_catalog_id||"",name:Q.name,description:Q.description,image_url:Q.image_url,specs:Q.specs,warranty_text:Q.warranty_text,quantity:Q.quantity,display_mode:Q.display_mode,eyebrow:Q.eyebrow,tagline:Q.tagline,discount_type:Q.discount_type,discount_value:Q.discount_value,list_price:Q.list_price,list_rental_monthly:Q.list_rental_monthly,install_fee:Q.install_fee,min_sell_price:Q.min_sell_price,offered_price:Q.offered_price,offered_rental_monthly:Q.offered_rental_monthly}))))},[r]);const k=j.trim()===""?null:Number(j),q=x||null,$={bundle_discount_type:q,bundle_discount_value:k,expires_on:S,items:h},{expiry:I,alloc:B,bundlePrice:J}=g.useMemo(()=>a0($),[e,m,A,q,k,S,h]),te=h.filter(Q=>Q.display_mode==="purchase"||Q.display_mode==="both").length>=oh,U=h.length>0&&B.ok&&I.ok&&!L,W=g.useMemo(()=>{const Q=p.trim().toLowerCase();return Q?o.filter(oe=>oe.name.toLowerCase().includes(Q)||(oe.category||"").toLowerCase().includes(Q)):o},[o,p]);function G(Q){const oe=Q.rental_price_monthly==null?"purchase":"both",ne=Q.family_id?l.get(Q.family_id)??null:null;y(ge=>[...ge,rP(Q,oe,ne)])}function V(Q,oe){y(ne=>ne.map(ge=>ge.key===Q?{...ge,...oe}:ge))}function ee(Q){y(oe=>oe.filter(ne=>ne.key!==Q))}async function re(Q){E(!0),N("");try{const oe={lead_id:e,headline:m.trim()||null,message:A.trim()||null,bundle_discount_type:q,bundle_discount_value:k,bundle_price:J,expires_on:S,items:h};let ne=r?await lP(r.id,oe):await aP(oe);if(Q){await dP(ne.id),ne={...ne,status:"active",sent_at:new Date().toISOString()},z(Ay(ne.token));return}s(ne)}catch(oe){N(oe instanceof Pr?oe.message:`Could not save the offer: ${oe.message}`)}finally{E(!1)}}return O?t.jsxs("div",{style:{maxWidth:560,margin:"80px auto",padding:24},children:[t.jsx("h2",{style:{fontSize:20,fontWeight:700,color:"#e2e8f0",marginBottom:8},children:"The offer is live"}),t.jsxs("p",{style:{fontSize:14,color:"#94a3b8",marginBottom:20,lineHeight:1.6},children:["Send this link to ",n,". It stops working at the end of ",S,", and anyone opening it after that sees an expired notice rather than the prices."]}),t.jsxs("div",{style:{display:"flex",gap:8,marginBottom:20},children:[t.jsx("input",{readOnly:!0,value:O,onFocus:Q=>Q.currentTarget.select(),style:{flex:1,padding:"10px 12px",fontSize:13,color:"#e2e8f0",background:"#162232",border:"1px solid #1e3a4f",borderRadius:8}}),t.jsx("button",{onClick:()=>{navigator.clipboard.writeText(O).then(()=>{D(!0),setTimeout(()=>D(!1),2e3)},()=>N("Could not copy. Select the link and copy it manually."))},style:{padding:"10px 16px",fontSize:13,fontWeight:600,color:"#0f1c2b",background:P?"#4ade80":"#38bdf8",border:"none",borderRadius:8,cursor:"pointer"},children:P?"Copied":"Copy link"})]}),R&&t.jsx("p",{style:{fontSize:13,color:"#f87171",marginBottom:16},children:R}),t.jsx("button",{onClick:i,style:{padding:"10px 16px",fontSize:13,fontWeight:600,color:"#e2e8f0",background:"#1e3a4f",border:"none",borderRadius:8,cursor:"pointer"},children:"Back to the lead"})]}):t.jsxs("div",{style:{maxWidth:1180,margin:"0 auto",padding:"20px 24px 64px"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"baseline",justifyContent:"space-between",marginBottom:20},children:[t.jsxs("div",{children:[t.jsx("h2",{style:{fontSize:20,fontWeight:700,color:"#e2e8f0"},children:"Final offer"}),t.jsxs("p",{style:{fontSize:13,color:"#64748b",marginTop:2},children:["For ",n,". This is a page they can look at, not a quote â if they take it, you build the quote as normal."]})]}),t.jsx("button",{onClick:i,style:{fontSize:13,color:"#64748b",background:"none",border:"none",cursor:"pointer"},children:"Cancel"})]}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"minmax(0,1fr) 340px",gap:20,alignItems:"start"},children:[t.jsxs("div",{children:[t.jsxs("div",{style:{border:"1px solid #1e3a4f",borderRadius:12,padding:14,marginBottom:16},children:[t.jsx("div",{style:{fontSize:11,fontWeight:700,letterSpacing:"0.06em",color:"#64748b",marginBottom:8},children:"Add a product"}),t.jsx("input",{value:p,onChange:Q=>u(Q.target.value),placeholder:"Search the catalog",style:{width:"100%",padding:"8px 10px",fontSize:13,color:"#e2e8f0",background:"#162232",border:"1px solid #1e3a4f",borderRadius:8,marginBottom:10}}),c?t.jsx("p",{style:{fontSize:13,color:"#64748b"},children:"Loading the catalogâ¦"}):W.length?t.jsx("div",{style:{maxHeight:200,overflowY:"auto"},children:W.map(Q=>t.jsxs("button",{onClick:()=>G(Q),style:{display:"flex",width:"100%",gap:12,alignItems:"baseline",padding:"7px 8px",fontSize:13,color:"#e2e8f0",textAlign:"left",background:"none",border:"none",borderRadius:6,cursor:"pointer"},children:[t.jsx("span",{style:{flex:1},children:Q.name}),t.jsx("span",{style:{color:"#64748b",fontSize:12},children:Ur(Q.retail_price)})]},Q.id))}):t.jsxs("p",{style:{fontSize:13,color:"#64748b"},children:["Nothing matches â",p,"â. Try a shorter search."]})]}),h.length?h.map(Q=>{const oe=Q.display_mode==="purchase"||Q.display_mode==="both",ne=Q.display_mode==="rental"||Q.display_mode==="both",ge=Q.list_rental_monthly==null;return t.jsxs("div",{style:{border:"1px solid #1e3a4f",borderRadius:12,padding:14,marginBottom:10},children:[t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:12,marginBottom:10},children:[t.jsx("div",{style:{fontSize:14,fontWeight:600,color:"#e2e8f0"},children:Q.name}),t.jsx("button",{onClick:()=>ee(Q.key),style:{fontSize:12,color:"#64748b",background:"none",border:"none",cursor:"pointer"},children:"Remove"})]}),t.jsx("div",{style:{display:"flex",gap:6,marginBottom:12},children:WB.map(be=>{const we=ge&&be.value!=="purchase",F=Q.display_mode===be.value;return t.jsx("button",{disabled:we,onClick:()=>V(Q.key,{display_mode:be.value}),title:we?"This product has no rental price in the catalog.":void 0,style:{padding:"5px 12px",fontSize:12,fontWeight:600,borderRadius:6,color:we?"#475569":F?"#0f1c2b":"#94a3b8",background:F?"#38bdf8":"#162232",border:"1px solid #1e3a4f",cursor:we?"not-allowed":"pointer"},children:be.label},be.value)})}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit,minmax(130px,1fr))",gap:10},children:[t.jsx(Ba,{label:"Quantity",children:t.jsx("input",{type:"number",min:1,step:1,value:Q.quantity,onChange:be=>V(Q.key,{quantity:Math.max(1,parseInt(be.target.value,10)||1)}),style:Hr})}),oe&&t.jsx(Ba,{label:"Discount",hint:`Off ${Ur(Q.list_price)} list`,children:t.jsxs("div",{style:{display:"flex",gap:4},children:[t.jsxs("select",{value:Q.discount_type??"",onChange:be=>V(Q.key,{discount_type:be.target.value||null,discount_value:be.target.value?Q.discount_value:null}),style:{...Hr,width:58,padding:"8px 4px"},children:[t.jsx("option",{value:"",children:"â"}),t.jsx("option",{value:"percent",children:"%"}),t.jsx("option",{value:"amount",children:"$"})]}),t.jsx("input",{type:"number",min:0,step:"0.01",disabled:!Q.discount_type,value:Q.discount_value??"",onChange:be=>V(Q.key,{discount_value:be.target.value===""?null:Number(be.target.value)}),style:{...Hr,flex:1,opacity:Q.discount_type?1:.5}})]})}),oe&&t.jsx(Ba,{label:"They pay",hint:"Worked out from the discount",children:t.jsx("div",{style:{...Hr,display:"flex",alignItems:"center",fontWeight:700},children:Ur(MB(Q))})}),ne&&t.jsx(Ba,{label:"Monthly",hint:`Catalog ${Ur(Q.list_rental_monthly)}`,children:t.jsx("input",{type:"number",min:0,step:"0.01",value:Q.offered_rental_monthly??"",onChange:be=>V(Q.key,{offered_rental_monthly:be.target.value===""?null:Number(be.target.value)}),style:Hr})}),ne&&t.jsx(Ba,{label:"Install",hint:"Charged on rentals only",children:t.jsx("div",{style:{...Hr,color:"#94a3b8",display:"flex",alignItems:"center"},children:Q.install_fee?Ur(Q.install_fee):"None"})})]}),Q.min_sell_price!=null&&t.jsxs("p",{style:{fontSize:11,color:"#475569",marginTop:8},children:["Minimum ",Ur(Q.min_sell_price)," each"]})]},Q.key)}):t.jsx("div",{style:{border:"1px dashed #1e3a4f",borderRadius:12,padding:"32px 16px",textAlign:"center"},children:t.jsxs("p",{style:{fontSize:13,color:"#64748b"},children:["Add the products you want ",n," to see."]})}),t.jsxs("div",{style:{border:"1px solid #1e3a4f",borderRadius:12,padding:14,marginTop:16},children:[t.jsx("div",{style:{fontSize:11,fontWeight:700,letterSpacing:"0.06em",color:"#64748b",marginBottom:8},children:"Bundle discount"}),t.jsxs("p",{style:{fontSize:12,color:"#64748b",marginBottom:10,lineHeight:1.5},children:["Extra off when they take ",oh," or more, on top of the line discounts. Spread across the purchase lines. Monthly rental prices and install fees are never discounted."]}),t.jsxs("div",{style:{display:"flex",gap:6},children:[t.jsxs("select",{value:x,disabled:!te,onChange:Q=>_(Q.target.value),style:{...Hr,width:70,marginBottom:0,opacity:te?1:.5},children:[t.jsx("option",{value:"",children:"â"}),t.jsx("option",{value:"percent",children:"%"}),t.jsx("option",{value:"amount",children:"$"})]}),t.jsx("input",{type:"number",min:0,step:"0.01",value:j,disabled:!te||!x,onChange:Q=>C(Q.target.value),placeholder:te?"e.g. 500":`Add ${oh} products shown as Buy first`,style:{...Hr,flex:1,marginBottom:0,opacity:te&&x?1:.5}})]}),J!=null&&t.jsxs("p",{style:{fontSize:12,color:"#4ade80",marginTop:8},children:["Bundle total ",Ur(J)]})]}),t.jsxs("div",{style:{border:"1px solid #1e3a4f",borderRadius:12,padding:14,marginTop:16},children:[t.jsx("div",{style:{fontSize:11,fontWeight:700,letterSpacing:"0.06em",color:"#64748b",marginBottom:10},children:"What they read"}),t.jsx("input",{value:m,onChange:Q=>b(Q.target.value),placeholder:"Headline â e.g. A better price, until Friday",style:{...Hr,width:"100%",marginBottom:10}}),t.jsx("textarea",{value:A,onChange:Q=>
647v(Q.target.value),rows:3,placeholder:"A line or two about why they're getting this price.",style:{...Hr,width:"100%",resize:"vertical"}}),t.jsx("div",{style:{marginTop:12},children:t.jsx(Ba,{label:"Expires at the end of",hint:"Up to 30 days out",children:t.jsx("input",{type:"date",value:S,min:M.min,max:M.max,onChange:Q=>T(Q.target.value),style:Hr})})})]})]}),t.jsx("div",{style:{position:"sticky",top:20},children:t.jsxs("div",{style:{border:"1px solid #1e3a4f",borderRadius:12,padding:14},children:[t.jsx("div",{style:{fontSize:11,fontWeight:700,letterSpacing:"0.06em",color:"#64748b",marginBottom:12},children:"Totals"}),B.ok?t.jsxs(t.Fragment,{children:[t.jsx(Tp,{label:"To buy",value:Ur(B.purchase_total)}),B.savings>0&&t.jsx(Tp,{label:"They save",value:Ur(B.savings),accent:"#4ade80"}),B.rental_monthly_total>0&&t.jsx(Tp,{label:"Monthly",value:Ur(B.rental_monthly_total)+"/mo"}),B.install_total>0&&t.jsx(Tp,{label:"Install",value:Ur(B.install_total)})]}):t.jsxs("div",{style:{background:"rgba(251,191,36,0.08)",border:"1px solid rgba(251,191,36,0.3)",borderRadius:10,padding:"10px 12px"},children:[t.jsx("div",{style:{fontSize:12,fontWeight:700,color:"#fbbf24",marginBottom:4},children:"This price won't send"}),t.jsx("p",{style:{fontSize:12,color:"#e2e8f0",lineHeight:1.5},children:B.error})]}),!I.ok&&t.jsx("p",{style:{fontSize:12,color:"#fbbf24",marginTop:12,lineHeight:1.5},children:I.error}),R&&t.jsx("p",{style:{fontSize:12,color:"#f87171",marginTop:12,lineHeight:1.5},children:R}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8,marginTop:16},children:[t.jsx("button",{disabled:!U,onClick:()=>re(!0),style:{padding:"10px 0",fontSize:13,fontWeight:700,borderRadius:8,border:"none",color:U?"#0f1c2b":"#475569",background:U?"#38bdf8":"#1e3a4f",cursor:U?"pointer":"not-allowed"},children:L?"Savingâ¦":"Make it live"}),t.jsx("button",{disabled:!U,onClick:()=>re(!1),style:{padding:"9px 0",fontSize:13,fontWeight:600,borderRadius:8,color:"#94a3b8",background:"none",border:"1px solid #1e3a4f",cursor:U?"pointer":"not-allowed"},children:"Save as a draft"})]})]})})]})]})}function MB(e){return e.list_price==null?null:!e.discount_type||e.discount_value==null||e.discount_value<=0?e.list_price:e.discount_type==="percent"?Math.max(0,Math.round(e.list_price*(1-Math.min(e.discount_value,100)/100)*100)/100):Math.max(0,Math.round((e.list_price-e.discount_value)*100)/100)}const Hr={padding:"8px 10px",fontSize:13,color:"#e2e8f0",background:"#162232",border:"1px solid #1e3a4f",borderRadius:8,minHeight:35,boxSizing:"border-box"};function Ba({label:e,hint:n,children:r}){return t.jsxs("label",{style:{display:"block"},children:[t.jsx("div",{style:{fontSize:11,color:"#64748b",marginBottom:4},children:e}),r,n&&t.jsx("div",{style:{fontSize:10,color:"#475569",marginTop:3},children:n})]})}function Tp({label:e,value:n,accent:r}){return t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",padding:"5px 0"},children:[t.jsx("span",{style:{fontSize:13,color:"#94a3b8"},children:e}),t.jsx("span",{style:{fontSize:14,fontWeight:600,color:r||"#e2e8f0"},children:n})]})}const tj=e=>e==null?"â":"$"+Number(e).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g,",");function FB(e){const n=new Date(e).getTime()-Date.now();if(n<=0)return"Expired";const r=Math.floor(n/864e5);if(r>=1)return`${r} ${r===1?"day":"days"} left`;const s=Math.floor(n/36e5);return s>=1?`${s} ${s===1?"hour":"hours"} left`:`${Math.max(1,Math.floor(n/6e4))} minutes left`}function BB(e){return new Intl.DateTimeFormat("en-US",{weekday:"short",month:"short",day:"numeric"}).format(new Date(e))}function UB({leadId:e,leadName:n}){const[r,s]=g.useState(null),[i,o]=g.useState(!0),[a,l]=g.useState(!1),[d,c]=g.useState(!1),[f,p]=g.useState(""),[u,h]=g.useState(""),[y,m]=g.useState(""),[b,A]=g.useState(!1),v=g.useCallback(async()=>{o(!0);try{s(await P4(e)),h("")}catch(E){h(E.message)}finally{o(!1)}},[e]);g.useEffect(()=>{v()},[v]);async function x(E){var R,N;if(r){p(E),h(""),m("");try{const O=await fetch("/api/final-offers/send",{method:"POST",headers:await At(),body:JSON.stringify({offer_id:r.id,channel:E})}),z=await O.json().catch(()=>({}));if(!O.ok){h(z.error||"That did not send.");return}const P=[];(R=z.sent)!=null&&R.length&&P.push(`Sent by ${z.sent.join(" and ")}.`),(N=z.skipped)!=null&&N.length&&P.push(z.skipped.join(" ")),m(P.join(" ")),await v()}catch(O){h(`That did not send: ${O.message}`)}finally{p("")}}}async function _(){if(r&&window.confirm("Cancel this offer? The link stops working straight away.")){p("cancel"),h(""),m("");try{await cP(r.id),s(null)}catch(E){h(E instanceof Pr?E.message:`Could not cancel: ${E.message}`)}finally{p("")}}}
647if(a||d)return t.jsx("div",{className:"fixed inset-0 z-50 overflow-y-auto",style:{background:"#162232"},children:t.jsx($B,{leadId:e,leadName:n,existing:d?r:null,onDone:E=>{s(E),l(!1),c(!1)},onCancel:()=>{l(!1),c(!1),v()}})});const j=(r==null?void 0:r.status)==="active",C=(r==null?void 0:r.status)==="draft",S=r?new Date(r.expires_at).getTime()<=Date.now():!1,T=r?r.items.reduce((E,R)=>E+(R.allocated_total??0),0):0,L=r?r.items.reduce((E,R)=>E+(R.display_mode==="rental"||R.display_mode==="both"?(R.offered_rental_monthly??0)*(R.quantity||1):0),0):0;return t.jsxs("div",{style:{border:`1px solid ${j&&!S?"rgba(56,189,248,0.35)":"#1e3a4f"}`,background:j&&!S?"rgba(56,189,248,0.06)":void 0,borderRadius:12,padding:"10px 14px"},children:[t.jsx("div",{style:{fontSize:11,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:8,color:j&&!S?"#38bdf8":"#64748b"},children:"Final offer"}),i?t.jsx("p",{style:{fontSize:13,color:"#64748b"},children:"Loadingâ¦"}):r?t.jsxs(t.Fragment,{children:[t.jsxs("div",{style:{display:"flex",alignItems:"baseline",gap:10,marginBottom:8},children:[t.jsx("span",{style:{fontSize:14,fontWeight:700,color:"#e2e8f0"},children:C?"Draft, not sent":S?"Expired":FB(r.expires_at)}),t.jsxs("span",{style:{fontSize:12,color:"#64748b"},children:["ends ",BB(r.expires_at)]})]}),t.jsxs("div",{style:{fontSize:13,color:"#94a3b8",lineHeight:1.6,marginBottom:10},children:[r.items.map((E,R)=>t.jsxs("div",{children:[E.quantity>1?`${E.quantity} à `:"",E.name]},R)),t.jsxs("div",{style:{marginTop:6,color:"#e2e8f0"},children:[T>0&&t.jsxs(t.Fragment,{children:["Buy ",tj(r.bundle_price??T)]}),T>0&&L>0&&" · ",L>0&&t.jsxs(t.Fragment,{children:["Rent ",tj(L),"/mo"]})]})]}),!C&&t.jsxs("div",{style:{display:"flex",gap:6,marginBottom:10},children:[t.jsx("input",{readOnly:!0,value:Ay(r.token),onFocus:E=>E.currentTarget.select(),style:{flex:1,padding:"6px 8px",fontSize:11,color:"#94a3b8",background:"#162232",border:"1px solid #1e3a4f",borderRadius:6}}),t.jsx("button",{onClick:()=>{navigator.clipboard.writeText(Ay(r.token)).then(()=>{A(!0),setTimeout(()=>A(!1),2e3)},()=>h("Could not copy. Select the link and copy it manually."))},style:{padding:"6px 10px",fontSize:12,fontWeight:600,color:b?"#4ade80":"#94a3b8",background:"#1e3a4f",border:"none",borderRadius:6,cursor:"pointer"},children:b?"Copied":"Copy"})]}),t.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:[!S&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:()=>x("email"),disabled:!!f,style:HB(!!f),children:f==="email"?"Sendingâ¦":C?"Send by email":"Email again"}),t.jsx("button",{onClick:()=>x("sms"),disabled:!!f,style:vm(!!f),children:f==="sms"?"Sendingâ¦":C?"Send by text":"Text again"}),t.jsx("button",{onClick:()=>x("both"),disabled:!!f,style:vm(!!f),children:f==="both"?"Sendingâ¦":"Both"})]}),C&&t.jsx("button",{onClick:()=>c(!0),disabled:!!f,style:vm(!!f),children:"Edit"}),t.jsx("button",{onClick:_,disabled:!!f,style:VB(!!f),children:f==="cancel"?"Cancellingâ¦":"Cancel offer"})]}),S&&t.jsx("p",{style:{fontSize:12,color:"#fbbf24",marginTop:10,lineHeight:1.5},children:"The deadline has passed, so the page no longer shows the prices. Cancel this one to build another."})]}):t.jsxs(t.Fragment,{children:[t.jsx("p",{style:{fontSize:13,color:"#94a3b8",lineHeight:1.55,marginBottom:10},children:"A page with a deadline on it, for a lead who has gone quiet. They tell you whether they want to buy or rent, and you quote it the normal way."}),t.jsx("button",{onClick:()=>l(!0),style:{padding:"8px 14px",fontSize:13,fontWeight:600,color:"#0f1c2b",background:"#38bdf8",border:"none",borderRadius:8,cursor:"pointer"},children:"Build a final offer"})]}),y&&t.jsx("p",{style:{fontSize:12,color:"#4ade80",marginTop:10,lineHeight:1.5},children:y}),u&&t.jsx("p",{style:{fontSize:12,color:"#f87171",marginTop:10,lineHeight:1.5},children:u})]})}function HB(e){return{padding:"7px 12px",fontSize:12,fontWeight:700,borderRadius:7,border:"none",color:e?"#475569":"#0f1c2b",background:e?"#1e3a4f":"#38bdf8",cursor:e?"not-allowed":"pointer"}}function vm(e){return{padding:"7px 12px",fontSize:12,fontWeight:600,borderRadius:7,color:"#94a3b8",background:"none",border:"1px solid #1e3a4f",cursor:e?"not-allowed":"pointer"}}function VB(e){return{padding:"7px 12px",fontSize:12,fontWeight:600,borderRadius:7,color:"#f87171",background:"none",border:"1px solid #1e3a4f",cursor:e?"not-allowed":"pointer"}}
647const ZB={lead_created:{icon:"â",color:"bg-accent"},stage_change:{icon:"â",color:"bg-purple-500"},call_logged:{icon:"ð",color:"bg-green-500"},note_added:{icon:"ð",color:"bg-slate-500"},agreement_signed:{icon:"â
",color:"bg-emerald-500"},job_created:{icon:"ð§",color:"bg-cyan-500"},lead_lost:{icon:"â",color:"bg-red-500"},lead_dnd:{icon:"ð",color:"bg-amber-500"},lead_followup:{icon:"ð",color:"bg-violet-500"},field_updated:{icon:"âï¸",color:"bg-slate-500"},rep_changed:{icon:"ð¤",color:"bg-sky-500"},stage_changed:{icon:"â",color:"bg-purple-500"},lead_updated:{icon:"âï¸",color:"bg-slate-500"},rep_assigned:{icon:"ð¤",color:"bg-sky-500"},slot_available:{icon:"â",color:"bg-green-500"},slot_unavailable:{icon:"â",color:"bg-amber-500"},booking_advanced:{icon:"ð
",color:"bg-cyan-500"},chase_synced:{icon:"ðª",color:"bg-cyan-500"},sms_sent:{icon:"ð¬",color:"bg-green-500"},email_sent:{icon:"âï¸",color:"bg-sky-500"},lead_reopened:{icon:"â»",color:"bg-amber-500"},sms_received:{icon:"ð¥",color:"bg-green-500"},contact_attempt:{icon:"ð²",color:"bg-teal-500"},appointment_confirmed:{icon:"â
",color:"bg-emerald-500"},dnd_requested:{icon:"ð",color:"bg-amber-500"}};function KB(e){const n=new Date(e),s=new Date().getTime()-n.getTime(),i=Math.floor(s/6e4),o=Math.floor(s/36e5);return i<1?"Just now":i<60?`${i}m ago`:o<24?`${o}h ago`:n.toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function _m(e){const n=N0[e]||e;return t.jsx("span",{className:"inline-block text-xs px-1.5 py-0.5 rounded bg-surface border border-border text-slate-300 font-medium",children:n})}function YB(e){const n=e.metadata||{};switch(e.event_type){case"stage_change":case"stage_changed":return n.from_stage&&n.to_stage?t.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap",children:[_m(n.from_stage)," ",t.jsx("span",{className:"text-muted",children:"â"})," ",_m(n.to_stage),n.cleared_fields&&t.jsxs("span",{className:"text-xs text-muted ml-1",children:["(cleared: ",n.cleared_fields.join(", "),")"]})]}):null;case"agreement_signed":return t.jsxs("div",{className:"text-xs text-muted space-y-0.5",children:[n.quote_total&&t.jsxs("div",{children:["Quote: ",t.jsxs("span",{className:"text-slate-300",children:["$",Number(n.quote_total).toLocaleString()]})]}),n.deposit_amount&&t.jsxs("div",{children:["Deposit: ",t.jsxs("span",{className:"text-slate-300",children:["$",Number(n.deposit_amount).toLocaleString()]})]}),n.payment_method&&t.jsxs("div",{children:["Payment: ",t.jsx("span",{className:"text-slate-300 capitalize",children:n.payment_method})]}),n.signed_by&&t.jsxs("div",{children:["Signed by: ",t.jsx("span",{className:"text-slate-300",children:n.signed_by})]})]});case"lead_lost":return n.reason?t.jsxs("div",{className:"text-xs text-red-400/80",children:["Reason: ",String(n.reason)]}):null;case"lead_followup":return t.jsxs("div",{className:"text-xs text-muted",children:[n.followup_date&&t.jsxs("div",{children:["Date: ",t.jsx("span",{className:"text-slate-300",children:n.followup_date})]}),n.followup_notes&&t.jsxs("div",{children:["Notes: ",t.jsx("span",{className:"text-slate-300",children:String(n.followup_notes)})]})]});case"job_created":return t.jsxs("div",{className:"text-xs text-muted",children:[n.install_preference&&t.jsxs("div",{children:["Preference: ",t.jsx("span",{className:"text-slate-300 capitalize",children:String(n.install_preference).replace("_"," ")})]}),n.install_date&&t.jsxs("div",{children:["Date: ",t.jsx("span",{className:"text-slate-300",children:n.install_date})]})]});case"call_logged":return t.jsxs("div",{className:"text-xs text-muted",children:[n.outcome&&t.jsxs("div",{children:["Outcome: ",t.jsx("span",{className:"text-slate-300 capitalize",children:String(n.outcome).replace(/_/g," ")})]}),n.notes&&t.jsxs("div",{children:["Notes: ",t.jsx("span",{className:"text-slate-300",children:String(n.notes)})]})]});case"lead_dnd":return n.previous_stage?t.jsxs("div",{className:"text-xs text-muted",children:["From: ",_m(n.previous_stage)]}):null;case"rep_changed":return t.jsxs("div",{className:"text-xs text-muted",children:[n.from_rep&&t.jsx("span",{children:String(n.from_rep)}),n.from_rep&&n.to_rep&&t.jsx("span",{className:"mx-1",children:"â"}),n.to_rep&&t.jsx("span",{className:"text-slate-300",children:String(n.to_rep)})]});case"field_updated":return t.jsxs("div",{className:"text-xs text-muted",children:[n.field_name,": ",n.old_value?`${n.old_value} â `:"",t.jsx("span",{className:"text-slate-300",children:n.new_value})]});default:return null}}function XB({activity:e,isLoading:n}){return n?t.jsx("p",{className:"text-sm text-muted text-center py-8",children:"Loading activity..."}):e!=null&&e.length?t.jsx("div",{className:"space-y-0",children:e.map((r,s)=>{const i=ZB[r.event_type]||{icon:"â¢",color:"bg-muted"},o=YB(r);return t.jsxs("div",{className:"flex gap-3 relative",children:[s<e.length-1&&t.jsx("div",{className:"absolute left-[11px] top-7 bottom-0 w-px bg-border"}),t.jsx("div",{className:`w-6 h-6 rounded-full ${i.color} flex items-center justify-center flex-shrink-0 text-xs text-white z-10`,children:i.icon}),t.jsxs("div",{className:"flex-1 pb-4 min-w-0",children:[t.jsxs("div",{className:"flex items-start justify-between gap-2",children:[t.jsx("div",{className:"text-sm text-slate-200 font-medium leading-tight",children:r.description}),t.jsx("div",{className:"text-xs text-muted whitespace-nowrap flex-shrink-0",children:KB(r.created_at)})]}),o&&t.jsx("div",{className:"mt-1",children:o}),r.actor_name&&t.jsxs("div",{className:"text-xs text-muted mt-1",children:["by ",r.actor_name]})]})]},r.id)})}):t.jsx("p",{className:"text-sm text-muted text-center py-8",children:"No activity yet."})}async function GB(e,n,r){let s=w.from("entity_notes").select("*").eq("entity_type",e).eq("entity_id",n).order("pinned",{ascending:!1}).order("created_at",{ascending:!1});r&&(s=s.eq("section",r));const{data:i,error:o}=await s;if(o)throw o;return i||[]}async function b8(e){const n=e.body.trim();if(!n)throw new Error("Note body cannot be empty");const{data:r,error:s}=await w.from("entity_notes").insert({entity_type:e.entity_type,entity_id:e.entity_id,body:n,section:e.section||"general",visibility:e.visibility||"all"}).select().single();if(s)throw s;return r}async function A8(e,n){if(n.body!==void 0&&!n.body.trim())throw new Error("Note body cannot be empty");const r={};n.body!==void 0&&(r.body=n.body.trim()),n.section!==void 0&&(r.section=n.section),n.visibility!==void 0&&(r.visibility=n.visibility),n.pinned!==void 0&&(r.pinned=n.pinned);const{data:s,error:i}=await w.from("entity_notes").update(r).eq("id",e).select().single();if(i)throw i;return s}async function JB(e,n){return A8(e,{pinned:n})}async function QB(e){const{error:n}=await w.from("entity_notes").delete().eq("id",e);if(n)throw n}const da={complaint:"Complaint",warranty:"Warranty",filter_change:"Filter change",leak:"Leak",water_quality:"Water quality",billing:"Billing question",other:"Other"},Cl={low:"Low",normal:"Normal",high:"High",urgent:"Urgent"},v8={phone:"Phone call",text:"Text",email:"Email",walk_in:"Walk-in",service_due:"Service Due list",other:"Other"},_8={open:"Open",scheduled:"Scheduled",in_progress:"In progress",waiting_on_customer:"Waiting on customer",resolved:"Resolved",closed:"Closed"},j8={open:{bg:"rgba(96,165,250,0.15)",fg:"#93c5fd"},scheduled:{bg:"rgba(251,191,36,0.15)",fg:"#fbbf24"},in_progress:{bg:"rgba(167,139,250,0.15)",fg:"#c4b5fd"},waiting_on_customer:{bg:"rgba(244,114,182,0.15)",fg:"#f9a8d4"},resolved:{bg:"rgba(74,222,128,0.15)",fg:"#4ade80"},closed:{bg:"rgba(148,163,184,0.15)",fg:"#9ca3af"}},w8={low:"#94a3b8",normal:"#cbd5e1",high:"#f87171",urgent:"#ef4444"},eU=["frontdesk","salesrep","admin","super_admin"],R0=`
648 id, tenant_id, branch_id, ticket_number, customer_id, installed_system_id, 649 category, priority, source, subject, description, status, status_changed_at, 650 owner_id, created_by, resolution, resolved_at, closed_at, reopened_count, 651 last_activity_at, created_at, updated_at, 652 owner:profiles!owner_id(id, full_name), 653 jobs(id, job_status, scheduled_at, completed_at, 654 assigned_technician:profiles!assigned_technician_id(id, full_name)) 655`;async function tU(e){const n=cn(),{data:r,error:s}=await w.from("service_tickets").select(R0).eq("tenant_id",n).eq("customer_id",e).order("created_at",{ascending:!1});if(s)throw s;return r||[]}async function E0(){const e=cn(),{data:n,error:r}=await w.from("profiles").select("id, full_name, role").eq("tenant_id",e).in("role",eU).eq("is_active",!0).order("full_name");if(r)throw r;return n||[]}function nU(e){const n=e.trim().split(/\r?\n/)[0].trim();return n.length>80?n.slice(0,77).trimEnd()+"â¦":n}async function rU(e,n){const r=cn(),s=Kt(),i=e.description.trim();if(!i)throw new Error("Describe what the customer reported.");const{data:o,error:a}=await w.from("service_tickets").insert({tenant_id:r,branch_id:s??null,customer_id:e.customer_id,category:e.category,priority:e.priority,source:e.source,subject:nU(i),description:i,status:"open",owner_id:e.owner_id}).select(R0).single();if(a)throw a;const l=o;return await Tt({entity_type:"customer",entity_id:e.customer_id,ticket_id:l.id,event_type:"ticket_opened",title:`Service ticket ${l.ticket_number} opened: ${l.subject}`,metadata:{ticket_id:l.id,ticket_number:l.ticket_number,category:e.category,priority:e.priority,source:e.source,owner_id:e.owner_id},actor_id:n.actor_id,actor_name:n.actor_name??null}),l}async function sU(){const e=cn(),{data:n,error:r}=await w.from("service_tickets").select(`${R0}, 656 customer:customers!customer_id(id, first_name, last_name)`).eq("tenant_id",e).neq("status","closed").order("created_at",{ascending:!0});if(r)throw r;return n||[]}async function iU(e,n){const r=cn(),s=new Date().toISOString(),{error:i}=await w.from("service_tickets").update({status:n,status_changed_at:s,last_activity_at:s}).eq("id",e).eq("tenant_id",r);if(i)throw i}const oU="America/Indiana/Indianapolis";function Ey(e){const n=new Date(Date.now()+e*864e5);return new Intl.DateTimeFormat("en-CA",{timeZone:oU,year:"numeric",month:"2-digit",day:"2-digit"}).format(n)}async function Bn(e,n,r,s,i={}){await Tt({entity_type:"customer",entity_id:e.customer_id,ticket_id:e.id,event_type:n,description:r,metadata:{ticket_id:e.id,ticket_number:e.ticket_number,...i},actor_id:s.actor_id,actor_name:s.actor_name??null})}async function xo(e,n){const r=cn(),s=new Date().toISOString(),{error:i}=await w.from("service_tickets").update({...n,last_activity_at:s}).eq("id",e).eq("tenant_id",r);if(i)throw i}async function S8(e){const{data:n,error:r}=await w.from("follow_up_tasks").select("id, title, due_date, due_time, assigned_to, completed_at, created_at").eq("ticket_id",e).order("completed_at",{ascending:!0,nullsFirst:!0}).order("due_date",{ascending:!0});if(r)throw r;return n||[]}async function lf(e,n,r,s,i){const o=n.trim();if(!o)throw new Error("Task needs a title.");await Bf({task_type:"call_back",customer_id:e.customer_id,assigned_to:s,title:o,notes:`${e.ticket_number} · ${e.subject}`,due_date:r,ticket_id:e.id}),await Bn(e,"ticket_task_added",`${e.ticket_number}: task added â ${o}`,i,{due_date:r,assigned_to:s})}async function aU(e,n,r){await fd(n.id),await Bn(e,"ticket_task_done",`${e.ticket_number}: task done â ${n.title}`,r,{task_id:n.id})}async function lU(e){const n=cn(),{data:r,error:s}=await w.from("activity_log").select("id, event_type, description, actor_name, created_at").eq("tenant_id",n).eq("ticket_id",e).order("created_at",{ascending:!1}).limit(50);if(s)throw s;return r||[]}async function dU(e,n,r,s){await xo(e.id,{owner_id:n}),await Bn(e,"ticket_owner_changed",`${e.ticket_number}: owner â ${r??"nobody"}`,s,{owner_id:n})}async function P0(e,n,r,s="closed out"){if(n.length===0)return 0;const i=cn(),{data:o,error:a}=await w.from("jobs").update({job_status:"cancelled",updated_at:new Date().toISOString()}).in("id",n).eq("tenant_id",i).eq("ticket_id",e.id).neq("job_type","standard_install").not("job_status","in",'("complete","cancelled")').select("id");if(a)throw a;const l=(o==null?void 0:o.length)??0;for(const d of o??[])await Tt({entity_type:"job",entity_id:d.id,event_type:"status_changed",description:`Status: â cancelled (${e.ticket_number} ${s})`,metadata:{new_status:"cancelled",ticket_id:e.id},actor_id:r.actor_id,actor_name:r.actor_name??null});return l>0&&await Bn(e,"ticket_visits_cancelled",`${e.ticket_number}: ${l} scheduled visit${l===1?"":"s"} cancelled`,r,{job_ids:n}),l}function Sa(e){return{status:e,status_changed_at:new Date().toISOString()}}async function cU(e,n){await xo(e.id,Sa("waiting_on_customer")),await Bn(e,"ticket_status_changed",`${e.ticket_number}: waiting on customer`,n,{status:"waiting_on_customer"})}async function q0(e,n){await xo(e.id,Sa("open")),await Bn(e,"ticket_status_changed",`${e.ticket_number}: back to open`,n,{status:"open"})}async function k8(e,n,r,s={}){var o;const i=n.trim();if(!i)throw new Error("Say what fixed it.");await xo(e.id,{...Sa("resolved"),resolution:i,resolved_at:new Date().toISOString(),resolved_by:r.actor_id}),(o=s.cancelVisitIds)!=null&&o.length&&await P0(e,s.cancelVisitIds,r),await Bn(e,"ticket_resolved",`${e.ticket_number} resolved: ${i}`,r,{resolution:i}),await lf(e,`Confirm fix with customer â ${e.ticket_number}`,Ey(2),e.owner_id,r)}async function uU(e,n,r,s={}){var a;const i=n.trim();if(!i)throw new Error("A ticket cannot be closed without saying what fixed it.");await xo(e.id,{...Sa("closed"),resolution:i,closed_at:new Date().toISOString(),closed_by:r.actor_id}
656),(a=s.cancelVisitIds)!=null&&a.length&&await P0(e,s.cancelVisitIds,r);const o=(await S8(e.id)).filter(l=>!l.completed_at);for(const l of o)await fd(l.id);return await Bn(e,"ticket_closed",`${e.ticket_number} closed: ${i}`,r,{resolution:i,tasks_completed:o.length}),o.length}async function pU(e,n,r){await xo(e.id,{...Sa("open"),reopened_count:(e.reopened_count??0)+1,resolved_at:null,resolved_by:null,closed_at:null,closed_by:null});const s=n.trim();await Bn(e,"ticket_reopened",`${e.ticket_number} reopened${s?`: ${s}`:""}`,r,{reason:s||null})}async function tg(e){const n=cn(),{data:r,error:s}=await w.from("service_tickets").select("id, ticket_number, customer_id, owner_id, subject, status, reopened_count").eq("id",e).eq("tenant_id",n).limit(1);if(s)throw s;return r&&r[0]?r[0]:null}async function hU(e,n){const r=await tg(e);!r||r.status!=="open"&&r.status!=="scheduled"||(await xo(r.id,Sa("in_progress")),await Bn(r,"ticket_status_changed",`${r.ticket_number}: visit started`,n,{status:"in_progress"}))}async function fU(e,n,r,s){const i=await tg(e);if(!i)throw new Error("Ticket not found for this visit.");const o=r.trim();if(await b8({entity_type:"service_ticket",entity_id:i.id,body:`Visit completed â ${n==="fixed"?"fixed":n==="not_fixed"?"NOT fixed":"not sure if fixed"}. 657${o}`,section:"general",visibility:"all"}),n==="fixed"){if(i.status==="closed"||i.status==="resolved"){await Bn(i,"ticket_visit_fixed",`${i.ticket_number}: another visit completed, reported fixed`,s);return}await k8(i,o,s);return}if(n==="not_fixed"){i.status!=="open"&&await q0(i,s),await lf(i,`Book follow-up visit â ${i.ticket_number}`,Ey(1),i.owner_id,s);return}await Bn(i,"ticket_visit_unsure",`${i.ticket_number}: visit done, tech not sure it is fixed`,s),await lf(i,`Check with customer whether ${i.ticket_number} is fixed`,Ey(1),i.owner_id,s)}async function D0(e){(e.status==="open"||e.status==="waiting_on_customer")&&await xo(e.id,Sa("scheduled"))}async function gU(e,n,r,s,i,o){const a=cn(),{data:l,error:d}=await w.from("jobs").select("id, job_status, assigned_technician_id").eq("id",n).eq("tenant_id",a).eq("ticket_id",e.id).limit(1);if(d)throw d;const c=l==null?void 0:l[0];if(!c)throw new Error("That visit is not on this ticket.");if(c.job_status==="complete"||c.job_status==="cancelled")throw new Error("That visit is already finished.");const f=new Date().toISOString(),p={scheduled_at:r,updated_at:f};c.job_status==="ready_to_schedule"&&(p.job_status="scheduled"),(c.assigned_technician_id??null)!==s&&(p.assigned_technician_id=s,p.assigned_at=s?f:null);const{error:u}=await w.from("jobs").update(p).eq("id",n).eq("tenant_id",a);if(u)throw u;await Tt({entity_type:"job",entity_id:n,event_type:"job_rescheduled",description:`Visit moved to ${i}`,metadata:{scheduled_at:r,assigned_technician_id:s,ticket_id:e.id},actor_id:o.actor_id,actor_name:o.actor_name??null}),await Bn(e,"ticket_visit_moved",`${e.ticket_number}: visit moved to ${i}`,o,{job_id:n}),await D0(e)}async function mU(e,n,r){await Bn(e,"ticket_visit_booked",`${e.ticket_number}: visit booked â ${n}`,r),await D0(e)}async function xU(e,n,r){const s=await tg(e);s&&(await Bn(s,"ticket_visit_moved",`${s.ticket_number}: visit moved to ${n} (from Dispatch)`,r),await D0(s))}async function yU(e,n,r){const s=await tg(e);if(!s)throw new Error("Ticket not found for this visit.");const i=await P0(s,[n],r,"visit cancelled from Dispatch");if(i>0&&(s.status==="scheduled"||s.status==="in_progress")){const o=cn(),{data:a,error:l}=await w.from("jobs").select("id").eq("tenant_id",o).eq("ticket_id",s.id).not("job_status","in",'("complete","cancelled")').limit(1);if(l)throw l;(!a||a.length===0)&&await q0(s,r)}return i}async function Au(e){e.jobId&&await Tt({entity_type:"job",entity_id:e.jobId,event_type:e.eventType,title:e.title,metadata:{...e.metadata??{},from_status:e.fromStatus??null,to_status:e.toStatus??null},actor_id:e.actor.actor_id,actor_name:e.actor.actor_name??null})}function ka(e){const n=e.customers??null;return{...e,status:e.job_status??e.status??"scheduled",scheduled_date:e.scheduled_at?e.scheduled_at.split("T")[0]:e.sc
657heduled_date??null,customer_name_snapshot:e.customer_name_snapshot??(n?`${n.first_name} ${n.last_name}`:"Unknown"),phone_snapshot:e.phone_snapshot??(n==null?void 0:n.phone)??"",email_snapshot:e.email_snapshot??(n==null?void 0:n.email)??"",service_address_snapshot:e.service_address_snapshot??(n==null?void 0:n.address)??"",assigned_technician:e.assigned_technician??null}}async function bU(){const e=cn(),n=Kt();let r=w.from("jobs").select(` 658 id, tenant_id, branch_id, customer_id, lead_id, quote_id, 659 job_type, job_status, scheduled_at, completed_at, notes, 660 customer_name_snapshot, phone_snapshot, email_snapshot, service_address_snapshot, 661 source_quote_id, proof_approved, created_at, updated_at, 662 assigned_technician_id, 663 assigned_technician:profiles!assigned_technician_id(id, full_name), 664 ticket_id, 665 ticket:service_tickets!ticket_id(id, ticket_number, priority, subject, status), 666 customers!customer_id(first_name, last_name, phone, email) 667 `).eq("tenant_id",e);n&&(r=r.eq("branch_id",n));const{data:s,error:i}=await r;if(i)throw i;const o={ready_to_schedule:[],scheduled:[],waiting_for_stock:[],in_progress:[],complete:[]};for(const a of s||[]){const l=ka(a),d=l.status;o[d]&&o[d].push(l)}return o}async function AU(e){const n=cn(),{data:r,error:s}=await w.from("jobs").select(` 668 id, tenant_id, branch_id, customer_id, lead_id, quote_id, 669 job_type, job_status, scheduled_at, completed_at, notes, 670 customer_name_snapshot, phone_snapshot, email_snapshot, service_address_snapshot, 671 source_quote_id, proof_approved, created_at, updated_at, 672 assigned_technician_id, 673 assigned_technician:profiles!assigned_technician_id(id, full_name), 674 ticket_id, 675 ticket:service_tickets!ticket_id(id, ticket_number, priority, subject, status), 676 customers!customer_id(id, first_name, last_name, phone, email) 677 `).eq("id",e).eq("tenant_id",n).single();if(s)throw s;return ka(r)}async function vU(e){const{data:n,error:r}=await w.from("activity_log").select("*, title:description, job_id:entity_id").eq("entity_type","job").eq("entity_id",e).order("created_at",{ascending:!1}).limit(50);return r?(console.error("[fetchJobActivity] query failed:",r.message),[]):(n||[]).map(s=>({...s,description:s.title,lead_id:s.job_id}))}async function _U(e){const{data:n,error:r}=await w.from("job_checklists").select(` 678 id, job_id, item_text, section, sort_order, is_required, 679 is_completed, completed_at, completed_by, photo_url, 680 requires_photo, requires_tech_verification, tech_verified, 681 tech_verified_at, template_id, tenant_id 682 `).eq("job_id",e).order("sort_order",{ascending:!0});return r?[]:(n||[]).map(s=>({...s,status:s.is_completed?"complete":s.tech_verified?"verified":"pending"}))}async function jU(e){return[]}async function wU(e){return[]}async function SU(e){return[]}async function kU(){const e=cn(),{data:n,error:r}=await w.from("profiles").select("id, full_name, email, role, is_active").eq("tenant_id",e).in("role",["technician","admin"]).eq("is_active",!0).order("full_name");if(r)throw r;return n||[]}async function CU(e,n,r){const s=cn(),{data:i,error:o}=await w.from("jobs").update({assigned_technician_id:n,updated_at:new Date().toISOString()}).eq("id",e).eq("tenant_id",s).select(` 683 id, tenant_id, branch_id, customer_id, job_type, job_status, scheduled_at, 684 assigned_technician_id, customer_name_snapshot, phone_snapshot, email_snapshot, 685 service_address_snapshot, source_quote_id, proof_approved, notes, created_at, updated_at, 686 assigned_technician:profiles!assigned_technician_id(id, full_name) 687 `).single();if(o)throw o;return Au({jobId:e,actor:r,eventType:"technician_assigned",title:`Technician assigned by ${r.actor_name??"user"}`,metadata:{technician_id:n}}),ka(i)}async function TU(e,n,r,s){const i=cn(),o=(r==null?void 0:r.status)??null,a={job_status:n,updated_at:new Date().toISOString()};n==="complete"&&(a.completed_at=new Date().toISOString());const{data:l,error:d}=await w.from("jobs").update(a).eq("id",e).eq("tenant_id",i).select(` 688 id, tenant_id, branch_id, customer_id, job_type, job_status, scheduled_at, 689 assigned_technician_id, customer_name_snapshot, phone_snapshot, email_snapshot, 690 service_address_snapshot, source_quote_id, proof_approved, notes, created_at, updated_at, 691 assigned_technician:profiles!assigned_technician_id(id, full_name) 692 `).single();if(d)throw d;Au({jobId:e,actor:s,eventType:"status_changed",title:`Status: ${o??"unknown"} â ${n}`,fromStatus:o,toStatus:n,metadata:{new_status:n,old_status:o}});const c=r==null?void 0:r.ticket_id;return n==="in_progress"&&c&&hU(c,s).catch(f=>console.error("[ticket] start sync failed",f)),ka(l)}async function C8(e){const n={checklistTotal:0,checklistCompleted:0,photosRequired:0,photosProvided:0,verificationRequired:0,verificationCompleted:0,formsRequired:0,formsCompleted:0,generalPhotos:0,inventoryStatus:null,issues:[],ready:!1},{data:r}=await w.from("job_checklists").select("*").eq("job_id",e).eq("is_required",!0);return r&&(n.checklistTotal=r.length,n.checklistCompleted=r.filter(s=>s.is_completed).length,n.checklistCompleted<n.checklistTotal&&n.issues.push(n.checklistTotal-n.checklistCompleted+" required checklist items incomplete")),n.ready=n.issues.length===0,n}
692async function zU(e,n,r,s){const i={is_completed:!0,completed_at:new Date().toISOString(),completed_by:r.actor_id};s&&(i.photo_url=s);const{data:o,error:a}=await w.from("job_checklists").update(i).eq("id",e);if(a)throw a;return o}async function NU(e){const{data:n,error:r}=await w.from("job_checklists").update({is_completed:!1,completed_at:null,completed_by:null}).eq("id",e);if(r)throw r;return n}async function RU(e,n,r){const{data:s,error:i}=await w.from("job_checklists").update({tech_verified:!0,tech_verified_at:new Date().toISOString()}).eq("id",e);if(i)throw i;return s}async function EU(e,n,r,s,i){return{jobId:e,formType:n,responseData:r,signatureUrl:s}}async function PU(e,n){const r=cn(),s=Kt(),{data:i,error:o}=await w.from("jobs").insert({tenant_id:r,branch_id:s??null,lead_id:e.lead_id,customer_id:e.customer_id??null,quote_id:e.quote_id??null,job_type:e.job_type,job_status:"ready_to_schedule",scheduled_at:e.scheduled_at??null,notes:e.notes??null}).select(` 693 id, tenant_id, branch_id, customer_id, lead_id, quote_id, 694 job_type, job_status, scheduled_at, completed_at, notes, 695 customer_name_snapshot, phone_snapshot, email_snapshot, service_address_snapshot, 696 source_quote_id, proof_approved, created_at, updated_at, 697 assigned_technician_id, 698 assigned_technician:profiles!assigned_technician_id(id, full_name), 699 customers!customer_id(first_name, last_name, phone, email) 700 `).single();if(o)throw o;return Au({jobId:i.id,actor:n,eventType:"job_created",title:`Install job created for ${e.job_type}`,metadata:{job_type:e.job_type,lead_id:e.lead_id}}),ka(i)}async function T8(e,n){const r=cn(),s=Kt(),i=e.scheduled_at??null,o=e.assigned_technician_id??null,{data:a,error:l}=await w.from("jobs").insert({tenant_id:r,branch_id:s??null,customer_id:e.customer_id,job_type:"service",job_status:i?"scheduled":"ready_to_schedule",scheduled_at:i,notes:e.notes,created_by:n.actor_id,assigned_technician_id:o,assigned_at:o?new Date().toISOString():null,ticket_id:e.ticket_id??null}).select(` 701 id, tenant_id, branch_id, customer_id, lead_id, quote_id, 702 job_type, job_status, scheduled_at, completed_at, notes, 703 customer_name_snapshot, phone_snapshot, email_snapshot, service_address_snapshot, 704 source_quote_id, proof_approved, created_at, updated_at, 705 assigned_technician_id, 706 assigned_technician:profiles!assigned_technician_id(id, full_name), 707 customers!customer_id(first_name, last_name, phone, email) 708 `).single();if(l)throw l;return Au({jobId:a.id,actor:n,eventType:"job_created",title:"Service job created",metadata:{job_type:"service",customer_id:e.customer_id,scheduled:!!i,assigned:!!o,ticket_id:e.ticket_id??null}}),ka(a)}async function qU(e,n,r){const s=cn(),{data:i,error:o}=await w.from("jobs").update({scheduled_at:n,job_status:"scheduled",updated_at:new Date().toISOString()}).eq("id",e).eq("tenant_id",s).select(` 709 id, tenant_id, branch_id, customer_id, job_type, job_status, scheduled_at, 710 assigned_technician_id, customer_name_snapshot, phone_snapshot, email_snapshot, 711 service_address_snapshot, source_quote_id, proof_approved, notes, created_at, updated_at, 712 assigned_technician:profiles!assigned_technician_id(id, full_name) 713 `).single();if(o)throw o;return Au({jobId:e,actor:r,eventType:"job_scheduled",title:`Job scheduled for ${n}`,metadata:{scheduled_at:n}}),ka(i)}async function DU(e,n,r){return qU(e,n,r)}const et={all:["jobs"],board:()=>[...et.all,"board"],detail:e=>[...et.all,"detail",e],activity:e=>[...et.all,"activity",e],checklist:e=>[...et.all,"checklist",e],forms:e=>[...et.all,"forms",e],responses:e=>[...et.all,"responses",e],photos:e=>[...et.all,"photos",e],techs:["technicians"]};function z8(){return Ae({queryKey:et.board(),queryFn:bU,staleTime:2e4,refetchInterval:6e4})}function OU(e){return Ae({queryKey:et.detail(e),queryFn:()=>AU(e),enabled:!!e})}function IU(e){return Ae({queryKey:et.activity(e),queryFn:()=>vU(e),enabled:!!e})}function LU(e){return Ae({queryKey:et.checklist(e),queryFn:()=>_U(e),enabled:!!e})}function N8(e){return Ae({queryKey:et.forms(e),queryFn:()=>jU(),enabled:!!e})}function WU(e){return Ae({queryKey:et.responses(e),queryFn:()=>wU(),enabled:!!e})}function $U(e){return Ae({queryKey:et.photos(e),queryFn:()=>SU(),enabled:!!e})}function vu(){return Ae({queryKey:et.techs,queryFn:kU,staleTime:3e5})}function MU(){const e=rt(),{user:n,profile:r}=Ee();return _n({mutationFn:({jobId:s,techId:i}
713)=>CU(s,i,{actor_id:n.id,actor_name:r==null?void 0:r.full_name}),onSuccess:s=>{e.invalidateQueries({queryKey:et.board()}),e.setQueryData(et.detail(s.id),s),e.invalidateQueries({queryKey:et.activity(s.id)})}})}function ng(){const e=rt(),{user:n,profile:r}=Ee();return _n({mutationFn:({jobId:s,newStatus:i,currentJob:o})=>TU(s,i,o,{actor_id:n.id,actor_name:r==null?void 0:r.full_name}),onSuccess:s=>{e.invalidateQueries({queryKey:et.board()}),e.setQueryData(et.detail(s.id),s),e.invalidateQueries({queryKey:et.activity(s.id)})}})}function FU(){const e=rt(),{user:n,profile:r}=Ee();return _n({mutationFn:({itemId:s,jobId:i,photoUrl:o})=>zU(s,i,{actor_id:n.id,actor_name:r==null?void 0:r.full_name},o),onSuccess:(s,i)=>{e.invalidateQueries({queryKey:et.checklist(i.jobId)}),e.invalidateQueries({queryKey:et.activity(i.jobId)})}})}function BU(){const e=rt();return _n({mutationFn:({itemId:n,jobId:r})=>NU(n),onSuccess:(n,r)=>{e.invalidateQueries({queryKey:et.checklist(r.jobId)})}})}function UU(){const e=rt(),{user:n,profile:r}=Ee();return _n({mutationFn:({itemId:s,jobId:i})=>RU(s,i,{actor_id:n.id,actor_name:r==null?void 0:r.full_name}),onSuccess:(s,i)=>{e.invalidateQueries({queryKey:et.checklist(i.jobId)}),e.invalidateQueries({queryKey:et.activity(i.jobId)})}})}function R8(){const e=rt(),{user:n,profile:r}=Ee();return _n({mutationFn:({jobId:s,formType:i,responseData:o,signatureUrl:a})=>EU(s,i,o,a,{actor_id:n.id,actor_name:r==null?void 0:r.full_name}),onSuccess:(s,i)=>{e.invalidateQueries({queryKey:et.forms(i.jobId)}),e.invalidateQueries({queryKey:et.responses(i.jobId)}),e.invalidateQueries({queryKey:et.activity(i.jobId)})}})}const nd={ready_to_schedule:"Ready to Schedule",scheduled:"Scheduled",waiting_for_stock:"Waiting for Stock",in_progress:"In Progress",complete:"Complete",cancelled:"Cancelled"},E8={ready_to_schedule:"bg-purple-500/20 text-purple-400 border-purple-500/30",scheduled:"bg-accent/20 text-accent border-accent/30",waiting_for_stock:"bg-amber/20 text-amber border-amber/30",in_progress:"bg-cyan/20 text-cyan border-cyan/30",complete:"bg-green/20 text-green border-green/30",cancelled:"bg-red-500/20 text-red-400 border-red-500/30"},lo={softener_only:"Softener Only",pure_start_softener:"Pure Start + Softener",advanced_softener:"Advanced + Softener",dual_tank:"Dual Tank",ro_install:"RO Install",combo_whole_home_ro:"Combo (Whole Home + RO)"},P8={whole_home_handover:"Whole Home Customer Handover",ro_handover:"RO Customer Handover",ro_drilling_consent:"RO Drilling Consent"},HU={pre_installation:"Pre-Installation",system_installation:"System Installation",programming:"Programming",final_testing:"Final Testing",cleanup:"Cleanup",photo_requirements:"Photo Requirements",technician_verification:"Technician Verification"},VU=["ready_to_schedule","scheduled","waiting_for_stock","in_progress","complete"],ZU={draft:"Draft",sent:"Sent",paid:"Paid",overdue:"Overdue",void:"Void",signed:"Signed",partially_paid:"Part paid"},q8={draft:"#64748B",sent:"#0EA5E9",paid:"#16A34A",overdue:"#DC2626",void:"#94A3B8",signed:"#F59E0B",partially_paid:"#14B8A6"};function O0(e){var n,r,s;return{...e,customer_name:(n=e.customers)==null?void 0:n.full_name,customer_email:(r=e.customers)==null?void 0:r.email,customer_phone:(s=e.customers)==null?void 0:s.phone,line_items_snapshot:e.line_items_snapshot||[],subtotal:parseFloat(e.subtotal)||0,tax_amount:parseFloat(e.tax_amount)||0,discount_total:parseFloat(e.discount_total)||0,total:parseFloat(e.total_amount)||0,amount_paid:parseFloat(e.amount_paid)||0,amount_due:parseFloat(e.amount_due)||0}}async function KU(e){let n=w.from("invoices").select("*, customers!invoices_customer_id_fkey(full_name, email, phone)").order("created_at",{ascending:!1});const r=Kt();r&&(n=n.eq("branch_id",r));const{data:s,error:i}=await n;if(i)throw i;return(s||[]).map(O0)}async function D8(e){const{data:n,error:r}=await w.from("invoices").select("*, customers!invoices_customer_id_fkey(full_name, email, phone)").eq("id",e).single();return r?null:O0(n)}async function I0(e){const{data:n}=await w.from("addresses").select("address_line1, address_line2, city, state, zip").eq("entity_type","customer").eq("entity_id",e).eq("is_primary",!0).maybeSingle();if(n&&(n.address_line1||n.city)){const r=[n.address_line1,n.address_line2].filter(
713Boolean).join(" "),s=[n.city,n.state].filter(Boolean).join(", ")+(n.zip?` ${n.zip}`:"");return[r,s].filter(Boolean).join(", ")||null}return null}async function YU(){var o;const e=new Date().getFullYear(),n=Yt();let r=w.from("invoices").select("invoice_number").like("invoice_number",`INV-${e}-%`).order("invoice_number",{ascending:!1}).limit(1);n&&(r=r.eq("tenant_id",n));const{data:s}=await r,i=(o=s==null?void 0:s[0])!=null&&o.invoice_number&&parseInt(s[0].invoice_number.split("-")[2])||0;return`INV-${e}-${String(i+1).padStart(4,"0")}`}async function O8(e){const n=await I0(e.customer_id),r=await YU(),{data:s,error:i}=await w.from("invoices").insert({invoice_number:r,customer_id:e.customer_id,quote_id:e.quote_id||null,status:"draft",line_items_snapshot:e.line_items,subtotal:e.subtotal,tax_amount:e.tax_amount,total_amount:e.total,amount_due:e.total,due_date:e.due_date||null,notes:e.notes||null,customer_address:n}).select().single();if(i)throw i;return O0(s)}async function XU(e){const{data:n,error:r}=await w.from("quotes").select("*, quote_line_items(*)").eq("id",e).single();if(r||!n)throw new Error("Quote not found");const s=(n.quote_line_items||[]).map(i=>({description:i.description,quantity:i.quantity,unit_price:parseFloat(i.unit_price),total:parseFloat(i.total),item_type:i.item_type,discount_pct:parseFloat(i.discount_pct)||0,discount_amount:parseFloat(i.discount_amount)||0}));return O8({customer_id:n.customer_id,quote_id:e,line_items:s,subtotal:parseFloat(n.subtotal),tax_amount:parseFloat(n.tax_amount),total:parseFloat(n.total),due_date:new Date(Date.now()+14*864e5).toISOString().slice(0,10)})}async function nj(e,n,r){const s={status:n,...r};"total"in s&&delete s.total,s.sent_at=new Date().toISOString();const{error:i}=await w.from("invoices").update(s).eq("id",e);if(i)throw i}async function GU(e,n){const r=await D8(e);if(!r)throw new Error("Invoice not found");const s=n??r.total,i=s>=r.total,o={amount_paid:s,amount_due:Math.max(0,r.total-s)};i&&(o.status="paid",o.paid_at=new Date().toISOString());const{error:a}=await w.from("invoices").update(o).eq("id",e);if(a)throw a}async function JU(e){const{error:n}=await w.from("invoices").update({status:"void"}).eq("id",e);if(n)throw n}async function QU(){const e=new Date().toISOString().slice(0,10);let n=w.from("invoices").update({status:"overdue"}).in("status",["sent"]).lt("due_date",e);const r=Kt();r&&(n=n.eq("branch_id",r)),await n}function ac(e){return Math.max(0,e.total-e.amount_paid)}async function df(){var n;const{data:{user:e}}=await w.auth.getUser();return((n=e==null?void 0:e.user_metadata)==null?void 0:n.tenant_id)||null}async function L0(e){if(!e)return .07;const{data:n}=await w.from("tenants").select("tax_rate").eq("id",e).maybeSingle();return typeof(n==null?void 0:n.tax_rate)=="number"?n.tax_rate:.07}function I8(e){return parseFloat(e.reduce((n,r)=>n+(Number(r.discount_amount)||0),0).toFixed(2))}async function eH(e){const n=new Map;if(e.length===0)return n;const{data:r}=await w.from("addresses").select("entity_id, address_line1, address_line2, city, state, zip").eq("entity_type","customer").eq("is_primary",!0).in("entity_id",e);for(const s of r||[]){const i=[s.address_line1,s.address_line2,s.city,s.state,s.zip].filter(Boolean);i.length&&n.set(s.entity_id,i.join(", "))}for(const s of e)n.has(s)||n.set(s,"");return n}async function L8(){const{data:e,error:n}=await w.from("product_catalog").select("*").eq("is_active",!0).order("name");if(n)throw n;return e||[]}async function rg(e){let n=w.from("quotes").select("*").order("created_at",{ascending:!1});e&&(n=n.eq("customer_id",e));const r=Kt();r&&(n=n.eq("branch_id",r));const{data:s,error:i}=await n;if(i)throw i;if(!s||s.length===0)return[];const o=[...new Set(s.map(u=>u.customer_id).filter(Boolean))],{data:a}=o.length?await w.from("customers").select("id, full_name, email, phone").in("id",o):{data:[]},l={};for(const u of a||[])l[u.id]=u;const d=await eH(o),c=s.map(u=>u.id),{data:f}=c.length?await w.from("document_audit_log").select("entity_id").eq("entity_type","quote").eq("event","viewed").in("entity_id",c):{data:[]},p={};for(const u of f||[])p[u.entity_id]=(p[u.entity_id]||0)+1;return s.map(u=>{const h=l[u.customer_id]||{};return{...u,valid_until:u.expires_at,customer_name:h.full_name||"",customer_email:h.email||"",customer_phone:h.phone||"",customer_address:d.get(u.customer_id)||"",view_count:p[u.id]||0}})}async function W8(e){const{data:n}=await w.from("document_audit_log").select("event, actor_type, created_at").eq("entity_type","quote").eq("entity_id",e).order("created_at",{ascending:!1}).limit(50);return n||[]}async function tH(e){const{data:n,error:r}=await w.from("quotes").select("*").eq("id",e).single();if(r)throw r;if(!n)return null;let{data:s}=await w.from("document_line_items").select("*").eq("quote_id",e).order("sort_order");if(!s||s.length===0){const{data:l}=await w.from("quote_line_items").select("*").eq("quote_id",e).order("sort_order");s=l||[]}
713const i=(s||[]).map(l=>({...l,total:l.total??l.total_price??0})).sort((l,d)=>l.sort_order-d.sort_order),{data:o}=await w.from("customers").select("id, full_name, email, phone").eq("id",n.customer_id).single(),a=await I0(n.customer_id).catch(()=>null);return{...n,valid_until:n.expires_at,customer_name:(o==null?void 0:o.full_name)||"",customer_email:(o==null?void 0:o.email)||"",customer_phone:(o==null?void 0:o.phone)||"",customer_address:a||"",line_items:i}}async function $8(e){const n=await df(),r=await L0(n),s=e.line_items.reduce((b,A)=>b+A.total,0),i=parseFloat((s*r).toFixed(2)),o=parseFloat((s+i).toFixed(2)),l=e.commercial_type==="rental"?e.line_items.filter(b=>b.item_type!=="install_fee"&&b.item_type!=="service_plan").reduce((b,A)=>b+A.total,0):null,d=e.line_items.filter(b=>b.item_type==="install_fee").reduce((b,A)=>b+A.total,0)||null,c=new Date().getFullYear();let f=w.from("quotes").select("quote_number").like("quote_number",`Q-${c}-%`).order("quote_number",{ascending:!1}).limit(1);n&&(f=f.eq("tenant_id",n));const{data:p}=await f.maybeSingle();let u=1;if(p!=null&&p.quote_number){const b=p.quote_number.split("-");u=(parseInt(b[b.length-1],10)||0)+1}const h=`Q-${c}-${String(u).padStart(4,"0")}`,{data:y,error:m}=await w.from("quotes").insert({tenant_id:n,quote_number:h,customer_id:e.customer_id,commercial_type:e.commercial_type,lead_id:e.lead_id||null,created_by:e.created_by||null,notes:e.notes||null,expires_at:e.valid_until||null,subtotal:s,tax_amount:i,total:o,monthly_rental_price:l,install_fee:d,discount_total:I8(e.line_items),status:"draft"}).select().single();if(m)throw m;if(e.line_items.length>0){const b=e.line_items.map((x,_)=>({product_id:x.product_id||null,product_catalog_id:x.item_type==="product"&&x.product_id||null,description:x.description,quantity:x.quantity,unit_price:x.unit_price,total:x.total,item_type:x.item_type,sort_order:_,sku:x.sku||null,discount_pct:x.discount_pct??0,discount_amount:x.discount_amount??0})),{error:A}=await w.from("document_line_items").insert(b.map(x=>({tenant_id:n,quote_id:y.id,product_id:x.product_id,product_catalog_id:x.product_catalog_id,description:x.description,quantity:x.quantity,unit_price:x.unit_price,total_price:x.total,item_type:x.item_type,sort_order:x.sort_order,sku:x.sku,discount_pct:x.discount_pct,discount_amount:x.discount_amount})));if(A)throw A;const{error:v}=await w.from("quote_line_items").insert(b.map(x=>({tenant_id:n,quote_id:y.id,product_id:x.product_id,description:x.description,quantity:x.quantity,unit_price:x.unit_price,total:x.total,item_type:x.item_type,sort_order:x.sort_order,sku:x.sku,discount_pct:x.discount_pct,discount_amount:x.discount_amount})));v&&console.warn("quote_line_items insert failed (non-fatal):",v.message)}return{...y,valid_until:y.expires_at}}async function M8(e,n){const{data:r}=await w.from("quotes").select("status").eq("id",e).single();if((r==null?void 0:r.status)!=="draft")throw new Error("Cannot edit a non-draft quote");if(n.line_items!==void 0){const s=await df(),i=await L0(s),o=n.line_items.reduce((p,u)=>p+u.total,0),a=parseFloat((o*i).toFixed(2)),l=parseFloat((o+a).toFixed(2)),c=n.commercial_type==="rental"?n.line_items.filter(p=>p.item_type!=="install_fee").reduce((p,u)=>p+u.total,0):null,f=n.line_items.filter(p=>p.item_type==="install_fee").reduce((p,u)=>p+u.total,0)||null;if(await w.from("document_line_items").delete().eq("quote_id",e),await w.from("quote_line_items").delete().eq("quote_id",e),n.line_items.length>0){const p=n.line_items.map((u,h)=>({product_id:u.product_id||null,product_catalog_id:u.item_type==="product"&&u.product_id||null,description:u.description,quantity:u.quantity,unit_price:u.unit_price,total:u.total,item_type:u.item_type,sort_order:h,sku:u.sku||null,discount_pct:u.discount_pct??0,discount_amount:u.discount_amount??0}));await w.from("document_line_items").insert(p.map(u=>({tenant_id:s,quote_id:e,product_id:u.product_id,product_catalog_id:u.product_catalog_id,description:u.description,quantity:u.quantity,unit_price:u.unit_price,total_price:u.total,item_type:u.item_type,sort_order:u.sort_order,sku:u.sku,discount_pct:u.discount_pct,discount_amount:u.discount_amount}))),await w.from("quote_line_items").insert(p.map(u=>({tenant_id:s,quote_id:e,product_id:u.product_id,description:u.description,quantity:u.quantity,unit_price:u.unit_price,total:u.total,item_type:u.item_type,sort_order:u.sort_order,sku:u.sku,discount_pct:u.discount_pct,discount_amount:u.discount_amount}))).then(({error:u})=>{u&&console.warn("quote_line_items update failed (non-fatal):",u.message)})}await w.from("quotes").update({commercial_type:n.commercial_type,notes:n.notes,expires_at:n.valid_until,subtotal:o,tax_amount:a,total:l,monthly_rental_price:c,install_fee:f,discount_total:I8(n.line_items)}).eq("id",e)}}async function _u(e){var d,c,f;const n=crypto.randomUUID(),r=n,{data:s}=await w.from("document_line_items").select("*").eq("quote_id",e).order("sort_order"),i=s||[],{data:o,error:a}=await w.from("quotes").update({status:"sent",sent_at:new Date().toISOString(),line_items_snapshot:i,accept_token:n,public_token:r}).eq("id",e).eq("status","draft").select("id, lead_id").maybeSingle();if(a)throw a;let l=(o==null?void 0:o.lead_id)??null;if(!l){const{data:p}=await w.from("quotes").select("lead_id").eq("id",e).maybeSingle();l=(p==null?void 0:p.lead_id)??null}if(l)try{const{data:p}=await w.from("leads").select("id, stage").eq("id",l).maybeSingle();if(p&&["new_lead","qualifying","qualified","site_visit_scheduled","proposal_in_progress"].includes(p.stage)){const{data:h}=await w.auth.getUser(),y={actor_id:((d=h==null?void 0:h.user)==null?void 0:d.id)||"",actor_name:((f=(c=h==null?void 0:h.user)==null?void 0:c.user_metadata)==null?void 0:f.full_name)||void 0};y.actor_id?await xl(p.id,p.stage,"quote_sent",y):console.warn("sendQuote: no authenticated user, stage not advanced")}}catch(p){console.warn("sendQuote: stage advance failed (non-fatal):",p)}try{await w.from("document_audit_log").insert({entity_type:"quote",entity_id:e,event:"sent",actor_type:"staff"})}catch(p){console.warn("document_audit_log insert failed (non-fatal):",p)}return n}const cf={draft:"Draft",sent:"Sent",viewed:"Viewed",accepted:"Accepted",signed:"Signed",declined:"Declined",expired:"Expired",superseded:"Superseded"},uf={draft:{bg:"#1e293b",text:"#94a3b8"},sent:{bg:"#1e3a5f",text:"#60a5fa"},viewed:{bg:"#1c3a2e",text:"#34d399"},accepted:{bg:"#14532d",text:"#4ade80"},signed:{bg:"#0c2a3f",text:"#38bdf8"},declined:{bg:"#3b1414",text:"#f87171"},expired:{bg:"#27272a",text:"#71717a"},superseded:{bg:"#27272a",text:"#71717a"}},pf={rental:"Rental",purchase:"Purchase",financed:"Financed"},hf={rental:"#22d3ee",purchase:"#4ade80",financed:"#f472b6"};async function F8(e,n){const{error:r}=await w.from("leads").update({financing_status:n}).eq("id",e);if(r)throw r}async function B8(e,n,r){const{data:s,error:i}=await w.from("quotes").select("*").eq("id",e).single();if(i||!s)throw new Error("Original quote not found");const{data:o}=await w.from("document_line_items").select("*").eq("quote_id",e).order("sort_order"),{data:a}=await w.from("quote_line_items").select("*").eq("quote_id",e).order("sort_order"),l=o!=null&&o.length?o:a||[],d=l.map(O=>
713O.product_id).filter(Boolean),c=new Map;if(d.length){const{data:O}=await w.from("product_catalog").select("id, rental_price_monthly, retail_price, install_fee").in("id",d);(O||[]).forEach(z=>c.set(z.id,z))}function f(O){if(O.item_type==="install_fee"||(O.description||"").toLowerCase().includes("installation fee"))return{unit_price:O.unit_price,total:O.total??O.total_price??0};if(O.product_id&&c.has(O.product_id)){const P=c.get(O.product_id);if(n==="rental"){const D=P.rental_price_monthly??O.unit_price;return{unit_price:D,total:D*(O.quantity||1)}}else{const D=P.retail_price??O.unit_price;return{unit_price:D,total:D*(O.quantity||1)}}}return{unit_price:O.unit_price,total:O.total??O.total_price??0}}const p=l.map(O=>{const{unit_price:z,total:P}=f(O);return{...O,unit_price:z,total:P}}),u=p.filter(O=>O.item_type==="install_fee"||(O.description||"").toLowerCase().includes("installation fee")),y=p.filter(O=>O.item_type!=="install_fee"&&!(O.description||"").toLowerCase().includes("installation fee")).reduce((O,z)=>O+(z.total||0),0),m=u.reduce((O,z)=>O+(z.total||0),0),b=n==="rental"?y:null,A=n==="rental"?y:y+m,v=await L0(await df()),x=n==="rental"?0:parseFloat((y*v).toFixed(2)),_=n==="rental"?A:parseFloat((A+x).toFixed(2)),j=await df(),C=new Date().getFullYear();let S=w.from("quotes").select("quote_number").like("quote_number",`Q-${C}-%`).order("quote_number",{ascending:!1}).limit(1);j&&(S=S.eq("tenant_id",j));const{data:T}=await S.maybeSingle();let L=1;if(T!=null&&T.quote_number){const O=T.quote_number.split("-");L=(parseInt(O[O.length-1],10)||0)+1}const E=`Q-${C}-${String(L).padStart(4,"0")}`,{data:R,error:N}=await w.from("quotes").insert({tenant_id:j,quote_number:E,lead_id:r,customer_id:s.customer_id,commercial_type:n,status:"draft",subtotal:y,tax_amount:x,total:_,monthly_rental_price:b,install_fee:m||s.install_fee,expires_at:new Date(Date.now()+14*24*60*60*1e3).toISOString().split("T")[0],notes:s.notes,parent_quote_id:e,reissue_reason:"financing_declined"}).select("id").single();if(N||!R)throw new Error("Failed to create cloned quote: "+(N==null?void 0:N.message));if(o!=null&&o.length){const O=p.map(({id:z,created_at:P,...D})=>({tenant_id:j,quote_id:R.id,product_id:D.product_id||null,product_catalog_id:D.product_catalog_id||null,description:D.description,quantity:D.quantity,unit_price:D.unit_price,total_price:D.total??D.total_price??0,item_type:D.item_type,sort_order:D.sort_order,sku:D.sku||null}));await w.from("document_line_items").insert(O)}if(a!=null&&a.length||!(o!=null&&o.length)){const O=p;if(O.length){const z=O.map(({id:P,created_at:D,...M})=>({tenant_id:j,quote_id:R.id,product_id:M.product_id||null,description:M.description,quantity:M.quantity,unit_price:M.unit_price,total:M.total??M.total_price??0,item_type:M.item_type,sort_order:M.sort_order,sku:M.sku||null}));await w.from("quote_line_items").insert(z)}}return R.id}const nH=Object.freeze(Object.defineProperty({__proto__:null,STATUS_COLORS:uf,STATUS_LABELS:cf,TYPE_COLORS:hf,TYPE_LABELS:pf,cloneQuote:B8,createQuote:$8,fetchProducts:L8,fetchQuote:tH,fetchQuoteActivity:W8,fetchQuotes:rg,sendQuote:_u,updateLeadFinancingStatus:F8,updateQuote:M8},Symbol.toStringTag,{value:"Module"}));function jm(e){return e?`$${Number(e).toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}`:"â"}function rH(e){return e?new Date(e).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit"}):"â"}function rj({active:e,activeLabel:n,inactiveLabel:r}){return t.jsx("span",{className:`text-xs px-2 py-0.5 rounded-full font-semibold ${e?"bg-green/20 text-green":"bg-muted/20 text-muted"}`,children:e?n:r})}function wm(e){const n=r=>e.includes(r);return n("ro")&&n("softener")||n("ro")&&n("whole_home_filter")?"combo_whole_home_ro":n("ro")?"ro_install":(n("softener")||n("whole_home_filter")||n("filtration"),"softener_only")}function Sm(e,n){if(n!=null&&n.length){const r=n.map(s=>(s.description||s.name||"").toLowerCase()).join(" ");if(r.includes("combo")||(r.includes("ro")||r.includes("reverse osmosis"))&&r.includes("softener"))return"combo_whole_home_ro";if(r.includes("dual tank"))return"dual_tank";if(r.includes("advanced")&&r.includes("softener"))return"advanced_softener";if(r.includes("pure start"))return"pure_start_softener";if(r.includes("ro")||r.includes("reverse osmosis"))return"ro_install";if(r.includes("softener"))return"softener_only"}if(e){const r=e.toLowerCase();if(r.includes("combo"))return"combo_whole_home_ro";if(r.includes("dual"))return"dual_tank";if(r.includes("advanced"))return"advanced_softener";if(r.includes("pure"))return"pure_start_softener";if(r.includes("ro"))return"ro_install";if(r.includes("softener"))return"softener_only"}return"softener_only"}const sH=["softener_only","pure_start_softener","advanced_softener","dual_tank","ro_install","combo_whole_home_ro"],iH={ro:"Reverse Osmosis",softener:"Water Softener",whole_home_filter:"Whole Home Filter",replacement_filter:"Replacement Filter",accessory:"Accessory",service:"Service"},oH=["Su","Mo","Tu","We","Th","Fr","Sa"],aH=["January","February","March","April","May","June","July","August","September","October","November","December"],Py=[8,9,10,11,12,13,14,15,16,17];function qy(e){return e===12?"12:00 PM":e<12?`${e}:00 AM`:`${e-12}:00 PM`}function lH({selectedHour:e,onSelect:n,bookedHours:r}
713){return t.jsx("div",{className:"grid grid-cols-5 gap-1.5",children:Py.map(s=>{const i=r.includes(s),o=e===s;return t.jsxs("button",{onClick:()=>{i||n(s)},disabled:i,className:` 714 py-2 rounded-lg text-xs font-semibold transition-all border 715 ${i?"bg-red-500/10 border-red-500/30 text-red-400/60 cursor-not-allowed line-through":o?"bg-cyan border-cyan text-white shadow-lg shadow-cyan/20":"bg-surface border-border text-slate-300 hover:border-accent hover:text-white cursor-pointer"} 716 `,children:[qy(s),i&&t.jsx("div",{className:"text-[9px] mt-0.5 no-underline",style:{textDecoration:"none"},children:"Booked"})]},s)})})}function dH({selectedDate:e,onSelect:n,jobSlots:r}){const s=new Date,[i,o]=g.useState(()=>{if(e){const b=new Date(e+"T12:00:00");return new Date(b.getFullYear(),b.getMonth(),1)}return new Date(s.getFullYear(),s.getMonth(),1)}),a=i.getFullYear(),l=i.getMonth(),d=g.useMemo(()=>{const b=new Map;return r.forEach(A=>b.set(A.date,A)),b},[r]),c=new Date(a,l,1).getDay(),f=new Date(a,l+1,0).getDate(),p=new Date(a,l,0).getDate(),u=[];for(let b=c-1;b>=0;b--)u.push({date:new Date(a,l-1,p-b),current:!1});for(let b=1;b<=f;b++)u.push({date:new Date(a,l,b),current:!0});for(;u.length<42;)u.push({date:new Date(a,l+1,u.length-c-f+1),current:!1});function h(b){return`${b.getFullYear()}-${String(b.getMonth()+1).padStart(2,"0")}-${String(b.getDate()).padStart(2,"0")}`}function y(b){return b.getFullYear()===s.getFullYear()&&b.getMonth()===s.getMonth()&&b.getDate()===s.getDate()}function m(b){const A=new Date(s.getFullYear(),s.getMonth(),s.getDate());return b<A}return t.jsxs("div",{className:"bg-surface border border-border rounded-xl p-3",children:[t.jsxs("div",{className:"flex items-center justify-between mb-3",children:[t.jsx("button",{onClick:()=>o(new Date(a,l-1,1)),className:"text-muted hover:text-white w-6 h-6 flex items-center justify-center rounded transition-colors",children:"â¹"}),t.jsxs("span",{className:"text-xs font-bold text-white",children:[aH[l]," ",a]}),t.jsx("button",{onClick:()=>o(new Date(a,l+1,1)),className:"text-muted hover:text-white w-6 h-6 flex items-center justify-center rounded transition-colors",children:"âº"})]}),t.jsx("div",{className:"grid grid-cols-7 mb-1",children:oH.map(b=>t.jsx("div",{className:"text-center text-xs text-muted font-semibold py-0.5",children:b},b))}),t.jsx("div",{className:"grid grid-cols-7 gap-0.5",children:u.map((b,A)=>{const v=h(b.date),x=d.get(v),_=e===v,j=m(b.date),C=(x==null?void 0:x.count)||0,S=C>=Py.length,T=C===0?"text-green/60":C<=2?"text-yellow-400":C<=5?"text-orange-400":"text-red-400";return t.jsxs("button",{onClick:()=>{b.current&&!j&&!S&&n(v)},disabled:!b.current||j||S,title:x?`${C} booked: ${x.customerNames.join(", ")}`:"Open",className:` 717 relative flex flex-col items-center justify-center rounded-lg py-1.5 transition-all 718 ${!b.current||j||S?"opacity-30 cursor-not-allowed":"cursor-pointer hover:bg-card"} 719 ${_?"bg-cyan ring-2 ring-cyan text-white":""} 720 ${y(b.date)&&!_?"ring-1 ring-accent":""} 721 `,children:[t.jsx("span",{className:`text-xs font-semibold leading-none ${_?"text-white":b.current?"text-slate-300":"text-muted"}`,children:b.date.getDate()}),b.current&&!j&&t.jsx("span",{className:`text-[9px] font-bold mt-0.5 leading-none ${_?"text-white/80":T}`,children:C===0?"â":`${C}/${Py.length}`})]},A)})}),t.jsxs("div",{className:"flex items-center gap-3 mt-3 pt-2 border-t border-border/50",children:[t.jsx("span",{className:"text-[10px] text-green/70 font-semibold",children:"â open"}),t.jsx("span",{className:"text-[10px] text-yellow-400 font-semibold",children:"light"}),t.jsx("span",{className:"text-[10px] text-orange-400 font-semibold",children:"moderate"}),t.jsx("span",{className:"text-[10px] text-red-400 font-semibold",children:"busy"})]})]})}function cH({lead:e,onLeadUpdated:n}){const{user:r,profile:s}=Ee(),i=rt(),{data:o}=vu(),a=(s==null?void 0:s.role)==="salesrep",[l,d]=g.useState(!1),[c,f]=g.useState(!1),[p,u]=g.useState(!1),[h,y]=g.useState(!1),[m,b]=g.useState(e.install_preferred_date?new Date(e.install_preferred_date).toISOString().split("T")[0]:""),[A,v]=g.useState(null),[x,_]=g.useState(""),[j,C]=g.useState("softener_only"),[S,T]=g.useState(!1),[L,E]=g.useState(""),[R,N]=g.useState(!1),[O,z]=g.useState([]),[P,D]=g.useState(null),[M,k]=g.useState([]),[q,$]=g.useState(null),[I,B]=g.useState(!1),[J,ae]=g.useState(null),[te,U]=g.useState(null),[W,G]=g.useState(null),[V,ee]=g.useState(null),[re,Q]=g.useState(null),[oe,ne]=g.useState(null),ge=!!e.job_created||!!V,be=V&&(re==="ready_to_schedule"||re==="waiting_for_stock"),we=V&&re==="scheduled";g.useEffect(()=>{async function fe(){const{data:le}=await w.from("jobs").select("id, job_status, scheduled_at").eq("lead_id",e.id).limit(1).maybeSingle();le&&(ee(le.id),Q(le.job_status),ne(le.scheduled_at))}fe()},[e.id]),g.useEffect(()=>{async function fe(){const le=e.converted_to_customer_id??null,ce=le?await ba("customer",le):await ba("lead",e.id),xe=[(ce==null?void 0:ce.address_line1)??e.address,(ce==null?void 0:ce.city)??e.city,(ce==null?void 0:ce.state)??e.state,(ce==null?void 0:ce.zip)??(e.zip||e.zip_code)].filter(
721Boolean).join(", ");U(xe||null);let ve=null;const{data:_e}=await w.from("agreements").select("signed_by, signed_at").eq("lead_id",e.id).order("created_at",{ascending:!1}).limit(1).maybeSingle();if(ve=_e,!ve&&le){const{data:bt}=await w.from("agreements").select("signed_by, signed_at").eq("customer_id",le).order("created_at",{ascending:!1}).limit(1).maybeSingle();ve=bt}let je=null;const{data:Be}=await w.from("quotes").select("total, monthly_rental_price, commercial_type, signed_at").eq("lead_id",e.id).in("status",["accepted","signed"]).order("created_at",{ascending:!1}).limit(1).maybeSingle();if(je=Be,!je&&le){const{data:bt}=await w.from("quotes").select("total, monthly_rental_price, commercial_type, signed_at").eq("customer_id",le).in("status",["accepted","signed"]).order("created_at",{ascending:!1}).limit(1).maybeSingle();je=bt}if(!je){const{data:bt}=await w.from("quotes").select("total, monthly_rental_price, commercial_type, signed_at").eq("lead_id",e.id).order("created_at",{ascending:!1}).limit(1).maybeSingle();je=bt}G({signed_by:(ve==null?void 0:ve.signed_by)||e.signed_by||null,signed_at:(ve==null?void 0:ve.signed_at)||(je==null?void 0:je.signed_at)||e.signed_at||null,quote_total:(je==null?void 0:je.total)||e.quote_total||null,monthly_amount:(je==null?void 0:je.monthly_rental_price)||null,commercial_type:(je==null?void 0:je.commercial_type)||null});const{data:Je}=await w.from("leads").select("financing_status").eq("id",e.id).maybeSingle();Je!=null&&Je.financing_status&&$(Je.financing_status)}fe()},[e.id]);function F(fe){C(fe),(fe==="ro_install"||fe==="combo_whole_home_ro")&&T(!0)}async function K(fe){const le=fe.map(ve=>ve.product_id).filter(Boolean);if(!le.length)return[];const{data:ce}=await w.from("product_catalog").select("id, name, category").in("id",le),xe=new Map((ce||[]).map(ve=>[ve.id,ve]));return fe.filter(ve=>ve.product_id&&xe.has(ve.product_id)).map(ve=>({name:xe.get(ve.product_id).name,category:xe.get(ve.product_id).category,quantity:ve.quantity||1}))}async function Z(){y(!0);try{const{data:fe}=await w.from("jobs").select("scheduled_at, customer_name_snapshot, job_status").not("scheduled_at","is",null).in("job_status",["scheduled","in_progress","waiting_for_stock"]),le=new Map;(fe||[]).forEach(ce=>{const xe=new Date(ce.scheduled_at),ve=`${xe.getFullYear()}-${String(xe.getMonth()+1).padStart(2,"0")}-${String(xe.getDate()).padStart(2,"0")}`,_e=xe.getHours();le.has(ve)||le.set(ve,{date:ve,count:0,customerNames:[],bookedHours:[]});const je=le.get(ve);je.count++,je.customerNames.push(ce.customer_name_snapshot),_e>=8&&je.bookedHours.push(_e)}),k(Array.from(le.values()))}catch(fe){console.error("Failed to load job slots",fe)}finally{y(!1)}}async function ie(){if(!R){u(!0);try{const{data:fe}=await w.from("quotes").select("id").eq("lead_id",e.id).in("status",["accepted","signed"]).order("created_at",{ascending:!1}).limit(1).maybeSingle();if(fe){const{data:xe}=await w.from("document_line_items").select("product_id, description, quantity").eq("document_id",fe.id).order("sort_order",{ascending:!0});if(xe&&xe.length>0){const ve=xe.map(Je=>Je.product_id).filter(Boolean);let _e=new Map;if(ve.length>0){const{data:Je}=await w.from("product_catalog").select("id, name, category, sku").in("id",ve);_e=new Map((Je||[]).map(bt=>[bt.id,bt]))}const je=xe.filter(Je=>Je.product_id&&_e.has(Je.product_id)).map(Je=>{const bt=_e.get(Je.product_id);return{name:bt.name,category:bt.category,quantity:Je.quantity||1,sku:bt.sku}});if(je.length>0){z(je),D("line_items"),F(wm(je.map(Je=>Je.category))),N(!0);return}const Be=xe.filter(Je=>Je.description).map(Je=>({name:Je.description,category:"",quantity:Je.quantity||1}));if(Be.length>0){z(Be),D("line_items");const Je=Sm(null,xe.map(bt=>({description:bt.description})));F(Je),N(!0);return}}}const{data:le}=await w.from("agreements").select("agreement_type, line_items_snapshot, commercial_type").eq("lead_id",e.id).order("created_at",{ascending:!1}).limit(1).maybeSingle();if(le!=null&&le.line_items_snapshot){const xe=typeof le.line_items_snapshot=="string"?JSON.parse(le.line_items_snapshot):le.line_items_snapshot,ve=await K(xe);if(ve.length>0){z(ve),D("invoice"),F(wm(ve.map(Be=>Be.category))),N(!0);return}const _e=Sm(le.agreement_type||le.commercial_type||null,xe),je=xe.filter(Be=>Be.description||Be.name).map(Be=>({name:Be.description||Be.name,category:"",quantity:Be.quantity||1}
721));z(je),D("invoice"),F(_e),N(!0);return}const{data:ce}=await w.from("quotes").select("line_items_snapshot, commercial_type").eq("lead_id",e.id).order("created_at",{ascending:!1}).limit(1).maybeSingle();if(ce!=null&&ce.line_items_snapshot){const xe=typeof ce.line_items_snapshot=="string"?JSON.parse(ce.line_items_snapshot):ce.line_items_snapshot,ve=await K(xe);if(ve.length>0){z(ve),D("quote"),F(wm(ve.map(Be=>Be.category))),N(!0);return}const _e=Sm(ce.commercial_type||null,xe),je=xe.filter(Be=>Be.description||Be.name).map(Be=>({name:Be.description||Be.name,category:"",quantity:Be.quantity||1}));z(je),D("quote"),F(_e),N(!0);return}if(D("fallback"),e.water_concern){const xe=e.water_concern.toLowerCase();xe.includes("ro")||xe.includes("reverse")?F("ro_install"):xe.includes("combo")&&F("combo_whole_home_ro")}N(!0)}catch(fe){console.error("Could not detect system type:",fe)}finally{u(!1)}}}function Y(){d(!0),ie(),Z()}function X(fe){b(fe),v(null)}function H(){return!m||A===null?m||null:`${m}T${String(A).padStart(2,"0")}:00:00`}async function de(){if(r){f(!0);try{const fe=H();if(V&&be)await DU(V,fe||m,x||null,L||null,{actor_id:r.id,actor_name:s==null?void 0:s.full_name}),Q("scheduled"),ne(fe||m);else{const le=await PU(e,j,fe,S,{actor_id:r.id,actor_name:s==null?void 0:s.full_name});x&&await w.from("jobs").update({assigned_technician_id:x,assigned_at:new Date().toISOString()}).eq("id",le.id),L&&await w.from("jobs").update({notes:L}).eq("id",le.id),ee(le.id),Q(le.status)}i.invalidateQueries({queryKey:et.board()}),i.invalidateQueries({queryKey:it.kanban()}),i.invalidateQueries({queryKey:it.counts}),n==null||n(e),d(!1)}catch(fe){alert("Failed: "+(fe.message||fe))}finally{f(!1)}}}const pe=m?M.find(fe=>fe.date===m):null,Ne=(pe==null?void 0:pe.bookedHours)||[],Ie=m?new Date(m+"T12:00:00").toLocaleDateString("en-US",{weekday:"long",month:"long",day:"numeric",year:"numeric"}):null,Ze=!c&&!p&&!!m&&A!==null;async function ht(fe){B(!0);try{if(await F8(e.id,fe),$(fe),fe==="approved"){let le=e.converted_to_customer_id;const ce=e.tenant_id;if(!le&&ce){const{data:xe}=await w.from("quotes").select("customer_id").eq("lead_id",e.id).in("status",["signed","accepted"]).order("created_at",{ascending:!1}).limit(1).maybeSingle();le=(xe==null?void 0:xe.customer_id)||null}if(le&&ce){const{data:{session:xe}}=await w.auth.getSession(),_e=await(await fetch("/api/financing/approve",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${(xe==null?void 0:xe.access_token)||""}`},body:JSON.stringify({lead_id:e.id,customer_id:le,tenant_id:ce})})).json();_e.success?console.log("[AgreementSignedPanel] Financing approved, payment link sent"):(console.error("[AgreementSignedPanel] Financing approve API error:",_e.error),alert("Financing status updated, but failed to send payment link: "+(_e.error||"Unknown error")))}}}catch(le){alert("Failed to update financing status: "+le.message)}finally{B(!1)}}async function ke(fe){B(!0),ae(null);try{const{data:le}=await w.from("quotes").select("id").eq("lead_id",e.id).eq("commercial_type","financed").in("status",["signed","accepted"]).order("created_at",{ascending:!1}).limit(1).maybeSingle();if(!le)throw new Error("Original financed quote not found");const ce=await B8(le.id,fe,e.id);try{await fetch("/api/email/send-quote",{method:"POST",headers:await At(),body:JSON.stringify({quoteId:ce,senderEmail:s==null?void 0:s.email,senderName:s==null?void 0:s.full_name})})}catch{}await _u(ce),ae({quoteId:ce,type:fe})}catch(le){alert("Failed to clone quote: "+le.message)}finally{B(!1)}}const Pe=(W==null?void 0:W.commercial_type)==="rental",nt=Pe?`${jm(W==null?void 0:W.monthly_amount)}/mo`:jm((W==null?void 0:W.quote_total)||e.quote_total),ue=Pe?"Monthly Amount":"Quote Total";return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"bg-green/5 border border-green/20 rounded-xl p-4 space-y-3",children:[t.jsxs("div",{className:"flex items-center justify-between mb-1",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{className:"text-green text-sm",children:"â
"}),t.jsx("h4",{className:"text-sm font-bold text-green",children:"Agreement Signed"})]}),we?t.jsx("span",{className:"text-xs px-3 py-1.5 bg-green/20 text-green border border-green/30 rounded-lg font-semibold",children:"â Scheduled"}):be?a?t.jsx("span",{className:"text-xs px-3 py-1.5 rounded-lg font-semibold",style:{background:"rgba(245,158,11,0.1)",color:"#f59e0b",border:"1px solid rgba(245,158,11,0.3)"},children:"Awaiting scheduling"}):t.jsx("button",{onClick:Y,className:"text-xs px-3 py-1.5 rounded-lg font-semibold transition-colors",style:{background:"rgba(245,158,11,0.15)",color:"#f59e0b",border:"1px solid rgba(245,158,11,0.3)"},children:"ð
Confirm Date & Tech"}):ge?t.jsx("span",{className:"text-xs px-3 py-1.5 bg-green/20 text-green border border-green/30 rounded-lg font-semibold",children:"â Job Created"}):a?t.jsx("span",{className:"text-xs px-3 py-1.5 rounded-lg font-semibold",style:{background:"rgba(255,255,255,0.05)",color:"#94a3b8",border:"1px solid rgba(255,255,255,0.1)"},children:"Pending scheduling"}):t.jsx("button",{onClick:Y,className:"text-xs px-3 py-1.5 bg-cyan/20 hover:bg-cyan/30 text-cyan border border-cyan/30 rounded-lg font-semibold transition-colors",children:"ð
Schedule Install"})]}),t.jsxs("div",{className:"text-center py-2",children:[t.jsx("div",{className:"text-xs text-muted uppercase tracking-wide",children:ue}),t.jsx("div",{className:"text-2xl font-bold text-white mt-0.5",children:nt})]}),t.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-xs text-muted",children:"Signed By"}),t.jsx("div",{className:"text-sm text-slate-200",children:(W==null?void 0:W.signed_by)||"â"})]}),t.jsxs("div",{children:[t.jsx("div",{className:"text-xs text-muted",children:"Signed At"}),t.jsx("div",{className:"text-sm text-slate-200",children:rH(W==null?void 0:W.signed_at)})]}),t.jsxs("div",{children:[t.jsx("div",{className:"text-xs text-muted",children:"Type"}),t.jsx("div",{className:"text-sm text-slate-200",children:(W==null?void 0:W.commercial_type)==="rental"?"ð Rental":(W==null?void 0:W.commercial_type)==="purchase"?"ð° Purchase":(W==null?void 0:W.commercial_type)==="financed"?"ð¦ Financed":"â"})]}),t.jsxs("div",{children:[t.jsx("div",{className:"text-xs text-muted",children:"Agreement"}),t.jsx("div",{className:"text-sm",children:e.agreement_file_url?t.jsx("a",{href:e.agreement_file_url,target:"_blank",rel:"noopener noreferrer",className:"text-accent hover:underline",children:"View PDF"}):t.jsx("span",{className:"text-green",children:"â Digitally Signed"})})]})]}),(W==null?void 0:W.commercial_type)==="financed"&&!a&&t.jsxs("div",{className:"border border-pink-500/20 rounded-xl p-3 space-y-3",style:{background:"rgba(244,114,182,0.05)"},children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx("span",{className:"text-xs font-bold",style:{color:"#f472b6"},children:"ð¦ Financing Status"}),q&&t.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full font-bold",style:{background:q==="approved"?"rgba(74,222,128,0.15)":q==="declined"?"rgba(248,113,113,0.15)":"rgba(251,191,36,0.15)",color:q==="approved"?"#4ade80":q==="declined"?"#f87171":"#fbbf24"},children:q==="approved"?"â Approved":q==="declined"?"â Declined":"â³ Pending"})]}),t.jsxs("div",{className:"flex gap-2",children:[t.jsx("button",{onClick:()=>ht("pending"),disabled:I||q==="pending",className:"flex-1 py-1.5 rounded-lg text-xs font-semibold transition-all border",style:{background:q==="pending"?"rgba(251,191,36,0.2)":"transparent",borderColor:"#fbbf24",color:"#fbbf24",opacity:I?.5:1},children:"â³ Pending"}),t.jsx("button",{onClick:()=>ht("approved"),disabled:I,className:"flex-1 py-1.5 rounded-lg text-xs font-semibold transition-all border",style:{background:"rgba(74,222,128,0.1)",borderColor:"#4ade80",color:"#4ade80",opacity:I?.5:1},children:"â Approved"}),t.jsx("button",{onClick:()=>ht("declined"),disabled:I,className:"flex-1 py-1.5 rounded-lg text-xs font-semibond transition-all border",style:{background:"rgba(248,113,113,0.1)",borderColor:"#f87171",color:"#f87171",opacity:I?.5:1},children:"â Declined"})]}),q==="declined"&&t.jsxs("div",{children:[t.jsx("div",{className:"text-xs mb-2",style:{color:"#94a3b8"},children:"Financing declined â resend customer a new quote:"}),J?t.jsxs("div",{className:"rounded-lg p-3 text-xs text-center",style:{background:"rgba(34,211,238,0.1)",border:"1px solid rgba(34,211,238,0.3)",color:"#22d3ee"},children:["â New ",J.type," quote created as draft."," ",t.jsx("a",{href:"/quotes",className:"underline font-bold",style:{color:"#22d3ee"},children:"Go to Quotes â"})]}):t.jsxs("div",{className:"flex gap-2",children:[t.jsx("button",{onClick:()=>ke("rental"),disabled:I,className:"flex-1 py-2 rounded-lg text-xs font-bold transition-all border",style:{background:"rgba(34,211,238,0.1)",borderColor:"#22d3ee",color:"#22d3ee",opacity:I?.5:1},children:I?"â¦":"ð Resend as Rental"}),t.jsx("button",{onClick:()=>ke("purchase"),disabled:I,className:"flex-1 py-2 rounded-lg text-xs font-bold transition-all border",style:{background:"rgba(74,222,128,0.1)",borderColor:"#4ade80",color:"#4ade80",opacity:I?.5:1},children:I?"â¦":"ð° Resend as Purchase"})]})]})]}),t.jsxs("div",{className:"flex items-center gap-2 pt-2 border-t border-green/10",children:[t.jsx(rj,{active:ge,activeLabel:be?"Job Ready â Needs Date":we?"Job Scheduled":"Job Created",inactiveLabel:"Job Pending"}),t.jsx(rj,{active:!!e.inventory_reserved,activeLabel:"Inventory Reserved",inactiveLabel:"Not Reserved"})]})]}),l&&!a&&t.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-start justify-center p-4 z-50 overflow-y-auto",children:t.jsxs("div",{className:"bg-card border border-border rounded-2xl w-full max-w-lg p-6 shadow-2xl my-4",children:[t.jsx("h3",{className:"font-bold text-white text-base mb-1",children:"Schedule Install"}),t.jsx("p",{className:"text-xs text-muted mb-5",children:"Creates a job on the Dispatch board. Lead moves to Won when Kendrick marks install c
721omplete."}),t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{children:[t.jsx("label",{className:"block text-xs font-semibold text-muted uppercase tracking-wide mb-2",children:p?t.jsx("span",{className:"text-accent animate-pulse",children:"Loading productsâ¦"}):O.length>0?t.jsxs(t.Fragment,{children:["Products Being Installed ",t.jsxs("span",{className:"ml-1 font-normal normal-case text-green",children:["â from ",P==="line_items"?"quote line items":P==="invoice"?"signed agreement":"quote"]})]}):"Products Being Installed"}),p?t.jsxs("div",{className:"bg-surface border border-border rounded-lg p-3 space-y-2",children:[t.jsx("div",{className:"h-4 bg-muted/20 rounded animate-pulse w-3/4"}),t.jsx("div",{className:"h-4 bg-muted/20 rounded animate-pulse w-1/2"})]}):O.length>0?t.jsx("div",{className:"bg-surface border border-border rounded-lg divide-y divide-border",children:O.map((fe,le)=>t.jsxs("div",{className:"flex items-center justify-between px-3 py-2.5",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-medium text-slate-200",children:fe.name}),t.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[fe.category&&t.jsx("span",{className:"text-xs text-muted",children:iH[fe.category]||fe.category}),fe.sku&&t.jsx("span",{className:"text-xs font-mono",style:{color:"#64748b"},children:fe.sku})]})]}),t.jsxs("span",{className:"text-xs text-slate-400 font-semibold ml-3",children:["à ",fe.quantity]})]},le))}):t.jsx("div",{className:"bg-surface border border-border rounded-lg px-3 py-3 text-xs text-muted",children:"No products found â select system type manually below."})]}),O.length===0&&!p&&t.jsxs("div",{children:[t.jsxs("label",{className:"block text-xs font-semibold text-muted uppercase tracking-wide mb-1.5",children:["Install Type ",t.jsx("span",{className:"text-red-400",children:"*"})]}),t.jsx("select",{value:j,onChange:fe=>C(fe.target.value),className:"w-full bg-surface border border-border rounded-lg px-3 py-2.5 text-sm text-slate-200 focus:outline-none focus:border-accent",children:sH.map(fe=>t.jsx("option",{value:fe,children:lo[fe]},fe))}),t.jsx("div",{className:"text-xs text-muted mt-1",children:"No products detected â select install type manually."})]}),(j==="ro_install"||j==="combo_whole_home_ro")&&t.jsxs("div",{className:"flex items-center gap-3",children:[t.jsx("input",{type:"checkbox",id:"faucet_hole",checked:S,onChange:fe=>T(fe.target.checked),className:"w-4 h-4 accent-cyan"}),t.jsx("label",{htmlFor:"faucet_hole",className:"text-sm text-slate-300 cursor-pointer",children:"Requires new faucet hole (adds drilling consent form)"})]}),t.jsxs("div",{children:[t.jsxs("label",{className:"block text-xs font-semibold text-muted uppercase tracking-wide mb-2",children:["Step 1 â Pick a Date ",t.jsx("span",{className:"text-red-400",children:"*"}),e.install_preferred_date&&t.jsxs("span",{className:"ml-2 text-accent font-normal normal-case",children:["Customer requested: ",new Date(e.install_preferred_date).toLocaleDateString()]})]}),h?t.jsx("div",{className:"bg-surface border border-border rounded-xl p-4 text-xs text-accent animate-pulse text-center",children:"Loading availabilityâ¦"}):t.jsx(dH,{selectedDate:m,onSelect:X,jobSlots:M})]}),m&&!h&&t.jsxs("div",{children:[t.jsxs("label",{className:"block text-xs font-semibold text-muted uppercase tracking-wide mb-2",children:["Step 2 â Pick a Time Slot ",t.jsx("span",{className:"text-red-400",children:"*"}),t.jsx("span",{className:"ml-2 font-normal normal-case text-slate-400",children:Ie})]}),t.jsx(lH,{selectedHour:A,onSelect:v,bookedHours:Ne}),Ne.length>0&&t.jsxs("div",{className:"text-xs text-muted mt-2",children:[Ne.length," slot",Ne.length!==1?"s":""," already booked this day"]})]}),m&&A!==null&&t.jsxs("div",{className:"flex items-center justify-between bg-cyan/10 border border-cyan/30 rounded-lg px-3 py-2.5",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-xs font-semibold text-cyan mb-0.5",children:"Scheduled For"}),t.jsx("div",{className:"text-sm text-white font-bold",children:Ie}),t.jsx("div",{className:"text-sm text-cyan",children:qy(A)})]}),t.jsx("div",{className:"text-2xl",children:"ð
"})]}),t.jsxs("div",{children:[t.jsx("label",{className:"block text-xs font-semibold text-muted uppercase tracking-wide mb-1.5",children:"Assign Technician"}),t.jsxs("select",{value:x,onChange:fe=>_(fe.target.value),className:"w-full bg-surface border border-border rounded-lg px-3 py-2.5 text-sm text-slate-200 focus:outline-none focus:border-accent",children:[t.jsx("option",{value:"",children:"â Unassigned â"}),o==null?void 0:o.map(fe=>t.jsx("option",{value:fe.id,children:fe.full_name},fe.id))]}),!x&&t.jsx("div",{className:"text-xs text-amber mt-1",children:"â Tech required to Start Installation on the dispatch board"})]}),t.jsxs("div",{children:[t.jsx("label",{className:"block text-xs font-semibold text-muted uppercase tracking-wide mb-1.5",children:"Notes for Tech"}),t.jsx("textarea",{value:L,onChange:fe=>E(fe.target.value),placeholder:"Any install notesâ¦",rows:2,className:"w-full bg-surface border border-border rounded-lg px-3 py-2.5 text-sm text-slate-200 placeholder-muted focus:outline-none focus:border-accent resize-none"})]}),t.jsxs("div",{className:"bg-surface rounded-lg p-3 text-xs text-muted space-y-1",children:[t.jsxs("div",{children:[t.jsx("span",{className:"text-slate-400 font-semibold",children:"Customer: "}),e.first_name?`${e.first_name} ${e.last_name||""}`.trim():e.full_name||""]}),t.jsxs("div",{children:[t.jsx("span",{className:"text-slate-400 font-semibold",children:"Address: "}),te||"â"]}),t.jsxs("div",{children:[t.jsx("span",{className:"text-slate-400 font-semibold",children:"Phone: "}),e.phone]}
721),(W==null?void 0:W.quote_total)&&t.jsxs("div",{children:[t.jsx("span",{className:"text-slate-400 font-semibold",children:"Quote Total: "}),jm(W.quote_total)]})]})]}),t.jsxs("div",{className:"flex gap-3 mt-5",children:[t.jsx("button",{onClick:()=>d(!1),disabled:c,className:"flex-1 py-2.5 text-sm text-muted hover:text-white transition-colors",children:"Cancel"}),t.jsx("button",{onClick:de,disabled:!Ze,className:"flex-1 py-2.5 bg-cyan hover:bg-cyan/80 disabled:opacity-50 text-white font-bold rounded-lg text-sm transition-colors",title:m?A===null?"Select a time slot":"":"Select a date first",children:c?"Creating Jobâ¦":A!==null?`ð Schedule for ${qy(A)}`:"ð Create Job & Schedule"})]})]})})]})}async function uH(e){var x;const{bucket:n,path:r,file:s,entityType:i,entityId:o,fileType:a="photo",metadata:l={},userId:d,additionalLinks:c=[]}=e,{data:f}=await w.auth.getUser(),p=(x=f==null?void 0:f.user)==null?void 0:x.id;if(!p)throw new Error("Upload failed: no authenticated session");const{data:u,error:h}=await w.from("profiles").select("tenant_id").eq("id",p).single();if(h||!(u!=null&&u.tenant_id))throw new Error("Upload failed: could not resolve tenant for storage path");const y=r.startsWith(u.tenant_id+"/")?r:u.tenant_id+"/"+r,{error:m}=await w.storage.from(n).upload(y,s,{cacheControl:"3600",upsert:!1});if(m)throw new Error(`Upload failed: ${m.message}`);const b={...l,uploaded_at:new Date().toISOString()},{data:A,error:v}=await w.from("media").insert({entity_type:i,entity_id:o,file_type:a,bucket:n,storage_path:y,url:null,filename:s.name,metadata:b,uploaded_by:d||null}).select().single();if(v)throw new Error(`Media record failed: ${v.message}`);if(c.length>0){const _=c.map(C=>({media_id:A.id,entity_type:C.entity_type,entity_id:C.entity_id,context:C.context||"reference"})),{error:j}=await w.from("media_links").insert(_);j&&console.error("Media links creation failed:",j.message)}return A}const pH=3600;async function Dy(e,n,r=pH){if(!n)return null;const{data:s,error:i}=await w.storage.from(e).createSignedUrl(n,r);return i?(console.warn("[#265] signed url failed:",n,i.message),null):(s==null?void 0:s.signedUrl)??null}async function U8(e,n){const{data:r,error:s}=await w.from("media").select("*").eq("entity_type",e).eq("entity_id",n).order("created_at",{ascending:!0});if(s)throw s;return r||[]}async function H8(e,n){const{data:r,error:s}=await w.from("media").select("storage_path, bucket").eq("id",e).single();if(s)throw s;if(r!=null&&r.storage_path){const{error:o}=await w.storage.from(r.bucket||n).remove([r.storage_path]);if(o)throw new Error(`Storage delete failed: ${o.message}`)}const{error:i}=await w.from("media").delete().eq("id",e);if(i)throw i}function hh(e,n){return e.replace(/{{(\w+)}}/g,(r,s)=>n[s]||"")}const hH=new Set(["service_plan","maintenance","discount","custom"]);function fH(e){return{tier:0,maxCoreDiscount:0,categories:[],label:"",color:""}}function gH(e){return null}function Ud(e){return{allowed:0,blocked:!0,capped:!1,message:e}}function V8(e,n,r,s){if(e.is_open_item)return Ud("Open SKU lines cannot be discounted");if(e.item_type&&hH.has(e.item_type))return Ud("This line type cannot be discounted");if(e.item_type==="install_fee")return{allowed:100,blocked:!1,capped:!1,message:"Install fee: up to 100% (waive)"};if(n==="rental")return Ud("Rental lines cannot be discounted. Fixed contract pricing");if(s)return{allowed:100,blocked:!1,capped:!1,message:"Admin: no limit"};if(!e.product_id)return Ud("Only catalog products can be discounted");let i=Math.min(100,Math.max(0,Number(e.max_discount_pct)||0)),o=!1;const a=Number(e.unit_price)||0,l=e.min_sell_price==null?null:Number(e.min_sell_price);if(l!=null&&a>0){const d=Math.floor(Math.max(0,(1-l/a)*100)*100)/100;d<i&&(i=d,o=!0)}return i<=0?Ud(o?"At the minimum price. No discount":"No discount set for this product"):{allowed:i,blocked:!1,capped:o,message:o?`Max ${i}% (price floor)`:`Max ${i}% on this product`}}const Xe={navy:"#0c1e35",teal:"#0d7ea3",light:"#f0f4f8",border:"#e2e8f0",text:"#1a2a3a",muted:"#64748b"},mH=`Why This System Is Recommended for Your Home 722This system has been recommended based on your home size, water usage, and water quality needs. It is designed to improve overall water quality, enhance efficiency, and protect your plumbing, appli
722ances, and fixtures. The configuration selected provides reliable performance, long-term durability, and a better water experience throughout your home.`;function xH(e){return`This is an estimate, not a final invoice or contract for services. 723The summary above is a good-faith estimate based on our evaluation of the work to be performed at the installation address. It does not include potential material price changes or any additional labor or materials that may be required if unforeseen conditions arise during installation. 724I understand that the final cost of the work may differ from this estimate if extra materials, modifications, or labor are required. This estimate does not guarantee the final price of the work to be performed. 725By approving this estimate, I authorize ${e} to proceed as outlined and agree to pay the full amount for all services rendered. 726For complete details, please refer to the Terms & Conditions link.`}function Z8(e){const n=[e.address_line1||e.address],r=[e.city,e.state].filter(Boolean).join(", ");return(r||e.zip)&&n.push([r,e.zip].filter(Boolean).join(" ")),n.filter(Boolean).join(", ")}function K8(e){if(!e)return"CO";const n=e.split(/\s+/).filter(Boolean);return n.length>=2?(n[0][0]+n[1][0]).toUpperCase():e.substring(0,2).toUpperCase()}function Es(e){return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}).format(e)}function yH(){return new Date().toISOString().split("T")[0]}function bH(e=14){const n=new Date;return n.setDate(n.getDate()+e),n.toISOString().split("T")[0]}function sj(e){return new Date(e).toLocaleDateString("en-US",{month:"2-digit",day:"2-digit",year:"numeric"})}function To(){return Math.random().toString(36).slice(2,10)}function W0({customerId:e,customerName:n,customerAddress:r="",customerPhone:s="",opportunityId:i=null,leadId:o=null,existingQuote:a=null,initialView:l="form",onSaved:d,onCancel:c}){var fe;const{profile:f}=Ee(),p=y8(),[u,h]=g.useState(l),[y,m]=g.useState(!1),[b,A]=g.useState(!1),[v,x]=g.useState(!1),[_,j]=g.useState(!1),[C,S]=g.useState((a==null?void 0:a.status)||"draft");g.useRef(null);const[T,L]=g.useState([]),[E,R]=g.useState(!0),[N,O]=g.useState([]),[z,P]=g.useState((a==null?void 0:a.commercial_type)||"rental"),[D,M]=g.useState((a==null?void 0:a.notes)||mH),[k,q]=g.useState((a==null?void 0:a.valid_until)||bH(14)),[$,I]=g.useState(((fe=a==null?void 0:a.line_items)==null?void 0:fe.map(le=>({...le,_key:To(),discount_pct:Number(le.discount_pct)||0,original_unit_price:le.unit_price})))||[]),[B,J]=g.useState((a==null?void 0:a.quote_number)||""),[ae,te]=g.useState((a==null?void 0:a.id)||null),[U,W]=g.useState(r||(a==null?void 0:a.customer_address)||""),[G,V]=g.useState([]),ee=(f==null?void 0:f.role)==="admin"||(f==null?void 0:f.role)==="super_admin",re=fH();g.useEffect(()=>{a!=null&&a.id&&(a.line_items&&a.line_items.length>0||Fo(async()=>{const{fetchQuote:le}=await Promise.resolve().then(()=>nH);return{fetchQuote:le}},void 0).then(({fetchQuote:le})=>{le(a.id).then(ce=>{var xe;if(ce!=null&&ce.line_items&&ce.line_items.length>0){const ve=[],_e=[];for(const je of ce.line_items)je.item_type==="service_plan"&&((xe=je.metadata)!=null&&xe.plan_template_id)?_e.push({_key:To(),template_id:je.metadata.plan_template_id,name:je.description.split(" â ")[0]||je.description,billing_cycle:je.metadata.billing_cycle||"yearly",price:je.unit_price,original_price:je.unit_price,fulfillment_type:je.metadata.fulfillment_type||"none",description:je.description}):ve.push({...je,_key:To(),discount_pct:Number(je.discount_pct)||0,original_unit_price:je.unit_price});I(ve),_e.length>0&&V(_e)}}).catch(console.error)}))},[a==null?void 0:a.id]),g.useEffect(()=>{e&&(a!=null&&a.customer_address||I0(e).then(le=>{le&&W(le)}).catch(le=>{console.error("[QuoteBuilder] address resolve failed:",le)}))},[e,a==null?void 0:a.customer_address]),g.useEffect(()=>{L8().then(L).catch(console.error).finally(()=>R(!1))},[]),g.useEffect(()=>{if(T.length===0)return;const le=new Map(T.map(ce=>[ce.id,ce]));I(ce=>{let xe=!1;const ve=ce.map(_e=>{if(!_e.product_id||_e.max_discount_pct!==void 0)return _e;const je=le.get(_e.product_id);return je?(xe=!0,{..._e,max_discount_pct:je.max_discount_pct??0,min_sell_price:je.min_sell_price??null,is_open_item:!!je.is_open_item}):_e});return xe?ve:ce})},[T,$.length]),g.useEffect(()=>{b0(!0).then(O).catch(console.error)},[]),g.useEffect(()=>{u==="preview"&&window.scrollTo({top:0,behavior:"smooth"})},[u]);function Q(le){let ce;if(z==="rental"){if(le.rental_price_monthly==null){alert(`"${le.name}" does not have a rental monthly price configured. Contact admin to update the product catalog before adding this item to a rental quote.`);return}ce=le.rental_price_monthly}else ce=le.retail_price??0;const xe={_key:To(),product_id:le.id,sku:le.sku||"",description:oe(le),quantity:1,unit_price:ce,original_unit_price:ce,total:ce,item_type:"product",sort_order:0,discount_pct:0,discount_category:le.discount_category||null,max_discount_pct:le.max_discount_pct??0,min_sell_price:le.min_sell_price??null,is_open_item:!1};if(le.install_fee&&le.install_fee>0){const ve={_key:To(),product_id:le.id,sku:"",description:`Installation Fee â ${le.name}`,quantity:1,unit_price:le.install_fee,original_unit_price:le.install_fee,total:le.install_fee,item_type:"install_fee",sort_order:1,discount_pct:0,discount_category:null};I(_e=>[..._e,xe,ve])}else I(ve=>[...ve,xe])}function oe(le){let ce=le.name;le.description&&(ce+=` 727${le.description}`);const xe=Number(le.parts_warranty)||0,ve=le.parts_warranty_unit||"months",_e=Number(le.labour_warranty)||0,je=le.labour_warranty_unit||"months",Be=(Je,bt)=>{const Vn=bt==="years"?"year":"month";return`${Je} ${Je===1?Vn:Vn+"s"}`};if(xe>0||_e>0)ce+=` 728`,xe>0&&(ce+=` 729Parts Warranty â ${Be(xe,ve)}`),_e>0&&(ce+=` 730Labor Warranty â ${Be(_e,je)}`);else if(le.warranty_months){const Je=Math.floor(le.warranty_months/12);ce+=` 731 732Warranty â ${Je>0?`${Je} year${Je>1?"s":""}`:`${le.warranty_months} months`}`}return ce}function ne(le){const ce=le??T.find(ve=>ve.is_open_item);if(!ce){alert('No open SKU is set up yet. An admin can create one in the Product Catalog (tick "Use as an open SKU").');return}const xe=z==="rental"?ce.rental_price_monthly??0:ce.retail_price??0;I(ve=>[...ve,{_key:To(),product_id:ce.id,sku:ce.sku||"",description:ce.name,quantity:1,unit_price:xe,original_unit_price:xe,total:xe,item_type:"custom",sort_order:ve.length,discount_pct:0,discount_amount:0,discount_category:null,max_discount_pct:0,min_sell_price:null,is_open_item:!0}])}function ge(le,ce,xe){I(ve=>ve.map(_e=>{if(_e._key!==le||!ee&&ce==="item_type"||!ee&&ce==="unit_price"&&!_e.is_open_item)return _e;const je={..._e,[ce]:xe};if(ce==="discount_pct"){const Be=V8(_e,z,re,ee),Je=parseFloat(xe)||0;je.discount_pct=Be.blocked?0:Math.min(Je,Be.allowed)}if(ce==="quantity"||ce==="unit_price"||ce==="discount_pct"){const Be=je.discount_pct,Je=je.quantity,bt=je.unit_price,Vn=Je*bt,fr=parseFloat((Vn*Be/100).toFixed(2));je.discount_amount=fr,je.total=parseFloat((Vn-fr).toFixed(2))}return je}))}function be(le){I(ce=>ce.filter(xe=>xe._key!==le))}function we(le,ce){I(xe=>{const ve=xe.findIndex(Be=>Be._key===le);if(ve<0)return xe;const _e=[...xe],je=ce==="up"?ve-1:ve+1;return je<0||je>=_e.length?xe:([_e[ve],_e[je]]=[_e[je],_e[ve]],_e)})}function F(le){if(G.some(ce=>ce.template_id===le.id)){alert(`"${le.name}" is already added to this quote.`);return}V(ce=>[...ce,{_key:To(),template_id:le.id,name:le.name,billing_cycle:le.billing_interval||le.billing_cycle||"monthly",price:Number(le.price_monthly??le.price??0),original_price:Number(le.price_monthly??le.price??0),fulfillment_type:le.fulfillment_type,description:le.description||""}])}function K(le){V(ce=>ce.filter(xe=>xe._key!==le))}function Z(le,ce){V(xe=>xe.map(ve=>ve._key===le?{...ve,price:ce}:ve))}const ie=$.filter(le=>le.item_type!=="install_fee"),Y=$.filter(le=>le.item_type==="install_fee"),X=ie.reduce((le,ce)=>le+ce.total,0),H=Y.reduce((le,ce)=>le+ce.total,0),de=$.reduce((le,ce)=>le+ce.total,0),pe=parseFloat($.reduce((le,ce)=>le+(Number(ce.discount_amount)||0),0).toFixed(2)),Ne=parseFloat((de+pe).toFixed(2)),Ie=parseFloat((de*.07).toFixed(2)),Ze=parseFloat((de+Ie).toFixed(2));async function ht(){if(!e)return null;m(!0);try{const le=[...$.map((ce,xe)=>({product_id:ce.product_id||null,product_catalog_id:ce.item_type==="product"&&ce.product_id||null,description:ce.description,quantity:ce.quantity,unit_price:ce.unit_price,total:ce.total,item_type:ce.item_type,sort_order:xe,sku:ce.sku,discount_category:ce.discount_category||null,discount_pct:ce.discount_pct||0,discount_amount:Number(ce.discount_amount)||0})),...G.map((ce,xe)=>({product_id:ce.template_id,product_catalog_id:null,description:`${ce.name} â ${Es(ce.price)}${ya[ce.billing_cycle]||""}`,quantity:1,unit_price:ce.price,total:ce.price,item_type:"service_plan",sort_order:$.length+xe,sku:""}))];if(ae){const xe=$.filter(je=>je.item_type==="product").reduce((je,Be)=>je+Be.total,0),ve=$.filter(je=>je.item_type==="install_fee").reduce((je,Be)=>je+Be.total,0);await M8(ae,{commercial_type:z,notes:D,valid_until:k,line_items:le,monthly_rental_price:z==="rental"?xe:null,install_fee:ve>0?ve:null,expires_at:k});const{data:_e}=await w.from("quotes").select("*").eq("id",ae).single();return _e&&d&&d(_e),ae}else{const xe=$.filter(je=>je.item_type==="product").reduce((je,Be)=>je+Be.total,0),ve=$.filter(je=>je.item_type==="install_fee").reduce((je,Be)=>
732je+Be.total,0),_e=await $8({customer_id:e,commercial_type:z,opportunity_id:i,lead_id:o,created_by:(f==null?void 0:f.id)||null,notes:D,valid_until:k,line_items:le,monthly_rental_price:z==="rental"?xe:null,install_fee:ve>0?ve:null,expires_at:k});return te(_e.id),_e.quote_number&&J(_e.quote_number),d&&d(_e),_e.id}}catch(le){return alert(le.message||"Save failed"),null}finally{m(!1)}}async function ke(){let le=ae;if(le||(le=await ht()),!le)return;A(!0);let ce=null,xe="";try{const ve=await fetch("/api/email/send-quote",{method:"POST",headers:await At(),body:JSON.stringify({quoteId:le,senderEmail:f==null?void 0:f.email,senderName:f==null?void 0:f.full_name})}),_e=await ve.json();ve.ok?ce=_e:xe=(_e==null?void 0:_e.error)||"Send failed ("+ve.status+")"}catch(ve){xe=(ve==null?void 0:ve.message)||"Could not reach the send service"}try{await _u(le);const{data:ve}=await w.from("quotes").select("*").eq("id",le).single();if(ve?(S(ve.status||"sent"),d&&d(ve)):S("sent"),xe)alert("Quote NOT sent: "+xe);else{const _e=(ce==null?void 0:ce.channels)||[],je=[];if(_e.includes("email")&&je.push("emailed to "+ce.to),_e.includes("sms")&&je.push("texted to "+ce.phone),je.length){let Be="â Quote "+je.join(" and ");ce!=null&&ce.email_error&&!_e.includes("email")&&(Be+=` 733 734Email not sent: `+ce.email_error),alert(Be)}else alert("Quote marked as sent, but nothing was delivered."+(ce!=null&&ce.email_error?` 735 736`+ce.email_error:""))}}catch(ve){alert(ve.message||"Send failed")}finally{A(!1)}}async function Pe(){if(!ae){alert("Save the quote first.");return}x(!0);try{await w.from("quotes").update({status:"signed",accepted_at:new Date().toISOString()}).eq("id",ae),S("signed"),z==="rental"?j(!0):alert("Quote accepted. Generate invoice from the quotes list.")}catch(le){alert(le.message||"Accept failed")}finally{x(!1)}}function nt(){if(typeof html2pdf>"u"){const le=document.createElement("script");le.src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js",le.onload=()=>ue(),document.head.appendChild(le)}else ue()}function ue(){const le=document.getElementById("zenith-quote-preview");if(!le){alert("Switch to Preview tab first.");return}const ce=`${B||"Quote"}_${n.replace(/\s+/g,"-")}.pdf`;html2pdf().set({margin:0,filename:ce,image:{type:"jpeg",quality:.98},html2canvas:{scale:2,useCORS:!0},jsPDF:{unit:"mm",format:"a4",orientation:"portrait"}}).from(le).save()}return t.jsxs("div",{style:{background:"#0f1923",minHeight:"100vh",fontFamily:"'DM Sans', system-ui, sans-serif"},children:[t.jsxs("div",{style:{background:"#162232",borderBottom:"1px solid #1e3a4f",padding:"16px 24px",display:"flex",alignItems:"center",gap:12},children:[t.jsx("button",{onClick:c,style:{color:"#64748b",background:"none",border:"none",cursor:"pointer",fontSize:14},children:"â Back"}),t.jsxs("div",{style:{flex:1},children:[t.jsx("div",{style:{color:"#e2e8f0",fontWeight:700,fontSize:16},children:B||(ae?"Loading...":"New Quote")}),t.jsx("div",{style:{color:"#64748b",fontSize:12},children:n})]}),t.jsx("div",{style:{display:"flex",background:"#0f1923",borderRadius:8,padding:2,gap:2},children:["form","preview"].map(le=>t.jsx("button",{onClick:()=>h(le),style:{padding:"6px 16px",borderRadius:6,border:"none",cursor:"pointer",fontSize:13,fontWeight:600,transition:"all 0.15s",background:u===le?"#1e3a5f":"transparent",color:u===le?"#60a5fa":"#64748b"},children:le==="form"?"â Build":"ð Preview"},le))}),t.jsx("button",{onClick:nt,style:{padding:"8px 14px",borderRadius:8,border:"1px solid #1e3a4f",cursor:"pointer",background:"transparent",color:"#64748b",fontWeight:600,fontSize:13},children:"⬠PDF"}),t.jsx("button",{onClick:ht,disabled:y||C!=="draft",style:{padding:"8px 18px",borderRadius:8,border:"none",cursor:"pointer",background:"#1e3a5f",color:"#60a5fa",fontWeight:600,fontSize:13,opacity:C!=="draft"?.4:1},children:y?"Savingâ¦":"Save Draft"}),t.jsx("button",{onClick:ke,disabled:b||$.length===0||C!=="draft",style:{padding:"8px 18px",borderRadius:8,border:"none",cursor:"pointer",background:$.length===0||C!=="draft"?"#1a2a3a":"#0d7ea3",color:$.length===0||C!=="draft"?"#334155":"#fff",fontWeight:700,fontSize:13},children:b?"Sendingâ¦":"Send Quote"}),C==="sent"&&t.jsx("button",{onClick:Pe,disabled:v,style:{padding:"8px 18px",borderRadius:8,border:"none",cursor:"pointer",background:"#16a34a",color:"#fff",fontWeight:700,fontSize:13},children:v?"Acceptingâ¦":"â Accept Quote"}),C==="signed"&&t.jsx("div",{style:{padding:"8px 14px",borderRadius:8,background:"#14532d",color:"#86efac",fontWeight:700,fontSize:13},children:"â Accepted"})]}),_&&t.jsx(_H,{quoteNumber:B,customerName:n,customerAddress:U,lineItems:$,monthlySubtotal:X,installFeeTotal:H,onClose:()=>j(!1),branding:p}),u==="form"?t.jsx(AH,{commercialType:z,setCommercialType:P,serviceAddress:U,setServiceAddress:W,estimation:D,setEstimation:M,validUntil:k,setValidUntil:q,lineItems:$,products:T,loadingProducts:E,onAddProduct:Q,onAddCustom:ne,onUpdateLine:ge,onRemoveLine:be,onMoveLine:we,subtotal:de,taxAmount:Ie,total:Ze,discountTotal:pe,grossSubtotal:Ne,monthlySubtotal:X,installFeeTotal:H,planTemplates:N,selectedPlans:G,onAddServicePlan:F,onRemoveServicePlan:K,onUpdatePlanPrice:Z,quoteTier:re,isAdmin:ee}):t.jsx(vH,{quoteNumber:ae?B:"Q-DRAFT",quoteDate:yH(),validUntil:k,customerName:n,customerAddress:U,customerPhone:s,salesConsultant:(f==null?void 0:f.full_name)||p.company_name,estimation:D,lineItems:$,subtotal:de,taxAmount:Ie,total:Ze,discountTotal:pe,grossSubtotal:Ne,monthlySubtotal:X,installFeeTotal:H,commercialType:z,selectedPlans:G,branding:p})]})}function AH({commercialType:e,setCommercialType:n,serviceAddress:r,setServiceAddress:s,estimation:i,setEstimation:o,validUntil:a,setValidUntil:l,lineItems:d,products:c,loadingProducts:f,onAddProduct:p,onAddCustom:u,onUpdateLine:h,onRemoveLine:y,onMoveLine:m,subtotal:b,taxAmount:A,total:v,monthlySubtotal:x,installFeeTotal:_,discountTotal:j=0,grossSubtotal:C=0,planTemplates:S,selectedPlans:T,onAddServicePlan:L,onRemoveServicePlan:E,onUpdatePlanPrice:R,quoteTier:N,isAdmin:O}){const[z,P]=g.useState(""),[D,M]=g.useState(!1),[k,q]=g.useState(!1),[$,I]=g.useState(!1),B=e==="rental",J=c.filter(W=>W.is_open_item),ae=c.filter(W=>!W.is_open_item&&(!z||W.name.toLowerCase().includes(z.toLowerCase())||(W.sku||"").toLowerCase().includes(z.toLowerCase()))),te={section:{background:"#162232",borderRadius:12,border:"1px solid #1e3a4f",padding:20,marginBottom:16},label:{color:"#94a3b8",fontSize:12,fontWeight:600,textTransform:"uppercase",letterSpacing:"0.08em",marginBottom:6}
736,input:{background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:8,color:"#e2e8f0",padding:"9px 12px",width:"100%",fontSize:13,outline:"none"},th:{color:"#64748b",fontSize:11,fontWeight:600,textTransform:"uppercase",padding:"8px 10px",textAlign:"left"},td:{padding:"8px 6px",borderTop:"1px solid #1a2e42",verticalAlign:"top"}},U=gH();return t.jsxs("div",{style:{padding:24,maxWidth:920,margin:"0 auto"},children:[t.jsxs("div",{style:te.section,children:[t.jsx("div",{style:te.label,children:"Quote Type"}),t.jsx("div",{style:{display:"flex",gap:8},children:["rental","purchase","financed"].map(W=>t.jsx("button",{onClick:()=>n(W),style:{padding:"8px 20px",borderRadius:8,border:"2px solid",cursor:"pointer",fontWeight:700,fontSize:13,borderColor:e===W?"#0d7ea3":"#1e3a4f",background:e===W?"#0a2a3a":"transparent",color:e===W?"#22d3ee":"#64748b"},children:W.charAt(0).toUpperCase()+W.slice(1)},W))})]}),t.jsxs("div",{style:te.section,children:[t.jsx("div",{style:te.label,children:"Service / Installation Address"}),t.jsx("input",{type:"text",value:r,onChange:W=>s(W.target.value),placeholder:"e.g. 123 Main St, Indianapolis, IN 46201",style:{...te.input}})]}),t.jsxs("div",{style:te.section,children:[t.jsx("div",{style:te.label,children:"Estimation Details (shown on quote)"}),t.jsx("textarea",{value:i,onChange:W=>o(W.target.value),rows:4,style:{...te.input,resize:"vertical",lineHeight:1.6}})]}),t.jsx("div",{style:{...te.section,display:"flex",gap:16,alignItems:"flex-end"},children:t.jsxs("div",{style:{flex:1},children:[t.jsx("div",{style:te.label,children:"Valid Until"}),t.jsx("input",{type:"date",value:a,onChange:W=>l(W.target.value),style:te.input})]})}),t.jsxs("div",{style:te.section,children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:12},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[t.jsx("div",{style:te.label,children:"Line Items"}),U]}),t.jsxs("div",{style:{display:"flex",gap:8},children:[t.jsx("button",{onClick:()=>M(W=>!W),style:{padding:"7px 14px",borderRadius:8,border:"1px solid #0d7ea3",background:D?"#0a2a3a":"transparent",color:"#22d3ee",cursor:"pointer",fontSize:13,fontWeight:600},children:"+ From Catalog"}),t.jsxs("div",{style:{position:"relative"},children:[t.jsx("button",{onClick:()=>J.length>1?I(W=>!W):u(),style:{padding:"7px 14px",borderRadius:8,border:"1px solid #1e3a4f",background:"transparent",color:"#94a3b8",cursor:"pointer",fontSize:13},children:"+ Custom Line"}),$&&t.jsx("div",{style:{position:"absolute",right:0,top:"110%",zIndex:20,background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:8,minWidth:220,overflow:"hidden"},children:J.map(W=>t.jsxs("button",{onClick:()=>{u(W),I(!1)},style:{display:"block",width:"100%",textAlign:"left",padding:"8px 12px",background:"none",border:"none",borderBottom:"1px solid #1a2a3a",color:"#e2e8f0",cursor:"pointer",fontSize:13},children:[W.name,W.sku?t.jsxs("span",{style:{color:"#64748b",fontSize:11},children:[" · ",W.sku]}):null]},W.id))})]})]})]}),D&&t.jsxs("div",{style:{background:"#0f1923",borderRadius:10,border:"1px solid #1e3a4f",marginBottom:12,overflow:"hidden"},children:[t.jsx("div",{style:{padding:"10px 12px",borderBottom:"1px solid #1e3a4f"},children:t.jsx("input",{placeholder:"Search productsâ¦",value:z,onChange:W=>P(W.target.value),style:{...te.input,padding:"7px 10px"},autoFocus:!0})}),t.jsx("div",{style:{maxHeight:260,overflowY:"auto"},children:f?t.jsx("div",{style:{padding:16,color:"#64748b",fontSize:13},children:"Loadingâ¦"}):ae.length===0?t.jsx("div",{style:{padding:16,color:"#64748b",fontSize:13},children:"No products found"}):ae.map(W=>t.jsxs("button",{onClick:()=>{p(W),M(!1),P("")},style:{display:"flex",width:"100%",padding:"10px 14px",gap:12,background:"none",border:"none",cursor:"pointer",textAlign:"left",borderBottom:"1px solid #1a2a3a"},onMouseEnter:G=>G.currentTarget.style.background="#162232",onMouseLeave:G=>G.currentTarget.style.background="none",children:[t.jsxs("div",{style:{flex:1},children:[t.jsx("div",{style:{color:"#e2e8f0",fontSize:13,fontWeight:600},children:W.name}),W.sku&&t.jsx("div",{style:{color:"#64748b",fontSize:11},children:W.sku})]}),t.jsxs("div",{style:{textAlign:"right",flexShrink:0},children:[e==="rental"&&(W.rental_price_monthly!=null?t.jsxs("div",{style:{color:"#22d3ee",fontSize:12,fontWeight:700},children:[Es(W.rental_price_monthly),"/mo"]}):t.jsx("div",{style:{color:"#ef4444",fontSize:11,fontWeight:600},children:"No rental price"})),(e==="purchase"||e==="financed")&&(W.retail_price!=null?t.jsx("div",{style:{color:"#4ade80",fontSize:12,fontWeight:700},children:Es(W.retail_price)}):t.jsx("div",{style:{color:"#ef4444",fontSize:11,fontWeight:600},children:"No purchase price"})),W.install_fee!=null&&W.install_fee>0&&t.jsxs("div",{style:{color:"#f59e0b",fontSize:11},children:["+",Es(W.install_fee)," install"]})]})]},W.id))})]}),d.length===0?t.jsx("div",{style:{textAlign:"center",padding:"32px 0",color:"#334155",fontSize:13},children:"No line items yet. Add from catalog or create a custom line."}):t.jsxs("table",{style:{width:"100%",borderCollapse:"collapse"},children:[t.jsx("thead",{children:t.jsxs("tr",{children:[t.jsx("th",{style:te.th}),t.jsx("th",{style:te.th,children:"Description"}),t.jsx("th",{style:{...te.th,textAlign:"center",width:60},children:"Qty"}),t.jsx("th",{style:{...te.th,textAlign:"right",width:100},children:"Unit Price"}),t.jsx("th",{style:{...te.th,textAlign:"center",width:70},children:"Disc %"}),t.jsx("th",{style:{...te.th,textAlign:"right",width:100},children:"Total"}),t.jsx("th",{style:{...te.th,width:40}})]})}),t.jsx("tbody",{children:d.map((W,G)=>{const V=V8(W,e,N,O),ee=!V.blocked&&W.discount_pct>V.allowed;return t.jsxs("tr",{children:[t.jsx("td",{style:{...te.td,width:28},children:t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:2},children:[t.jsx("button",{onClick:()=>m(W._key,"up"),disabled:G===0,style:{background:"none",border:"none",cursor:G===0?"default":"pointer",color:G===0?"#1e3a4f":"#64748b",lineHeight:1,padding:0},children:"â²"}),t.jsx("button",{onClick:()=>m(W._key,"down"),disabled:G===d.length-1,style:{background:"none",border:"none",cursor:G===d.length-1?"default":"pointer",color:G===d.length-1?"#1e3a4f":"#64748b",lineHeight:1,padding:0},children:"â¼"})]})}),t.jsxs("td",{style:te.td,children:[W.sku&&t.jsx("div",{style:{color:"#0d7ea3",fontSize:11,fontWeight:700,marginBottom:3},children:W.sku}),W.item_type==="install_fee"&&t.jsx("div",{style:{color:"#f59e0b",fontSize:10,fontWeight:700,marginBottom:3,textTransform:"uppercase"},children:"One-time â charged after installation"}),t.jsx("textarea",{value:W.description,onChange:re=>h(W._key,"description",re.target.value),rows:4,style:{...te.input,width:"100%",resize:"vertical",fontSize:12,padding:"6px 8px"}}),t.jsx("div",{style:{marginTop:4},children:t.jsx("select",{value:W.item_type,disabled:!O,onChange:re=>h(W._key,"item_type",re.target.value),style:{...te.input,fontSize:11,padding:"4px 8px",width:"auto"},children:["product","install_fee","maintenance","discount","custom"].map(re=>t.jsx("option",{value:re,children:re},re))})})]}),t.jsx("td",{style:{...te.td,textAlign:"center"},children:t.jsx("input",{type:"number",min:1,value:W.quantity,onChange:re=>h(W._key,"quantity",Number(re.target.value)),style:{...te.input,textAlign:"center",width:56}})}),t.jsx("td",{style:{...te.td,textAlign:"right"},children:t.jsx("input",{type:"number",step:"0.01",min:0,value:W.unit_price,onChange:re=>h(W._key,"unit_price",parseFloat(re.target.value)||0),disabled:!O&&!W.is_open_item,title:!O&&!W.is_open_item?"Catalog price. Only an admin can change it":void 0,style:{...te.input,textAlign:"right",width:96,opacity:!O&&!W.is_open_item?.6:1}})}),t.jsx("td",{style:{...te.td,textAlign:"center"},children:t.jsxs("div",{style:{position:"relative"},children:[t.jsx("input",{type:"number",min:0,max:V.blocked?0:V.allowed,step:.5,value:W.discount_pct,disabled:V.blocked,title:V.message,onChange:re=>h(W._key,"discount_pct",parseFloat(re.target.value)||0),style:{...te.input,textAlign:"center",width:60,border:ee?"1px solid #ef4444":(V.blocked,"1px solid #1e3a4f"),opacity:V.blocked?.4:1,cursor:V.blocked?"not-allowed":"auto"}}),V.blocked&&t.jsx("div",{style:{fontSize:9,color:"#64748b",marginTop:2,lineHeight:1.2,maxWidth:60},children:"locked"}),!V.blocked&&t.jsxs("div",{style:{fontSize:9,color:ee?"#ef4444":"#64748b",marginTop:2,lineHeight:1.2},children:["max ",V.allowed,"%"]})]})}),t.jsx("td",{style:{...te.td,textAlign:"right",color:"#e2e8f0",fontWeight:700,fontSize:13},children:Es(W.total)}),t.jsx("td",{style:te.td,children:t.jsx("button",{onClick:()=>y(W._key),style:{background:"none",border:"none",cursor:"pointer",color:"#475569",fontSize:16,padding:2},children:"Ã"})})]},W._key)})})]}),d.length>0&&t.jsx("div",{style:{display:"flex",justifyContent:"flex-end",marginTop:16},children:t.jsx("div",{style:{minWidth:280},children:B?t.jsxs(t.Fragment,{children:[t.jsx("div",{style:{color:"#22d3ee",fontSize:11,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.08em",marginBottom:6},children:"Monthly Recurring"}),t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",padding:"5px 0",marginBottom:10},children:[t.jsx("span",{style:{color:"#64748b",fontSize:13},children:"Monthly subtotal"}),t.jsxs("span",{style:{color:"#22d3ee",fontSize:13,fontWeight:700},children:[Es(x),"/mo"]})]}),_>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{style:{color:"#f59e0b",fontSize:11,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.08em",marginBottom:6,paddingTop:10,borderTop:"1px solid #1e3a4f"},children:"One-time (after installation)"}),t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",padding:"5px 0"},children:[t.jsx("span",{style:{color:"#64748b",fontSize:13},children:"Installation fee"}),t.jsx("span",{style:{color:"#fbbf24",fontSize:13,fontWeight:700},children:Es(_)})]})]})]}):[{label:"Subtotal",val:C,color:"#94a3b8"},...j>0?[{label:"Discount",val:-j,color:"#4ade80"}]:[],{label:"Tax (7%)",val:A,color:"#64748b"},{label:"Total",val:v,color:"#e2e8f0",bold:!0}].map(W=>t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",padding:"5px 0",borderTop:W.label==="Total"?"1px solid #1e3a4f":"none"},children:[t.jsx("span",{style:{color:"#64748b",fontSize:13},children:W.label}),t.jsx("span",{style:{color:W.color,fontSize:13,fontWeight:W.bold?700:400},children:Es(W.val)})]},W.label))})})]}),t.jsxs("div",{style:te.section,children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:12},children:[t.jsxs("div",{children:[t.jsx("div",{style:te.label,children:"Service Plans"}),t.jsx("div",{style:{color:"#64748b",fontSize:11,marginTop:-2},children:"Optional â plans activate after installation is complete"})]}),t.jsx("button",{onClick:()=>q(W=>!W),style:{padding:"7px 14px",borderRadius:8,border:"1px solid #f59e0b",background:k?"rgba(245,158,11,0.1)":"transparent",color:"#f59e0b",curs
736or:"pointer",fontSize:13,fontWeight:600},children:k?"Close":"+ Add Service Plan"})]}),k&&t.jsxs("div",{style:{background:"#0f1923",borderRadius:10,border:"1px solid #1e3a4f",marginBottom:12,overflow:"hidden"},children:[t.jsx("div",{style:{padding:"10px 14px",borderBottom:"1px solid #1e3a4f",fontSize:11,color:"#64748b"},children:"Select a plan to include on this quote"}),t.jsx("div",{style:{maxHeight:240,overflowY:"auto"},children:S.length===0?t.jsx("div",{style:{padding:16,color:"#64748b",fontSize:13},children:"No active plan templates. Create them in Admin Settings."}):S.map(W=>{const G=T.some(V=>V.template_id===W.id);return t.jsxs("button",{disabled:G,onClick:()=>{L(W),q(!1)},style:{display:"flex",width:"100%",padding:"10px 14px",gap:12,background:"none",border:"none",cursor:G?"not-allowed":"pointer",textAlign:"left",borderBottom:"1px solid #1a2e42",opacity:G?.4:1},onMouseEnter:V=>{G||(V.currentTarget.style.background="#162232")},onMouseLeave:V=>{V.currentTarget.style.background="none"},children:[t.jsxs("div",{style:{flex:1},children:[t.jsxs("div",{style:{color:"#e2e8f0",fontSize:13,fontWeight:600},children:[W.name,G&&t.jsx("span",{style:{color:"#64748b",fontWeight:400},children:" (added)"})]}),W.description&&t.jsxs("div",{style:{color:"#64748b",fontSize:11,marginTop:2},children:[W.description.slice(0,80),W.description.length>80?"...":""]})]}),t.jsxs("div",{style:{textAlign:"right",flexShrink:0},children:[t.jsxs("div",{style:{color:"#f59e0b",fontSize:12,fontWeight:700},children:[Es(Number(W.price_monthly??W.price??0)),ya[W.billing_interval||W.billing_cycle]||""]}),t.jsx("div",{style:{color:"#64748b",fontSize:10},children:td[W.fulfillment_type]||W.fulfillment_type})]})]},W.id)})})]}),T.length===0?t.jsx("div",{style:{textAlign:"center",padding:"20px 0",color:"#334155",fontSize:13},children:"No service plans added. These are optional recurring services."}):t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:T.map(W=>t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,background:"#0f1923",borderRadius:10,border:"1px solid #1e3a4f",padding:"10px 14px"},children:[t.jsxs("div",{style:{flex:1},children:[t.jsx("div",{style:{color:"#e2e8f0",fontWeight:600,fontSize:13},children:W.name}),t.jsxs("div",{style:{color:"#64748b",fontSize:11,marginTop:2},children:[td[W.fulfillment_type]||W.fulfillment_type," · Billed ",W.billing_cycle]})]}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[t.jsx("input",{type:"number",step:"0.01",min:0,value:W.price,onChange:G=>R(W._key,parseFloat(G.target.value)||0),style:{...te.input,width:90,textAlign:"right",padding:"6px 8px"}}),t.jsx("span",{style:{color:"#f59e0b",fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:ya[W.billing_cycle]||""}),t.jsx("button",{onClick:()=>E(W._key),style:{background:"none",border:"none",cursor:"pointer",color:"#475569",fontSize:16,padding:"0 4px"},children:"Ã"})]})]},W._key))})]})]})}function vH({quoteNumber:e,quoteDate:n,validUntil:r,customerName:s,customerAddress:i="",customerPhone:o,salesConsultant:a,estimation:l,lineItems:d,subtotal:c,taxAmount:f,total:p,discountTotal:u=0,grossSubtotal:h=0,monthlySubtotal:y,installFeeTotal:m,commercialType:b,selectedPlans:A=[],branding:v}){const x=v,_=b==="rental",j=x.company_name||"Water Treatment Company";Z8(x);const C=K8(j),S=x.accounts_email||x.email||"",T=xH(j);x.owner_name||x.authorized_signer_name;const L=x.slug?`${window.location.origin}/t/${x.slug}/terms`:`${window.location.origin}/terms`;return t.jsx("div",{style:{padding:"0 24px 40px",overflowY:"auto"},children:t.jsxs("div",{id:"zenith-quote-preview",style:{background:"#fff",maxWidth:860,margin:"24px auto",borderRadius:4,boxShadow:"0 4px 40px rgba(0,0,0,0.5)",fontFamily:"'DM Sans', Arial, sans-serif",color:Xe.text,fontSize:13},children:[t.jsxs("div",{style:{padding:"32px 40px"},children:[t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",marginBottom:28},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[x.logo_url?t.jsx("img",{src:x.logo_url,alt:j,style:{height:52,width:"auto",maxWidth:260,objectFit:"contain"}}):t.jsx("div",{style:{width:48,height:48,borderRadius:4,background:Xe.navy,display:"flex",alignItems:"center",justifyContent:"center"},children:t.jsx("span",{style:{color:Xe.teal,fontWeight:900,fontSize:18},children:C})}),!x.logo_url&&t.jsxs("div",{children:[t.jsx("div",{style:{fontWeight:900,fontSize:15,color:Xe.navy},children:j.toUpperCase()}
736),x.tagline&&t.jsx("div",{style:{fontSize:10,color:Xe.teal,fontWeight:600,letterSpacing:"0.15em"},children:x.tagline.toUpperCase()})]})]}),t.jsxs("div",{style:{textAlign:"right",fontSize:12,color:Xe.muted,lineHeight:1.7},children:[t.jsx("div",{style:{fontWeight:600,color:Xe.text},children:j}),x.address_line1&&t.jsx("div",{children:x.address_line1}),(x.city||x.state||x.zip)&&t.jsxs("div",{children:[[x.city,x.state].filter(Boolean).join(", "),x.zip?` ${x.zip}`:""]}),t.jsx("div",{children:x.country||"United States"})]})]}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:24,marginBottom:28},children:[t.jsxs("div",{children:[t.jsx("div",{style:{fontWeight:700,fontSize:12,marginBottom:6},children:"BILL TO:"}),t.jsxs("div",{style:{color:Xe.text,lineHeight:1.8,fontSize:12},children:[t.jsx("div",{children:s}),i&&t.jsx("div",{children:i}),t.jsx("div",{children:"United States"})]})]}),t.jsxs("div",{children:[t.jsx("div",{style:{fontWeight:700,fontSize:12,marginBottom:6},children:"INSTALLATION ADDRESS"}),t.jsxs("div",{style:{color:Xe.text,lineHeight:1.8,fontSize:12},children:[t.jsx("div",{children:s}),i&&t.jsx("div",{children:i}),t.jsx("div",{children:"United States"}),o&&t.jsx("div",{children:o})]})]})]}),t.jsxs("div",{style:{marginBottom:20},children:[t.jsxs("h1",{style:{fontSize:28,fontWeight:900,color:Xe.navy,margin:"0 0 14px"},children:["QUOTATION # ",e]}),t.jsx("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:8},children:[{label:"QUOTATION DATE",val:sj(n)},{label:"EXPIRATION",val:sj(r)},{label:"SALES CONSULTANT",val:a}].map(E=>t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:10,fontWeight:700,color:Xe.teal,letterSpacing:"0.1em",marginBottom:3},children:E.label}),t.jsx("div",{style:{fontSize:13},children:E.val})]},E.label))})]}),l&&t.jsxs("div",{style:{marginBottom:20},children:[t.jsx("div",{style:{fontWeight:700,fontSize:13,marginBottom:6},children:"ESTIMATION DETAILS"}),t.jsx("div",{style:{fontSize:12,lineHeight:1.7,color:Xe.text,whiteSpace:"pre-wrap"},children:l})]}),t.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",marginBottom:20},children:[t.jsx("thead",{children:t.jsx("tr",{style:{borderBottom:"2px solid "+Xe.navy},children:["Code","Name and Description","Qty","Unit Price","Discount","Total"].map((E,R)=>t.jsx("th",{style:{padding:"8px 8px",fontSize:12,fontWeight:700,color:Xe.navy,textAlign:R>=2?"right":"left"},children:E},E))})}),t.jsx("tbody",{children:d.map(E=>{const R=E.discount_amount!=null?Number(E.discount_amount)||0:E.discount_pct>0?parseFloat((E.quantity*E.unit_price*E.discount_pct/100).toFixed(2)):0,N=E.description.split(` 737`),O=E.item_type==="install_fee";return t.jsxs("tr",{style:{borderBottom:"1px solid "+Xe.border,background:O?"#fffbf0":"transparent"},children:[t.jsx("td",{style:{padding:"10px 8px",fontSize:11,color:Xe.muted,verticalAlign:"top",whiteSpace:"nowrap"},children:E.sku||""}),t.jsxs("td",{style:{padding:"10px 8px",verticalAlign:"top",maxWidth:340},children:[O&&t.jsx("div",{style:{fontSize:10,fontWeight:700,color:"#b45309",marginBottom:2,textTransform:"uppercase"},children:"One-time · Charged after installation"}),t.jsx("div",{style:{fontWeight:700,fontSize:13},children:N[0]}),N.slice(1).join(` 738`)&&t.jsx("div",{style:{fontSize:11,color:Xe.muted,marginTop:4,whiteSpace:"pre-wrap",lineHeight:1.6},children:N.slice(1).join(` 739`)})]}),t.jsxs("td",{style:{padding:"10px 8px",textAlign:"right",verticalAlign:"top"},children:[E.quantity,".0"]}),t.jsxs("td",{style:{padding:"10px 8px",textAlign:"right",verticalAlign:"top"},children:["$ ",E.unit_price.toFixed(2),_&&E.item_type==="product"&&t.jsx("span",{style:{fontSize:10,color:Xe.teal,fontWeight:700},children:"/mo"})]}),t.jsx("td",{style:{padding:"10px 8px",textAlign:"right",verticalAlign:"top",color:Xe.muted},children:R>0?`$ ${R.toFixed(2)} (${E.discount_pct}%)`:"â"}),t.jsxs("td",{style:{padding:"10px 8px",textAlign:"right",fontWeight:700,verticalAlign:"top"},children:["$ ",E.total.toFixed(2)]})]},E._key)})})]}),t.jsx("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:28},children:t.jsx("div",{style:{minWidth:280},children:_?t.jsxs(t.Fragment,{children:[t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",padding:"8px 0",borderTop:"2px solid "+Xe.navy,fontSize:14,fontWeight:900},children:[t.jsx("span",{children:"Monthly Total"}),t.jsxs("span",{children:["$ ",y.toFixed(2)," ",t.jsx("span",{style:{fontSize:11,fontWeight:400,color:Xe.teal},children:"/mo"})]})]}),m>0&&t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",padding:"8px 0",borderTop:"1px dashed #d4a843",marginTop:4,fontSize:13,fontWeight:700,color:"#b45309"},children:[t.jsxs("span",{children:["Installation Fee ",t.jsx("span",{style:{fontSize:10,fontWeight:400,color:Xe.muted},children:"(one-time, after install)"})]}),t.jsxs("span",{children:["$ ",m.toFixed(2)]})]})]}):t.jsxs(t.Fragment,{children:[[{label:"Subtotal",val:h},...u>0?[{label:"Discount",val:-u}]:[],{label:"Taxes",val:f}].map(E=>t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",padding:"4px 0",fontSize:13},children:[t.jsx("span",{style:{color:Xe.muted},children:E.label}),t.jsx("span",{children:E.val<0?`â $ ${Math.abs(E.val).toFixed(2)}`:`$ ${E.val.toFixed(2)}`})]},E.label)),t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",padding:"8px 0",borderTop:"2px solid "+Xe.navy,fontSize:14,fontWeight:900},children:[t.jsx("span",{children:"Total"}),t.jsxs("span",{children:["$ ",p.toFixed(2)]})]})]})})}),A.length>0&&t.jsxs("div",{style:{marginBottom:24,borderTop:"1px solid "+Xe.border,paddingTop:18},children:[t.jsx("div",{style:{fontWeight:700,fontSize:13,color:Xe.navy,marginBottom:10},children:"INCLUDED SERVICE PLANS"}),t.jsx("div",{style:{fontSize:11,color:Xe.muted,marginBottom:10},children:"The following service plans are included with this quote. Plans activate after installation is complete. Billing begins according to each plan's schedule."}),t.jsxs("table",{style:{width:"100%",borderCollapse:"collapse"},children:[t.jsx("thead",{children:t.jsxs("tr",{style:{borderBottom:"1px solid "+Xe.border},children:[t.jsx("th",{style:{padding:"6px 8px",fontSize:11,fontWeight:700,color:Xe.navy,textAlign:"left"},children:"Plan"}),t.jsx("th",{style:{padding:"6px 8px",fontSize:11,fontWeight:700,color:Xe.navy,textAlign:"left"},children:"Service Type"}),t.jsx("th",{style:{padding:"6px 8px",fontSize:11,fontWeight:700,color:Xe.navy,textAlign:"right"},children:"Price"})]})}),t.jsx("tbody",{children:A.map(E=>
739t.jsxs("tr",{style:{borderBottom:"1px solid "+Xe.border,background:"#fefbf3"},children:[t.jsx("td",{style:{padding:"8px 8px",fontSize:12,fontWeight:600},children:E.name}),t.jsx("td",{style:{padding:"8px 8px",fontSize:11,color:Xe.muted},children:td[E.fulfillment_type]||E.fulfillment_type}),t.jsxs("td",{style:{padding:"8px 8px",fontSize:12,fontWeight:700,textAlign:"right",color:"#b45309"},children:["$ ",E.price.toFixed(2),ya[E.billing_cycle]||""]})]},E._key))})]})]}),t.jsxs("div",{style:{borderTop:"1px solid "+Xe.border,paddingTop:20,marginBottom:20},children:[t.jsx("div",{style:{fontWeight:700,fontSize:13,marginBottom:8},children:"CUSTOMER AUTHORIZATION"}),t.jsx("div",{style:{fontSize:11.5,lineHeight:1.8,color:Xe.text,whiteSpace:"pre-wrap"},children:T}),t.jsx("div",{style:{marginTop:10,fontSize:12},children:t.jsx("a",{href:L,style:{color:Xe.teal,textDecoration:"underline",fontWeight:600},children:"Click here to view Terms & Conditions (Version v1.0, Date 01/30/2026)"})})]}),_&&t.jsxs("div",{style:{background:"#f0f8ff",border:"1px solid #b3d9ed",borderRadius:6,padding:"12px 16px",marginBottom:20,fontSize:12},children:[t.jsx("strong",{children:"Rental Agreement:"})," Accepting this quote initiates a 36-month Residential Equipment Rental Agreement. Monthly payments of the rental amount apply. Equipment remains property of ",j,". 50% of payments made apply toward buyout at any time.",m>0&&t.jsxs("div",{style:{marginTop:6,color:"#b45309",fontWeight:600},children:["Installation fee of $",m.toFixed(2)," is a one-time charge collected after installation is complete."]})]}),x.bank_name&&t.jsxs("div",{style:{borderTop:"1px solid "+Xe.border,paddingTop:20,marginBottom:20},children:[t.jsx("div",{style:{fontWeight:700,fontSize:13,marginBottom:12},children:"DIRECT TRANSFER / ACH DETAILS"}),t.jsx("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:12},children:t.jsx("tbody",{children:[["Bank Name",x.bank_name],["ACH ABA Number",x.bank_routing],["Account Number",x.bank_account],["Account Name",x.bank_account_name||j.toUpperCase()],["Email",S],["Phone Number",x.phone]].filter(([,E])=>E).map(([E,R])=>t.jsxs("tr",{children:[t.jsxs("td",{style:{border:"1px solid "+Xe.border,padding:"7px 12px",fontWeight:600,width:"40%",background:Xe.light},children:[E,":"]}),t.jsx("td",{style:{border:"1px solid "+Xe.border,padding:"7px 12px"},children:R})]},E))})}),t.jsxs("div",{style:{fontSize:11,color:Xe.muted,marginTop:10,textAlign:"right"},children:["Quote Version: ",new Date().toLocaleDateString("en-US")," ",new Date().toLocaleTimeString("en-US")]})]}),!x.bank_name&&t.jsx("div",{style:{borderTop:"1px solid "+Xe.border,paddingTop:10,marginBottom:20},children:t.jsxs("div",{style:{fontSize:11,color:Xe.muted,textAlign:"right"},children:["Quote Version: ",new Date().toLocaleDateString("en-US")," ",new Date().toLocaleTimeString("en-US")]})}),t.jsx("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:40,paddingTop:8},children:["Sign here","Date"].map(E=>t.jsxs("div",{children:[t.jsx("div",{style:{borderBottom:"1px solid "+Xe.text,marginBottom:4,height:36}}),t.jsx("div",{style:{fontSize:12,fontWeight:600},children:E})]},E))})]}),t.jsxs("div",{style:{borderTop:"1px solid "+Xe.border,padding:"12px 40px",display:"flex",justifyContent:"space-between"},children:[t.jsx("div",{style:{fontSize:11,color:Xe.muted,fontStyle:"italic"},children:x.tagline||`Professional water treatment by ${j}.`}),t.jsx("div",{style:{fontSize:11,color:Xe.muted},children:"Page 1 / 1"})]})]})})}function _H({quoteNumber:e,customerName:n,customerAddress:r,lineItems:s,monthlySubtotal:i,installFeeTotal:o,onClose:a,branding:l}){const d=l,c=new Date().toLocaleDateString("en-US",{month:"long",day:"numeric",year:"numeric"}),f=s.filter(x=>x.item_type!=="install_fee"),p=d.company_name||"Water Treatment Company",u=Z8(d),h=K8(p),y=d.owner_name||d.authorized_signer_name||"Authorized Representative",m=d.governing_law_state||d.state||"Indiana",b=d.slug?`${window.location.origin}/t/${d.slug}/terms`:`${window.location.origin}/terms`;function A(){if(typeof html2pdf>"u"){const x=document.createElement("script");x.src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js",x.onload=()=>v(),document.head.appendChild(x)}else v()}function v(){const x=document.getElementById("zenith-agreement-content");x&&html2pdf().set({margin:10,filename:`Rental_Agreement_${n.replace(/\s+/g,"-")}.pdf`,image:{type:"jpeg",quality:.98},html2canvas:{scale:2,useCORS:!0},jsPDF:{unit:"mm",format:"a4",orientation:"portrait"}}).from(x).save()}return t.jsx("div",{style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.85)",zIndex:1e3,display:"flex",alignItems:"flex-start",justifyContent:"center",overflowY:"auto",padding:"24px 16px"},children:t.jsxs("div",{style:{background:"#162232",borderRadius:12,width:"100%",maxWidth:800,boxShadow:"0 20px 60px rgba(0,0,0,0.7)"},children:[t.jsxs("div",{style:{padding:"20px 28px",borderBottom:"1px solid #1e3a4f",dis
739play:"flex",justifyContent:"space-between",alignItems:"center"},children:[t.jsxs("div",{children:[t.jsx("div",{style:{color:"#e2e8f0",fontWeight:700,fontSize:18},children:"Rental Agreement Generated"}),t.jsxs("div",{style:{color:"#64748b",fontSize:13,marginTop:2},children:["Auto-generated from accepted quote ",e]})]}),t.jsxs("div",{style:{display:"flex",gap:10},children:[t.jsx("button",{onClick:A,style:{padding:"8px 18px",borderRadius:8,border:"none",cursor:"pointer",background:"#0d7ea3",color:"#fff",fontWeight:700,fontSize:13},children:"⬠Download PDF"}),t.jsx("button",{onClick:a,style:{padding:"8px 18px",borderRadius:8,border:"1px solid #334155",cursor:"pointer",background:"transparent",color:"#94a3b8",fontWeight:600,fontSize:13},children:"Close"})]})]}),t.jsx("div",{style:{padding:28,overflowY:"auto",maxHeight:"75vh"},children:t.jsxs("div",{id:"zenith-agreement-content",style:{background:"#fff",color:"#1a2a3a",fontFamily:"'DM Sans', Arial, sans-serif",fontSize:12,lineHeight:1.6,padding:"40px 48px",borderRadius:4},children:[t.jsxs("div",{style:{textAlign:"center",marginBottom:28,borderBottom:"2px solid #0c1e35",paddingBottom:20},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",gap:12,marginBottom:8},children:[d.logo_url?t.jsx("img",{src:d.logo_url,alt:p,style:{height:44,width:"auto",maxWidth:220,objectFit:"contain"}}):t.jsx("div",{style:{width:40,height:40,background:"#0c1e35",borderRadius:4,display:"flex",alignItems:"center",justifyContent:"center"},children:t.jsx("span",{style:{color:"#0d7ea3",fontWeight:900,fontSize:16},children:h})}),t.jsxs("div",{children:[!d.logo_url&&t.jsx("div",{style:{fontWeight:900,fontSize:16,color:"#0c1e35"},children:p.toUpperCase()}),u&&t.jsx("div",{style:{fontSize:10,color:"#64748b"},children:u})]})]}),t.jsx("div",{style:{fontWeight:800,fontSize:18,color:"#0c1e35",letterSpacing:1,marginTop:12},children:"RESIDENTIAL EQUIPMENT RENTAL AGREEMENT"}),t.jsxs("div",{style:{fontSize:11,color:"#64748b",marginTop:4},children:["Generated: ",c," ⢠Ref: ",e]})]}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:24,marginBottom:20},children:[t.jsxs("div",{children:[t.jsx("div",{style:{fontWeight:700,fontSize:11,textTransform:"uppercase",color:"#64748b",marginBottom:6},children:"Company (Lessor)"}),t.jsx("div",{style:{fontWeight:600},children:p}),d.address_line1&&t.jsx("div",{children:d.address_line1}),(d.city||d.state||d.zip)&&t.jsxs("div",{children:[[d.city,d.state].filter(Boolean).join(", "),d.zip?` ${d.zip}`:""]}),d.phone&&t.jsxs("div",{children:["Phone: ",d.phone]})]}),t.jsxs("div",{children:[t.jsx("div",{style:{fontWeight:700,fontSize:11,textTransform:"uppercase",color:"#64748b",marginBottom:6},children:"Customer (Lessee)"}),t.jsx("div",{style:{fontWeight:600},children:n}),r&&t.jsx("div",{children:r})]})]}),t.jsxs("div",{style:{marginBottom:20},children:[t.jsx("div",{style:{fontWeight:700,fontSize:13,color:"#0c1e35",borderBottom:"1px solid #e2e8f0",paddingBottom:6,marginBottom:10},children:"APPENDIX A â EQUIPMENT SCHEDULE"}),t.jsxs("table",{style:{width:"100%",borderCollapse:"collapse"},children:[t.jsx("thead",{children:t.jsx("tr",{style:{background:"#f0f4f8"},children:["Description","Monthly Rate","Term"].map(x=>t.jsx("th",{style:{border:"1px solid #e2e8f0",padding:"8px 12px",textAlign:"left",fontSize:11,fontWeight:700},children:x},x))})}),t.jsxs("tbody",{children:[f.map((x,_)=>t.jsxs("tr",{children:[t.jsx("td",{style:{border:"1px solid #e2e8f0",padding:"8px 12px"},children:x.description}),t.jsxs("td",{style:{border:"1px solid #e2e8f0",padding:"8px 12px"},children:["$",x.total.toFixed(2),"/mo"]}),t.jsx("td",{style:{border:"1px solid #e2e8f0",padding:"8px 12px"},children:"36 months"})]},_)),t.jsxs("tr",{style:{fontWeight:700,background:"#f8fafc"},children:[t.jsx("td",{style:{border:"1px solid #e2e8f0",padding:"8px 12px"},children:"Total Monthly Payment"}),t.jsxs("td",{style:{border:"1px solid #e2e8f0",padding:"8px 12px",color:"#0c1e35"},children:["$",i.toFixed(2),"/mo"]}),t.jsx("td",{style:{border:"1px solid #e2e8f0",padding:"8px 12px"}})]}),o>0&&t.jsxs("tr",{style:{background:"#fffbf0"},children:[t.jsxs("td",{style:{border:"1px solid #e2e8f0",padding:"8px 12px",color:"#b45309",fontWeight:600},children:["Installation Fee ",t.jsx("span",{style:{fontSize:10,fontWeight:400},children:"(one-time)"})]}),t.jsxs("td",{style:{border:"1px solid #e2e8f0",padding:"8px 12px",color:"#b45309",fontWeight:700},children:["$",o.toFixed(2)]}),t.jsx("td",{style:{border:"1px solid #e2e8f0",padding:"8px 12px",fontSize:11,color:"#64748b"},children:"One-time"})]})]})]})]}),t.jsxs("div",{style:{marginBottom:20},children:[t.jsx("div",{style:{fontWeight:700,fontSize:13,color:"#0c1e35",borderBottom:"1px solid #e2e8f0",paddingBottom:6,marginBottom:10},children:"KEY TERMS & CONDITIONS"}),[["Initial Term","36 months from installation date. Automatically renews month-to-month after initial term."],["Monthly Payment",`$${i.toFixed(2)}/month, due on the same day each month. Autopay via ACH or card on file.`],["Installation Fee",o>0?`$${o.toFixed(2)} one-time fee, charged after installation is complete. Credited 100% toward equipment buyout.`:"Included."],["Buy
739out Option","Current Retail Price minus 50% of payments made minus installation fee. Exercisable at any time after month 6."],["Late Fee","1.75% per month (21% APR) on balances past due. NSF fee: $25.00."],["Annual Price Increase","Up to CPI-U + 3% annually, with 30-day written notice."],["Cancellation","Customer may cancel with 30 days written notice. Early termination fee applies if within initial 36-month term."],["Right of Rescission",`${m} Home Solicitation Sales Act â 3 business day cancellation right from date of signing.`],["Equipment Ownership",`Equipment remains property of ${p} until buyout is exercised and confirmed in writing.`],["Dispute Resolution",`Binding arbitration under AAA rules in ${d.city||m}${d.state?`, ${d.state}`:""}. Class action waiver applies.`]].map(([x,_])=>t.jsxs("div",{style:{marginBottom:8,display:"grid",gridTemplateColumns:"180px 1fr",gap:12},children:[t.jsxs("div",{style:{fontWeight:600,fontSize:11},children:[x,":"]}),t.jsx("div",{style:{fontSize:11},children:_})]},x))]}),d.bank_name&&t.jsxs("div",{style:{marginBottom:24},children:[t.jsx("div",{style:{fontWeight:700,fontSize:13,color:"#0c1e35",borderBottom:"1px solid #e2e8f0",paddingBottom:6,marginBottom:10},children:"PAYMENT â ACH DETAILS"}),t.jsx("table",{style:{width:"100%",borderCollapse:"collapse",maxWidth:400},children:[["Bank Name",d.bank_name],["ABA / Routing",d.bank_routing],["Account Number",d.bank_account],["Account Name",d.bank_account_name||p.toUpperCase()]].filter(([,x])=>x).map(([x,_])=>t.jsxs("tr",{children:[t.jsxs("td",{style:{border:"1px solid #e2e8f0",padding:"7px 12px",fontWeight:600,background:"#f0f4f8",width:"40%"},children:[x,":"]}),t.jsx("td",{style:{border:"1px solid #e2e8f0",padding:"7px 12px"},children:_})]},x))})]}),t.jsx("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:40,marginTop:32},children:[["Customer Signature",n,"Date"],[`Authorized by ${p}`,`${y}, ${p}`,"Date"]].map(([x,_,j])=>t.jsxs("div",{children:[t.jsx("div",{style:{borderBottom:"1px solid #1a2a3a",marginBottom:4,height:40}}),t.jsx("div",{style:{fontSize:11,fontWeight:600},children:x}),t.jsx("div",{style:{fontSize:10,color:"#64748b"},children:_}),t.jsx("div",{style:{borderBottom:"1px solid #1a2a3a",marginBottom:4,height:28,marginTop:16}}),t.jsx("div",{style:{fontSize:11,fontWeight:600},children:j})]},x))}),t.jsxs("div",{style:{marginTop:28,paddingTop:16,borderTop:"1px solid #e2e8f0",fontSize:10,color:"#94a3b8",textAlign:"center"},children:[p," ⢠",u,d.phone?` ⢠${d.phone}`:"",d.website?` ⢠${d.website}`:"",t.jsx("br",{}),"Terms & Conditions: ",b," â¢"," ","Version v1.0 ⢠",c]})]})})]})})}function ij({lead:e,onLeadUpdated:n,onCompletionChange:r,readOnly:s}){const[i,o]=g.useState([]),[a,l]=g.useState({}),[d,c]=g.useState(!0),[f,p]=g.useState(!1);g.useEffect(()=>{async function x(){c(!0);const{data:_}
739=await w.from("qualifying_questions").select("*").eq("is_active",!0).order("sort_order");_&&o(_);const C={...e.qualifying_answers||{}};if(_){for(const S of _)if(C[S.id]===void 0){if(S.field_type==="prefill_water_concern"&&e.water_concern&&(C[S.id]=of[e.water_concern]||e.water_concern),S.field_type==="prefill_address"){const T=await ba("lead",e.id),L=[(T==null?void 0:T.address_line1)??e.address,(T==null?void 0:T.city)??e.city,(T==null?void 0:T.state)??e.state,(T==null?void 0:T.zip)??(e.zip_code||e.zip)].filter(Boolean).join(", ");L&&(C[S.id]=L)}S.field_type==="prefill_source"&&e.source&&(C[S.id]=sf[e.source]||e.source)}}l(C),c(!1)}x()},[e.id]);const u=g.useCallback(async(x,_)=>{if(s)return;const j={...a,[x]:_};l(j),p(!0);const{data:C,error:S}=await w.from("leads").update({qualifying_answers:j}).eq("id",e.id).select("*").single();!S&&C&&n({...e,...C}),p(!1)},[a,e,n,s]),h=i.filter(x=>x.is_required),y=h.filter(x=>{const _=a[x.id];return _!=null&&_!==""}),m=y.length===h.length,b=i.filter(x=>{const _=a[x.id];return _!=null&&_!==""}).length;if(g.useEffect(()=>{r==null||r(m&&i.length>0)},[m,i.length]),d)return t.jsx("div",{style:{background:"rgba(34,211,238,0.08)",border:"1px solid rgba(34,211,238,0.2)",borderRadius:14,padding:16},children:t.jsx("div",{style:{fontSize:12,color:"#22d3ee"},children:"Loading checklist..."})});if(i.length===0)return null;const A={width:"100%",background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:8,padding:"6px 10px",fontSize:13,color:"#e2e8f0",outline:"none"},v={...A,appearance:"auto"};return t.jsxs("div",{style:{background:"rgba(34,211,238,0.06)",border:"1px solid rgba(34,211,238,0.2)",borderRadius:14,padding:16},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:10},children:[t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:12,fontWeight:800,color:"#22d3ee",textTransform:"uppercase",letterSpacing:"0.07em"},children:"Qualifying Checklist"}),t.jsxs("div",{style:{fontSize:11,color:"#94a3b8",marginTop:3},children:[b," of ",i.length," answered",!m&&t.jsxs("span",{style:{color:"#f59e0b",marginLeft:6},children:["· ",h.length-y.length," required remaining"]})]})]}),f&&t.jsx("div",{style:{fontSize:11,color:"#22d3ee"},children:"Saving..."}),m&&!f&&t.jsx("div",{style:{fontSize:11,fontWeight:700,color:"#34d399",display:"flex",alignItems:"center",gap:4},children:"â Ready to qualify"})]}),t.jsx("div",{style:{width:"100%",height:6,background:"#1e3a4f",borderRadius:6,overflow:"hidden",marginBottom:14},children:t.jsx("div",{style:{height:"100%",borderRadius:6,transition:"all 0.3s",background:m?"#34d399":"#22d3ee",width:`${y.length/Math.max(h.length,1)*100}%`}})}),t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:12},children:i.map(x=>{const _=a[x.id],j=_!=null&&_!=="",C=x.field_type.startsWith("prefill_");return t.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:10},children:[t.jsx("div",{style:{marginTop:2,width:18,height:18,borderRadius:4,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,fontSize:11,fontWeight:700,...j?{background:"rgba(52,211,153,0.15)",color:"#34d399",border:"1px solid rgba(52,211,153,0.3)"}:x.is_required?{background:"rgba(100,116,139,0.1)",border:"1px solid rgba(245,158,11,0.3)",color:"transparent"}:{background:"rgba(100,116,139,0.1)",border:"1px solid rgba(100,116,139,0.2)",color:"transparent"}},children:j?"â":""}),t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsxs("label",{style:{fontSize:12,fontWeight:500,color:"#e2e8f0",display:"flex",alignItems:"center",gap:4},children:[x.question_text,x.is_required&&t.jsx("span",{style:{color:"#f87171"},children:"*"}),C&&j&&t.jsx("span",{style:{fontSize:10,color:"#64748b",fontWeight:400},children:"(auto-filled)"})]}),t.jsxs("div",{style:{marginTop:4},children:[x.field_type==="dropdown"&&t.jsxs("select",{value:_||"",onChange:S=>u(x.id,S.target.value),disabled:s,style:v,children:[t.jsx("option",{value:"",children:"â Select â"}),(x.options||[]).map(S=>t.jsx("option",{value:S,children:S},S))]}),x.field_type==="yes_no"&&t.jsx("div",{style:{display:"flex",gap:8},children:["Yes","No"].map(S=>t.jsx("button",{onClick:()=>u(x.id,S),disabled:s,style:{padding:"4px 14px",fontSize:12,borderRadius:8,fontWeight:600,cursor:s?"default":"pointer",transition:"all 0.12s",..._===S?S==="Yes"?{background:"rgba(52,211,153,0.15)",color:"#34d399",border:"1px solid rgba(52,211,153,0.3)"}:{background:"rgba(248,113,113,0.15)",color:"#f87171",border:"1px solid rgba(248,113,113,0.3)"}:{background:"#0f1923",color:"#64748b",border:"1px solid #1e3a4f"}},children:S},S))}),x.field_type==="number"&&t.jsx("input",{type:"number",min:"0",max:"20",value:_||"",onChange:S=>u(x.id,S.target.value?parseInt(S.target.value):""),placeholder:"Enter number",disabled:s,style:{...A,width:100}}),x.field_type==="text"&&t.jsx("input",{type:"text",value:_||"",onChange:S=>u(x.id,S.target.value),placeholder:"Type answer...",disabled:s,style:A}),x.field_type==="prefill_water_concern"&&t.jsxs("select",{value:_||"",onChange:S=>u(x.id,S.target.value),disabled:s,style:v,children:[t.jsx("option",{value:"",children:"â Select â"}),Object.entries(of).map(([S,T])=>t.jsx("option",{value:T,children:T},S))]}),x.field_type==="prefill_address"&&t.jsxs("div",{children:[t.jsx("input",{type:"text",value:_||"",onChange:S=>u(x.id,S.target.value),placeholder:"Service address...",disabled:s,style:A}),!j&&t.jsx("div",{style:{fontSize:11,color:"#f59e0b",marginTop:4},children:"No address on file â please enter"})]}),x.field_type==="prefill_source"&&t.jsxs("select",{value:_||"",onChange:S=>u(x.id,S.target.value),disabled:s,style:v,children:[t.jsx("option",{value:"",children:"â Select â"}),Object.entries(sf).map(([S,T])=>t.jsx("option",{value:T,children:T},S))]})]})]})]},x.id)})})]})}const jH={all:["notes"],list:(e,n,r)=>["notes",e,n,r??null],count:(e,n,r)=>["notes-count",e,n,r??null]};function wH(e,n,r){return Ae({queryKey:jH.list(e,n??"",r),queryFn:()=>GB(e,n,r),enabled:!!n,staleTime:3e4})}function SH(){const e=rt();return _n({mutationFn:n=>b8(n),onSuccess:n=>
739{e.invalidateQueries({queryKey:["notes",n.entity_type,n.entity_id]}),e.invalidateQueries({queryKey:["notes-count",n.entity_type,n.entity_id]})}})}function kH(){const e=rt();return _n({mutationFn:({id:n,patch:r})=>A8(n,r),onSuccess:n=>{e.invalidateQueries({queryKey:["notes",n.entity_type,n.entity_id]})}})}function CH(){const e=rt();return _n({mutationFn:({id:n,pinned:r})=>JB(n,r),onSuccess:n=>{e.invalidateQueries({queryKey:["notes",n.entity_type,n.entity_id]})}})}function TH(){const e=rt();return _n({mutationFn:n=>QB(n.id),onSuccess:(n,r)=>{e.invalidateQueries({queryKey:["notes",r.entityType,r.entityId]}),e.invalidateQueries({queryKey:["notes-count",r.entityType,r.entityId]})}})}function zH(e,n,r){return!e||!n?!1:e.author_id===n||r==="super_admin"||r==="admin"}const km={all:"Everyone",admin_only:"Admins only",tech_only:"Technicians only",sales_only:"Sales only",office_only:"Office only"},oj={general:"General",qualifying:"Qualifying",plumbing:"Plumbing",field_service:"Field Service",install:"Install",office:"Office",sales:"Sales"};function NH(e){const n=new Date(e).getTime(),r=Date.now(),s=Math.floor((r-n)/1e3);return s<60?"just now":s<3600?`${Math.floor(s/60)}m ago`:s<86400?`${Math.floor(s/3600)}h ago`:s<604800?`${Math.floor(s/86400)}d ago`:new Date(e).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}function ru({entityType:e,entityId:n,section:r,visibilityDefault:s,visibilitySelectorMode:i,title:o}){s="all",i="hidden";const{user:a,role:l}=Ee(),{data:d=[],isLoading:c,isError:f,error:p}=wH(e,n,r),u=SH(),h=kH(),y=CH(),m=TH(),[b,A]=g.useState(!1),[v,x]=g.useState(""),[_,j]=g.useState(s),[C,S]=g.useState(i==="visible"),[T,L]=g.useState(null),[E,R]=g.useState(""),N=o??oj[r]+" Notes";async function O(){if(v.trim())try{await u.mutateAsync({entity_type:e,entity_id:n,body:v.trim(),section:r,visibility:_}),x(""),A(!1),j(s),i==="collapsed"&&S(!1)}catch(q){console.error("createNote failed:",q)}}function z(q){L(q.id),R(q.body)}function P(){L(null),R("")}async function D(q){if(E.trim())try{await h.mutateAsync({id:q,patch:{body:E.trim()}}),P()}catch($){console.error("updateNote failed:",$)}}async function M(q){try{await y.mutateAsync({id:q.id,pinned:!q.pinned})}catch($){console.error("togglePin failed:",$)}}async function k(q){if(confirm("Delete this note? This cannot be undone."))try{await m.mutateAsync({id:q.id,entityType:e,entityId:n})}catch($){console.error("deleteNote failed:",$)}}return t.jsxs("div",{className:"bg-card border border-border rounded-xl p-4",children:[t.jsxs("div",{className:"flex items-center justify-between mb-3",children:[t.jsxs("div",{className:"text-xs font-bold text-slate-300 uppercase tracking-wide",children:[N,d.length>0&&t.jsxs("span",{className:"text-muted font-normal normal-case ml-1",children:["(",d.length,")"]})]}),!b&&t.jsx("button",{onClick:()=>A(!0),className:"text-xs font-semibold px-2.5 py-1 rounded-lg",style:{backgroundColor:"rgba(96,165,250,0.12)",color:"#60a5fa"},children:"+ Add Note"})]}),b&&t.jsxs("div",{className:"mb-3 space-y-2",children:[t.jsx("textarea",{value:v,onChange:q=>x(q.target.value),placeholder:"Write a note...",rows:3,className:"w-full text-sm rounded-lg px-3 py-2 resize-none outline-none",style:{backgroundColor:"#0f172a",border:"1px solid rgba(148,163,184,0.2)",color:"#e2e8f0"},autoFocus:!0}),t.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[t.jsx("span",{className:"text-xs px-2 py-1 rounded-lg",style:{backgroundColor:"rgba(148,163,184,0.1)",color:"#94a3b8"},children:oj[r]}),i!=="hidden"&&!C&&t.jsxs("button",{onClick:()=>S(!0),className:"text-xs px-2 py-1 rounded-lg",style:{backgroundColor:"rgba(148,163,184,0.1)",color:"#94a3b8"},children:["Visibility: ",km[_]," â¾"]}),i!=="hidden"&&C&&t.jsx("select",{value:_,onChange:q=>j(q.target.value),className:"text-xs rounded-lg px-2 py-1 outline-none",style:{backgroundColor:"#1e293b",border:"1px solid rgba(148,163,184,0.2)",color:"#94a3b8"},children:Object.keys(km).map(q=>t.jsx("option",{value:q,children:km[q]},q))}),t.jsxs("div",{className:"flex gap-2 ml-auto",children:[t.jsx("button",{onClick:()=>{A(!1),x(""),j(s),i==="collapsed"&&S(!1)},className:"text-xs px-3 py-1 rounded-lg text-muted hover:text-slate-300",children:"Cancel"}),t.jsx("button",{onClick:O,disabled:u.isPending||!v.trim(),className:"text-xs px-3 py-1 rounded-lg font-semibold disabled:opacity-50",style:{backgroundColor:"rgba(96,165,250,0.15)",color:"#60a5fa"},children:u.isPending?"Saving...":"Save Note"})]})]}),u.isError&&t.jsx("div",{className:"text-xs",style:{color:"#f87171"},children:"Failed to save note. Check console."})]}),c&&t.jsx("div",{className:"text-xs text-muted italic",children:"Loading..."}),f&&!c&&t.jsxs("div",{className:"text-xs",style:{color:"#f87171"},children:["Failed to load notes: ",(p==null?void 0:p.message)??"unknown error"]}),!c&&!f&&d.length===0&&!b&&t.jsx("div",{className:"text-xs text-muted italic",children:"No notes yet"}),!c&&!f&&d.length>0&&t.jsx("div",{className:"space-y-2",children:d.map(q=>{const $=zH(q,a==null?void 0:a.id,l),I=T===q.id;return t.jsxs("div",{className:"rounded-lg px-3 py-2.5",style:{backgroundColor:q.pinned?"rgba(251,191,36,0.06)":"rgba(148,163,184,0.06)",border:q.pinned?"1px solid rgba(251,191,36,0.2)":"1px solid rgba(148,163,184,0.12)"},children:[t.jsxs("div",{className:"flex items-center justify-between mb-1 gap-2 flex-wrap",children:[t.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[q.pinned&&t.jsx("span",{title:"Pinned",children:"ð"}),t.jsx("span",{className:"font-semibold text-slate-300",children:q.author_name}),q.author_role&&t.jsxs("span",{className:"text-muted",children:["· ",q.author_role]}
739),t.jsxs("span",{className:"text-muted",children:["· ",NH(q.created_at)]}),q.edited_at&&t.jsx("span",{className:"text-muted italic",children:"(edited)"}),!1]}),$&&!I&&t.jsxs("div",{className:"flex items-center gap-1",children:[t.jsx("button",{onClick:()=>M(q),className:"text-xs px-2 py-0.5 rounded text-muted hover:text-slate-300",title:q.pinned?"Unpin":"Pin",children:q.pinned?"Unpin":"Pin"}),t.jsx("button",{onClick:()=>z(q),className:"text-xs px-2 py-0.5 rounded text-muted hover:text-slate-300",children:"Edit"}),t.jsx("button",{onClick:()=>k(q),className:"text-xs px-2 py-0.5 rounded",style:{color:"#f87171"},children:"Delete"})]})]}),!I&&t.jsx("div",{className:"text-sm text-slate-300 whitespace-pre-wrap",children:q.body}),I&&t.jsxs("div",{className:"space-y-2",children:[t.jsx("textarea",{value:E,onChange:B=>R(B.target.value),rows:3,className:"w-full text-sm rounded-lg px-3 py-2 resize-none outline-none",style:{backgroundColor:"#0f172a",border:"1px solid rgba(148,163,184,0.2)",color:"#e2e8f0"},autoFocus:!0}),t.jsxs("div",{className:"flex gap-2 justify-end",children:[t.jsx("button",{onClick:P,className:"text-xs px-3 py-1 rounded-lg text-muted hover:text-slate-300",children:"Cancel"}),t.jsx("button",{onClick:()=>D(q.id),disabled:h.isPending||!E.trim(),className:"text-xs px-3 py-1 rounded-lg font-semibold disabled:opacity-50",style:{backgroundColor:"rgba(96,165,250,0.15)",color:"#60a5fa"},children:h.isPending?"Saving...":"Save"})]})]})]},q.id)})})]})}function RH(e){const n=new Date;n.setHours(0,0,0,0);const r=new Date(e+"T00:00:00");return Math.floor((r.getTime()-n.getTime())/864e5)}function EH(e){return new Date(e+"T00:00:00").toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}function PH({leadId:e,leadName:n,userId:r}){const[s,i]=g.useState(!1),[o,a]=g.useState([]),[l,d]=g.useState(!0),[c,f]=g.useState(!1),p=g.useCallback(async()=>{d(!0);try{const m=await _E(e);a(m.filter(b=>!b.completed_at))}catch{a([])}finally{d(!1)}},[e]);g.useEffect(()=>{p()},[p]);async function u(m){try{await fd(m),await p()}catch{}}async function h(m){try{await Bf({...m,lead_id:e}),f(!1),await p()}catch{}}const y=o.length;return t.jsxs("div",{style:{background:"#162232",border:"1px solid #1e3a4f",borderRadius:14,overflow:"hidden"},children:[t.jsxs("button",{onClick:()=>i(m=>!m),style:{width:"100%",display:"flex",alignItems:"center",gap:8,padding:"10px 14px",background:"transparent",border:"none",cursor:"pointer",textAlign:"left"},children:[t.jsx("span",{style:{fontSize:13},children:"ð"}),t.jsx("span",{style:{color:"#94a3b8",fontWeight:700,fontSize:12,textTransform:"uppercase",letterSpacing:"0.06em",flex:1},children:"Follow-Ups"}),y>0&&t.jsx("span",{style:{background:"rgba(248,113,113,0.15)",color:"#f87171",borderRadius:20,padding:"1px 8px",fontSize:11,fontWeight:700},children:y}),t.jsx("span",{style:{color:"#64748b",fontSize:12},children:s?"â²":"â¼"})]}),s&&t.jsxs("div",{style:{padding:"0 14px 12px"},children:[l?t.jsx("div",{style:{color:"#64748b",fontSize:12,padding:"8px 0"},children:"Loadingâ¦"}):o.length===0?t.jsx("div",{style:{color:"#64748b",fontSize:12,padding:"8px 0"},children:"No open follow-ups."}):t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8,marginBottom:10},children:o.map(m=>{const b=RH(m.due_date),A=b<0,v=b===0,x=A?"#f87171":v?"#fbbf24":b<=3?"#fb923c":"#94a3b8",_=A?`${Math.abs(b)}d overdue`:v?"Due today":b===1?"Tomorrow":`In ${b}d`;return t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:10,padding:"8px 12px"},children:[t.jsx("button",{onClick:()=>u(m.id),title:"Mark complete",style:{width:18,height:18,borderRadius:4,flexShrink:0,border:"2px solid #475569",background:"transparent",cursor:"pointer"},onMouseEnter:j=>{j.currentTarget.style.borderColor="#4ade80",j.currentTarget.style.background="rgba(74,222,128,0.15)"},onMouseLeave:j=>{j.currentTarget.style.borderColor="#475569",j.currentTarget.style.background="transparent"}}),t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexWrap:"wrap"},children:[t.jsxs("span",{style:{fontSize:13,color:"#e2e8f0",fontWeight:600},children:[Xl[m.task_type]||"ð"," ",m.title]}),t.jsx("span",{style:{fontSize:10,fontWeight:700,color:"#60a5fa",background:"rgba(96,165,250,0.15)",padding:"2px 6px",borderRadius:6},children:Vi[m.task_type]||"Task"})]}),m.notes&&t.jsx("div",{style:{fontSize:11,color:"#64748b",marginTop:2},children:m.notes})]}),t.jsxs("div",{style:{textAlign:"right",flexShrink:0},children:[t.jsx("div",{style:{fontSize:11,fontWeight:600,color:x},children:_}
739),t.jsx("div",{style:{fontSize:10,color:"#475569",marginTop:1},children:EH(m.due_date)})]})]},m.id)})}),t.jsx("button",{onClick:()=>f(!0),style:{padding:"6px 14px",borderRadius:8,fontSize:12,fontWeight:700,background:"rgba(13,126,163,0.1)",color:"#22d3ee",border:"1px solid rgba(13,126,163,0.25)",cursor:"pointer"},children:"+ Add Follow-Up"})]}),c&&t.jsx(t0,{onClose:()=>f(!1),onCreate:h,userId:r})]})}const qH=9*60,DH=17*60,OH=30;function us(e){const n=Math.floor(e/60),r=String(e%60).padStart(2,"0");return n===0?`12:${r} AM`:n<12?`${n}:${r} AM`:n===12?`12:${r} PM`:`${n-12}:${r} PM`}function Cm(e){return Number(e.visit_hour)*60+Number(e.visit_minute||0)}function IH(e){const n=new Date,r=new Date(n);r.setDate(n.getDate()+e*7-n.getDay()+1);const s=[];for(let i=0;i<7;i++){const o=new Date(r);o.setDate(r.getDate()+i),s.push(o)}return s}function zp(e){return e.toISOString().split("T")[0]}function LH(e){return e.toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric"})}function aj(e){return e.getDay()===0||e.getDay()===6}function Tm(e,n){const r=new Date,s=new Date(e);return s.setHours(Math.floor(n/60),n%60,0,0),s<r}function WH({leadId:e,leadName:n,leadPhone:r,leadAddress:s,preferredSlotAt:i,onScheduled:o,onCancel:a}){var re;const{user:l,profile:d}=Ee(),[c,f]=g.useState([]),[p,u]=g.useState([]),[h,y]=g.useState(0),[m,b]=g.useState(null),[A,v]=g.useState(null),[x,_]=g.useState(null),[j,C]=g.useState(""),[S,T]=g.useState(!1),[L,E]=g.useState(!0),[R,N]=g.useState(null),[O,z]=g.useState(null),P=g.useMemo(()=>IH(h),[h]),D=zp(P[0]),M=zp(P[6]);g.useEffect(()=>{async function Q(){try{const ne=(await T0()||[]).filter(ge=>ge.role==="salesrep");f(ne),ne.length>0&&z(ne[0].id)}catch(oe){console.error("Failed to load reps:",oe)}}Q()},[]),g.useEffect(()=>{async function Q(){E(!0);const{data:oe}=await w.from("site_visits").select("id, lead_id, assigned_rep_id, visit_date, visit_hour, visit_minute, status, customer_name_snapshot, address_snapshot").gte("visit_date",D).lte("visit_date",M).neq("status","cancelled");oe&&u(oe),E(!1)}Q()},[D,M]);const[k,q]=g.useState(60),[$,I]=g.useState(qH),[B,J]=g.useState(DH);g.useEffect(()=>{async function Q(){const oe=d==null?void 0:d.tenant_id;if(!oe)return;const{data:ne,error:ge}=await w.from("tenants").select("visit_duration_minutes, visit_day_start_minutes, visit_day_end_minutes").eq("id",oe).maybeSingle();if(ge){console.error("[SiteVisitScheduler] tenant visit config read FAILED:",ge.message);return}if(!ne)return;ne.visit_duration_minutes&&q(Number(ne.visit_duration_minutes));const be=Number(ne.visit_day_start_minutes),we=Number(ne.visit_day_end_minutes);Number.isFinite(be)&&Number.isFinite(we)&&be>
739=0&&we<=24*60&&be<we?(I(be),J(we)):console.error("[SiteVisitScheduler] tenant day bounds rejected, using defaults:",be,we)}Q()},[d==null?void 0:d.tenant_id]);const ae=g.useMemo(()=>{const Q=[];for(let oe=$;oe+k<=B;oe+=OH)Q.push(oe);return Q},[k,$,B]),te=g.useMemo(()=>{const Q={};for(const oe of p){const ne=Cm(oe);for(const ge of ae)if(ge<ne+k&&ne<ge+k){const be=`${oe.assigned_rep_id}-${oe.visit_date}-${ge}`;(ge===ne||!Q[be])&&(Q[be]=oe)}}return Q},[p,k,ae]);function U(Q,oe,ne){return te[`${Q}-${oe}-${ne}`]||null}g.useEffect(()=>{if(!i||!O||A||x!==null)return;const Q=new Date(i);if(isNaN(Q.getTime()))return;const oe=new Intl.DateTimeFormat("en-US",{timeZone:"America/Indiana/Indianapolis",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1}).formatToParts(Q),ne=Y=>{var X;return((X=oe.find(H=>H.type===Y))==null?void 0:X.value)||""},ge=ne("year"),be=ne("month"),we=ne("day");let F=parseInt(ne("hour"),10);F===24&&(F=0);const K=parseInt(ne("minute"),10)||0,Z=F*60+K,ie=`${ge}-${be}-${we}`;ie<D||ie>M||ae.includes(Z)&&(Tm(Q,Z)||U(O,ie,Z)||(b(O),v(ie),_(Z)))},[i,O,D,M,te,ae]);function W(Q,oe,ne){if(U(Q,oe,ne))return;const ge=new Date(oe+"T12:00:00");Tm(ge,ne)||(b(Q),v(oe),_(ne))}async function G(){var ne;if(!m||!A||x===null||!l)return;T(!0);const Q=Math.floor(x/60),oe=x%60;try{const{data:ge,error:be}=await w.from("site_visits").select("id, visit_date, visit_hour, visit_minute").eq("lead_id",e).eq("status","scheduled");if(be)throw new Error("Could not check existing visits: "+be.message);const we=ge||[];if(we.length>0){const ie=`${A} ${us(x)}`,{error:Y}=await w.from("site_visits").update({status:"cancelled",notes:`Rescheduled to ${ie} by ${(d==null?void 0:d.full_name)||"staff"} on ${new Date().toLocaleDateString()}.`}).in("id",we.map(X=>X.id));if(Y)throw new Error("Could not retire the previous visit: "+Y.message)}const{error:F}=await w.from("site_visits").insert({lead_id:e,assigned_rep_id:m,visit_date:A,visit_hour:Q,visit_minute:oe,status:"scheduled",notes:j||null,address_snapshot:s||null,customer_name_snapshot:n,phone_snapshot:r||null,created_by:l.id});if(F)throw F;if(we.length>0){const ie=we[0];Tt({entity_type:"lead",entity_id:e,event_type:"site_visit_rescheduled",description:`Site visit moved from ${ie.visit_date} ${us(Cm(ie))} to ${A} ${us(x)}`,actor_id:l.id,actor_name:(d==null?void 0:d.full_name)??null}).catch(()=>{})}if(r){const ie=new Date(A+"T12:00:00").toLocaleDateString("en-US",{weekday:"long",month:"long",day:"numeric"});w.auth.getSession().then(({data:{session:Y}})=>{Y!=null&&Y.access_token&&fetch("/api/automations/trigger",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${(Y==null?void 0:Y.access_token)||""}`},body:JSON.stringify({key:"consult_booking_sms",to:r,entity_type:"lead",entity_id:e,tenant_id:(d==null?void 0:d.tenant_id)||null,variables:{first_name:n.split(" ")[0],name:n.split(" ")[0],date:ie,time:us(x)}})})}).catch(()=>{})}const K=c.find(ie=>ie.id===m);if(K!=null&&K.phone){const ie=new Date(A+"T12:00:00").toLocaleDateString("en-US",{weekday:"long",month:"long",day:"numeric"});w.auth.getSession().then(({data:{session:Y}})=>{Y!=null&&Y.access_token&&fetch("/api/automations/trigger",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Y.access_token}`},body:JSON.stringify({key:"site_visit_assigned_sms",to:K.phone,entity_type:"lead",entity_id:e,tenant_id:(d==null?void 0:d.tenant_id)||null,variables:{customer_name:n,date:ie,time:us(x),address:s||""}})})}).catch(()=>{})}const Z=((ne=c.find(ie=>ie.id===m))==null?void 0:ne.full_name)||"Rep";o({rep_name:Z,date:A,hour:Q,minute:oe})}catch(ge){alert("Failed to schedule: "+ge.message)}finally{T(!1)}}const V=(re=c.find(Q=>Q.id===m))==null?void 0:re.full_name,ee=(Q,oe,ne)=>m===Q&&A===oe&&x===ne;return t.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4",style:{backgroundColor:"rgba(0,0,0,0.7)"},children:[t.jsxs("div",{className:"w-full max-w-5xl max-h-[90vh] rounded-2xl overflow-hidden flex flex-col",style:{backgroundColor:"#1e293b",border:"1px solid #334155"},children:[t.jsxs("div",{className:"flex items-center justify-between px-6 py-4 flex-shrink-0",style:{borderBottom:"1px solid #334155"},children:[t.jsxs("div",{children:[t.jsx("h2",{className:"text-lg font-bold text-white",children:"Schedule Site Visit"}),t.jsxs("p",{className:"text-sm text-slate-400 mt-0.5",children:[n," · ",s||"No address"]})]}),t.jsx("button",{onClick:a,className:"text-slate-400 hover:text-white text-xl leading-none",children:"â"})]}),t.jsxs("div",{className:"flex items-center justify-between px-6 py-3 flex-shrink-0",style:{borderBottom:"1px solid #334155"},children:[t.jsx("button",{onClick:()=>y(Q=>Q-1),className:"px-3 py-1.5 text-sm font-medium rounded-lg text-slate-300 hover:text-white",style:{backgroundColor:"#334155"},children:"â Prev Week"}),t.jsxs("div",{className:"text-sm font-semibold text-white",children:[P[0].toLocaleDateString("en-US",{month:"long",day:"numeric"})," â ",P[6].toLocaleDateString("en-US",{month:"long",day:"numeric",year:"numeric"})]}),t.jsx("button",{onClick:()=>y(Q=>Q+1),className:"px-3 py-1.5 text-sm font-medium rounded-lg text-slate-300 hover:text-white",style:{backgroundColor:"#334155"},children:"Next Week â"})]}),t.jsx("div",{className:"flex-1 overflow-auto px-6 py-4",children:L?t.jsx("div",{className:"text-center text-slate-400 py-12",children:"Loading c
739alendar..."}):c.length===0?t.jsxs("div",{className:"text-center py-12",children:[t.jsx("div",{className:"text-3xl mb-3",children:"ð¤"}),t.jsx("p",{className:"text-slate-400",children:"No sales reps found. Add reps in Team & Users first."})]}):t.jsxs("div",{children:[t.jsx("div",{className:"flex gap-2 mb-4",children:c.map(Q=>{const oe=O===Q.id;return t.jsxs("button",{onClick:()=>z(Q.id),className:"flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-colors",style:{backgroundColor:oe?"#1d4ed8":"#1e293b",color:oe?"#ffffff":"#94a3b8",border:oe?"2px solid #3b82f6":"1px solid #334155"},children:[t.jsx("div",{className:"w-6 h-6 rounded-full flex items-center justify-center text-xs font-bold text-white",style:{backgroundColor:oe?"#2563eb":"#475569"},children:Q.full_name.split(" ").map(ne=>ne[0]).join("").slice(0,2).toUpperCase()}),Q.full_name]},Q.id)})}),O&&t.jsx("div",{className:"grid grid-cols-7 gap-1.5",children:P.map(Q=>{const oe=zp(Q),ne=aj(Q),ge=zp(new Date)===oe;return t.jsxs("div",{className:"rounded-lg overflow-hidden",style:{backgroundColor:"#0f172a",border:ge?"2px solid #3b82f6":"1px solid #1e293b"},children:[t.jsxs("div",{className:"px-2 py-1.5 text-center",style:{backgroundColor:ne?"#451a03":"#1e293b",borderBottom:"1px solid #334155"},children:[t.jsx("div",{className:"text-xs font-semibold",style:{color:ge?"#60a5fa":ne?"#fbbf24":"#94a3b8"},children:LH(Q)}),ne&&t.jsx("div",{className:"text-xs mt-0.5",style:{color:"#f59e0b"},children:"â¡ Confirm w/ rep"})]}),t.jsx("div",{className:"p-1 space-y-0.5",children:ae.map(be=>{var Z;const we=U(O,oe,be),F=Tm(Q,be),K=ee(O,oe,be);return F?t.jsx("div",{className:"px-1.5 py-1 rounded text-center",style:{backgroundColor:"#1e293b"},children:t.jsx("div",{className:"text-xs",style:{color:"#475569"},children:us(be)})},be):we?t.jsx("div",{onMouseEnter:ie=>{const Y=ie.currentTarget.getBoundingClientRect();N({visit:we,x:Y.left+Y.width/2,y:Y.top})},onMouseLeave:()=>N(null),children:t.jsxs("div",{className:"px-1.5 py-1 rounded text-center cursor-default",style:{backgroundColor:"#7f1d1d",border:"1px solid #991b1b"},children:[t.jsx("div",{className:"text-xs font-medium",style:{color:"#fca5a5"},children:us(be)}),t.jsx("div",{className:"text-xs truncate",style:{color:"#f87171"},children:((Z=we.customer_name_snapshot)==null?void 0:Z.split(" ")[0])||"Booked"})]})},be):t.jsxs("button",{onClick:()=>W(O,oe,be),className:"w-full px-1.5 py-1 rounded text-center transition-all",style:{backgroundColor:K?"#166534":"#0f2a1a",border:K?"2px solid #22c55e":"1px solid #1a3a2a",cursor:"pointer"},children:[t.jsx("div",{className:"text-xs font-medium",style:{color:K?"#4ade80":"#86efac"},children:us(be)}),K&&t.jsx("div",{className:"text-xs",style:{color:"#4ade80"},children:"â Selected"})]},be)})})]},oe)})})]})}),t.jsxs("div",{className:"flex items-center justify-between px-6 py-4 flex-shrink-0",style:{backgroundColor:"#0f172a",borderTop:"1px solid #334155"},children:[t.jsx("div",{children:m&&A&&x!==null?t.jsxs("div",{className:"text-sm text-white",children:[t.jsx("span",{className:"font-bold",style:{color:"#4ade80"},children:"â Selected: "}),V," · ",new Date(A+"T12:00:00").toLocaleDateString("en-US",{weekday:"long",month:"long",day:"numeric"})," · ",us(x),aj(new Date(A+"T12:00:00"))&&t.jsx("span",{className:"ml-2 text-xs font-medium px-2 py-0.5 rounded",style:{backgroundColor:"#451a03",color:"#fbbf24"},children:"â¡ Weekend"})]}):t.jsx("div",{className:"text-sm text-slate-500",children:"Click an open (green) slot above to select a time"})}),t.jsxs("div",{className:"flex items-center gap-3",children:[m&&t.jsx("input",{type:"text",value:j,onChange:Q=>C(Q.target.value),placeholder:"Notes (optional)",className:"px-3 py-2 rounded-lg text-sm text-white w-48",style:{backgroundColor:"#1e293b",border:"1px solid #334155"}}),t.jsx("button",{onClick:a,className:"px-4 py-2 text-sm text-slate-400 hover:text-white",children:"Cancel"}),t.jsx("button",{onClick:G,disabled:!m||!A||x===null||S,className:"px-5 py-2 text-sm font-bold text-white rounded-lg disabled:opacity-30 transition-colors",style:{backgroundColor:m?"#16a34a":"#334155"},children:S?"Scheduling...":"Confirm Visit"})]})]})]}),R&&t.jsxs("div",{style:{position:"fixed",left:R.x,top:R.y-8,transform:"translate(-50%, -100%)",zIndex:9999,pointerEvents:"none",minWidth:200},children:[t.jsxs("div",{style:{background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:10,padding:"10px 14px",boxShadow:"0 8px 24px rgba(0,0,0,0.7)"},children:[t.jsx("div",{style:{fontSize:13,fontWeight:700,color:"#e2e8f0",marginBottom:4},children:R.visit.customer_name_snapshot||"Booked"}),R.visit.address_snapshot?t.jsxs("div",{style:{fontSize:12,color:"#64748b",lineHeight:1.4},children:["ð ",R.visit.address_snapshot]}):t.jsx("div",{style:{fontSize:12,color:"#334155",fontStyle:"italic"},children:"No address on file"}),t.jsx("div",{style:{fontSize:11,color:"#475569",marginTop:6,paddingTop:6,borderTop:"1px solid #1e3a4f"},children:us(Cm(R.visit))})]}),t.jsx("div",{style:{width:0,height:0,borderLeft:"6px solid transparent",borderRight:"6px solid transparent",borderTop:"6px solid #1e3a4f",margin:"0 auto"}})]})]})}function $H({lead:e,onLeadUpdated:n,onCompletionChange:r}){const{user:s}=Ee(),[i,o]=g.useState([]),[a,l]=g.useState({}),[d,c]=g.useState(null),[f,p]=g.useState({}),[u,h]=g.useState(!0),[y,m]=g.useState(!1),[b,A]=g.useState(null);g.useEffect(()=>{async function L(){h(!0);const{data:E}=await w.from("site_visit_questions").select("*").eq("is_active",!0).order("sort_order");E&&o(E);const{data:R,error:N}=await w.from("leads").select("site_visit_answers").eq("id",e.id).single();N?(console.warn("[#342] site_visit_answers fetch failed:",N.message),p({})):p((R==null?void 0:R.site_visit_answers)||{}),h(!1)}L()},[e.id]);const v=g.useCallback(async(L,E)=>{const R={...f,[L]:E};p(R),m(!0);const{data:N,error:O}=await w.from("leads").update({site_visit_answers:R}).eq("id",e.id).select("*").single();!O&&N&&n({...e,...N}),m(!1)},[f,e,n]),x=g.useCallback(async()=>{var L;try{const E=await U8("site_visit_photo",e.id),R={};for(const N of E){const O=(L=N.metadata)==null?void 0:L.question_id;O&&(R[O]=await Dy(N.bucket,N.storage_path))}l(R)}catch(E){console.warn("[#263] photo url resolve failed:",E.message)}},[e.id]);g.useEffect(()=>{x()},[x]);async function _(L,E){if(s){A(L);try{const R=E.name.split(".").pop()||"jpg",N=`site-visit-photos/${e.id}/${L}-${Date.now()}.${R}`,O=f[L];if(O&&!String(O).startsWith("data:")&&!String(O).startsWith("http"))try{await H8(String(O),"site-survey-photos")}catch(D){console.warn("[#263] prior photo delete failed:",D.message)}const z=await uH({bucket:"site-survey-photos",path:N,file:E,entityType:"site_visit_photo",entityId:e.id,fileType:"photo",metadata:{question_id:L,captured_context:"lead"},userId:s.id});await v(L,z.id);const P=await Dy("site-survey-photos",z.storage_path);l(D=>({...D,[L]:P}))}catch(R){console.error("Photo upload failed:",R),alert(`Photo upload failed: ${R.message}`)}finally{A(null)}}}const j=i.filter(L=>L.is_required),C=j.filter(L=>{const E=f[L.id];return E!=null&&E!==""}),S=C.length===j.length,T=i.filter(L=>{const E=f[L.id];return E!=null&&E!==""}).length;return g.useEffect(()=>{r==null||r(S&&i.length>0)},[S,i.length]),u?t.jsx("div",{className:"rounded-xl p-4",style:{backgroundColor:"rgba(168,85,247,0.1)",border:"1px solid rgba(168,85,247,0.2)"},children:t.jsx("div",{className:"text-xs animate-pulse",style:{color:"#c084fc"},children:"Loading site visit checklist..."})}):i.length===0?null:t.jsxs("div",{className:"rounded-xl p-4 space-y-3",style:{backgroundColor:"rgba(168,85,247,0.1)",border:"1px solid rgba(168,85,247,0.2)"},children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-xs font-bold uppercase tracking-wide",style:{color:"#c084fc"},children:"Site Visit Checklist"}),t.jsxs("div",{className:"text-xs mt-0.5",style:{color:"#94a3b8"},children:[T," of ",i.length," completed",!S&&t.jsxs("span",{style:{color:"#fbbf24"},className:"ml-1",children:["· ",j.length-C.length," required remaining"]})]})]}),y&&t.jsx("div",{className:"text-xs animate-pulse",style:{color:"#c084fc"},children:"Saving..."}),S&&!y&&t.jsx("div",{className:"text-xs font-bold flex items-center gap-1",style:{color:"#4ade80"},children:"â Ready to build quote"})]}),t.jsx("div",{className:"w-full h-1.5 rounded-full overflow-hidden",style:{backgroundColor:"rgba(100,116,139,0.3)"},children:t.jsx("div",{className:"h-full rounded-full transition-all duration-300",style:{width:`${C.length/Math.max(j.length,1)*100}
739%`,backgroundColor:S?"#4ade80":"#a855f7"}})}),t.jsx("div",{className:"space-y-3",children:i.map(L=>{const E=f[L.id],R=E!=null&&E!=="",N=L.field_type==="photo";return t.jsxs("div",{className:"flex items-start gap-2.5",children:[t.jsx("div",{className:"mt-1 w-4 h-4 rounded flex items-center justify-center flex-shrink-0 text-xs",style:{backgroundColor:R?"rgba(74,222,128,0.2)":"rgba(100,116,139,0.2)",border:R?"1px solid rgba(74,222,128,0.3)":L.is_required?"1px solid rgba(245,158,11,0.3)":"1px solid rgba(100,116,139,0.3)",color:R?"#4ade80":"transparent"},children:R?"â":""}),t.jsxs("div",{className:"flex-1 min-w-0",children:[t.jsxs("label",{className:"text-xs font-medium flex items-center gap-1",style:{color:"#cbd5e1"},children:[N&&"ð· ",L.question_text,L.is_required&&t.jsx("span",{style:{color:"#f87171"},children:"*"})]}),t.jsxs("div",{className:"mt-1",children:[N&&t.jsx("div",{children:R?t.jsxs("div",{className:"space-y-1",children:[t.jsx("img",{src:a[L.id]||(String(E).startsWith("data:")||String(E).startsWith("http")?E:""),alt:L.question_text,className:"w-full max-w-xs rounded-lg border cursor-pointer",style:{borderColor:"#334155",maxHeight:200,objectFit:"contain",backgroundColor:"rgba(15,23,42,0.6)"},onClick:()=>{const O=a[L.id];O&&c(O)}}),t.jsxs("div",{className:"flex gap-2",children:[t.jsx("span",{className:"text-xs",style:{color:"#4ade80"},children:"â Photo uploaded"}),t.jsxs("label",{className:"text-xs cursor-pointer",style:{color:"#60a5fa"},children:["Replace",t.jsx("input",{type:"file",accept:"image/*",capture:"environment",className:"hidden",onChange:O=>{var P;const z=(P=O.target.files)==null?void 0:P[0];z&&_(L.id,z)}})]})]})]}):t.jsxs("label",{className:"flex items-center justify-center gap-2 px-4 py-3 rounded-lg cursor-pointer transition-colors",style:{backgroundColor:b===L.id?"rgba(168,85,247,0.2)":"rgba(100,116,139,0.15)",border:"2px dashed rgba(100,116,139,0.3)"},children:[t.jsx("span",{className:"text-sm",children:b===L.id?"â³":"ð·"}),t.jsx("span",{className:"text-xs font-medium",style:{color:"#94a3b8"},children:b===L.id?"Uploading...":"Take Photo or Upload"}),t.jsx("input",{type:"file",accept:"image/*",capture:"environment",className:"hidden",disabled:b===L.id,onChange:O=>{var P;const z=(P=O.target.files)==null?void 0:P[0];z&&_(L.id,z)}})]})}),L.field_type==="dropdown"&&t.jsxs("select",{value:E||"",onChange:O=>v(L.id,O.target.value),className:"w-full rounded-lg px-2.5 py-1.5 text-sm focus:outline-none",style:{backgroundColor:"rgba(30,41,59,0.6)",border:"1px solid rgba(100,116,139,0.4)",color:"#e2e8f0"},children:[t.jsx("option",{value:"",children:"â Select â"}),(L.options||[]).map(O=>t.jsx("option",{value:O,children:O},O))]}),L.field_type==="yes_no"&&t.jsxs("div",{className:"flex gap-2",children:[t.jsx("button",{onClick:()=>v(L.id,"Yes"),className:"px-3 py-1 text-xs rounded-lg font-medium transition-colors",style:{backgroundColor:E==="Yes"?"rgba(74,222,128,0.2)":"rgba(30,41,59,0.4)",color:E==="Yes"?"#4ade80":"#94a3b8",border:E==="Yes"?"1px solid rgba(74,222,128,0.3)":"1px solid rgba(100,116,139,0.3)"},children:"Yes"}),t.jsx("button",{onClick:()=>v(L.id,"No"),className:"px-3 py-1 text-xs rounded-lg font-medium transition-colors",style:{backgroundColor:E==="No"?"rgba(239,68,68,0.2)":"rgba(30,41,59,0.4)",color:E==="No"?"#f87171":"#94a3b8",border:E==="No"?"1px solid rgba(239,68,68,0.3)":"1px solid rgba(100,116,139,0.3)"},children:"No"})]}),L.field_type==="number"&&t.jsx("input",{type:"number",min:"0",value:E||"",onChange:O=>v(L.id,O.target.value?parseInt(O.target.value):""),placeholder:"Enter number",className:"w-24 rounded-lg px-2.5 py-1.5 text-sm focus:outline-none",style:{backgroundColor:"rgba(30,41,59,0.6)",border:"1px solid rgba(100,116,139,0.4)",color:"#e2e8f0"}}),L.field_type==="text"&&t.jsx("input",{type:"text",value:E||"",onChange:O=>v(L.id,O.target.value),placeholder:"Type answer...",className:"w-full rounded-lg px-2.5 py-1.5 text-sm focus:outline-none",style:{backgroundColor:"rgba(30,41,59,0.6)",border:"1px solid rgba(100,116,139,0.4)",color:"#e2e8f0"}})]})]})]},L.id)})}),d&&t.jsx("div",{onClick:()=>c(null),style:{position:"fixed",inset:0,zIndex:9999,backgroundColor:"rgba(0,0,0,0.85)",display:"flex",alignItems:"center",justifyContent:"center",padding:24,cursor:"zoom-out"},children:t.jsx("img",{src:d,alt:"Site visit photo",style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain",borderRadius:8},onClick:L=>L.stopPropagation()})})]})}const MH=["new_lead","qualifying","qualified","site_visit_scheduled","proposal_in_progress"];function $0({leadId:e,stage:n,defaultExpanded:r=!1,title:s="Site Visit Photos"}){const[i,o]=g.useState(r),[a,l]=g.useState(!1),[d,c]=g.useState(!1),[f,p]=g.useState(null),[u,h]=g.useState([]),[y,m]=g.useState(null),[b,A]=g.useState(null),v=!!n&&MH.includes(n),x=g.useCallback(async()=>
739{if(e){c(!0),p(null);try{const C=await U8("site_visit_photo",e),{data:S}=await w.from("site_visit_questions").select("id, question_text, sort_order"),T=new Map;for(const R of S||[])T.set(R.id,{text:R.question_text,order:typeof R.sort_order=="number"?R.sort_order:9999});const L=(C||[]).map(R=>{var z;const N=((z=R.metadata)==null?void 0:z.question_id)??null,O=N?T.get(N):void 0;return{mediaId:R.id,bucket:R.bucket,storagePath:R.storage_path,questionId:N,caption:(O==null?void 0:O.text)||"Unlabelled photo",sortOrder:(O==null?void 0:O.order)??9999,createdAt:R.created_at??null,url:null}});L.sort((R,N)=>R.sortOrder!==N.sortOrder?R.sortOrder-N.sortOrder:(R.createdAt||"").localeCompare(N.createdAt||""));const E=await Promise.all(L.map(async R=>{try{return{...R,url:await Dy(R.bucket,R.storagePath)}}catch{return{...R,url:null}}}));h(E),l(!0)}catch(C){p((C==null?void 0:C.message)||"Could not load photos")}finally{c(!1)}}},[e]);g.useEffect(()=>{i&&!a&&!d&&x()},[i,a,d,x]);async function _(C){if(v&&window.confirm(`Delete "${C.caption}"? This cannot be undone.`)){A(C.mediaId);try{await H8(C.mediaId,C.bucket),h(S=>S.filter(T=>T.mediaId!==C.mediaId)),m(null)}catch(S){p((S==null?void 0:S.message)||"Could not delete photo")}finally{A(null)}}}const j=u.length;return t.jsxs("div",{style:{background:"#162232",border:"1px solid #1e3a4f",borderRadius:14,overflow:"hidden"},children:[t.jsxs("button",{onClick:()=>o(C=>!C),className:"w-full flex items-center gap-2 text-left",style:{padding:"10px 14px",borderBottom:i?"1px solid #1e3a4f":"none",background:"transparent",cursor:"pointer"},children:[t.jsx("span",{style:{fontSize:13},children:"ð·"}),t.jsx("span",{style:{color:"#94a3b8",fontWeight:700,fontSize:12,textTransform:"uppercase",letterSpacing:"0.06em"},children:s}),a&&t.jsx("span",{style:{color:j>0?"#4ade80":"#64748b",fontSize:11,fontWeight:600},children:j}),t.jsx("span",{style:{marginLeft:"auto",color:"#64748b",fontSize:11},children:i?"â¾":"â¸"})]}),i&&t.jsxs("div",{style:{padding:"12px 14px"},children:[d&&t.jsx("div",{style:{color:"#94a3b8",fontSize:12},children:"Loading photosâ¦"}),!d&&f&&t.jsxs("div",{style:{fontSize:12,color:"#f87171"},children:[f," ",t.jsx("button",{onClick:()=>{l(!1),x()},style:{color:"#60a5fa",background:"none",border:"none",cursor:"pointer",padding:0},children:"Try again"})]}),!d&&!f&&j===0&&t.jsx("div",{style:{color:"#64748b",fontSize:12},children:"No photos from the site visit. Photos taken on the Site Visit Checklist appear here."}),!d&&!f&&j>0&&t.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2.5",children:u.map(C=>t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{onClick:()=>C.url&&m(C),style:{borderRadius:10,border:"1px solid #334155",backgroundColor:"rgba(15,23,42,0.6)",height:120,display:"flex",alignItems:"center",justifyContent:"center",overflow:"hidden",cursor:C.url?"pointer":"default"},children:C.url?t.jsx("img",{src:C.url,alt:C.caption,style:{maxHeight:"100%",maxWidth:"100%",objectFit:"contain"}}):t.jsx("span",{style:{color:"#64748b",fontSize:11},children:"Unavailable"})}),t.jsx("div",{className:"mt-1 truncate",style:{color:"#cbd5e1",fontSize:11},title:C.caption,children:C.caption}),v&&t.jsx("button",{onClick:()=>_(C),disabled:b===C.mediaId,style:{color:"#f87171",fontSize:10,background:"none",border:"none",padding:0,cursor:"pointer"},children:b===C.mediaId?"Deletingâ¦":"Delete"})]},C.mediaId))})]}),y&&y.url&&t.jsxs("div",{onClick:()=>m(null),style:{position:"fixed",inset:0,zIndex:60,backgroundColor:"rgba(2,6,23,0.88)",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:24,cursor:"zoom-out"},children:[t.jsx("img",{src:y.url,alt:y.caption,onClick:C=>C.stopPropagation(),style:{maxWidth:"100%",maxHeight:"82vh",objectFit:"contain",borderRadius:10,cursor:"default"}}),t.jsx("div",{style:{color:"#cbd5e1",fontSize:13,marginTop:12,textAlign:"center"},children:y.caption})]})]})}function sg(e){const n=[];if(e.hardness_gpg!=null&&e.hardness_gpg>7){const r=e.hardness_gpg>15?"strongly_recommended":"recommended";n.push({product_category:"softener",reason:`Water hardness is ${e.hardness_gpg} gpg (threshold: 7 gpg). A water softener will prevent scale buildup and extend appliance life.`,reading_name:"hardness_gpg",reading_value:e.hardness_gpg,threshold:7,urgency:r})}if(e.tds_ppm!=null&&e.tds_ppm>300){const r=e.tds_ppm>500?"strongly_recommended":"recommended";n.push({product_category:"ro",reason:`Total dissolved solids is ${e.tds_ppm} ppm (threshold: 300 ppm). A reverse osmosis system will provide clean drinking water.`,reading_name:"tds_ppm",reading_value:e.tds_ppm,threshold:300,urgency:r})}if(e.iron_mgl!=null&&e.iron_mgl>.3){const r=e.iron_mgl>1?"strongly_recommended":"recommended";n.push({product_category:"iron_filter",reason:`Iron level is ${e.iron_mgl} ppm (threshold: 0.3 ppm). An iron filter will prevent staining and metallic taste.`,reading_name:"iron_mgl",reading_value:e.iron_mgl,threshold:.3,urgency:r})}if(e.ph!=null&&e.ph<6.5){const r=e.ph<5.5?"strongly_recommended":"recommended";n.push({product_category:"acid_neutralizer",reason:`pH is ${e.ph} (threshold: below 6.5). An acid neutralizer will protect plumbing from corrosion.`,reading_name:"ph",reading_value:e.ph,threshold:6.5,urgency:r})}if(e.chlorine_mgl!=null&&e.chlorine_mgl>1){const r=e.chlorine_mgl>3?"strongly_recommended":"recommended";n.push({product_category:"whole_home_filter",reason:`Chlorine level is ${e.chlorine_mgl} ppm (threshold: 1.0 ppm). A whole home carbon filter will remove chlorine taste and smell.`,reading_name:"chlorine_mgl",reading_value:e.chlorine_mgl,threshold:1,urgency:r})}return e.sulfur_present===!0&&n.push({product_category:"sulfur_treatment",reason:"Sulfur (hydrogen sulfide) detected. Treatment recommended to eliminate rotten egg smell.",reading_name:"sulfur_present",reading_value:1,threshold:0,urgency:"strongly_recommended"}),n}async function wi(e){try{const{data:n,error:r}=await w.from("water_tests").select("*").eq("lead_id",e).order("tested_at",{ascending:!1});if(r)throw r;return n||[]}catch(n){return console.error("fetchByLead error:",n),[]}}async function FH(e){return[]}async function Y8(e,n,r){try{const s=[];if(r){const{data:o,error:a}=await w.from("water_tests").select("*").eq("customer_id",r).order("tested_at",{ascending:!1});if(a)throw a;o&&s.push(...o)}if(e.length>0){const{data:o,error:a}=await w.from("water_tests").select("*").in("lead_id",e).order("tested_at",{ascending:!1});if(a)throw a;o&&s.push(...o)}const i=new Set;return s.filter(o=>i.has(o.id)?!1:(i.add(o.id),!0)).map(o=>({...o,hardness_gpg:o.hardness??null,tds_ppm:o.tds??null,iron_mgl:o.iron??null,chlorine_mgl:o.chlorine_mgl??null,sulfur_present:o.sulfur_present??null,test_type:o.test_type??"routine",recommendations:o.recommendations??[],raw_data:o.raw_data??{}}))}
739catch(s){return console.error("fetchByCustomer error:",s),[]}}async function X8(e){try{const n=sg({hardness_gpg:e.hardness_gpg,iron_mgl:e.iron_mgl,tds_ppm:e.tds_ppm,ph:e.ph,chlorine_mgl:e.chlorine_mgl,sulfur_present:e.sulfur_present}),{data:r,error:s}=await w.from("water_tests").insert({lead_id:e.lead_id||null,hardness_gpg:e.hardness_gpg??null,iron_mgl:e.iron_mgl??null,tds_ppm:e.tds_ppm??null,ph:e.ph??null,chlorine_mgl:e.chlorine_mgl??null,sulfur_present:e.sulfur_present??null,water_source:e.water_source||null,notes:e.notes||null,tested_by:e.tested_by||null,tested_at:new Date().toISOString(),test_type:e.test_type||"initial",location:e.location||null,raw_data:e.raw_data||{},recommendations:n}).select().single();if(s)throw s;return r}catch(n){return console.error("createWaterTest error:",n),null}}async function G8(e){try{const{data:n,error:r}=await w.from("water_tests").select("*").eq("id",e).maybeSingle();if(r)throw r;return n||null}catch(n){return console.error("fetchById error:",n),null}}async function J8(e,n){try{const r=await G8(e);if(!r)throw new Error("Water test not found");const s={hardness_gpg:n.hardness_gpg!==void 0?n.hardness_gpg:r.hardness_gpg,iron_mgl:n.iron_mgl!==void 0?n.iron_mgl:r.iron_mgl,tds_ppm:n.tds_ppm!==void 0?n.tds_ppm:r.tds_ppm,ph:n.ph!==void 0?n.ph:r.ph,chlorine_mgl:n.chlorine_mgl!==void 0?n.chlorine_mgl:r.chlorine_mgl,sulfur_present:n.sulfur_present!==void 0?n.sulfur_present:r.sulfur_present},o={recommendations:sg(s)};n.hardness_gpg!==void 0&&(o.hardness_gpg=n.hardness_gpg),n.iron_mgl!==void 0&&(o.iron_mgl=n.iron_mgl),n.tds_ppm!==void 0&&(o.tds_ppm=n.tds_ppm),n.ph!==void 0&&(o.ph=n.ph),n.chlorine_mgl!==void 0&&(o.chlorine_mgl=n.chlorine_mgl),n.sulfur_present!==void 0&&(o.sulfur_present=n.sulfur_present),n.water_source!==void 0&&(o.water_source=n.water_source),n.notes!==void 0&&(o.notes=n.notes),n.tested_by!==void 0&&(o.tested_by=n.tested_by),n.test_type!==void 0&&(o.test_type=n.test_type),n.location!==void 0&&(o.location=n.location),n.raw_data!==void 0&&(o.raw_data=n.raw_data),n.lead_id!==void 0&&(o.lead_id=n.lead_id);const{data:a,error:l}=await w.from("water_tests").update(o).eq("id",e).select().single();if(l)throw l;return a}catch(r){return console.error("updateWaterTest error:",r),null}}async function BH(e){try{const{error:n}=await w.from("water_tests").delete().eq("id",e);if(n)throw n;return!0}catch(n){return console.error("deleteWaterTest error:",n),!1}}function Q8(e){const n=e.filter(s=>s.test_type==="initial").sort((s,i)=>new Date(s.tested_at||"").getTime()-new Date(i.tested_at||"").getTime()),r=e.filter(s=>s.test_type==="post_install").sort((s,i)=>new Date(i.tested_at||"").getTime()-new Date(s.tested_at||"").getTime());return{before:n[0]||null,after:r[0]||null}}const M0={hardness_gpg:{label:"Hardness",unit:"gpg",good_direction:"lower"},iron_mgl:{label:"Iron",unit:"ppm",good_direction:"lower"},tds_ppm:{label:"TDS",unit:"ppm",good_direction:"lower"},ph:{label:"pH",unit:"",good_direction:"range"},chlorine_mgl:{label:"Chlorine",unit:"ppm",good_direction:"lower"}};function UH(e,n){if(n==null)return"â";if(e==="sulfur_present")return n?"Detected":"Not detected";if(typeof n=="number"){const r=M0[e];return r?`${n} ${r.unit}`.trim():String(n)}return String(n)}const e3=Object.freeze(Object.defineProperty({__proto__:null,READING_LABELS:M0,createWaterTest:X8,deleteWaterTest:BH,fetchByCustomer:Y8,fetchById:G8,fetchByJob:FH,fetchByLead:wi,formatReading:UH,generateRecommendations:sg,getBeforeAfterComparison:Q8,updateWaterTest:J8},Symbol.toStringTag,{value:"Module"})),HH=[{value:"municipal",label:"Municipal / City Water"},{value:"well",label:"Private Well"},{value:"community_well",label:"Community Well"},{value:"other",label:"Other"}],gi={width:"100%",boxSizing:"border-box",background:"rgba(255,255,255,0.05)",border:"1px solid #1e3a4f",borderRadius:10,padding:"9px 14px",color:"#e2e8f0",fontSize:13,outline:"none"},mi={display:"block",fontSize:11,color:"#64748b",marginBottom:6};function fh({leadId:e,testType:n="initial",existingTest:r,onSaved:s,onCancel:i}){var P,D,M,k,q;const{profile:o}=Ee(),[a,l]=g.useState(((P=r==null?void 0:r.hardness_gpg)==null?void 0:P.toString())||""),[d,c]=g.useState(((D=r==null?void 0:r.iron_mgl)==null?void 0:D.toString())||""),[f,p]=g.useState(((M=r==null?void 0:r.tds_ppm)==null?void 0:M.toString())||""),[u,h]=g.useState(((k=r==null?void 0:r.ph)==null?void 0:k.toString())||""),[y,m]=g.useState(((q=r==null?void 0:r.chlorine_mgl)==null?void 0:q.toString())||""),[b,A]=g.useState((r==null?void 0:r.sulfur_present)??!1),[v,x]=g.useState((r==null?void 0:r.water_source)||""),[_,j]=g.useState((r==null?void 0:r.location)||""),[C,S]=g.useState((r==null?void 0:r.notes)||""),[T,L]=g.useState(!1),[E,R]=g.useState(""),N=sg({hardness_gpg:a?parseFloat(a):null,iron_mgl:d?parseFloat(d):null,tds_ppm:f?parseInt(f):null,ph:u?parseFloat(u):null,chlorine_mgl:y?parseFloat(y):null,sulfur_present:b});async function O(){L(!0),R("");const $={lead_id:e||null,hardness_gpg:a?parseFloat(a):null,iron_mgl:d?parseFloat(d):null,tds_ppm:f?parseInt(f):null,ph:u?parseFloat(u):null,chlorine_mgl:y?parseFloat(y):null,sulfur_present:b,water_source:v||null,location:_||null,notes:C||null,tested_by:(o==null?void 0:o.id)||null,test_type:n};try{let I;r?I=await J8(r.id,$):I=await X8($),I?s==null||s(I):R("Failed to save water test")}catch(I){R(I.message||"Failed to save")}L(!1)}const z=n==="initial"?"Initial Water Test":n==="post_install"?"Post-Install Water Test":"Routine Water Test";return t.jsxs("div",{style:{background:"#162232",border:"1px solid #1e3a4f",borderRadius:14,overflow:"hidden"},children:[t.jsxs("div",{style:{padding:"14px 20px",borderBottom:"1px solid #1e3a4f",background:"rgba(34,211,238,0.04)",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[t.jsxs("div",{children:[t.jsxs("div",{style:{color:"#e2e8f0",fontWeight:700,fontSize:14},children:["ð§ ",r?"Edit":"New"," ",z]}),t.jsx("div",{style:{color:"#64748b",fontSize:11,marginTop:3},children:"Enter readings from water test kit"})]}),t.jsx("span",{style:{fontSize:10,padding:"3px 10px",borderRadius:20,background:n==="initial"?"rgba(96,165,250,0.12)":n==="post_install"?"rgba(74,222,128,0.12)":"rgba(245,158,11,0.12)",color:n==="initial"?"#60a5fa":n==="post_install"?"#4ade80":"#f59e0b",border:"1px solid transparent",fontWeight:700},children:n==="initial"?"INITIAL":n==="post_install"?"POST-INSTALL":"ROUTINE"})]}),t.jsxs("div",{style:{padding:20},children:[E&&t.jsx("div",{style:{background:"rgba(248,113,113,0.08)",border:"1px solid rgba(248,113,113,0.3)",borderRadius:10,padding:"8px 14px",marginBottom:14,fontSize:12,color:"#f87171"},children:E}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12,marginBottom:16},children:[t.jsxs("div",{children:[t.jsx("label",{style:mi,children:"Water Source"}
739),t.jsxs("select",{value:v,onChange:$=>x($.target.value),style:gi,children:[t.jsx("option",{value:"",style:{background:"#0f1923"},children:"Select..."}),HH.map($=>t.jsx("option",{value:$.value,style:{background:"#0f1923"},children:$.label},$.value))]})]}),t.jsxs("div",{children:[t.jsx("label",{style:mi,children:"Test Location"}),t.jsx("input",{type:"text",value:_,onChange:$=>j($.target.value),placeholder:"e.g., Kitchen sink, Hose bib",style:gi})]})]}),t.jsx("div",{style:{fontSize:10,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.06em",color:"#64748b",marginBottom:10},children:"Water Readings"}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(3, 1fr)",gap:12,marginBottom:16},children:[t.jsxs("div",{children:[t.jsxs("label",{style:mi,children:["Hardness ",t.jsx("span",{style:{color:"#334155"},children:"(gpg)"})]}),t.jsx("input",{type:"number",step:"0.1",min:"0",value:a,onChange:$=>l($.target.value),placeholder:"0.0",style:gi})]}),t.jsxs("div",{children:[t.jsxs("label",{style:mi,children:["Iron ",t.jsx("span",{style:{color:"#334155"},children:"(ppm)"})]}),t.jsx("input",{type:"number",step:"0.01",min:"0",value:d,onChange:$=>c($.target.value),placeholder:"0.00",style:gi})]}),t.jsxs("div",{children:[t.jsxs("label",{style:mi,children:["TDS ",t.jsx("span",{style:{color:"#334155"},children:"(ppm)"})]}),t.jsx("input",{type:"number",step:"1",min:"0",value:f,onChange:$=>p($.target.value),placeholder:"0",style:gi})]}),t.jsxs("div",{children:[t.jsxs("label",{style:mi,children:["pH ",t.jsx("span",{style:{color:"#334155"},children:"(0-14)"})]}),t.jsx("input",{type:"number",step:"0.1",min:"0",max:"14",value:u,onChange:$=>h($.target.value),placeholder:"7.0",style:gi})]}),t.jsxs("div",{children:[t.jsxs("label",{style:mi,children:["Chlorine ",t.jsx("span",{style:{color:"#334155"},children:"(ppm)"})]}),t.jsx("input",{type:"number",step:"0.1",min:"0",value:y,onChange:$=>m($.target.value),placeholder:"0.0",style:gi})]}),t.jsx("div",{style:{display:"flex",alignItems:"flex-end",paddingBottom:4},children:t.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer"},children:[t.jsx("input",{type:"checkbox",checked:b,onChange:$=>A($.target.checked),style:{width:16,height:16,accentColor:"#f59e0b"}}),t.jsx("span",{style:{fontSize:13,color:"#e2e8f0"},children:"Sulfur Present"})]})})]}),t.jsxs("div",{style:{marginBottom:16},children:[t.jsx("label",{style:mi,children:"Notes"}),t.jsx("textarea",{value:C,onChange:$=>S($.target.value),rows:2,placeholder:"Additional observations...",style:{...gi,resize:"none",fontFamily:"inherit"}})]}),N.length>0&&t.jsxs("div",{style:{background:"rgba(34,211,238,0.04)",border:"1px solid rgba(34,211,238,0.15)",borderRadius:10,padding:14,marginBottom:16},children:[t.jsxs("div",{style:{fontSize:10,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.06em",color:"#22d3ee",marginBottom:10},children:["ð¡ Recommendations (",N.length,")"]}),N.map(($,I)=>t.jsx(VH,{rec:$},I))]}),t.jsxs("div",{style:{display:"flex",gap:8},children:[i&&t.jsx("button",{onClick:i,style:{padding:"8px 16px",borderRadius:10,fontSize:13,color:"#64748b",cursor:"pointer",background:"rgba(255,255,255,0.04)",border:"1px solid #1e3a4f"},children:"Cancel"}),t.jsx("button",{onClick:O,disabled:T,style:{padding:"8px 20px",borderRadius:10,fontSize:13,fontWeight:700,color:"#fff",background:"linear-gradient(135deg, #22d3ee, #0891b2)",border:"none",cursor:T?"not-allowed":"pointer",opacity:T?.5:1},children:T?"Saving...":r?"Update Test":"Save Test"})]})]})]})}function VH({rec:e}){const n={recommended:{bg:"rgba(96,165,250,0.08)",text:"#60a5fa",border:"rgba(96,165,250,0.2)"},strongly_recommended:{bg:"rgba(245,158,11,0.08)",text:"#f59e0b",border:"rgba(245,158,11,0.2)"},urgent:{bg:"rgba(248,113,113,0.08)",text:"#f87171",border:"rgba(248,113,113,0.2)"}},r=n[e.urgency]||n.recommended,s={softener:"ð§ Water Softener",ro:"ð§ Reverse Osmosis",iron_filter:"ð© Iron Filter",acid_neutralizer:"âï¸ Acid Neutralizer",whole_home_filter:"ð Whole Home Filter",sulfur_treatment:"ð¨ Sulfur Treatment"};return t.jsx("div",{style:{display:"flex",alignItems:"flex-start",ga
739p:10,marginBottom:8,padding:"8px 10px",borderRadius:8,background:r.bg,border:`1px solid ${r.border}`},children:t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:3},children:[t.jsx("span",{style:{fontSize:12,fontWeight:700,color:r.text},children:s[e.product_category]||e.product_category}),t.jsx("span",{style:{fontSize:9,padding:"1px 6px",borderRadius:10,background:r.bg,color:r.text,border:`1px solid ${r.border}`,fontWeight:700,textTransform:"uppercase"},children:e.urgency.replace("_"," ")})]}),t.jsx("div",{style:{fontSize:11,color:"#94a3b8",lineHeight:1.4},children:e.reason})]})})}function ZH({test:e,onEdit:n,onDelete:r}){const s=Array.isArray(e.recommendations)?e.recommendations:[],i={initial:{bg:"rgba(96,165,250,0.12)",text:"#60a5fa",label:"Initial"},post_install:{bg:"rgba(74,222,128,0.12)",text:"#4ade80",label:"Post-Install"},routine:{bg:"rgba(245,158,11,0.12)",text:"#f59e0b",label:"Routine"}},o=i[e.test_type]||i.initial;return t.jsxs("div",{style:{background:"#162232",border:"1px solid #1e3a4f",borderRadius:14,overflow:"hidden"},children:[t.jsxs("div",{style:{padding:"12px 16px",borderBottom:"1px solid #1e3a4f",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[t.jsx("span",{style:{fontSize:16},children:"ð§"}),t.jsxs("div",{children:[t.jsxs("div",{style:{color:"#e2e8f0",fontWeight:600,fontSize:13},children:["Water Test",e.tested_at&&t.jsx("span",{style:{color:"#64748b",fontWeight:400,marginLeft:8},children:new Date(e.tested_at).toLocaleDateString()})]}),e.water_source&&t.jsxs("div",{style:{fontSize:11,color:"#64748b",marginTop:2},children:["Source: ",e.water_source,e.location?` · ${e.location}`:""]})]})]}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[t.jsx("span",{style:{fontSize:10,padding:"2px 10px",borderRadius:20,fontWeight:700,background:o.bg,color:o.text},children:o.label}),n&&t.jsx("button",{onClick:()=>n(e),style:{fontSize:11,color:"#60a5fa",background:"none",border:"none",cursor:"pointer"},children:"Edit"}),r&&t.jsx("button",{onClick:()=>r(e),style:{fontSize:11,color:"#f87171",background:"none",border:"none",cursor:"pointer"},children:"Delete"})]})]}),t.jsxs("div",{style:{padding:"12px 16px"},children:[t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(3, 1fr)",gap:8,marginBottom:8},children:[t.jsx(Hd,{label:"Hardness",value:e.hardness_gpg,unit:"gpg",threshold:7,direction:"above"}),t.jsx(Hd,{label:"Iron",value:e.iron_mgl,unit:"ppm",threshold:.3,direction:"above"}),t.jsx(Hd,{label:"TDS",value:e.tds_ppm,unit:"ppm",threshold:300,direction:"above"}),t.jsx(Hd,{label:"pH",value:e.ph,unit:"",threshold:6.5,direction:"below"}),t.jsx(Hd,{label:"Chlorine",value:e.chlorine_mgl,unit:"ppm",threshold:1,direction:"above"}),t.jsxs("div",{style:{padding:"8px 12px",borderRadius:10,background:e.sulfur_present?"rgba(245,158,11,0.08)":"rgba(255,255,255,0.03)",border:`1px solid ${e.sulfur_present?"rgba(245,158,11,0.2)":"#1e3a4f"}`},children:[t.jsx("div",{style:{fontSize:10,color:"#64748b",marginBottom:2},children:"Sulfur"}),t.jsx("div",{style:{fontSize:13,fontWeight:600,color:e.sulfur_present?"#f59e0b":"#4ade80"},children:e.sulfur_present===null?"â":e.sulfur_present?"Detected":"Clear"})]})]}),e.notes&&t.jsx("div",{style:{padding:"8px 12px",borderRadius:8,marginTop:8,background:"rgba(255,255,255,0.02)",border:"1px solid rgba(255,255,255,0.04)",fontSize:12,color:"#94a3b8",fontStyle:"italic"},children:e.notes}),s.length>0&&t.jsxs("div",{style:{marginTop:12},children:[t.jsxs("div",{style:{fontSize:10,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.06em",color:"#22d3ee",marginBottom:8},children:["Recommendations (",s.length,")"]}),t.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:s.map((a,l)=>{const d={recommended:"#60a5fa",strongly_recommended:"#f59e0b",urgent:"#f87171"};return t.jsx("span",{style:{fontSize:11,padding:"3px 10px",borderRadius:20,fontWeight:600,background:`${d[a.urgency]||"#60a5fa"}15`,color:d[a.urgency]||"#60a5fa",border:`1px solid ${d[a.urgency]||"#60a5fa"}30`},children:t3[a.product_category]||a.product_category},l)})})]})]})]})}function KH({tests:e}){const{before:n,after:r}=Q8(e);if(!n&&!r)return t.jsxs("div",{style:{background:"#162232",border:"1px solid #1e3a4f",borderRadius:14,padding:"32px 20px",textAlign:"center"},children:[t.jsx("div",{style:{fontSize:32,marginBottom:8,opacity:.4},children:"ð§"}),t.jsx("p",{style:{color:"#64748b",fontSize:13},children:"No water tests recorded yet."})]});const s=["hardness_gpg","iron_mgl","tds_ppm","ph","chlorine_mgl"];return t.jsxs("div",{style:{background:"#162232",border:"1px solid #1e3a4f",borderRadius:14,overflow:"hidden"},children:[t.jsxs("div",{style:{padding:"12px 16px",borderBottom:"1px solid #1e3a4f",dis
739play:"flex",alignItems:"center",gap:8},children:[t.jsx("span",{style:{fontSize:16},children:"ð"}),t.jsx("div",{style:{color:"#e2e8f0",fontWeight:700,fontSize:14},children:"Before & After Comparison"})]}),t.jsxs("table",{style:{width:"100%",borderCollapse:"collapse"},children:[t.jsx("thead",{children:t.jsxs("tr",{children:[t.jsx("th",{style:Np,children:"Reading"}),t.jsxs("th",{style:{...Np,textAlign:"center"},children:["Before",(n==null?void 0:n.tested_at)&&t.jsx("div",{style:{fontSize:9,fontWeight:400,color:"#475569",marginTop:2},children:new Date(n.tested_at).toLocaleDateString()})]}),t.jsxs("th",{style:{...Np,textAlign:"center"},children:["After",(r==null?void 0:r.tested_at)&&t.jsx("div",{style:{fontSize:9,fontWeight:400,color:"#475569",marginTop:2},children:new Date(r.tested_at).toLocaleDateString()})]}),t.jsx("th",{style:{...Np,textAlign:"center"},children:"Change"})]})}),t.jsxs("tbody",{children:[s.map(i=>{const o=M0[i],a=n?n[i]:null,l=r?r[i]:null;let d="â",c="#64748b";if(a!=null&&l!=null){const f=l-a,p=a!==0?Math.round(f/a*100):0;if(i==="ph"){const u=Math.abs(7-a),h=Math.abs(7-l);c=h<u?"#4ade80":h>u?"#f87171":"#64748b",d=f>0?`+${f.toFixed(1)}`:f.toFixed(1)}else c=f<0?"#4ade80":f>0?"#f87171":"#64748b",d=f>0?`+${p}%`:f<0?`${p}%`:"No change"}return t.jsxs("tr",{children:[t.jsxs("td",{style:xi,children:[t.jsx("span",{style:{fontWeight:600,color:"#e2e8f0"},children:o.label}),t.jsx("span",{style:{color:"#64748b",marginLeft:4,fontSize:11},children:o.unit})]}),t.jsx("td",{style:{...xi,textAlign:"center",fontFamily:"monospace"},children:a??"â"}),t.jsx("td",{style:{...xi,textAlign:"center",fontFamily:"monospace"},children:l??"â"}),t.jsx("td",{style:{...xi,textAlign:"center",fontWeight:600,color:c},children:d})]},i)}),t.jsxs("tr",{children:[t.jsx("td",{style:xi,children:t.jsx("span",{style:{fontWeight:600,color:"#e2e8f0"},children:"Sulfur"})}),t.jsx("td",{style:{...xi,textAlign:"center"},children:(n==null?void 0:n.sulfur_present)==null?"â":n.sulfur_present?"â ï¸ Yes":"â
No"}),t.jsx("td",{style:{...xi,textAlign:"center"},children:(r==null?void 0:r.sulfur_present)==null?"â":r.sulfur_present?"â ï¸ Yes":"â
No"}),t.jsx("td",{style:{...xi,textAlign:"center",fontWeight:600,color:n!=null&&n.sulfur_present&&!(r!=null&&r.sulfur_present)?"#4ade80":!(n!=null&&n.sulfur_present)&&(r!=null&&r.sulfur_present)?"#f87171":"#64748b"},children:(n==null?void 0:n.sulfur_present)==null||(r==null?void 0:r.sulfur_present)==null?"â":n.sulfur_present&&!r.sulfur_present?"Resolved":!n.sulfur_present&&r.sulfur_present?"New issue":"No change"})]})]})]})]})}function Oy({tests:e,onEdit:n,onDelete:r}){return e.length===0?t.jsxs("div",{style:{background:"#162232",border:"1px solid #1e3a4f",borderRadius:14,padding:"32px 20px",textAlign:"center"},children:[t.jsx("div",{style:{fontSize:32,marginBottom:8,opacity:.4},children:"ð§"}),t.jsx("p",{style:{color:"#64748b",fontSize:13},children:"No water tests recorded."})]}):t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:12},children:e.map(s=>t.jsx(ZH,{test:s,onEdit:n,onDelete:r},s.id))})}function lj({tests:e}){const r=e.filter(i=>i.test_type==="initial").sort((i,o)=>new Date(o.tested_at||"").getTime()-new Date(i.tested_at||"").getTime())[0];if(!r)return null;const s=Array.isArray(r.recommendations)?r.recommendations:[];return s.length===0?null:t.jsxs("div",{style:{background:"rgba(34,211,238,0.04)",border:"1px solid rgba(34,211,238,0.15)",borderRadius:14,padding:16},children:[t.jsx("div",{style:{fontSize:10,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.06em",color:"#22d3ee",marginBottom:10},children:"ð¡ Recommended Products (from water test)"}),s.map((i,o)=>{const l={recommended:"#60a5fa",strongly_recommended:"#f59e0b",urgent:"#f87171"}[i.urgency]||"#60a5fa";return t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"6px 0",borderBottom:o<s.length-1?"1px solid rgba(255,255,255,0.04)":"none"},children:[t.jsx("span",{style:{fontSize:11,fontWeight:700,color:l,minWidth:140},children:t3[i.product_category]||i.product_category}),t.jsx("span",{style:{fontSize:11,color:"#94a3b8",flex:1},children:i.reason})]},o)})]})}const t3={softener:"Water Softener",ro:"Reverse Osmosis",iron_filter:"Iron Filter",acid_neutralizer:"Acid Neutralizer",whole_home_filter:"Whole Home Filter",sulfur_treatment:"Sulfur Treatment"};function Hd({label:e,value:n,unit:r,threshold:s,direction:i}){const o=n!=null&&(i==="above"?n>s:n<s);return t.jsxs("div",{style:{padding:"8px 12px",borderRadius:10,background:o?"rgba(248,113,113,0.06)":"rgba(255,255,255,0.03)",border:`1px solid ${o?"rgba(248,113,113,0.15)":"#1e3a4f"}`}
739,children:[t.jsx("div",{style:{fontSize:10,color:"#64748b",marginBottom:2},children:e}),t.jsx("div",{style:{fontSize:14,fontWeight:700,fontFamily:"monospace",color:n==null?"#334155":o?"#f87171":"#4ade80"},children:n==null?"â":`${n} ${r}`.trim()}),n!=null&&t.jsx("div",{style:{fontSize:9,color:o?"#f87171":"#4ade80",marginTop:1},children:o?`Above ${s} ${r}`:"Normal"})]})}const Np={textAlign:"left",padding:"10px 16px",fontSize:10,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.06em",color:"#64748b",background:"rgba(255,255,255,0.03)",borderBottom:"1px solid #1e3a4f"},xi={padding:"10px 16px",borderBottom:"1px solid rgba(255,255,255,0.04)",fontSize:13,color:"#e2e8f0"};function dj(){const e=new Date,n=r=>String(r).padStart(2,"0");return e.getFullYear()+"-"+n(e.getMonth()+1)+"-"+n(e.getDate())+"T"+n(e.getHours())+":"+n(e.getMinutes())}function YH(e,n){const r=String(n||0).padStart(2,"0");return e===0?`12:${r} AM`:e<12?`${e}:${r} AM`:e===12?`12:${r} PM`:`${e-12}:${r} PM`}function cj(e){return new Intl.DateTimeFormat("en-US",{timeZone:"America/Indiana/Indianapolis",hour:"2-digit",minute:"2-digit",hour12:!1}).format(e)}function XH(e){return e.first_name?`${e.first_name} ${e.last_name||""}`.trim():e.full_name||""}function GH(e){if(e.first_name)return e.first_name;const n=e.full_name||"";return n.split(" ")[0]||n}function JH(e){const n=e.first_name||"",r=e.last_name||"";return n&&r?(n[0]+r[0]).toUpperCase():(e.full_name||"").split(" ").map(i=>i[0]).join("").slice(0,2).toUpperCase()}function QH(e){return e.zip||e.zip_code||""}function Rp(e){return new Date(e).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit"})}function eV(e){return e?Math.floor((Date.now()-new Date(e).getTime())/864e5):0}function tV({lead:e,onClose:n,onLeadUpdated:r,onLeadDeleted:s}){var Q0;const{role:i,user:o,profile:a}=Ee(),{can:l}=rs(),d=rt(),c=(a==null?void 0:a.tenant_id)??null,f=y8(),p=(a==null?void 0:a.role)==="admin"||(a==null?void 0:a.role)==="super_admin",u=i==="salesrep",[h,y]=g.useState(e),[m,b]=g.useState("overview"),[A,v]=g.useState(!1),[x,_]=g.useState(!1),[j,C]=g.useState("outbound"),[S,T]=g.useState(""),[L,E]=g.useState(dj()),[R,N]=g.useState(!1),[O,z]=g.useState("");async function P(){if(z(""),!S.trim()){z("Enter the message text.");return}N(!0);try{await m8({entityType:"lead",entityId:h.id,direction:j,body:S,occurredAt:new Date(L).toISOString(),actorId:(o==null?void 0:o.id)||null,actorName:(a==null?void 0:a.full_name)||null}),_(!1),T(""),E(dj()),C("outbound"),d.invalidateQueries({queryKey:["lead_activity_log",c,h.id]}),d.invalidateQueries({queryKey:it.activity(c,h.id)})}catch(he){z((he==null?void 0:he.message)||"Could not save. Try again.")}finally{N(!1)}}const[D,M]=g.useState("answered"),[k,q]=g.useState(""),[$,I]=g.useState(!1),[B,J]=g.useState(!1),[ae,te]=g.useState(""),[U,W]=g.useState(!1),[G,V]=g.useState(!1),[ee,re]=g.useState(""),[Q,oe]=g.useState([]),[ne,ge]=g.useState([]),[be,we]=g.useState(!1),[F,K]=g.useState(""),[Z,ie]=g.useState(""),[Y,X]=g.useState(!1),[H,de]=g.useState(""),[pe,Ne]=g.useState(!1),[Ie,Ze]=g.useState(null),[ht,ke]=g.useState(null),[Pe,nt]=g.useState(!1),[ue,fe]=g.useState(!1),[le,ce]=g.useState(!1),[xe,ve]=g.useState(null),[_e,je]=g.useState(!1),[Be,Je]=g.useState(!1),[bt,Vn]=g.useState(null),[fr,Ca]=g.useState(!1),[is,cg]=g.useState([]),[vd,Cu]=g.useState(!1),[K3,Tu]=g.useState(null),[Y3,ug]=g.useState(!1),[pg,Ta]=g.useState(!1),[X3,hg]=g.useState(!1);async function G3(he){if(o){Ta(!0);try{const{setSlotAvailability:Te}=await Fo(async()=>{const{setSlotAvailability:Nt}=await Promise.resolve().then(()=>kp);return{setSlotAvailability:Nt}},void 0),Oe=await Te(h.id,he,o.id);Sr(Oe)}catch(Te){alert("Could not update slot: "+((Te==null?void 0:Te.message)||Te))}finally{Ta(!1)}}}async function J3(he,Te){if(o!=null&&o.id){Ta(!0);try{const{bookCallSlot:Oe}=await Fo(async()=>{const{bookCallSlot:za}=await Promise.resolve().then(()=>kp);return{bookCallSlot:za}},void 0),Nt=await Oe(h.id,he,Te,o.id,{stage:h.stage,customer_id:h.customer_id??null,assigned_rep_id:h.assigned_rep_id??null,
739name:Rn});Sr(Nt)}catch(Oe){alert("Failed to book callback: "+((Oe==null?void 0:Oe.message)??Oe))}finally{Ta(!1),hg(!1)}}}async function Y0(he){if(o){Ta(!0);try{const{advanceBooking:Te}=await Fo(async()=>{const{advanceBooking:Nt}=await Promise.resolve().then(()=>kp);return{advanceBooking:Nt}},void 0),Oe=await Te(h.id,he,o.id);Sr(Oe)}catch(Te){alert("Could not advance booking: "+((Te==null?void 0:Te.message)||Te))}finally{Ta(!1)}}}const Rn=XH(h),_d=GH(h),zu=QH(h);g.useEffect(()=>{w.from("message_templates").select("*").eq("channel","sms").order("sort_order").order("key").then(({data:he})=>oe(he||[])),w.from("message_templates").select("*").eq("channel","email").order("sort_order").order("key").then(({data:he})=>ge(he||[]))},[]),g.useEffect(()=>{e.opened_at||Fo(async()=>{const{markLeadOpened:he}=await Promise.resolve().then(()=>kp);return{markLeadOpened:he}},void 0).then(({markLeadOpened:he})=>{he(e.id).then(()=>d.invalidateQueries({queryKey:it.kanban(c)})).catch(()=>{})})},[e.id]);const{mutateAsync:Q3}=PF(),{mutateAsync:e5,isPending:fg}=qF(),{data:t5,isLoading:n5}=DF(h.id),{data:En}=zF(h.id),{data:X0}=h8(),{data:zt}=TF(h.id);g.useEffect(()=>{h.stage==="quote_sent"&&w.from("quotes").select("public_token, quote_number, status").eq("lead_id",h.id).in("status",["sent","viewed","signed","accepted"]).order("created_at",{ascending:!1}).limit(1).maybeSingle().then(({data:he})=>{he!=null&&he.public_token&&ke(`${window.location.origin}/q/${he.public_token}`)})},[h.id,h.stage]),g.useEffect(()=>{["site_visit_scheduled","proposal_in_progress","quote_sent","agreement_signed"].includes(h.stage)&&w.from("site_visits").select("assigned_rep_id, visit_date, visit_hour, visit_minute, status, notes").eq("lead_id",h.id).eq("status","scheduled").order("created_at",{ascending:!1}).limit(1).maybeSingle().then(async({data:he})=>{if(he){const{data:Te}=await w.from("profiles").select("full_name").eq("id",he.assigned_rep_id).maybeSingle(),Oe=(Te==null?void 0:Te.full_name)||"Rep";ve({rep_name:Oe,date:he.visit_date,hour:he.visit_hour,minute:he.visit_minute||0});try{const{data:Nt}=await w.from("communications_log").select("id").eq("entity_type","lead").eq("entity_id",h.id).eq("direction","inbound").ilike("message","CONFIRM%").limit(1).maybeSingle();Je(!!Nt)}catch{}}})},[h.id,h.stage]);const G0=["site_visit_scheduled","proposal_in_progress","quote_sent","agreement_signed","won"];g.useEffect(()=>{if(G0.includes(h.stage)){if(!wi){ug(!0);return}wi(h.id).then(he=>{cg(he),ug(!0)}).catch(()=>{ug(!0)})}},[h.id,h.stage]);async function r5(he){if(ve(he),ce(!1),o)try{const Te={actor_id:o.id,actor_name:a==null?void 0:a.full_name},Oe=await xl(h.id,h.stage,"site_visit_scheduled",Te);Sr(Oe)}catch(Te){console.error("Stage move after visit schedule failed:",Te)}}const Sr=g.useCallback(he=>{y(he),r==null||r(he),d.invalidateQueries({queryKey:it.kanban(c)}),d.invalidateQueries({queryKey:it.counts(c)}),d.invalidateQueries({queryKey:it.activity(c,he.id)}),d.invalidateQueries({queryKey:["lead_activity_log",he.id]})},[r,d,c]);async function s5(he){if(o){Ca(!0);try{const{data:Te}=await w.from("site_visits").select("id").eq("lead_id",h.id).eq("status","scheduled").order("created_at",{ascending:!1}).limit(1).maybeSingle();Te!=null&&Te.id&&await w.from("site_visits").update({status:"cancelled",notes:he==="no_show"?`Marked NO-SHOW by rep on ${new Date().toLocaleDateString()}.`:`Cancelled by rep on ${new Date().toLocaleDateString()}.`}).eq("id",Te.id);const Oe={actor_id:o.id,actor_name:a==null?void 0:a.full_name};try{const Nt=await xl(h.id,h.stage,"qualified",Oe);Sr(Nt)}catch(Nt){console.error("Stage move on visit outcome failed:",Nt)}he==="no_show"&&w.from("follow_up_tasks").insert({lead_id:h.id,task_type:"call_back",title:`Site visit NO-SHOW: ${Rn}`,notes:"Customer no-show / no-answer at scheduled site visit. Follow up to reschedule.",description:"Customer no-show / no-answer at scheduled site visit. Follow up to reschedule.",due_date:new Date(Date.now()+2*60*60*1e3).toISOString().split("T")[0],due_time:cj(new Date(Date.now()+2*60*60*1e3)),status:"open",priority:"high",assigned_to:h.assigned_rep_id||null}).then(()=>{}).catch(()=>{}),ve(null),Je(!1),Vn(null)}catch(Te){alert("Failed to log visit outcome: "+Te.message)}finally{Ca(!1)}}}function i5(){ce(!0)}function o5(he){Cu(!1),Tu(null),wi&&wi(h.id).then(Te=>cg(Te))}function a5(he){Tu(he),Cu(!0)}async function l5(he){if(confirm("Delete this water test? This cannot be undone."))try{const{deleteWaterTest:Te}=await Fo(async()=>{const{deleteWaterTest:Oe}=await Promise.resolve().then(()=>e3);return{deleteWaterTest:Oe}},void 0);await Te(he.id),wi&&wi(h.id).then(Oe=>cg(Oe))}catch{}}async function d5(){if(!(!ae.trim()||!h.phone)){W(!0),re("");try{const he=await fetch("/api/openphone/send-sms",{method:"POST",headers:await At(),body:JSON.stringify({to:h.phone,body:ae.trim(),entity_type:"lead",entity_id:h.id,sent_by:(o==null?void 0:o.id)??null,tenant_id:c})});if(!he.ok){const Te=await he.json().catch(()=>({}));throw new Error(Te.error||`Send failed (${he.status})`)}J(!1),te("")}catch(he){re((he==null?void 0:he.message)||"Send failed")}finally{W(!1)}}}async function c5(){if(!(!F.trim()||!Z.trim()||!h.email)){X(!0),de("");try{const{data:{session:he}}=await w.auth.getSession();if(!(he!=null&&he.access_token))throw new Error("Session expired - please sign in again");const Te=await fetch("/api/email/send-booking",{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer "+he.access_token},body:JSON.stringify({to:h.email,subject:F.trim(),body:Z.trim(),entity_type:"lead",entity_id:h.id,tenant_id:c,sent_by:(o==null?void 0:o.id)??null})});if(!Te.ok){const Oe=await Te.json().catch(()=>({}));throw new Error(Oe.error||(Te.status===409?"Recipient is on Do Not Disturb":`Send failed (${Te.status})`))}Tt({entity_type:"lead",entity_id:h.id,event_type:"email_sent",description:`Email sent: ${F.trim()}`,actor_id:(o==null?void 0:o.id)??void 0,actor_name:(a==null?void 0:a.full_name)??null}).then(()=>{d.invalidateQueries({queryKey:["lead_activity_log",h.id]}),d.invalidateQueries({queryKey:it.activity(c,h.id)})}).catch(()=>{}),we(!1),K(""),ie("")}catch(he){de((he==null?void 0:he.message)||"Send failed")}finally{X(!1)}}}async function u5(){if(confirm(`Delete lead "${Rn}"? 740 741This will also delete linked quotes, agreements, and activity. Cannot be undone.`)){I(!0);try{const{data:he}=await w.from("quotes").select("id").eq("lead_id",h.id);if(he!=null&&he.length){const Oe=he.map(Nt=>Nt.id);await w.from("agreements").delete().in("quote_id",Oe),await w.from("quotes").delete().in("id",Oe)}await w.from("lead_activity_log").delete().eq("lead_id",h.id),await w.from("call_attempts").delete().eq("lead_id",h.id),await w.from("customers").update({lead_id:null}).eq("lead_id",h.id);const{error:Te}=await w.from("leads").delete().eq("id",h.id);if(Te)throw Te;d.invalidateQueries({queryKey:it.kanban(c)}),d.invalidateQueries({queryKey:it.counts(c)}),s==null||s(h.id),n()}catch(he){alert("Delete failed: "+(he.message||he)),I(!1)}}}async function p5(){var he,Te;if(o){nt(!0);try{const{data:Oe,error:Nt}=await w.from("customers").select("id").eq("lead_id",h.id).limit(2);if(Nt)throw Nt;if((Oe||[]).length>1){alert("This lead has more than one customer record. Those need to be resolved before a quote can be built.");return}let za=(he=Oe==null?void 0:Oe[0])==null?void 0:he.id;if(!za){const eA=(zt==null?void 0:zt.address_line1)??h.address??null,tA=(zt==null?void 0:zt.city)??h.city??null,
741nA=(zt==null?void 0:zt.state)??h.state??null,rA=(zt==null?void 0:zt.zip)??zu??null,{data:{user:gg}}=await w.auth.getUser(),x5=(Te=gg==null?void 0:gg.user_metadata)==null?void 0:Te.tenant_id,{data:y5,error:sA}=await w.from("customers").insert({tenant_id:x5,lead_id:h.id,first_name:h.first_name||Rn.split(" ")[0]||"",last_name:h.last_name||Rn.split(" ").slice(1).join(" ")||"",phone:h.phone,email:h.email||null,lifecycle_stage:"prospect"}).select("id").single();if(sA)throw sA;if(za=y5.id,eA||tA||nA||rA){const{error:iA}=await w.from("addresses").insert({entity_type:"customer",entity_id:za,is_primary:!0,label:"Primary",address_line1:eA,city:tA,state:nA,zip:rA});iA&&console.error("[C3 dual-write] addresses insert failed:",iA)}}Ze(za),Ne(!0)}catch(Oe){alert("Could not set up quote: "+Oe.message)}finally{nt(!1)}}}async function h5(he){if(he.public_token&&ke(`${window.location.origin}/q/${he.public_token}`),["sent","send","pending"].includes(he.status)&&h.stage!=="quote_sent"&&o)try{const Te={actor_id:o.id,actor_name:a==null?void 0:a.full_name},Oe=await xl(h.id,h.stage,"quote_sent",Te);Sr(Oe)}catch(Te){console.error("Stage move failed:",Te)}else if(["new_lead","qualifying","qualified","site_visit_scheduled"].includes(h.stage)&&o)try{const Te={actor_id:o.id,actor_name:a==null?void 0:a.full_name},Oe=await xl(h.id,h.stage,"proposal_in_progress",Te);Sr(Oe)}catch(Te){console.error("Stage move failed:",Te)}Ne(!1)}async function f5(){try{if(await e5({leadId:h.id,outcome:D,notes:k}),v(!1),q(""),zy(h.booking_stage)){const he=tu(h.booking_stage),Te=he?ef[he]:[],Oe=Te.indexOf(h.booking_stage);let Nt=null;D==="answered"||D==="callback_scheduled"?Nt="booked":D==="no_contact_requested"?Nt="dead":(D==="voicemail"||D==="no_answer"||D==="no_show")&&(Nt=Oe>=0&&Oe<Te.length-1?Te[Oe+1]:"dead"),Nt&&await Y0(Nt)}D==="no_show"&&w.from("follow_up_tasks").insert({lead_id:h.id,task_type:"call_back",title:`No-show follow-up: ${Rn}`,notes:"Customer did not show for scheduled consultation. Follow up to reschedule.",description:"Customer did not show for scheduled consultation. Follow up to reschedule.",due_date:new Date(Date.now()+2*60*60*1e3).toISOString().split("T")[0],due_time:cj(new Date(Date.now()+2*60*60*1e3)),status:"open",priority:"high",assigned_to:h.assigned_rep_id||null}).then(()=>{}).catch(()=>{})}catch(he){console.error(he)}}const g5=h.stage_entered_at||h.stage_changed_at,J0=eV(g5),jd=[(zt==null?void 0:zt.address_line1)??h.address,(zt==null?void 0:zt.city)??h.city,(zt==null?void 0:zt.state)??h.state,(zt==null?void 0:zt.zip)??zu].filter(
741Boolean).join(", "),m5=G0.includes(h.stage)&&!!wi;return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"fixed inset-0 z-40 flex justify-end",children:[t.jsx("div",{className:"absolute inset-0",style:{background:"rgba(0,0,0,0.4)"},onClick:n}),t.jsxs("div",{className:"relative w-full max-w-2xl h-full overflow-y-auto shadow-2xl flex flex-col",style:{background:"#162232",borderLeft:"1px solid #1e3a4f"},children:[t.jsxs("div",{className:"flex items-start justify-between p-5 flex-shrink-0",style:{borderBottom:"1px solid #1e3a4f"},children:[t.jsxs("div",{className:"flex items-start gap-3",children:[t.jsx("div",{className:"w-10 h-10 rounded-full font-bold flex items-center justify-center text-sm",style:{background:"rgba(13,126,163,0.2)",color:"#0d7ea3"},children:JH(h)}),t.jsxs("div",{children:[t.jsx("div",{className:"flex items-center gap-2",children:t.jsx("h2",{className:"text-lg font-bold text-white",children:Rn})}),t.jsx("div",{className:"text-sm",style:{color:"#64748b"},children:h.phone}),h.email&&t.jsx("div",{className:"text-xs",style:{color:"#64748b"},children:h.email})]})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("button",{onClick:()=>V(!0),title:"Edit contact details",style:{fontSize:11,padding:"2px 8px",borderRadius:6,border:"1px solid rgba(13,126,163,0.4)",background:"rgba(13,126,163,0.12)",color:"#0d7ea3",cursor:"pointer",flexShrink:0},children:"Edit"}),p&&t.jsx("button",{onClick:u5,disabled:$,title:"Delete lead",style:{fontSize:15,lineHeight:1,color:"rgba(239,68,68,0.5)",background:"transparent",border:"none",borderRadius:8,padding:"6px",cursor:"pointer"},children:$?"â¦":"ð"}),t.jsx("button",{onClick:n,style:{color:"#64748b",background:"none",border:"none",cursor:"pointer",fontSize:20,lineHeight:1},children:"â"})]})]}),t.jsxs("div",{className:"px-5 py-3 flex-shrink-0 space-y-2",style:{borderBottom:"1px solid #1e3a4f"},children:[t.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[t.jsx("div",{className:`stage-badge border ${HF[h.stage]}`,children:N0[h.stage]}),t.jsx("button",{onClick:()=>_(!0),style:{fontSize:12,padding:"4px 10px",borderRadius:8,cursor:"pointer",background:"rgba(96,165,250,0.1)",color:"#60a5fa",border:"1px solid rgba(96,165,250,0.3)"},children:"Log Text"}),t.jsx("button",{onClick:()=>v(!0),style:{fontSize:12,padding:"4px 10px",borderRadius:8,cursor:"pointer",background:"rgba(74,222,128,0.1)",color:"#4ade80",border:"1px solid rgba(74,222,128,0.3)"},children:"ð Log Call"}),h.phone&&t.jsx("button",{onClick:()=>{te(`Hi ${_d}, `),re(""),J(!0)},style:{fontSize:12,padding:"4px 10px",borderRadius:8,cursor:"pointer",background:"rgba(34,197,94,0.1)",color:"#22c55e",border:"1px solid rgba(34,197,94,0.3)"},children:"ð¬ Send Text"}),h.email&&t.jsx("button",{onClick:()=>{K(""),ie(""),de(""),we(!0)},style:{fontSize:12,padding:"4px 10px",borderRadius:8,cursor:"pointer",background:"rgba(13,126,163,0.12)",color:"#0d7ea3",border:"1px solid rgba(13,126,163,0.4)"},children:"âï¸ Send Email"})]}),t.jsx(OB,{lead:h,onLeadUpdated:Sr,onCreateQuote:p5,creatingQuote:Pe,qualifyingComplete:ue,onScheduleVisit:()=>ce(!0),siteVisitComplete:_e,callAttemptCount:(En==null?void 0:En.length)||0,hasNoContactRequest:(En==null?void 0:En.some(he=>he.outcome==="no_contact_requested"))??!1}),Pe&&t.jsx("div",{style:{fontSize:12,color:"#0d7ea3"},className:"animate-pulse",children:"Opening quote builderâ¦"})]}),t.jsx("div",{className:"flex flex-shrink-0",style:{borderBottom:"1px solid #1e3a4f"},children:["overview","activity","calls"].map(he=>t.jsxs("button",{onClick:()=>b(he),style:{flex:1,padding:"10px 0",fontSize:12,fontWeight:600,textTransform:"uppercase",letterSpacing:"0.05em",cursor:"pointer",background:"transparent",border:"none",color:m===he?"#0d7ea3":"#64748b",borderBottom:m===he?"2px solid #0d7ea3":"2px solid transparent"},children:[he,he==="calls"&&En&&En.length>0&&t.jsx("span",{style:{marginLeft:4,background:"rgba(100,116,139,0.3)",borderRadius:10,padding:"2px 6px",fontSize:11},children:En.length})]},he))}),t.jsxs("div",{className:"flex-1 overflow-y-auto p-5",children:[m==="overview"&&t.jsxs("div",{className:"space-y-4",children:[h.stage==="qualifying"&&t.jsx(ij,{lead:h,onLeadUpdated:Sr,onCompletionChange:fe}),t.jsx(PH,{leadId:h.id,leadName:Rn,userId:(o==null?void 0:o.id)||null}),t.jsx("button",{onClick:()=>hg(!0),disabled:pg,style:{width:"100%",fontSize:13,fontWeight:700,padding:"10px",borderRadius:10,marginBottom:4,color:"#4ade80",background:"rgba(34,197,94,0.1)",border:"1px solid rgba(34,197,94,0.35)",cursor:pg?"wait":"pointer"},children:"ð Book a callback"}),(h.preferred_slot_at||h.booking_stage)&&t.jsx(rV,{lead:h,busy:pg,onSetAvailability:G3,onAdvance:Y0}),X3&&t.jsx(gB,{leadName:Rn,currentSlotAt:h.preferred_slot_at??null,onPicked:J3,onCancel:()=>hg(!1)}),t.jsx(ru,{entityType:"lead",entityId:h.id,section:"qualifying",visibilityDefault:"all",visibilitySelectorMode:"collapsed",title:"Qualifying Notes"}),t.jsx(ru,{entityType:"lead",entityId:h.id,section:"plumbing",visibilityDefault:"all",visibilitySelectorMode:"collapsed",title:"Plumbing / Site Visit Notes"}),xe&&["site_visit_scheduled","proposal_in_progress","quote_sent","agreement_signed"].includes(h.stage)&&t.jsxs("div",{className:"rounded-xl p-4",style:{backgroundColor:"rgba(59,130,246,0.1)",border:"1px solid rgba(59,130,246,0.3)"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:8},children:[t.jsxs("div",{style:{fontSize:12,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.06em",color:"#60a5fa"},children:["ð
Site Visit ",h.stage==="site_visit_scheduled"?"Scheduled":"Completed"]}),Be?t.jsx("span",{style:{fontSize:11,fontWeight:800,padding:"3px 10px",borderRadius:20,background:"rgba(74,222,128,0.2)",color:"#4ade80",border:"1px solid rgba(74,222,128,0.4)",boxShadow:"0 0 8px rgba(74,222,128,0.2)"},children:"â Confirmed"}):t.jsx("span",{style:{fontSize:10,fontWeight:600,padding:"2px 8px",borderRadius:20,background:"rgba(100,116,139,0.15)",color:"#64748b",border:"1px solid rgba(100,116,139,0.2)"},children:"Awaiting"})]}),t.jsx("div",{className:"space-y-1",children:t.jsxs("div",{className:"text-sm text-white",children:[t.jsx("span",{className:"font-semibold",children:xe.rep_name})," · ",new Date(xe.date+"T12:00:00").toLocaleDateString("en-US",{weekday:"long",month:"long",day:"numeric"})," · ",YH(xe.hour,xe.minute)]})}),h.stage==="site_visit_scheduled"&&t.jsxs("div",{style:{marginTop:12,paddingTop:12,borderTop:"1px solid rgba(59,130,246,0.2)",display:"flex",gap:8,flexWrap:"wrap"},children:[t.jsx("button",{onClick:()=>Vn("no_show"),disabled:fr,style:{fontSize:12,padding:"6px 12px",borderRadius:8,cursor:"pointer",background:"rgba(239,68,68,0.1)",color:"#f87171",border:"1px solid rgba(239,68,68,0.3)",fontWeight:600},children:"ð« No-show"}),t.jsx("button",{onClick:i5,disabled:fr,style:{fontSize:12,padding:"6px 12px",borderRadius:8,cursor:"pointer",background:"rgba(251,191,36,0.1)",color:"#fbbf24",border:"1px solid rgba(251,191,36,0.3)",fontWeight:600},children:"ð
Reschedule"}),t.jsx("button",{onClick:()=>Vn("cancelled"),disabled:fr,style:{fontSize:12,padding:"6px 12px",borderRadius:8,cursor:"pointer",background:"rgba(100,116,139,0.1)",color:"#94a3b8",border:"1px solid rgba(100,116,139,0.3)",fontWeight:600},children:"â Cancelled"})]})]}),h.stage==="site_visit_scheduled"&&t.jsxs("div",{style:{background:"#162232",border:"1px solid #1e3a4f",borderRadius:14,overflow:"hidden"},children:[t.jsxs("div",{style:{padding:"10px 14px",borderBottom:"1px solid #1e3a4f",dis
741play:"flex",alignItems:"center",gap:8},children:[t.jsx("span",{style:{fontSize:13},children:"ð"}),t.jsx("span",{style:{color:"#94a3b8",fontWeight:700,fontSize:12,textTransform:"uppercase",letterSpacing:"0.06em"},children:"Qualifying Notes (from office)"})]}),t.jsx("div",{style:{padding:"10px 14px"},children:t.jsx(ij,{lead:h,onLeadUpdated:Sr,onCompletionChange:fe,readOnly:!0})})]}),h.stage==="site_visit_scheduled"&&t.jsx($H,{lead:h,onLeadUpdated:Sr,onCompletionChange:je}),t.jsx($0,{leadId:h.id,stage:h.stage}),m5&&Y3&&t.jsxs("div",{children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:10},children:[t.jsxs("div",{style:{fontSize:11,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.06em",color:"#22d3ee"},children:["ð§ Water Test",is.length>0&&t.jsxs("span",{style:{color:"#64748b",fontWeight:400,marginLeft:6},children:["(",is.length," recorded)"]})]}),!vd&&fh&&t.jsxs("button",{onClick:()=>{Tu(null),Cu(!0)},style:{padding:"4px 12px",borderRadius:8,fontSize:11,fontWeight:700,background:"rgba(34,211,238,0.1)",color:"#22d3ee",border:"1px solid rgba(34,211,238,0.25)",cursor:"pointer"},children:["+ ",is.length>0?"New Test":"Record Test"]})]}),vd&&fh&&t.jsx("div",{style:{marginBottom:12},children:t.jsx(fh,{leadId:h.id,testType:"initial",existingTest:K3,onSaved:o5,onCancel:()=>{Cu(!1),Tu(null)}})}),!vd&&is.length>0&&lj&&t.jsx("div",{style:{marginBottom:12},children:t.jsx(lj,{tests:is})}),!vd&&is.length>0&&Oy&&t.jsx(Oy,{tests:is,onEdit:a5,onDelete:l5}),!vd&&is.length===0&&t.jsxs("div",{style:{background:"#162232",border:"1px solid #1e3a4f",borderRadius:14,padding:"20px",textAlign:"center"},children:[t.jsx("div",{style:{fontSize:28,marginBottom:8,opacity:.4},children:"ð§"}),t.jsx("p",{style:{color:"#64748b",fontSize:12},children:"No water test recorded yet. Record a test during the site visit to get product recommendations."})]})]}),h.stage==="quote_sent"&&ht&&t.jsxs("div",{style:{background:"rgba(59,130,246,0.1)",border:"1px solid rgba(59,130,246,0.3)",borderRadius:14,padding:16},children:[t.jsx("div",{style:{fontSize:12,fontWeight:700,color:"#60a5fa",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:4},children:"ð Quote Sent â Awaiting Signature"}),t.jsx("div",{style:{fontSize:12,color:"#94a3b8",marginBottom:12},children:"Share this link. Customer signs quote â agreement auto-generates â payment collected."}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("div",{style:{flex:1,background:"rgba(15,25,35,0.5)",borderRadius:8,padding:"8px 12px",fontSize:12,color:"#60a5fa",fontFamily:"monospace",wordBreak:"break-all"},children:ht}),t.jsx("button",{onClick:()=>{navigator.clipboard.writeText(ht),alert("Copied!")},style:{flexShrink:0,padding:"8px 12px",borderRadius:8,background:"rgba(59,130,246,0.2)",color:"#60a5fa",fontSize:12,fontWeight:600,border:"none",cursor:"pointer"},children:"Copy"})]}),t.jsx("a",{href:ht,target:"_blank",rel:"noopener noreferrer",style:{display:"inline-block",marginTop:8,fontSize:12,color:"#3b82f6",textDecoration:"underline"},children:"Preview as customer â"})]}),h.stage==="agreement_signed"&&t.jsx(cH,{lead:h,onLeadUpdated:Sr}),!1,h.stage==="lost"&&h.lost_reason&&t.jsxs("div",{style:{background:"rgba(239,68,68,0.1)",border:"1px solid rgba(239,68,68,0.2)",borderRadius:14,padding:12},children:[t.jsx("div",{style:{fontSize:12,fontWeight:600,color:"#f87171",marginBottom:4},children:"Lost Reason"}),t.jsx("div",{className:"text-sm text-slate-300",children:h.lost_reason}),h.lost_at&&t.jsxs("div",{style:{fontSize:12,color:"#64748b",marginTop:4},children:["Lost on ",Rp(h.lost_at)]})]}),h.stage==="future_follow_up"&&h.followup_date&&t.jsxs("div",{style:{background:"rgba(168,85,247,0.1)",border:"1px solid rgba(168,85,247,0.2)",borderRadius:14,padding:12},children:[t.jsx("div",{style:{fontSize:12,fontWeight:600,color:"#a855f7",marginBottom:4},children:"Scheduled Follow-Up"}),t.jsx("div",{className:"text-sm text-slate-300",children:new Date(h.followup_date).toLocaleDateString("en-US",{weekday:"long",month:"long",day:"numeric",year:"numeric"})}),h.followup_notes&&t.jsx("div",{style:{fontSize:12,color:"#64748b",marginTop:4},children:h.followup_notes})]}),h.stage==="dnd"&&t.jsxs("div",{style:{background:"rgba(245,158,11,0.1)",border:"1px solid rgba(245,158,11,0.2)",borderRadius:14,padding:12},children:[t.jsx("div",{style:{fontSize:12,fontWeight:600,color:"#f59e0b",marginBottom:4},children:"Do Not Disturb"}),t.jsxs("div",{style:{fontSize:13,color:"#64748b"},children:["No further contact.",h.dnd_at&&t.jsxs("span",{children:[" Since ",Rp(
741h.dnd_at)]})]})]}),t.jsx(Ua,{label:"Source",value:sf[h.source]}),h.water_concern&&t.jsx(Ua,{label:"Water Concern",value:of[h.water_concern]||h.water_concern}),jd&&t.jsx(Ua,{label:"Address",value:jd}),!jd&&zu&&t.jsx(Ua,{label:"ZIP Code",value:zu}),t.jsx(Ua,{label:"Days in Stage",value:`${J0} day${J0!==1?"s":""}`}),t.jsx(Ua,{label:"Created",value:Rp(h.created_at)}),t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:12,fontWeight:600,color:"#64748b",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:6},children:"Assigned Rep"}),!u&&l("leads","assign_rep")&&X0?t.jsxs("select",{value:h.assigned_rep_id||"",onChange:he=>Q3({leadId:h.id,repId:he.target.value||null}),style:{width:"100%",background:"#1e3a4f",border:"1px solid #1e3a4f",borderRadius:8,padding:"8px 12px",fontSize:13,color:"#e2e8f0",outline:"none"},children:[t.jsx("option",{value:"",children:"â Unassigned â"}),X0.map(he=>t.jsx("option",{value:he.id,children:he.full_name},he.id))]}):t.jsx("div",{className:"text-sm text-slate-300",children:((Q0=h.assigned_rep)==null?void 0:Q0.full_name)||"â Unassigned â"})]}),h.notes&&t.jsxs("div",{style:{background:h.stage==="site_visit_scheduled"?"rgba(251,191,36,0.08)":void 0,border:h.stage==="site_visit_scheduled"?"1px solid rgba(251,191,36,0.3)":"1px solid #1e3a4f",borderRadius:12,padding:"10px 14px"},children:[t.jsx("div",{style:{fontSize:11,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:6,color:h.stage==="site_visit_scheduled"?"#fbbf24":"#64748b"},children:h.stage==="site_visit_scheduled"?"ð Office Notes for Rep":"Notes"}),t.jsx("div",{className:"text-sm text-slate-300 whitespace-pre-wrap",children:h.notes})]}),t.jsx(UB,{leadId:h.id,leadName:Rn})]}),m==="activity"&&t.jsx(XB,{activity:t5||[],isLoading:n5}),m==="calls"&&t.jsxs("div",{className:"space-y-2",children:[!(En!=null&&En.length)&&t.jsx("p",{style:{fontSize:13,color:"#64748b",textAlign:"center",padding:"32px 0"},children:"No call attempts logged."}),En==null?void 0:En.map(he=>{var Te;return t.jsxs("div",{style:{background:"#1e3a4f",border:"1px solid #1e3a4f",borderRadius:10,padding:12},children:[t.jsxs("div",{className:"flex items-center justify-between mb-1",children:[t.jsx("span",{style:{fontSize:12,fontWeight:600,color:"#e2e8f0",textTransform:"capitalize"},children:(Te=he.outcome)==null?void 0:Te.replace(/_/g," ")}),t.jsx("span",{style:{fontSize:12,color:"#64748b"},children:Rp(he.created_at)})]}),he.notes&&t.jsx("p",{style:{fontSize:12,color:"#64748b"},children:he.notes})]},he.id)})]})]}),x&&t.jsx("div",{className:"absolute inset-0 flex items-center justify-center p-4 z-20",style:{background:"rgba(0,0,0,0.6)"},children:t.jsxs("div",{style:{background:"#1e3a4f",border:"1px solid #1e3a4f",borderRadius:16,width:"100%",maxWidth:384,padding:20,boxShadow:"0 25px 50px -12px rgba(0,0,0,0.5)"},children:[t.jsx("h3",{className:"font-bold text-white mb-4",children:"Log a Text Message"}),t.jsx("p",{style:{fontSize:12,color:"#64748b",marginTop:-8,marginBottom:12},children:"For texts sent or received outside the CRM."}),t.jsx("div",{style:{display:"flex",gap:8,marginBottom:12},children:["outbound","inbound"].map(he=>t.jsx("button",{onClick:()=>C(he),style:{flex:1,padding:"7px 0",fontSize:12,fontWeight:600,borderRadius:8,cursor:"pointer",background:j===he?"#60a5fa":"#162232",color:j===he?"#0f172a":"#64748b",border:"1px solid "+(j===he?"#60a5fa":"#1e3a4f")},children:he==="outbound"?"I texted them":"They texted me"},he))}),t.jsx("textarea",{value:S,onChange:he=>T(he.target.value),placeholder:"What was said...",rows:4,style:{width:"100%",background:"#162232",border:"1px solid #1e3a4f",borderRadius:8,padding:"10px 12px",fontSize:13,color:"#e2e8f0",outline:"none",resize:"vertical",boxSizing:"border-box"}}),t.jsx("label",{style:{display:"block",fontSize:12,fontWeight:600,color:"#64748b",textTransform:"uppercase",letterSpacing:"0.06em",margin:"12px 0 6px"},children:"When"}),t.jsx("input",{type:"datetime-local",value:L,onChange:he=>E(he.target.value),style:{width:"100%",background:"#162232",border:"1px solid #1e3a4f",borderRadius:8,padding:"10px 12px",fontSize:13,color:"#e2e8f0",outline:"none",boxSizing:"border-box"}}),O&&t.jsx("div",{style:{marginTop:10,fontSize:12,color:"#f87171"},children:O}),t.jsxs("div",{className:"flex gap-3 mt-4",children:[t.jsx("button",{onClick:()=>_(!1),disabled:R,style:{flex:1,padding:"8px 0",fontSize:13,color:"#64748b",background:"none",border:"none",cursor:"pointer"},children:"Cancel"}),t.jsx("button",{onClick:P,disabled:R,style:{flex:1,padding:"8px 0",background:"#60a5fa",color:"#0f172a",fontWeight:600,borderRadius:8,fontSize:13,border:"none",cursor:"pointer",opacity:R?.5:1},children:R?"Saving...":"Save to timeline"})]})]})}),A&&t.jsx("div",{className:"absolute inset-0 flex items-center justify-center p-4 z-20",style:{background:"rgba(0,0,0,0.6)"},children:t.jsxs("div",{style:{background:"#1e3a4f",border:"1px solid #1e3a4f",borderRadius:16,width:"100%",maxWidth:384,padding:20,boxSh
741adow:"0 25px 50px -12px rgba(0,0,0,0.5)"},children:[t.jsx("h3",{className:"font-bold text-white mb-4",children:"Log Call Attempt"}),t.jsxs("div",{className:"space-y-3",children:[t.jsxs("div",{children:[t.jsx("label",{style:{display:"block",fontSize:12,fontWeight:600,color:"#64748b",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:6},children:"Outcome"}),t.jsxs("select",{value:D,onChange:he=>M(he.target.value),style:{width:"100%",background:"#162232",border:"1px solid #1e3a4f",borderRadius:8,padding:"10px 12px",fontSize:13,color:"#e2e8f0",outline:"none"},children:[t.jsx("option",{value:"answered",children:"Answered"}),t.jsx("option",{value:"voicemail",children:"Voicemail"}),t.jsx("option",{value:"no_answer",children:"No Answer"}),t.jsx("option",{value:"callback_scheduled",children:"Callback Scheduled"}),t.jsx("option",{value:"no_show",children:"ð« No Show"}),t.jsx("option",{value:"no_contact_requested",children:"â Requested No Contact"})]})]}),t.jsxs("div",{children:[t.jsx("label",{style:{display:"block",fontSize:12,fontWeight:600,color:"#64748b",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:6},children:"Notes"}),t.jsx("textarea",{value:k,onChange:he=>q(he.target.value),placeholder:"Brief notes...",rows:3,style:{width:"100%",background:"#162232",border:"1px solid #1e3a4f",borderRadius:8,padding:"10px 12px",fontSize:13,color:"#e2e8f0",outline:"none",resize:"none",boxSizing:"border-box"}})]})]}),t.jsxs("div",{className:"flex gap-3 mt-4",children:[t.jsx("button",{onClick:()=>v(!1),style:{flex:1,padding:"8px 0",fontSize:13,color:"#64748b",background:"none",border:"none",cursor:"pointer"},children:"Cancel"}),t.jsx("button",{onClick:f5,disabled:fg,style:{flex:1,padding:"8px 0",background:"#4ade80",color:"#fff",fontWeight:600,borderRadius:8,fontSize:13,border:"none",cursor:"pointer",opacity:fg?.5:1},children:fg?"Saving...":"Log Call"})]})]})}),G&&t.jsx(x8,{entityType:"lead",entityId:h.id,displayName:Rn,initial:{first_name:h.first_name,last_name:h.last_name,phone:h.phone,email:h.email},onClose:()=>V(!1),onSaved:()=>{d.invalidateQueries({queryKey:it.detail(c,h.id)}),d.invalidateQueries({queryKey:it.primaryAddr(c,h.id)}),d.invalidateQueries({queryKey:it.kanban(c)})}}),B&&t.jsx("div",{className:"absolute inset-0 flex items-center justify-center p-4 z-20",style:{background:"rgba(0,0,0,0.6)"},children:t.jsxs("div",{style:{background:"#1e3a4f",border:"1px solid #1e3a4f",borderRadius:16,width:"100%",maxWidth:384,padding:20,boxShadow:"0 25px 50px -12px rgba(0,0,0,0.5)"},children:[t.jsx("h3",{className:"font-bold text-white mb-1",children:"Send Text"}),t.jsxs("p",{style:{fontSize:12,color:"#64748b",marginBottom:16},children:["To: ",h.phone]}),t.jsxs("div",{children:[Q.length>0&&t.jsxs("div",{style:{marginBottom:10},children:[t.jsx("label",{style:{display:"block",fontSize:12,fontWeight:600,color:"#64748b",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:6},children:"Use Template"}),t.jsxs("select",{defaultValue:"",onChange:he=>{const Te=Q.find(Oe=>Oe.id===he.target.value);Te&&(te(hh(Te.body,{first_name:_d,name:_d,rep_name:(a==null?void 0:a.full_name)||"Your Rep",company_name:f.company_name,company_phone:f.phone,review_url:"",visit_date:xe!=null&&xe.date?new Date(xe.date+"T12:00:00").toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric"}):"",install_date:""})),he.target.value="")},style:{width:"100%",background:"#162232",border:"1px solid #1e3a4f",borderRadius:8,padding:"10px 12px",fontSize:13,color:"#e2e8f0",outline:"none"},children:[t.jsx("option",{value:"",children:"â Pick a template â"}),Object.entries(Q.reduce((he,Te)=>{const Oe=Te.group_name||"Other";return he[Oe]||(he[Oe]=[]),he[Oe].push(Te),he},{})).map(([he,Te])=>t.jsx("optgroup",{label:he,style:{background:"#0f1a26",color:"#64748b"},children:Te.map(Oe=>t.jsx("option",{value:Oe.id,style:{background:"#162232",color:"#e2e8f0"},children:Oe.label||Oe.key},Oe.id))},he))]})]}),t.jsx("label",{style:{display:"block",fontSize:12,fontWeight:600,color:"#64748b",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:6},children:"Message"}),t.jsx("textarea",{value:ae,onChange:he=>te(he.target.value),placeholder:"Type your message...",rows:4,autoF
741ocus:!0,style:{width:"100%",background:"#162232",border:"1px solid #1e3a4f",borderRadius:8,padding:"10px 12px",fontSize:13,color:"#e2e8f0",outline:"none",resize:"none",boxSizing:"border-box"}}),t.jsxs("div",{style:{textAlign:"right",fontSize:12,color:"#64748b",marginTop:4},children:[ae.length," chars"]})]}),ee&&t.jsx("div",{style:{marginTop:10,padding:"8px 10px",borderRadius:8,background:"rgba(239,68,68,0.1)",border:"1px solid rgba(239,68,68,0.3)",color:"#f87171",fontSize:12},children:ee}),t.jsxs("div",{className:"flex gap-3 mt-4",children:[t.jsx("button",{onClick:()=>{J(!1),te(""),re("")},style:{flex:1,padding:"8px 0",fontSize:13,color:"#64748b",background:"none",border:"none",cursor:"pointer"},children:"Cancel"}),t.jsx("button",{onClick:d5,disabled:U||!ae.trim(),style:{flex:1,padding:"8px 0",background:"#22c55e",color:"#fff",fontWeight:600,borderRadius:8,fontSize:13,border:"none",cursor:"pointer",opacity:U||!ae.trim()?.5:1},children:U?"Sendingâ¦":"Send Text ð¬"})]})]})}),be&&t.jsx("div",{className:"absolute inset-0 flex items-center justify-center p-4 z-20",style:{background:"rgba(0,0,0,0.6)"},children:t.jsxs("div",{style:{background:"#1e3a4f",border:"1px solid #1e3a4f",borderRadius:16,width:"100%",maxWidth:384,padding:20,boxShadow:"0 25px 50px -12px rgba(0,0,0,0.5)"},children:[t.jsx("h3",{className:"font-bold text-white mb-1",children:"Send Email"}),t.jsxs("p",{style:{fontSize:12,color:"#64748b",marginBottom:16},children:["To: ",h.email]}),t.jsxs("div",{children:[ne.length>0&&t.jsxs("div",{style:{marginBottom:10},children:[t.jsx("label",{style:{display:"block",fontSize:12,fontWeight:600,color:"#64748b",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:6},children:"Use Template"}),t.jsxs("select",{defaultValue:"",onChange:he=>{const Te=ne.find(Nt=>Nt.id===he.target.value);if(!Te)return;const Oe={first_name:_d,name:_d,rep_name:(a==null?void 0:a.full_name)||"Your Rep",company_name:f.company_name,company_phone:f.phone,review_url:"",visit_date:xe!=null&&xe.date?new Date(xe.date+"T12:00:00").toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric"}):"",install_date:""};K(hh(Te.subject,Oe)),ie(hh(Te.body,Oe)),he.target.value=""},style:{width:"100%",background:"#162232",border:"1px solid #1e3a4f",borderRadius:8,padding:"10px 12px",fontSize:13,color:"#e2e8f0",outline:"none"},children:[t.jsx("option",{value:"",children:"â Pick a template â"}),Object.entries(ne.reduce((he,Te)=>{const Oe=Te.group_name||"Other";return he[Oe]||(he[Oe]=[]),he[Oe].push(Te),he},{})).map(([he,Te])=>t.jsx("optgroup",{label:he,style:{background:"#0f1a26",color:"#64748b"},children:Te.map(Oe=>t.jsx("option",{value:Oe.id,style:{background:"#162232",color:"#e2e8f0"},children:Oe.label||Oe.key},Oe.id))},he))]})]}),t.jsx("label",{style:{display:"block",fontSize:12,fontWeight:600,color:"#64748b",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:6},children:"Subject"}),t.jsx("input",{type:"text",value:F,onChange:he=>K(he.target.value),placeholder:"Subject line...",style:{width:"100%",background:"#162232",border:"1px solid #1e3a4f",borderRadius:8,padding:"10px 12px",fontSize:13,color:"#e2e8f0",outline:"none",marginBottom:10,boxSizing:"border-box"}}),t.jsx("label",{style:{display:"block",fontSize:12,fontWeight:600,color:"#64748b",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:6},children:"Message"}),t.jsx("textarea",{value:Z,onChange:he=>ie(he.target.value),placeholder:"Type your message...",rows:6,style:{width:"100%",background:"#162232",border:"1px solid #1e3a4f",borderRadius:8,padding:"10px 12px",fontSize:13,color:"#e2e8f0",outline:"none",resize:"none",boxSizing:"border-box"}})]}),H&&t.jsx("div",{style:{marginTop:10,padding:"8px 10px",borderRadius:8,background:"rgba(239,68,68,0.1)",border:"1px solid rgba(239,68,68,0.3)",color:"#f87171",fontSize:12},children:H}),t.jsxs("div",{className:"flex gap-3 mt-4",children:[t.jsx("button",{onClick:()=>{we(!1),K(""),ie(""),de("")},style:{flex:1,padding:"8px 0",fontSize:13,color:"#64748b",background:"none",border:"none",cursor:"pointer"},children:"Cancel"}),t.jsx("button",{onClick:c5,disabled:Y||!F.trim()||!Z.trim(),style:{flex:1,padding:"8px 0",background:"#0d7ea3",color:"#fff",fontWeight:600,borderRadius:8,fontSize:13,border:"none",cursor:"pointer",opacity:Y||!F.trim()||!Z.trim()?.5:1},children:Y?"Sendingâ¦":"Send Email âï¸"})]})]})}),bt&&t.jsx("div",{className:"absolute inset-0 flex items-center justify-center p-4 z-20",style:{background:"rgba(0,0,0,0.6)"},children:t.jsxs("div",{style:{background:"#1e3a4f",border:"1px solid #1e3a4f",borderRadius:16,width:"100%",maxWidth:400,padding:20,boxSh
741adow:"0 25px 50px -12px rgba(0,0,0,0.5)"},children:[t.jsx("h3",{className:"font-bold text-white mb-2",children:bt==="no_show"?"Mark Visit as No-Show?":"Cancel This Visit?"}),t.jsx("p",{style:{fontSize:13,color:"#94a3b8",marginBottom:16,lineHeight:1.5},children:bt==="no_show"?`${Rn} did not show. The lead will return to the Qualified queue and a 2-hour follow-up task will be created to reschedule.`:`Cancel the scheduled visit for ${Rn}. The lead will return to the Qualified queue.`}),t.jsxs("div",{className:"flex gap-3",children:[t.jsx("button",{onClick:()=>Vn(null),disabled:fr,style:{flex:1,padding:"8px 0",fontSize:13,color:"#64748b",background:"none",border:"none",cursor:"pointer"},children:"Cancel"}),t.jsx("button",{onClick:()=>s5(bt),disabled:fr,style:{flex:1,padding:"8px 0",fontSize:13,fontWeight:600,borderRadius:8,border:"none",cursor:"pointer",color:"#fff",background:bt==="no_show"?"#ef4444":"#94a3b8",opacity:fr?.5:1},children:fr?"Savingâ¦":"Confirm"})]})]})})]})]}),pe&&Ie&&t.jsx("div",{className:"fixed inset-0 z-50 overflow-y-auto",style:{background:"#162232"},children:t.jsx(W0,{customerId:Ie,customerName:Rn,customerAddress:jd,customerPhone:h.phone,leadId:h.id,onSaved:h5,onCancel:()=>Ne(!1)})}),le&&t.jsx(WH,{leadId:h.id,leadName:Rn,leadPhone:h.phone,leadAddress:jd,preferredSlotAt:h.preferred_slot_at,onScheduled:r5,onCancel:()=>ce(!1)})]})}function Ua({label:e,value:n}){return t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:12,fontWeight:600,color:"#64748b",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:2},children:e}),t.jsx("div",{className:"text-sm text-slate-300",children:n})]})}function nV(e){if(!e)return"No slot on file";const n=new Date(e);return isNaN(n.getTime())?"No slot on file":n.toLocaleDateString("en-US",{weekday:"long",month:"long",day:"numeric"})+" at "+n.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit"})}function rV({lead:e,busy:n,onSetAvailability:r,onAdvance:s}){const i=e.booking_stage,o=e.slot_available!==null&&e.slot_available!==void 0,a=e.chase_kind||tu(i),l=a&&ef[a]||[],d=!!i&&l.includes(i),c=(()=>{if(!i)return null;const f=l.indexOf(i);return f<0||f>=l.length-1?null:l[f+1]})();return t.jsxs("div",{style:{background:"rgba(56,189,248,0.08)",border:"1px solid rgba(56,189,248,0.3)",borderRadius:14,padding:16},children:[t.jsxs("div",{style:{fontSize:12,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.06em",color:"#38bdf8",marginBottom:8},children:["ð
",a==="quote"?"Quote â Awaiting Signature":"Booking â Requested Slot"]}),t.jsx("div",{style:{fontSize:14,color:"#e2e8f0",marginBottom:4},children:nV(e.preferred_slot_at)}),i&&t.jsxs("div",{style:{fontSize:12,color:"#94a3b8",marginBottom:12},children:["Current: ",t.jsx("span",{style:{color:i==="booked"||i==="signed"?"#22c55e":i==="dead"?"#94a3b8":"#f59e0b",fontWeight:700},children:tf[i]||i})]}),!o&&i!=="booked"&&t.jsxs("div",{style:{display:"flex",gap:8,flexWrap:"wrap"},children:[t.jsx("button",{onClick:()=>r(!0),disabled:n,style:{fontSize:12,padding:"6px 14px",borderRadius:8,cursor:"pointer",fontWeight:700,background:"rgba(34,197,94,0.12)",color:"#22c55e",border:"1px solid rgba(34,197,94,0.35)",opacity:n?.5:1},children:"â Available â Book"}),t.jsx("button",{onClick:()=>r(!1),disabled:n,style:{fontSize:12,padding:"6px 14px",borderRadius:8,cursor:"pointer",fontWeight:700,background:"rgba(239,68,68,0.1)",color:"#f87171",border:"1px solid rgba(239,68,68,0.3)",opacity:n?.5:1},children:"â Not Available â Chase"})]}),d&&t.jsxs("div",{style:{marginTop:12,paddingTop:12,borderTop:"1px solid rgba(56,189,248,0.2)",display:"flex",gap:8,flexWrap:"wrap"},children:[c&&t.jsxs("button",{onClick:()=>s(c),disabled:n,style:{fontSize:12,padding:"6px 12px",borderRadius:8,cursor:"pointer",fontWeight:600,background:"rgba(245,158,11,0.1)",color:"#f59e0b",border:"1px solid rgba(245,158,11,0.3)",opacity:n?.5:1},children:["â ",tf[c]]}),t.jsx("button",{onClick:()=>s("booked"),disabled:n,style:{fontSize:12,padding:"6px 12px",borderRadius:8,cursor:"pointer",fontWeight:600,background:"rgba(34,197,94,0.1)",color:"#22c55e",border:"1px solid rgba(34,197,94,0.3)",opacity:n?.5:1},children:"â Booked"}),t.jsx("button",{onClick:()=>s("dead"),disabled:n,style:{fontSize:12,padding:"6px 12px",borderRadius:8,cursor:"pointer",fontWeight:600,background:"rgba(100,116,139,0.1)",color:"#94a3b8",border:"1px solid rgba(100,116,139,0.3)",opacity:n?.5:1},children:"Close"})]}),i==="booked"&&t.jsx("div",{style:{fontSize:13,color:"#22c55e",fontWeight:600,marginTop:4},children:"â Site visit booked â confirmation sent."})]})}const gh=[{key:"new_lead",label:"New Lead",hex:"#64748b"},{key:"qualifying",label:"Qualifying",hex:"#a78bfa"},{key:"qualified",label:"Qualified",hex:"#818cf8"},{key:"site_visit_scheduled",label:"Site Visit Scheduled",hex:"#22d3ee"},{key:"quote_sent",label:"Quote Sent",hex:"#fb923c"},{key:"agreement_signed",label:"Agreement Signed",hex:"#34d399"}],uj=[{key:"won",label:"Won",hex:"#34d399"},{key:"lost",label:"Lost",hex:"#f87171"},{key:"future_follow_up",label:"Cold Lead",hex:"#fbbf24"},{key:"dnd",label:"DND",hex:"#94a3b8"}],pj=Object.fromEntries(gh.map(e=>[e.key,e.hex]));function sV(){const{role:e,profile:n}=Ee();rs(e);const{data:r,isLoading:s,error:i}=CF(),{data:o}=NF(),{data:a}=RF(),[l,d]=If(),c=rt(),f=(n==null?void 0:n.tenant_id)??null,[p,u]=g.useState(!1),[h,y]=g.useState(null),[m,b]=g.useState(""),[A,v]=g.useState("");g.useEffect(()=>{const M=setTimeout(()=>v(m.trim()),300);return()=>
741clearTimeout(M)},[m]);const{data:x,isLoading:_}=Ae({queryKey:["lead_search_terminal",f,A],queryFn:()=>s8(A),enabled:A.length>=2,staleTime:2e4}),[j,C]=g.useState("new_lead"),[S,T]=g.useState(()=>Date.now()),[L,E]=g.useState(null),{data:R,isLoading:N}=kF(L);g.useEffect(()=>{const M=l.get("lead");if(!M||!r)return;const q=Object.values(r).flat().find(I=>I.id===M);if(q){y(q),d({},{replace:!0});return}let $=!1;return k0(M).then(I=>{$||y(I)}).catch(I=>{console.error("[pipeline] deep-link lead not found",M,I)}).finally(()=>{$||d({},{replace:!0})}),()=>{$=!0}},[l,r]),g.useEffect(()=>{const M=w.channel("pipeline_leads_realtime").on("postgres_changes",{event:"UPDATE",schema:"public",table:"leads"},()=>{c.invalidateQueries({queryKey:it.kanban(f)}),c.invalidateQueries({queryKey:it.counts(f)})}).subscribe();return()=>{w.removeChannel(M)}},[c,f]),g.useEffect(()=>{const M=setInterval(()=>T(Date.now()),3e4);return()=>clearInterval(M)},[]);const O=Object.values(o||{}).reduce((M,k)=>M+k,0),z=gh.length+1;if(s)return t.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%"},children:t.jsx("div",{style:{color:"#64748b",fontSize:14},children:"Loading pipeline..."})});if(i)return t.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%"},children:t.jsx("div",{style:{color:"#f87171",fontSize:14},children:"Failed to load pipeline. Please refresh."})});function P(M){const q=(M==="site_visit_scheduled"?["site_visit_scheduled","proposal_in_progress"]:[M]).flatMap($=>(r==null?void 0:r[$])||[]);return m?q.filter($=>($.full_name||"").toLowerCase().includes(m.toLowerCase())||`${$.first_name||""} ${$.last_name||""}`.toLowerCase().includes(m.toLowerCase())||($.phone||"").includes(m)||($.email||"").toLowerCase().includes(m.toLowerCase())):q}function D(M){E(k=>k===M?null:M)}return t.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:16,flexShrink:0,flexWrap:"wrap",gap:10},children:[t.jsxs("div",{children:[t.jsx("h1",{style:{color:"#f1f5f9",fontWeight:800,fontSize:20,margin:0},children:"Lead Pipeline"}),t.jsxs("p",{style:{color:"#64748b",fontSize:13,marginTop:2,marginBottom:0},children:[O," active lead",O!==1?"s":""," in pipeline"]})]}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[t.jsx("input",{type:"text",value:m,onChange:M=>b(M.target.value),placeholder:"Search leads...",style:{background:"#162232",border:"1px solid #1e3a4f",borderRadius:8,color:"#e2e8f0",padding:"8px 14px",fontSize:13,outline:"none",width:180}}),t.jsxs("button",{onClick:()=>u(!0),style:{display:"flex",alignItems:"center",gap:6,background:"#0d7ea3",color:"#fff",fontWeight:700,padding:"8px 16px",borderRadius:8,fontSize:13,border:"none",cursor:"pointer"},onMouseEnter:M=>M.currentTarget.style.background="#0e8fb8",onMouseLeave:M=>M.currentTarget.style.background="#0d7ea3",children:[t.jsx("span",{style:{fontSize:16,lineHeight:1},children:"+"}),"New Lead"]})]})]}),A.length>=2&&t.jsxs("div",{style:{flexShrink:0,marginBottom:12,padding:"12px 14px",borderRadius:12,background:"#0d1520",border:"1px solid #1e3a4f"},children:[t.jsxs("div",{style:{fontSize:11,fontWeight:700,color:"#64748b",letterSpacing:"0.06em",marginBottom:10},children:["WON / LOST / COLD LEAD / DND",_&&t.jsx("span",{style:{marginLeft:8,fontWeight:400,letterSpacing:0},children:"searching..."})]}),!_&&((x==null?void 0:x.length)||0)===0?t.jsx("div",{style:{fontSize:13,color:"#64748b"},children:"No matches outside the pipeline."}):t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:(x||[]).map(M=>t.jsx(Bd,{lead:M,onClick:y,now:S,installFlag:a==null?void 0:a[M.id]},M.id))})]}),t.jsxs("div",{className:"flex flex-col flex-1 overflow-hidden md:hidden",children:[t.jsx("div",{style:{display:"flex",gap:6,overflowX:"auto",paddingBottom:10,scrollbarWidth:"none",flexShrink:0},children:gh.map(({key:M,label:k,hex:q})=>{const $=P(M).length,I=j===M;return t.jsxs("button",{onClick:()=>C(M),style:{flexShrink:0,padding:"7px 14px",borderRadius:20,fontSize:11,fontWeight:700,cursor:"pointer",whiteSpace:"nowrap",background:I?`${q}22`:"rgba(255,255,255,0.04)",border:`1px solid ${I?q:"#1e3a4f"}`,color:I?q:"#64748b"},children:[k,$>0&&t.jsx("span",{style:{marginLeft:6,fontSize:10,background:I?q:"#1e3a4f",color:I?"#0f1923":"#64748b",borderRadius:20,padding:"1px 6px",fontWeight:800},children:$})]},M)})}),t.jsx("div",{style:{flex:1,overflowY:"auto",background:"#0d1520",borderRadius:14,border:`2px solid ${pj[j]||"#1e3a4f"}30`,borderTop:`3px solid ${pj[j]||"#1e3a4f"}`,padding:10},children:P(j).length===0?t.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:"48px 0",gap:8},children:[t.jsx("span",{style:{fontSize:32},children:"ð"}),t.jsx("div",{style:{color:"#64748b",fontSize:14},children:"No leads in this stage"})]}):t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:P(j).map(M=>t.jsx(Bd,{lead:M,onClick:y,now:S,installFlag:a==null?void 0:a[M.id]},M.id))})}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6,paddingTop:8,paddingBottom:4,flexShrink:0},children:[t.jsx("div",{style:{display:"flex",gap:8,flexWrap:"wrap"},children:uj.map(M=>{const k=L===M.key;return t.jsxs("button",{onClick:()=>D(M.key),style:{display:"flex",alignItems:"center",gap:6,cursor:"pointer",background:k?`${M.hex}22`:"rgba(255,255,255,0.04)",border:`1px solid ${k?M.hex:"#1e3a4f"}`,borderRadius:20,padding:"5px 12px"},children:[t.jsx("span",{style:{color:k?M.hex:"#64748b",fontSize:11,fontWeight:700},children:M.label}),t.jsx("span",{style:{color:k?M.hex:"#94a3b8",fontWeight:800,fontSize:11},children:(o==null?void 0:o[M.key])||0})]},M.key)})}),L&&t.jsx("div",{style:{maxHeight:260,overflowY:"auto",background:"#0d1520",border:"1px solid #182636",borderRadius:12,padding:8,display:"flex",flexDirection:"column",gap:8},children:N?t.jsx("div",{style:{textAlign:"center",padding:"18px 0",color:"#64748b",fontSize:12},children:"Loadingâ¦"}):R&&R.length>0?R.map(M=>t.jsx(Bd,{lead:M,onClick:y,now:S,installFlag:a==null?void 0:a[M.id]},M.id)):t.jsx("div",{style:{textAlign:"center",padding:"18px 0",color:"#1e3a4f",fontSize:12},children:"No leads"})})]})]}),t.jsxs("div",{className:"hidden md:grid flex-1 pb-2",style:{gridTemplateColumns:`repeat(${z}, minmax(0, 1fr))`,gap:8,overflow:"hidden",minWidth:0},children:[gh.map(({key:M,label:k,hex:q})=>{const $=P(M);return t.jsxs("div",{style:{background:"#0d1520",borderTop:`3px solid ${q}`,borderRadius:12,minWidth:0,overflow:"hidden",display:"flex",flexDirection:"column",border:"1px solid #182636"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 10px",borderBottom:"1px solid #182636",flexShrink:0},children:[t.jsx("span",{style:{fontSize:10,fontWeight:800,color:q,textTransform:"uppercase",letterSpacing:"0.07em"},children:k}),t.jsx("span",{style:{fontSize:10,fontWeight:700,background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:20,padding:"2px 8px",color:"#64748b"},children:$.length})]}),t.jsx("div",{style:{flex:1,overflowY:"auto",padding:6,display:"flex",flexDirection:"column",gap:6},children:$.length===0?t.jsx("div",{style:{textAlign:"center",padding:"24px 0",color:"#1e3a4f",fontSize:11},children:"No leads"}):$.map(I=>t.jsx(Bd,{lead:I,onClick:y,now:S,installFlag:a==null?void 0:a[I.id]},I.id))})]},M)}),t.jsxs("div",{style:{background:"#0d1520",borderTop:"3px solid #1e3a4f",borderRadius:12,minWidth:0,overflow:"hidden",display:"flex",flexDirection:"column",border:"1px solid #182636"},children:[t.jsx("div",{style:{padding:"10px 10px",borderBottom:"1px solid #182636",flexShrink:0},children:t.jsx("span",{style:{fontSize:10,fontWeight:800,color:"#64748b",textTransform:"uppercase",letterSpacing:"0.07em"},children:"Other"})}),t.jsx("div",{style:{flex:1,overflowY:"auto",padding:8,display:"flex",flexDirection:"column",gap:6},children:uj.map(M=>{const k=L===M.key,q=(o==null?void 0:o[M.key])||0;return t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[t.jsxs("button",{onClick:()=>D(M.key),disabled:q===0,style:{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%",textAlign:"left",fontSize:11,background:k?`${M.hex}18`:"rgba(255,255,255,0.03)",border:`1px solid ${k?M.hex:"#182636"}`,borderRadius:8,padding:"8px 10px",cursor:q===0?"default":"pointer",opacity:q===0?.5:1},children:[t.jsxs("span",{style:{display:"flex",alignItems:"center",gap:6},children:[t.jsx("span",{style:{color:k?M.hex:"#64748b",fontSize:9},children:k?"â¾":"â¸"}),t.jsx("span",{style:{color:k?M.hex:"#94a3b8",fontWeight:700},children:M.label})]}),t.jsx("span",{style:{color:k?M.hex:"#64748b",fontWeight:800,background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:20,padding:"1px 8px"},children:q})]}),k&&t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6,paddingLeft:2},children:N?t.jsx("div",{style:{textAlign:"center",padding:"14px 0",color:"#64748b",fontSize:11},children:"Loadingâ¦"}):R&&R.length>0?R.map($=>t.jsx(Bd,{lead:$,onClick:y,now:S,installFlag:a==null?void 0:a[$.id]},$.id)):t.jsx("div",{style:{textAlign:"center",padding:"14px 0",color:"#1e3a4f",fontSize:11},children:"No leads"})})]},M.key)})})]})]}),p&&t.jsx(KF,{onClose:()=>u(!1),onCreated:()=>u(!1)}),h&&t.jsx(tV,{lead:h,onClose:()=>y(null),onLeadUpdated:M=>{y(M),c.invalidateQueries({queryKey:it.kanban(f)}),c.invalidateQueries({queryKey:it.counts(f)})}})]})}function iV(e){return e.split(" ").map(n=>n[0]).join("").slice(0,2).toUpperCase()}const oV={reserved:{label:"â
Stock",color:"#4ade80",bg:"rgba(74,222,128,0.1)",border:"rgba(74,222,128,0.25)"},short:{label:"â ï¸ Short",color:"#f87171",bg:"rgba(248,113,113,0.1)",border:"rgba(248,113,113,0.25)"},pending_check:{label:"â³ Checking",color:"#fbbf24",bg:"rgba(251,191,36,0.1)",border:"rgba(251,191,36,0.25)"}},hj={standard_install:{label:"ð§ Install",color:"#60a5fa",bg:"rgba(96,165,250,0.12)",border:"rgba(96,165,250,0.3)"},rental_setup:{label:"ð§ Rental setup",color:"#a78bfa",bg:"rgba(167,139,250,0.12)",border:"rgba(167,139,250,0.3)"},service:{label:"ð Service",color:"#fbbf24",bg:"rgba(251,191,36,0.12)",border:"rgba(251,191,36,0.3)"},warranty:{label:"ð Warranty",color:"#fbbf24",bg:"rgba(251,191,36,0.12)",border:"rgba(251,191,36,0.3)"},filter_change:{label:"ð Filter change",color:"#fbbf24",bg:"rgba(251,191,36,0.12)",border:"rgba(251,191,36,0.3)"}};function aV({job:e}){const n=hj[e.job_type]??hj.service,r=e.ticket,s=r&&(r.priority==="high"||r.priority==="urgent");return t.jsxs(t.Fragment,{children:[t.jsx("span",{style:{fontSize:10,fontWeight:700,padding:"1px 6px",borderRadius:8,background:n.bg,color:n.color,border:`1px solid ${n.border}`,whiteSpace:"nowrap"},children:r?`ð ${r.ticket_number}`:n.label}),s&&t.jsx("span",{style:{fontSize:10,fontWeight:800,padding:"1px 6px",borderRadius:8,whiteSpace:"nowrap",background:r.priority==="urgent"?"#b91c1c":"rgba(248,113,113,0.12)",color:r.priority==="urgent"?"#fff":"#f87171",border:"1px solid rgba(248,113,113,0.35)"},children:r.priority==="urgent"?"URGENT":"â² High"})]})}function F0({job:e,onClick:n}
741){const r=e.scheduled_at||e.scheduled_date,s=r?new Date(r).toLocaleDateString("en-US",{month:"short",day:"numeric"}):"Not scheduled",i=e.inventory_status,o=i?oV[i]:null;return t.jsxs("div",{onClick:()=>n(e),className:"bg-card border border-border rounded-xl p-3 cursor-pointer hover:border-accent/50 transition-all",children:[t.jsxs("div",{className:"flex items-start justify-between gap-2 mb-2",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"text-sm font-semibold text-white truncate",children:e.customer_name_snapshot}),t.jsx("div",{className:"text-xs text-muted truncate",children:e.phone_snapshot})]}),e.assigned_technician&&t.jsx("div",{className:"w-6 h-6 rounded-full bg-orange/20 text-orange text-xs font-bold flex items-center justify-center flex-shrink-0",title:e.assigned_technician.full_name,children:iV(e.assigned_technician.full_name)})]}),t.jsx("div",{className:"text-xs text-muted truncate mb-2",children:e.service_address_snapshot}),e.ticket&&t.jsx("div",{className:"text-xs truncate mb-2",style:{color:"#cbd5e1"},title:e.ticket.subject,children:e.ticket.subject}),t.jsxs("div",{className:"flex items-center gap-1.5 mb-2 flex-wrap",children:[t.jsx(aV,{job:e}),lo[e.system_type]&&t.jsx("span",{className:"text-xs bg-surface border border-border rounded px-1.5 py-0.5 text-muted",children:lo[e.system_type]}),o&&t.jsx("span",{style:{fontSize:10,fontWeight:600,padding:"1px 6px",borderRadius:8,background:o.bg,color:o.color,border:`1px solid ${o.border}`},children:o.label})]}),t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsxs("span",{className:"text-xs text-muted",children:["ð
",s]}),e.equipment_summary&&t.jsx("span",{className:"text-xs text-muted truncate max-w-[100px]",title:e.equipment_summary,children:e.equipment_summary})]})]})}function lV({job:e,ticketId:n,ticketNumber:r,onClose:s,onDone:i}){var x;const o=rt(),{user:a,profile:l}=Ee(),{mutateAsync:d}=ng(),[c,f]=g.useState(""),[p,u]=g.useState(!1),[h,y]=g.useState(null),[m,b]=g.useState(null);async function A(_){if(!c.trim()){y("Say what you did on this visit.");return}if(!(a!=null&&a.id)){y("Not signed in.");return}u(!0),y(null);let j=m;if(!j)try{j=await d({jobId:e.id,newStatus:"complete",currentJob:e}),b(j)}catch(C){y((C==null?void 0:C.message)||"Could not mark the visit complete."),u(!1);return}try{await fU(n,_,c,{actor_id:a.id,actor_name:(l==null?void 0:l.full_name)??null}),o.invalidateQueries({queryKey:["service_tickets"]}),i(j)}catch(C){y(`The visit is marked complete, but ${r||"the ticket"} was not updated: ${(C==null?void 0:C.message)||"unknown error"}. Press an answer again to retry the ticket only, or update it from the customer's Service tab.`),u(!1)}}const v=(_,j,C,S)=>t.jsxs("button",{disabled:p||!c.trim(),onClick:()=>A(C),style:{flex:1,textAlign:"left",padding:"10px 12px",borderRadius:10,cursor:p?"wait":"pointer",background:`${S}14`,border:`1px solid ${S}55`,opacity:p||!c.trim()?.5:1},children:[t.jsx("div",{style:{color:S,fontWeight:700,fontSize:13},children:_}),t.jsx("div",{style:{color:"#94a3b8",fontSize:11,marginTop:2},children:j})]});return t.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4",style:{backgroundColor:"rgba(0,0,0,0.65)"},onClick:p?void 0:s,children:t.jsxs("div",{className:"w-full max-w-lg rounded-xl",onClick:_=>_.stopPropagation(),style:{backgroundColor:"#0f172a",border:"1px solid rgba(148,163,184,0.2)"},children:[t.jsxs("div",{className:"px-5 py-4",style:{borderBottom:"1px solid rgba(148,163,184,0.15)"},children:[t.jsx("div",{style:{color:"#e2e8f0",fontSize:16,fontWeight:700},children:m?"Visit complete â update the ticket":"Complete visit"}),t.jsxs("div",{style:{color:"#64748b",fontSize:13,marginTop:2},children:[e.customer_name_snapshot," · ",r,(x=e.ticket)!=null&&x.subject?` · ${e.ticket.subject}`:""]})]}),t.jsxs("div",{className:"px-5 py-4 space-y-4",children:[t.jsxs("div",{children:[t.jsx("label",{style:{color:"#94a3b8",fontSize:12,fontWeight:600},children:"What did you do?"}),t.jsx("textarea",{value:c,onChange:_=>f(_.target.value),rows:3,autoFocus:!0,placeholder:"Replaced injector and flow control. Ran a manual regen, quiet.",style:{width:"100%",marginTop:6,resize:"vertical",backgroundColor:"rgba(15,23,42,0.6)",border:"1px solid rgba(148,163,184,0.25)",borderRadius:8,padding:"8px 10px",color:"#e2e8f0",fontSize:14}})]}),t.jsxs("div",{children:[t.jsx("div",{style:{color:"#e2e8f0",fontSize:13,fontWeight:700,marginBottom:8},children:"Did this fix the customer's problem?"}),t.jsxs("div",{className:"flex gap-2",children:[v("Yes â fixed","Ticket resolved; office confirms with customer","fixed","#4ade80"),v("No","Ticket reopened; office books another visit","not_fixed","#f87171"),v("Not sure","Office checks with customer","unsure","#fbbf24")]})]}),h&&t.jsx("div",{className:"rounded-lg px-3 py-2 text-sm",style:{backgroundColor:"rgba(239,68,68,0.12)",border:"1px solid rgba(239,68,68,0.3)",color:"#f87171"},children:h})]}),t.jsx("div",{className:"px-5 py-3 flex justify-end",style:{borderTop:"1px solid rgba(148,163,184,0.15)"},children:t.jsx("button",{disabled:p,onClick:m?()=>i(m):s,className:"rounded-lg px-4 py-2 text-sm font-semibold",style:{color:"#94a3b8",border:"1px solid rgba(148,163,184,0.25)"},children:m?"Close (ticket not updated)":"Cancel"})})]})})}const dV={ro:"Reverse Osmosis",softener:"Water Softener",whole_home_filter:"Whole Home Filter",replacement_filter:"Replacement Filter",accessory:"Accessory",service:"Service"},cV={reserved:{label:"Stock Reserved",color:"#4ade80",bg:"rgba(74,222,128,0.1)",border:"rgba(74,222,128,0.25)",icon:"â
"},short:{label:"Stock Shortage",color:"#f87171",bg:"rgba(248,113,113,0.1)",border:"rgba(248,113,113,0.25)",icon:"â ï¸"},pending_check:{label:"Checking Stock",color:"#fbbf24",bg:"rgba(251,191,36,0.1)",border:"rgba(251,191,36,0.25)",icon:"â³"},not_required:{label:"No Stock Needed",color:"#64748b",bg:"rgba(100,116,139,0.1)",border:"rgba(100,116,139,0.2)",icon:"â"},ready:{label:"Stock Ready",color:"#4ade80",bg:"rgba(74,222,128,0.1)",border:"rgba(74,222,128,0.25)",icon:"â
"},n_a:{label:"N/A",color:"#64748b",bg:"rgba(100,116,139,0.1)",border:"rgba(100,116,139,0.2)",icon:"â"}};function zm(e){return e?new Date(e).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit"}):"â"}
741function uV(e){return e?`$${Number(e).toLocaleString("en-US",{minimumFractionDigits:2})}`:"â"}const pV={ready_to_schedule:[{label:"Waiting for Stock",target:"waiting_for_stock",variant:"bg-amber/15 text-amber border-amber/30"}],scheduled:[{label:"Waiting for Stock",target:"waiting_for_stock",variant:"bg-amber/15 text-amber border-amber/30"},{label:"Unschedule â Back to Ready",target:"ready_to_schedule",variant:"bg-purple-500/15 text-purple-400 border-purple-500/30"}],waiting_for_stock:[{label:"â
Stock In â Ready",target:"ready_to_schedule"},{label:"Back to Scheduled",target:"scheduled"}]},hV=480,fV=1020,n3=30,r3=120,gV=(()=>{const e=[];for(let n=hV;n<=fV;n+=n3)e.push(n);return e})();function mV(e,n,r,s){const i=Date.UTC(e,n-1,r,s,0,0),o=new Intl.DateTimeFormat("en-US",{timeZone:yu,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1}).formatToParts(new Date(i)),a=c=>{var f;return((f=o.find(p=>p.type===c))==null?void 0:f.value)||""};let l=+a("hour");return l===24&&(l=0),(Date.UTC(+a("year"),+a("month")-1,+a("day"),l,+a("minute"),0)-i)/6e4}function xV(e,n,r,s,i){const o=mV(e,n,r,s),a=Date.UTC(e,n-1,r,s,i,0)-o*6e4;return new Date(a).toISOString()}function Bo(e){const n=Math.floor(e/60),r=e%60,s=n>=12?"PM":"AM";return`${n%12===0?12:n%12}:${String(r).padStart(2,"0")} ${s}`}function yV(e){const n=new Date,r=new Date(n);return r.setDate(n.getDate()+e*7-n.getDay()+1),Array.from({length:7},(s,i)=>{const o=new Date(r);return o.setDate(r.getDate()+i),o})}function Vd(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,"0")}-${String(e.getDate()).padStart(2,"0")}`}function fj(e,n){const r=new Date(e);return r.setHours(Math.floor(n/60),n%60,0,0),r<new Date}function gj(e){return e.getDay()===0||e.getDay()===6}function bV({currentJobId:e,techs:n,preselectedTechId:r,onConfirm:s,onCancel:i,customerName:o,title:a}){var D,M;const[l,d]=g.useState(0),[c,f]=g.useState(r||(((D=n[0])==null?void 0:D.id)??"")),[p,u]=g.useState([]),[h,y]=g.useState(!1),[m,b]=g.useState(null),[A,v]=g.useState(null),[x,_]=g.useState(""),[j,C]=g.useState(!1),S=g.useMemo(()=>yV(l),[l]),T=Vd(S[0]),L=Vd(S[6]);g.useEffect(()=>{if(!n.length)return;y(!0);const k=n.map(q=>q.id);w.from("jobs").select("assigned_technician_id, scheduled_at, duration_minutes, customer_name_snapshot").in("assigned_technician_id",k).gte("scheduled_at",T+"T00:00:00").lte("scheduled_at",L+"T23:59:59").not("job_status","in",'("complete","cancelled")').neq("id",e).then(({data:q})=>{if(q){const $=q.map(I=>{const B=new Date(I.scheduled_at),J=B.getHours()*60+B.getMinutes(),ae=Number(I.duration_minutes)||r3;return{assigned_technician_id:I.assigned_technician_id,scheduled_date:Vd(B),start_min:J,end_min:J+ae,customer_name_snapshot:I.customer_name_snapshot}});u($)}y(!1)})},[T,L,n,e]);const E=g.useMemo(()=>{const k={};for(const q of p){const $=`${q.assigned_technician_id}-${q.scheduled_date}`;k[$]||(k[$]=[]),k[$].push(q)}return k},[p]);function R(k,q,$){const I=E[`${k}-${q}`];if(!I)return null;const B=$+n3;for(const J of I)if($<J.end_min&&B>J.start_min)return J.customer_name_snapshot||"Booked";return null}function N(k,q){if(!c||R(c,k,q))return;const $=new Date(k+"T12:00:00");fj($,q)||(b(k),v(q))}async function O(){if(!(!m||A===null||!c)){C(!0);try{await s(m,A,c,x)}finally{C(!1)}}}const z=((M=n.find(k=>k.id===c))==null?void 0:M.full_name)||"",P=!!m&&A!==null&&!!c&&!j;return t.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4",style:{backgroundColor:"rgba(0,0,0,0.75)"},children:t.jsxs("div",{className:"w-full max-w-5xl max-h-[90vh] rounded-2xl overflow-hidden flex flex-col",style:{backgroundColor:"#1e293b",border:"1px solid #334155"},children:[t.jsxs("div",{className:"flex items-center justify-between px-6 py-4 flex-shrink-0",style:{borderBottom:"1px solid #334155"},children:[t.jsxs("div",{children:[t.jsx("h2",{className:"text-lg font-bold text-white",children:a??"Schedule Installation"}),t.jsxs("p",{className:"text-sm mt-0.5",style:{color:"#94a3b8"},children:[o," · Pick a tech and time slot"]})]}),t.jsx("button",{onClick:i,style:{color:"#64748b",fontSize:22,lineHeight:1,background:"none",border:"none",cursor:"pointer"},children:"â"})]}),t.jsx("div",{className:"flex items-center gap-2 px-6 py-3 flex-shrink-0",style:{borderBottom:"1px solid #334155",overflowX:"auto"},children:n.map(k=>{const q=c===k.id,$=k.full_name.split(" ").map(I=>I[0]).join("").slice(0,2).toUpperCase();return t.jsxs("button",{onClick:()=>{f(k.id),b(null),v(null)},className:"flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-colors flex-shrink-0",style:{background:q?"rgba(168,85,247,0.2)":"#1e293b",border:`2px solid ${q?"#a855f7":"#334155"}`,color:q?"#c084fc":"#94a3b8",boxShadow:q?"0 0 12px rgba(168,85,247,0.2)":"none",cursor:"pointer"},children:[t.jsx("div",{style:{width:28,height:28,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",fontSize:11,fontWeight:800,background:q?"rgba(168,85,247,0.4)":"#334155",color:q?"#e9d5ff":"#94a3b8"},children:$}),k.full_name]},k.id)})}),t.jsxs("div",{className:"flex items-center justify-between px-6 py-3 flex-shrink-0",style:{borderBottom:"1px solid #334155"},children:[t.jsx("button",{onClick:()=>{d(k=>k-1),b(null),v(null)},className:"px-3 py-1.5 text-sm font-medium rounded-lg",style:{background:"#334155",color:"#cbd5e1",border:"none",cursor:"pointer"},children:"â Prev Week"}),t.jsxs("div",{className:"text-sm font-bold text-white",children:[S[0].toLocaleDateString("en-US",{month:"long",day:"numeric"})," â ",S[6].toLocaleDateString("en-US",{month:"long",day:"numeric",year:"numeric"})]}),t.jsx("button",{onClick:()=>{d(k=>k+1),b(null),v(null)},className:"px-3 py-1.5 text-sm font-medium rounded-lg",style:{background:"#334155",color:"#cbd5e1",border:"none",cursor:"pointer"},children:"Next Week â"})]}),t.jsx("div",{className:"flex-1 overflow-auto px-6 py-4",children:h?t.jsx("div",{className:"text-center py-12",style:{color:"#64748b"},children:"Loading schedule..."}):t.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(7, 1fr)",gap:6},children:S.map(k=>{const q=Vd(k),$=gj(k),I=Vd(new Date)===q;return t.jsxs("div",{style:{borderRadius:12,overflow:"hidden",border:`1px solid ${I?"#a855f7":"#1e293b"}`,background:"#0f172a",boxShadow:I?"0 0 0 1px rgba(168,85,247,0.3)":"none"},children:[t.jsxs("div",{style:{padding:"8px 4px",textAlign:"center",background:$?"#451a03":"#1e293b",borderBottom:"1px solid #334155"},children:[t.jsx("div",{style:{fontSize:10,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.06em",color:I?"#c084fc":$?"#fbbf24":"#94a3b8"},children:k.toLocaleDateString("en-US",{weekday:"short"})}),t.jsx("div",{style:{fontSize:16,fontWeight:800,marginTop:2,color:I?"#e9d5ff":$?"#fbbf24":"#e2e8f0"},children:k.getDate()}),$&&t.jsx("div",{style:{fontSize:9,color:"#f59e0b",marginTop:1},children:"â¡ confirm w/ tech"})]}),t.jsx("div",{style:{padding:"4px",display:"flex",flexDirection:"column",gap:3},children:gV.map(B=>{const J=c?R(c,q,B):null,ae=fj(k,B),te=m===q&&A===B;return ae?t.jsx("div",{style:{padding:"4px 3px",borderRadius:6,textAlign:"center",background:"#1e293b"}
741,children:t.jsx("div",{style:{fontSize:10,color:"#475569"},children:Bo(B)})},B):J?t.jsxs("div",{title:J,style:{padding:"4px 3px",borderRadius:6,textAlign:"center",background:"rgba(239,68,68,0.12)",border:"1px solid rgba(239,68,68,0.25)"},children:[t.jsx("div",{style:{fontSize:10,color:"#f87171",fontWeight:600},children:Bo(B)}),t.jsx("div",{style:{fontSize:9,color:"#ef4444",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:J.split(" ")[0]})]},B):t.jsxs("button",{onClick:()=>N(q,B),style:{padding:"5px 3px",borderRadius:6,textAlign:"center",cursor:"pointer",background:te?"#166534":"#0f2a1a",border:`1px solid ${te?"#22c55e":"#1a3a2a"}`,boxShadow:te?"0 0 10px rgba(34,197,94,0.25)":"none"},children:[t.jsx("div",{style:{fontSize:10,color:te?"#4ade80":"#86efac",fontWeight:te?700:500},children:Bo(B)}),te&&t.jsx("div",{style:{fontSize:9,color:"#4ade80"},children:"â Selected"})]},B)})})]},q)})})}),t.jsxs("div",{className:"flex items-center justify-between px-6 py-4 flex-shrink-0",style:{background:"#0f172a",borderTop:"1px solid #334155"},children:[t.jsx("div",{children:m&&A!==null?t.jsxs("div",{className:"text-sm text-white",children:[t.jsx("span",{style:{color:"#4ade80",fontWeight:700},children:"â Selected: "}),z," · ",new Date(m+"T12:00:00").toLocaleDateString("en-US",{weekday:"long",month:"long",day:"numeric"})," · ",Bo(A),gj(new Date(m+"T12:00:00"))&&t.jsx("span",{className:"ml-2 text-xs font-medium px-2 py-0.5 rounded",style:{background:"#451a03",color:"#fbbf24"},children:"â¡ Weekend"})]}):t.jsx("div",{className:"text-sm",style:{color:"#475569"},children:"Click an open (green) slot to select a time"})}),t.jsxs("div",{className:"flex items-center gap-3",children:[m&&t.jsx("input",{type:"text",value:x,onChange:k=>_(k.target.value),placeholder:"Notes for tech (optional)",className:"px-3 py-2 rounded-lg text-sm text-white w-52",style:{background:"#1e293b",border:"1px solid #334155",outline:"none"}}),t.jsx("button",{onClick:i,className:"px-4 py-2 text-sm",style:{color:"#64748b",background:"none",border:"none",cursor:"pointer"},children:"Cancel"}),t.jsx("button",{onClick:O,disabled:!P,className:"px-5 py-2 text-sm font-bold text-white rounded-lg",style:{background:P?"linear-gradient(135deg, #a855f7, #7c3aed)":"#334155",border:"none",cursor:P?"pointer":"not-allowed",opacity:P?1:.4,boxShadow:P?"0 4px 20px rgba(168,85,247,0.35)":"none"},children:j?"Scheduling...":m&&A!==null?`ð
Confirm â ${new Date(m+"T12:00:00").toLocaleDateString("en-US",{month:"short",day:"numeric"})} at ${Bo(A)}`:"ð
Confirm Schedule"})]})]})]})})}function AV({job:e,onJobUpdated:n}){var R,N;const{profile:r}=Ee(),s=gt(),{data:i}=vu(),{mutateAsync:o}=MU(),{mutateAsync:a,isPending:l}=ng(),[d,c]=g.useState(!1),{data:f}=Ae({queryKey:["job_completion",e.id],queryFn:()=>C8(e.id),enabled:!!e.id,staleTime:15e3}),{data:p}=Ae({queryKey:["job_products",e.id],queryFn:async()=>{let O=e.source_quote_id||null;if(!O&&e.lead_id){const{data:M}=await w.from("quotes").select("id").eq("lead_id",e.lead_id).in("status",["accepted","signed"]).order("created_at",{ascending:!1}).limit(1).maybeSingle();O=(M==null?void 0:M.id)||null}if(!O)return[];const{data:z}=await w.from("document_line_items").select("product_catalog_id, description, quantity").eq("quote_id",O).order("sort_order",{ascending:!0});if(!(z!=null&&z.length))return[];const P=z.map(M=>M.product_catalog_id).filter(Boolean);let D=new Map;if(P.length>0){const{data:M}=await w.from("product_catalog").select("id, name, category, sku").in("id",P);D=new Map((M||[]).map(k=>[k.id,k]))}return z.filter(M=>M.product_catalog_id&&D.has(M.product_catalog_id)).map(M=>{const k=D.get(M.product_catalog_id);return{name:k.name,category:k.category,sku:k.sku,quantity:M.quantity||1}})},enabled:!!e.id,staleTime:6e4}),u=e.inventory_status,[h,y]=g.useState(!1),m=e.source_quote_id;async function b(){if(!h){y(!0);try{const O=await C$(e.id),{data:z}=await w.from("jobs").select("*").eq("id",e.id).single();if(z&&n(z),O.status==="short"){const P=O.results.filter(D=>D.result==="short").map(D=>D.product_name).join(", ");alert(`Reserved with shortages: ${P||"some items"}. Reorder request(s) created.`)}}catch(O){alert(`Reserve failed: ${O.message}`)}finally{y(!1)}}}const{data:A}=Ae({queryKey:["job_inventory_readiness",e.id],queryFn:()=>
741z$(e.id),enabled:!!e.id&&(u==="short"||u==="pending_check"||u==="reserved"),staleTime:15e3}),v=pV[e.status]||[],_=e.job_type!=="standard_install"&&(e.status==="scheduled"||e.status==="in_progress")?[...v,{label:"â Mark Complete",target:"complete",variant:"bg-emerald-500/15 text-emerald-400 border-emerald-500/30"}]:v,[j,C]=g.useState(!1);async function S(O){if(O==="complete"&&e.ticket_id){C(!0);return}try{const z=await a({jobId:e.id,newStatus:O,currentJob:e});n(z)}catch(z){alert(z.message)}}async function T(O){try{const z=await o({jobId:e.id,techId:O});n(z)}catch(z){console.error(z)}}async function L(O,z,P,D){const M=+O.slice(0,4),k=+O.slice(5,7),q=+O.slice(8,10),$=xV(M,k,q,Math.floor(z/60),z%60),I=e.job_type==="service",B=D.trim(),J={scheduled_at:$,duration_minutes:r3,assigned_technician_id:P};B&&(J.notes=e.notes?`${e.notes} 742${B}`:B),await w.from("jobs").update(J).eq("id",e.id);const ae=await a({jobId:e.id,newStatus:"scheduled",currentJob:{...e,scheduled_date:$,assigned_technician_id:P}});n(ae);const te=new Date(O+"T12:00:00").toLocaleDateString("en-US",{weekday:"long",month:"long",day:"numeric"});e.ticket_id&&await xU(e.ticket_id,`${te} at ${Bo(z)}`,{actor_id:(r==null?void 0:r.id)??"",actor_name:(r==null?void 0:r.full_name)??null}).catch(U=>console.error("ticket timeline write failed:",U)),!I&&e.phone_snapshot&&w.auth.getSession().then(({data:{session:U}})=>{U!=null&&U.access_token&&fetch("/api/automations/trigger",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${(U==null?void 0:U.access_token)||""}`},body:JSON.stringify({key:"install_scheduled_sms",to:e.phone_snapshot,entity_type:"lead",entity_id:e.lead_id,tenant_id:(r==null?void 0:r.tenant_id)||null,variables:{first_name:e.customer_name_snapshot.split(" ")[0],name:e.customer_name_snapshot.split(" ")[0],date:te,time:Bo(z)}})})}).catch(()=>{})}const E=u?cV[u]:null;return t.jsxs("div",{className:"space-y-4",children:[t.jsxs("button",{onClick:()=>s(`/installations/${e.id}`),className:"w-full text-left px-3 py-2.5 bg-accent/10 border border-accent/30 rounded-xl text-sm text-accent font-medium hover:bg-accent/20 transition-colors",children:["ð§ Open in Installations â",t.jsx("span",{className:"block text-xs text-muted mt-0.5",children:"View checklist, photos, handover forms, and completion status"})]}),_.length>0&&t.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:_.map(O=>{const z=O.target==="ready_to_schedule",P=O.target==="scheduled",D=z?"rgba(168,85,247,0.15)":P?"rgba(100,116,139,0.15)":"rgba(245,158,11,0.15)",M=z?"#c084fc":P?"#cbd5e1":"#fbbf24",k=z?"rgba(168,85,247,0.35)":P?"rgba(100,116,139,0.3)":"rgba(245,158,11,0.35)";return t.jsx("button",{onClick:()=>S(O.target),disabled:l,style:{fontSize:12,padding:"6px 12px",borderRadius:8,fontWeight:600,background:D,color:M,border:`1px solid ${k}`,cursor:l?"not-allowed":"pointer",opacity:l?.5:1},children:O.label},O.target)})}),e.status==="ready_to_schedule"&&t.jsxs("div",{style:{background:"rgba(168,85,247,0.06)",border:"1px solid rgba(168,85,247,0.25)",borderRadius:14,padding:"16px",display:"flex",alignItems:"center",justifyContent:"space-between",gap:12},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[t.jsx("span",{style:{fontSize:16},children:"ð"}),t.jsxs("div",{children:[t.jsx("div",{style:{color:"#c084fc",fontWeight:700,fontSize:14},children:"Ready to Schedule"}),t.jsx("div",{style:{color:"#94a3b8",fontSize:11,marginTop:2},children:"Call customer, pick a date and tech"})]})]}),t.jsx("button",{onClick:()=>c(!0),style:{padding:"10px 18px",borderRadius:10,fontSize:13,fontWeight:700,cursor:"pointer",background:"linear-gradient(135deg, #a855f7, #7c3aed)",color:"#fff",border:"none",boxShadow:"0 4px 16px rgba(168,85,247,0.35)",flexShrink:0},children:"ð Open Calendar"})]}),j&&e.ticket_id&&t.jsx(lV,{job:e,ticketId:e.ticket_id,ticketNumber:((R=e.ticket)==null?void 0:R.ticket_number)??"",onClose:()=>C(!1),onDone:O=>{C(!1),n(O)}}),d&&i&&i.length>0&&t.jsx(bV,{currentJobId:e.id,techs:i,preselectedTechId:e.assigned_technician_id||null,customerName:e.customer_name_snapshot,title:e.job_type==="service"?"Schedule Service Visit":void 0,onConfirm:async(O,z,P,D)=>{await L(O,z,P,D),c(!1)},onCancel:()=>c(!1)}),p&&p.length>0&&t.jsxs("div",{style:{background:"#162232",border:"1px solid #1e3a4f",borderRadius:14,overflow:"hidden"},children:[t.jsxs("div",{style:{padding:"10px 14px",borderBottom:"1px solid #1e3a4f",dis
742play:"flex",alignItems:"center",gap:8},children:[t.jsx("span",{style:{fontSize:14},children:"ð¦"}),t.jsx("span",{style:{color:"#e2e8f0",fontWeight:700,fontSize:13},children:"Products Being Installed"}),t.jsxs("span",{style:{color:"#4ade80",fontSize:11,fontWeight:600},children:[p.length," item",p.length!==1?"s":""]})]}),p.map((O,z)=>t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"8px 14px",borderBottom:z<p.length-1?"1px solid rgba(255,255,255,0.04)":"none"},children:[t.jsxs("div",{children:[t.jsx("div",{style:{color:"#e2e8f0",fontSize:13,fontWeight:600},children:O.name}),t.jsxs("div",{style:{display:"flex",gap:8,marginTop:2},children:[O.category&&t.jsx("span",{style:{color:"#64748b",fontSize:11},children:dV[O.category]||O.category}),O.sku&&t.jsx("span",{style:{color:"#475569",fontSize:11,fontFamily:"monospace"},children:O.sku})]})]}),t.jsxs("span",{style:{color:"#94a3b8",fontSize:12,fontWeight:600},children:["à ",O.quantity]})]},z))]}),m&&u!=="reserved"&&u!=="ready"&&t.jsx("button",{onClick:b,disabled:h,style:{width:"100%",padding:"10px 14px",borderRadius:12,background:h?"rgba(100,116,139,0.15)":"rgba(168,85,247,0.15)",border:"1px solid rgba(168,85,247,0.35)",color:h?"#94a3b8":"#c084fc",fontSize:13,fontWeight:600,cursor:h?"default":"pointer"},children:h?"Reservingâ¦":"ð¦ Reserve Stock for Job"}),E&&u!=="not_required"&&u!=="n_a"&&t.jsxs("div",{style:{background:E.bg,border:`1px solid ${E.border}`,borderRadius:14,overflow:"hidden"},children:[t.jsx("div",{style:{padding:"12px 14px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[t.jsx("span",{style:{fontSize:14},children:E.icon}),t.jsxs("div",{children:[t.jsx("div",{style:{color:E.color,fontWeight:700,fontSize:13},children:E.label}),u==="short"&&t.jsx("div",{style:{color:"#f87171",fontSize:11,marginTop:2},children:"Cannot start installation until stock arrives"}),u==="pending_check"&&t.jsx("div",{style:{color:"#fbbf24",fontSize:11,marginTop:2},children:"Inventory check in progress"}),u==="reserved"&&t.jsx("div",{style:{color:"#4ade80",fontSize:11,marginTop:2},children:"All materials reserved â ready to install"})]})]})}),A&&A.items.length>0&&u==="short"&&t.jsxs("div",{style:{borderTop:`1px solid ${E.border}`,padding:"10px 14px"},children:[t.jsx("div",{style:{fontSize:11,fontWeight:700,color:"#94a3b8",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:8},children:"Material Status"}),A.items.map((O,z)=>t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"6px 0",borderBottom:z<A.items.length-1?"1px solid rgba(255,255,255,0.04)":"none"},children:[t.jsx("div",{style:{color:"#e2e8f0",fontSize:12},children:O.product_name}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[O.reserved?t.jsx("span",{style:{fontSize:11,color:"#4ade80",fontWeight:600},children:"â
Reserved"}):t.jsxs("span",{style:{fontSize:11,color:"#f87171",fontWeight:600},children:["Short ",O.shortage_amount>0?`(need ${O.shortage_amount})`:""]}),O.reorder_request_id&&t.jsx("span",{style:{fontSize:10,padding:"1px 6px",borderRadius:8,background:"rgba(251,191,36,0.1)",color:"#fbbf24",border:"1px solid rgba(251,191,36,0.2)"},children:"On Order"})]})]},z))]}),A&&A.items.length>0&&u==="reserved"&&t.jsx("div",{style:{borderTop:`1px solid ${E.border}`,padding:"10px 14px"},children:A.items.map((O,z)=>t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"4px 0"},children:[t.jsx("span",{style:{color:"#cbd5e1",fontSize:12},children:O.product_name}),t.jsxs("span",{style:{fontSize:11,color:"#4ade80",fontWeight:600},children:["â
à ",O.quantity_needed]})]},z))})]}),f&&f.total>0&&e.status!=="complete"&&t.jsxs("div",{className:"border border-border rounded-xl p-3 space-y-2",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx("span",{className:"text-xs font-bold text-slate-300 uppercase tracking-wide",children:"Checklist Progress"}),t.jsx("span",{className:`text-xs px-2 py-0.5 rounded-full font-semibold ${f.allComplete?"bg-green/20 text-green":"bg-amber/20 text-amber"}`,children:f.allComplete?"Complete":`${f.pct}%`})]}),t.jsxs("div",{className:"text-xs text-muted",children:[f.completed,"/",f.total," items complete",f.verified>0&&` · ${f.verified} verified`]})]}),e.status==="complete"&&t.jsxs("div",{className:"bg-green/10 border border-green/20 rounded-xl p-3 text-center",children:[t.jsx("div",{className:"text-green font-bold text-sm",children:"â
Job Complete"}),t.jsxs("div",{className:"text-xs text-muted mt-1",children:["Completed ",zm(e.completed_at)]}),e.ready_for_customer_conversion&&t.jsx("div",{className:"text-xs text-accent mt-1",children:"Ready for customer conversion"})]}),t.jsx(Vr,{label:"Customer",value:e.customer_name_snapshot}),t.jsx(Vr,{label:"Phone",value:e.phone_snapshot}),e.email_snapshot&&t.jsx(Vr,{label:"Email",value:e.email_snapshot}),t.jsx(Vr,{label:"Service Address",value:e.service_address_snapshot}),t.jsx(Vr,{label:"System Type",value:lo[e.system_type]}),e.equipment_summary&&t.jsx(Vr,{label:"Equipment",value:e.equipment_summary}),e.quote_total_snapshot&&t.jsx(Vr,{label:"Quote Total",value:uV(e.quote_total_snapshot)}),e.payment_method_snapshot&&t.jsx(Vr,{label:"Payment",value:e.payment_method_snapshot}),t.jsx(Vr,{label:"Scheduled",value:e.scheduled_date||"Not set"}),e.started_at&&t.jsx(Vr,{label:"Started",value:zm(e.started_at)}),e.serial_number&&t.jsx(Vr,{label:"Serial Number",value:e.serial_number}),t.jsxs("div",{children:[t.jsx("div",{className:"text-xs font-semibold text-muted uppercase tracking-wide mb-1.5",children:"Assigned Technician"}),i?t.jsxs("select",{value:e.assigned_technician_id||"",onChange:O=>O.target.value&&T(O.target.value),className:"w-full bg-card border border-border rounded-lg px-3 py-2 text-sm text-slate-200 focus:outline-none focus:border-accent",children:[t.jsx("option",{value:"",children:"â Unassigned â"}),i.map(O=>t.jsx("option",{value:O.id,children:O.full_name},O.id))]}):t.jsx("div",{className:"text-sm text-slate-300",children:((N=e.assigned_technician)==null?void 0:N.full_name)||"Unassigned"}),e.assigned_at&&t.jsxs("div",{className:"text-xs text-muted mt-1",children:["Assigned ",zm(e.assigned_at)]})]}),e.notes&&t.jsxs("div",{children:[t.jsx("div",{className:"text-xs font-semibold text-muted uppercase tracking-wide mb-1.5",children:"Notes"}),t.jsx("div",{className:"text-sm text-slate-300 bg-card border border-border rounded-lg p-3 whitespace-pre-wrap",children:e.notes})]}),t.jsx(ru,{entityType:"job",entityId:e.id,section:"field_service",visibilityDefault:"all",visibilitySelectorMode:"hidden",title:"Field Service Notes"})]})}function Vr({label:e,value:n}){return t.jsxs("div",{children:[t.jsx("div",{className:"text-xs font-semibold text-muted uppercase tracking-wide mb-0.5",children:e}),t.jsx("div",{className:"text-sm text-slate-300",children:n})]})}
742const vV={job_created:{icon:"â",color:"bg-accent"},status_change:{icon:"â",color:"bg-purple-500"},tech_assigned:{icon:"ð¤",color:"bg-orange-500"},checklist_item_completed:{icon:"â",color:"bg-green-500"},tech_verification:{icon:"â ",color:"bg-emerald-500"},photo_uploaded:{icon:"ð·",color:"bg-cyan-500"},handover_submitted:{icon:"ð",color:"bg-sky-500"},consent_submitted:{icon:"âï¸",color:"bg-amber-500"},job_completed:{icon:"ð",color:"bg-green-500"},note_added:{icon:"ð",color:"bg-slate-500"}};function _V(e){const n=new Date(e),r=Math.floor((Date.now()-n.getTime())/6e4);return r<1?"Just now":r<60?`${r}m ago`:r<1440?`${Math.floor(r/60)}h ago`:n.toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function s3({jobId:e}){const{data:n,isLoading:r}=IU(e);return r?t.jsx("p",{className:"text-sm text-muted text-center py-8",children:"Loading activity..."}):n!=null&&n.length?t.jsx("div",{className:"space-y-0",children:n.map((s,i)=>{const o=vV[s.event_type]||{icon:"â¢",color:"bg-muted"};return t.jsxs("div",{className:"flex gap-3 relative",children:[i<n.length-1&&t.jsx("div",{className:"absolute left-[11px] top-7 bottom-0 w-px bg-border"}),t.jsx("div",{className:`w-6 h-6 rounded-full ${o.color} flex items-center justify-center flex-shrink-0 text-xs text-white z-10`,children:o.icon}),t.jsxs("div",{className:"flex-1 pb-4 min-w-0",children:[t.jsxs("div",{className:"flex items-start justify-between gap-2",children:[t.jsx("div",{className:"text-sm text-slate-200 font-medium",children:s.title}),t.jsx("div",{className:"text-xs text-muted whitespace-nowrap flex-shrink-0",children:_V(s.created_at)})]}),s.from_status&&s.to_status&&t.jsxs("div",{className:"text-xs text-muted mt-0.5",children:[s.from_status.replace(/_/g," ")," â ",s.to_status.replace(/_/g," ")]}),s.actor_name&&t.jsxs("div",{className:"text-xs text-muted mt-0.5",children:["by ",s.actor_name]})]})]},s.id)})}):t.jsx("p",{className:"text-sm text-muted text-center py-8",children:"No activity yet."})}function jV({jobId:e,customerName:n,onClose:r,onDone:s}){var _;const[i,o]=g.useState(""),[a,l]=g.useState(""),[d,c]=g.useState(""),[f,p]=g.useState(!1),[u,h]=g.useState(null),[y,m]=g.useState(null),[b,A]=g.useState(null),v=i.trim().toLowerCase()===n.trim().toLowerCase();async function x(){if(!(!v||f)){p(!0),h(null),m(null);try{const{data:{session:j}}=await w.auth.getSession();if(!j)throw new Error("Not authenticated");const C=await fetch("/api/jobs/cancel-and-refund",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${j.access_token}`},body:JSON.stringify({job_id:e,reason:a.trim()||void 0,amount:d.trim()?Number(d):void 0})}),S=await C.json();if(!C.ok){S.stripe_refund_id&&S.action_required?m(`REFUND ISSUED (${S.stripe_refund_id}) BUT THE DATABASE WAS NOT UPDATED. 743 744${S.action_required} 745 746Detail: ${S.detail}`):h(S.error+(S.detail?` â ${S.detail}`:""));return}A(S)}catch(j){h(j.message)}finally{p(!1)}}}if(y)return t.jsxs(Nm,{onClose:()=>{s(),r()},title:"â Manual reconciliation required",children:[t.jsx("pre",{style:{whiteSpace:"pre-wrap",background:"rgba(239,68,68,0.12)",border:"1px solid rgba(239,68,68,0.5)",borderRadius:8,padding:16,color:"#fca5a5",fontSize:13,lineHeight:1.6},children:y}),t.jsx("button",{onClick:()=>{s(),r()},style:Ep("#dc2626"),children:"I understand"})]});if(b){const j=b.unwind||{};return t.jsxs(Nm,{onClose:()=>{s(),r()},title:"Job cancelled and refunded",children:[t.jsx(yi,{label:"Refund",value:`$${(_=b.refunded_amount)==null?void 0:_.toFixed(2)} · ${b.stripe_refund_id}`}),t.jsx(yi,{label:"Invoice",value:j.invoice||"â"}),t.jsx(yi,{label:"Payment",value:j.payment||"â"}),t.jsx(yi,{label:"Inventory",value:j.inventory||"â"}),t.jsx(yi,{label:"Service plan",value:j.service_plan||"â",warn:String(j.service_plan||"").startsWith("SKIPPED")}),t.jsx(yi,{label:"Plan components",value:j.service_plan_components!=null?String(j.service_plan_components):"â"}),t.jsx(yi,{label:"Lead",value:j.lead||"â"}),t.jsx(yi,{label:"Reorders cancelled",value:String(j.reorders_cancelled??0)}),String(j.service_plan||"").startsWith("SKIPPED")&&t.jsx("p",{style:{color:"#fbbf24",fontSize:12,marginTop:12},children:"An active service plan was left untouched because it did not originate from this job's quote. Cancel it manually if that was intended."}),t.jsx("button",{onClick:()=>{s(),r()},style:Ep("#16a34a"),children:"Done"})]})}return t.jsxs(Nm,{onClose:r,title:"Cancel job & refund customer",children:[t.jsxs("p",{style:{color:"#fca5a5",fontSize:13,lineHeight:1.6,marginBottom:16},children:["This issues a ",t.jsx("strong",{children:"real Stripe refund"})," and cannot be undone from this screen. It will also void the invoice, release reserved stock, cancel the service plan created by this job's quote, and mark the lead lost."]}),t.jsx("label",{style:Rm,children:"Reason (optional)"}),t.jsx("input",{value:a,onChange:j=>l(j.target.value),placeholder:"Customer cancelled within 3-day window",
746style:Em,disabled:f}),t.jsx("label",{style:Rm,children:"Partial refund amount (leave blank for full)"}),t.jsx("input",{value:d,onChange:j=>c(j.target.value),placeholder:"Full amount",inputMode:"decimal",style:Em,disabled:f}),t.jsxs("label",{style:Rm,children:["Type ",t.jsx("strong",{style:{color:"#f8fafc"},children:n})," to confirm"]}),t.jsx("input",{value:i,onChange:j=>o(j.target.value),style:{...Em,borderColor:v?"rgba(34,197,94,0.6)":"rgba(148,163,184,0.3)"},disabled:f,autoComplete:"off"}),u&&t.jsx("p",{style:{color:"#fca5a5",fontSize:13,marginTop:12},children:u}),t.jsxs("div",{style:{display:"flex",gap:8,marginTop:20},children:[t.jsx("button",{onClick:r,disabled:f,style:Ep("rgba(148,163,184,0.2)"),children:"Cancel"}),t.jsx("button",{onClick:x,disabled:!v||f,style:{...Ep("#dc2626"),opacity:v&&!f?1:.4,cursor:v&&!f?"pointer":"not-allowed"},children:f?"Refundingâ¦":"Refund & cancel"})]})]})}function Nm({title:e,children:n,onClose:r}){return t.jsx("div",{onClick:r,style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.7)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},children:t.jsxs("div",{onClick:s=>s.stopPropagation(),style:{background:"#0f172a",border:"1px solid rgba(148,163,184,0.2)",borderRadius:12,padding:24,width:480,maxWidth:"90vw",maxHeight:"85vh",overflowY:"auto"},children:[t.jsx("h3",{style:{color:"#f8fafc",margin:"0 0 16px",fontSize:18},children:e}),n]})})}function yi({label:e,value:n,warn:r}){return t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",padding:"8px 0",borderBottom:"1px solid rgba(148,163,184,0.1)"},children:[t.jsx("span",{style:{color:"#94a3b8",fontSize:13},children:e}),t.jsx("span",{style:{color:r?"#fbbf24":"#e2e8f0",fontSize:13,fontFamily:"monospace"},children:n})]})}const Rm={display:"block",color:"#94a3b8",fontSize:12,marginTop:14,marginBottom:6},Em={width:"100%",padding:"9px 12px",background:"rgba(15,23,42,0.8)",border:"1px solid rgba(148,163,184,0.3)",borderRadius:6,color:"#f8fafc",fontSize:14},Ep=e=>({flex:1,padding:"10px 16px",background:e,border:"none",borderRadius:6,color:"#fff",fontSize:14,fontWeight:500,cursor:"pointer",marginTop:16});function wV(e){return e.split(" ").map(n=>n[0]).join("").slice(0,2).toUpperCase()}const SV={ready_to_schedule:{background:"rgba(96,165,250,0.18)",color:"#93c5fd",border:"1px solid rgba(96,165,250,0.5)"},scheduled:{background:"rgba(34,211,238,0.15)",color:"#22d3ee",border:"1px solid rgba(34,211,238,0.4)"},waiting_for_stock:{background:"rgba(245,158,11,0.15)",color:"#fbbf24",border:"1px solid rgba(245,158,11,0.4)"},in_progress:{background:"rgba(74,222,128,0.15)",color:"#4ade80",border:"1px solid rgba(74,222,128,0.4)"},complete:{background:"rgba(74,222,128,0.2)",color:"#86efac",border:"1px solid rgba(74,222,128,0.5)"},cancelled:{background:"rgba(239,68,68,0.15)",color:"#fca5a5",border:"1px solid rgba(239,68,68,0.4)"}};function mj({job:e,onClose:n}){const{user:r,profile:s}=Ee(),[i,o]=g.useState(e),[a,l]=g.useState("overview"),d=rt(),{mutateAsync:c}=ng(),[f,p]=g.useState(!1),[u,h]=g.useState(!1),[y,m]=g.useState(!1),[b,A]=g.useState(""),[v,x]=g.useState(!1),[_,j]=g.useState(""),[C,S]=g.useState([]),[T,L]=g.useState(null);g.useEffect(()=>{w.from("message_templates").select("*").eq("channel","sms").eq("is_active",!0).order("key").then(({data:D})=>S(D||[]))},[]);const E=g.useCallback(D=>{o(M=>({...M,...D})),d.invalidateQueries({queryKey:et.board()}),d.invalidateQueries({queryKey:et.activity(D.id)})},[d]),R=i.job_type==="service",N=R&&["super_admin","admin","frontdesk","salesrep"].includes((s==null?void 0:s.role)??"")&&i.status!=="cancelled"&&i.status!=="complete";async function O(){if(f||!r)return;const D=i.customer_name_snapshot||"this customer";if(confirm(`Cancel this service visit for ${D}? 747 748Nothing is refunded or charged, and the customer is not texted.`)){p(!0);try{if(i.ticket_id){if(await yU(i.ticket_id,i.id,{actor_id:r.id,actor_name:(s==null?void 0:s.full_name)??null})===0)throw new Error("The visit was not cancelled. It may already be finished. Refresh and check.")}else await c({jobId:i.id,newStatus:"cancelled",currentJob:i});d.invalidateQueries({queryKey:et.board()}),n()}catch(M){alert((M==null?void 0:M.message)||"Cancel failed")}finally{p(!1)}}}async function z(){if(!(!b.trim()||!i.phone_snapshot)){x(!0),j("");try{const D=await fetch("/api/openphone/send-sms",{method:"POST",headers:await At(),body:JSON.stringify({to:i.phone_snapshot,body:b.trim(),entity_type:"job",entity_id:i.id,sent_by:(s==null?void 0:s.id)??null,tenant_id:(s==null?void 0:s.tenant_id)??null})});if(!D.ok){const M=await D.json().catch(()=>({}));throw new Error(M.error||`Send failed (${D.status})`)}h(!1),A("")}catch(D){j((D==null?void 0:D.message)||"Send failed")}finally{x(!1)}}}const P=SV[i.status]||{background:"rgba(100,116,139,0.15)",color:"#cbd5e1",border:"1px solid rgba(100,116,139,0.3)"};return t.jsxs("div",{className:"fixed inset-0 z-40 flex justify-end",children:[t.jsx("div",{className:"absolute inset-0 bg-black/40",onClick:n}),t.jsxs("div",{className:"relative w-full max-w-lg bg-surface border-l border-border h-full overflow-y-auto shadow-2xl flex flex-col",children:[t.jsxs("div",{className:"flex items-start justify-between p-5 border-b border-border flex-shrink-0",children:[t.jsxs("div",{className:"flex items-start gap-3",children:[t.jsx("div",{className:"w-10 h-10 rounded-full bg-cyan/20 text-cyan font-bold flex items-center justify-center text-sm",children:wV(i.customer_name_snapshot)}),t.jsxs("div",{children:[t.jsx("h2",{className:"text-lg font-bold text-white",children:i.customer_name_snapshot}),t.jsx("div",{className:"text-sm text-muted",children:i.phone_snapshot}),t.jsx("div",{className:"text-xs text-muted mt-0.5",children:lo[i.system_type]})]})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[N&&t.jsx("button",{onClick:O,disabled:f,style:{padding:"5px 10px",borderRadius:8,fontSize:11,fontWeight:600,cursor:f?"not-allowed":"pointer",opacity:f?.5:1,background:"rgba(239,68,68,0.1)",color:"#f87171",border:"1px solid rgba(239,68,68,0.3)"},children:f?"Cancellingâ¦":"Cancel visit"}),!R&&["super_admin","admin"].includes(s==null?void 0:s.role)&&i.status!=="c
748ancelled"&&i.customer_name_snapshot&&t.jsx("button",{onClick:()=>m(!0),style:{padding:"5px 10px",borderRadius:8,fontSize:11,fontWeight:600,cursor:"pointer",background:"rgba(239,68,68,0.1)",color:"#f87171",border:"1px solid rgba(239,68,68,0.3)"},children:"Cancel & refund"}),i.phone_snapshot&&t.jsx("button",{onClick:()=>{A(`Hi ${i.customer_name_snapshot.split(" ")[0]}, `),j(""),h(!0)},style:{padding:"5px 10px",borderRadius:8,fontSize:11,fontWeight:600,cursor:"pointer",background:"rgba(34,197,94,0.1)",color:"#22c55e",border:"1px solid rgba(34,197,94,0.3)"},children:"ð¬ Text"}),t.jsx("div",{style:{padding:"4px 10px",borderRadius:20,fontSize:11,fontWeight:700,whiteSpace:"nowrap",...P},children:nd[i.status]}),t.jsx("button",{onClick:n,className:"text-muted hover:text-white text-xl leading-none ml-1",children:"â"})]})]}),t.jsx("div",{className:"flex border-b border-border flex-shrink-0",children:["overview","activity"].map(D=>t.jsx("button",{onClick:()=>l(D),className:`flex-1 py-2.5 text-xs font-semibold uppercase tracking-wide transition-colors ${a===D?"text-accent border-b-2 border-accent":"text-muted hover:text-slate-300"}`,children:D},D))}),t.jsxs("div",{className:"flex-1 overflow-y-auto p-5",children:[a==="overview"&&t.jsx(AV,{job:i,onJobUpdated:E}),a==="activity"&&t.jsx(s3,{jobId:i.id})]}),y&&!R&&i.customer_name_snapshot&&t.jsx(jV,{jobId:i.id,customerName:i.customer_name_snapshot,onClose:()=>m(!1),onDone:()=>{d.invalidateQueries({queryKey:et.board()}),n()}}),u&&t.jsx("div",{className:"absolute inset-0 bg-black/60 flex items-center justify-center p-4 z-20",children:t.jsxs("div",{className:"bg-card border border-border rounded-2xl w-full max-w-sm p-5 shadow-2xl",children:[t.jsx("h3",{className:"font-bold text-white mb-1",children:"Send Text"}),t.jsxs("p",{className:"text-xs text-muted mb-4",children:["To: ",i.phone_snapshot]}),C.length>0&&t.jsxs("div",{style:{marginBottom:10},children:[t.jsx("label",{className:"block text-xs font-semibold text-muted uppercase tracking-wide mb-1.5",children:"Use Template"}),t.jsxs("select",{defaultValue:"",onChange:D=>{var q;const M=C.find($=>$.id===D.target.value);if(!M)return;const k=((q=i.customer_name_snapshot)==null?void 0:q.split(" ")[0])||"";A(hh(M.body,{first_name:k,name:k,rep_name:(s==null?void 0:s.full_name)||"Your Zenith Tech",company_name:"Zenith Pure Solutions",review_url:"",visit_date:"",install_date:i.scheduled_date?new Date(i.scheduled_date+"T12:00:00").toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric"}):""})),D.target.value=""},className:"w-full bg-surface border border-border rounded-lg px-3 py-2.5 text-sm text-slate-200 focus:outline-none focus:border-accent",children:[t.jsx("option",{value:"",children:"â Pick a template â"}),C.map(D=>t.jsx("option",{value:D.id,children:D.label||D.key},D.id))]})]}),t.jsx("label",{className:"block text-xs font-semibold text-muted uppercase tracking-wide mb-1.5",children:"Message"}),t.jsx("textarea",{value:b,onChange:D=>A(D.target.value),placeholder:"Type your message...",rows:4,autoFocus:!0,className:"w-full bg-surface border border-border rounded-lg px-3 py-2.5 text-sm text-slate-200 placeholder-muted focus:outline-none focus:border-accent resize-none"}),t.jsxs("div",{className:"text-right text-xs text-muted mt-1",children:[b.length," chars"]}),_&&t.jsx("div",{style:{marginTop:10,padding:"8px 10px",borderRadius:8,background:"rgba(239,68,68,0.1)",border:"1px solid rgba(239,68,68,0.3)",color:"#f87171",fontSize:12},children:_}),t.jsxs("div",{className:"flex gap-3 mt-4",children:[t.jsx("button",{onClick:()=>{h(!1),A(""),j("")},className:"flex-1 py-2 text-sm text-muted hover:text-white transition-colors",children:"Cancel"}),t.jsx("button",{onClick:z,disabled:v||!b.trim(),className:"flex-1 py-2 font-semibold rounded-lg text-sm transition-colors disabled:opacity-50",style:{background:"#22c55e",color:"#fff"},children:v?"Sendingâ¦":"Send Text ð¬"})]})]})})]})]})}const kV={ready_to_schedule:"border-t-purple-500",scheduled:"border-t-accent",waiting_for_stock:"border-t-amber",in_progress:"border-t-cyan",complete:"border-t-green",cancelled:"border-t-red-500"},CV={ready_to_schedule:"bg-purple-500",scheduled:"bg-accent",waiting_for_stock:"bg-amber",in_progress:"bg-cyan",complete:"bg-green",cancelled:"bg-red-500"},TV=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],i3=["January","February","March","April","May","June","July","August","September","October","November","December"];function zV({allJobs:e}){const n=new Date,r=u=>String(u).padStart(2,"0"),s=`${n.getFullYear()}-${r(n.getMonth()+1)}-${r(n.getDate())}
748`,i=e.filter(u=>u.status==="scheduled"),o=e.filter(u=>u.status==="in_progress"),a=e.filter(u=>u.status==="waiting_for_stock"),l=e.filter(u=>u.status==="complete"),d=e.filter(u=>{var h;return((h=u.scheduled_date)==null?void 0:h.split("T")[0])===s}),c=d.filter(u=>u.status==="complete"),f=e.filter(u=>!u.assigned_technician_id&&u.status==="scheduled"),p=[{label:"Scheduled",value:i.length,icon:"ð ",color:"#60a5fa",bg:"rgba(96,165,250,0.1)",border:"rgba(96,165,250,0.2)"},{label:"In Progress",value:o.length,icon:"â¡",color:"#22d3ee",bg:"rgba(34,211,238,0.1)",border:"rgba(34,211,238,0.2)"},{label:"Waiting Stock",value:a.length,icon:"ð¦",color:"#f59e0b",bg:"rgba(245,158,11,0.1)",border:"rgba(245,158,11,0.2)"},{label:"Complete",value:l.length,icon:"â ",color:"#4ade80",bg:"rgba(74,222,128,0.1)",border:"rgba(74,222,128,0.2)"},{label:"Today's Jobs",value:d.length,icon:"ðï¸",color:"#a78bfa",bg:"rgba(167,139,250,0.1)",border:"rgba(167,139,250,0.2)"},{label:"Done Today",value:c.length,icon:"ð",color:"#34d399",bg:"rgba(52,211,153,0.1)",border:"rgba(52,211,153,0.2)"}];return t.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(6, 1fr)",gap:10,marginBottom:16,flexShrink:0},children:p.map(u=>t.jsxs("div",{style:{background:u.bg,border:`1px solid ${u.border}`,borderRadius:12,padding:"12px 14px",display:"flex",flexDirection:"column",gap:4,position:"relative",overflow:"hidden"},children:[t.jsx("div",{style:{position:"absolute",top:-12,right:-12,width:50,height:50,borderRadius:"50%",background:`${u.color}20`,pointerEvents:"none"}}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[t.jsx("span",{style:{fontSize:14},children:u.icon}),t.jsx("span",{style:{fontSize:10,fontWeight:700,color:"#475569",textTransform:"uppercase",letterSpacing:"0.07em"},children:u.label})]}),t.jsx("div",{style:{fontSize:28,fontWeight:900,color:u.color,lineHeight:1,letterSpacing:"-0.02em"},children:u.value}),u.label==="Scheduled"&&f.length>0&&t.jsxs("div",{style:{fontSize:10,color:"#f59e0b",fontWeight:600},children:["â ",f.length," unassigned"]}),u.label==="Today's Jobs"&&c.length>0&&d.length>0&&t.jsxs("div",{style:{fontSize:10,color:"#64748b",fontWeight:500},children:[c.length,"/",d.length," done"]})]},u.label))})}function NV({allJobs:e}){const n=new Date,r=p=>String(p).padStart(2,"0"),s=`${n.getFullYear()}-${r(n.getMonth()+1)}-${r(n.getDate())}`,i=e.filter(p=>p.status==="in_progress").length,o=e.filter(p=>p.status==="scheduled").length,a=e.filter(p=>p.status==="complete").length,l=e.filter(p=>{var u;return((u=p.scheduled_date)==null?void 0:u.split("T")[0])===s}).length,d=e.filter(p=>{var u;return p.status==="complete"&&((u=p.scheduled_date)==null?void 0:u.split("T")[0])===s}).length,c=e.filter(p=>!p.assigned_technician_id&&p.status==="scheduled").length,f=[{label:"Scheduled",value:o,color:"#60a5fa",icon:"ð "},{label:"In Progress",value:i,color:"#22d3ee",icon:"â¡"},{label:"Today",value:l,color:"#a78bfa",icon:"ðï¸",sub:d>0?`${d} done`:void 0},{label:"Complete",value:a,color:"#4ade80",icon:"â ",sub:c>0?`â ${c} unassigned`:void 0}];return t.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(4, 1fr)",gap:8,marginBottom:12,flexShrink:0},children:f.map(p=>t.jsxs("div",{style:{background:`${p.color}10`,border:`1px solid ${p.color}25`,borderRadius:10,padding:"10px 10px 8px"},children:[t.jsxs("div",{style:{fontSize:10,color:"#475569",fontWeight:700,textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:4},children:[p.icon," ",p.label]}),t.jsx("div",{style:{fontSize:24,fontWeight:900,color:p.color,lineHeight:1},children:p.value}),p.sub&&t.jsx("div",{style:{fontSize:10,color:"#f59e0b",fontWeight:600,marginTop:3},children:p.sub})]},p.label))})}function RV({date:e,isCurrentMonth:n,isToday:r,jobs:s,onJobClick:i,onDayClick:o,selected:a}){const l=s.filter(p=>p.status==="scheduled"),d=s.filter(p=>p.status==="in_progress"),c=s.filter(p=>p.status==="waiting_for_stock"),f=s.filter(p=>p.status==="complete");return t.jsxs("div",{onClick:()=>o(e),className:` 749 min-h-[110px] rounded-xl border p-2 cursor-pointer transition-all 750 ${n?"bg-surface border-border":"bg-surface/30 border-border/30"} 751 ${r?"ring-2 ring-accent border-accent":""} 752 ${a?"ring-2 ring-cyan border-cyan":""} 753 ${s.length>0?"hover:border-accent/60":"hover:border-border/60"} 754 `,children:[t.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[t.jsx("span",{className:` 755 text-xs font-bold w-6 h-6 flex items-center justify-center rounded-full 756 ${r?"bg-accent text-white":n?"text-slate-300":"text-muted"} 757 `,children:e.getDate()}),s.length>0&&t.jsxs("span",{className:"text-xs text-muted font-semibold",children:[s.length," job",s.length!==1?"s":""]})]}),s.length>0&&t.jsxs("div",{className:"flex gap-1 mb-1.5 flex-wrap",children:[l.length>0&&t.jsxs("span",{className:"text-xs px-1.5 py-0.5 rounded bg-accent/20 text-accent font-semibold",children:[l.length," sched"]}),d.length>0&&t.jsxs("span",{className:"text-xs px-1.5 py-0.5 rounded bg-cyan/20 text-cyan font-semibold",children:[d.length," active"]}),c.length>0&&t.jsxs("span",{className:"text-xs px-1.5 py-0.5 rounded bg-amber/20 text-amber font-semibold",children:[c.length," wait"]}),f.length>0&&t.jsxs("span",{className:"text-xs px-1.5 py-0.5 rounded bg-green/20 text-green font-semibold",children:[f.length," done"]})]}),t.jsxs("div",{className:"space-y-1",children:[s.slice(0,3).map(p=>t.jsxs("div",{onClick:u=>{u.stopPropagation(),i(p)},className:"flex items-center gap-1.5 bg-card rounded px-1.5 py-1 hover:bg-card/80 transition-colors cursor-pointer group",children:[t.jsx("span",{className:`w-1.5 h-1.5 rounded-full flex-shrink-0 ${CV[p.status]}`}),t.jsx("span",{className:"text-xs text-slate-300 truncate group-hover:text-white transition-colors",children:p.customer_name_snapshot})]}
757,p.id)),s.length>3&&t.jsxs("div",{className:"text-xs text-muted pl-1",children:["+",s.length-3," more"]})]}),s.length===0&&n&&t.jsx("div",{className:"text-xs text-muted/40 mt-2 text-center",children:"open"})]})}function EV({date:e,jobs:n,onJobClick:r,onClose:s}){if(!e)return null;const i=e.toLocaleDateString("en-US",{weekday:"long",month:"long",day:"numeric",year:"numeric"}),o={ready_to_schedule:n.filter(a=>a.status==="ready_to_schedule"),scheduled:n.filter(a=>a.status==="scheduled"),waiting_for_stock:n.filter(a=>a.status==="waiting_for_stock"),in_progress:n.filter(a=>a.status==="in_progress"),complete:n.filter(a=>a.status==="complete"),cancelled:n.filter(a=>a.status==="cancelled")};return t.jsxs("div",{className:"w-80 flex-shrink-0 bg-surface border border-border rounded-xl overflow-hidden flex flex-col",children:[t.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-border",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-bold text-white",children:i}),t.jsx("div",{className:"text-xs text-muted mt-0.5",children:n.length===0?"No installs scheduled":`${n.length} job${n.length!==1?"s":""}`})]}),t.jsx("button",{onClick:s,className:"text-muted hover:text-white text-lg leading-none",children:"Ã"})]}),t.jsx("div",{className:"overflow-y-auto flex-1 p-3 space-y-4",children:n.length===0?t.jsxs("div",{className:"text-center py-8",children:[t.jsx("div",{className:"text-3xl mb-2",children:"ð
"}),t.jsx("div",{className:"text-sm text-muted",children:"Open slot â no installs scheduled"})]}):["ready_to_schedule","scheduled","in_progress","waiting_for_stock","complete"].map(a=>{const l=o[a];return l.length?t.jsxs("div",{children:[t.jsxs("div",{className:"text-xs font-bold text-muted uppercase tracking-wide mb-2",children:[nd[a]," (",l.length,")"]}),t.jsx("div",{className:"space-y-2",children:l.map(d=>t.jsxs("div",{onClick:()=>r(d),className:"bg-card border border-border rounded-lg p-3 cursor-pointer hover:border-accent/50 transition-colors",children:[t.jsxs("div",{className:"flex items-start justify-between gap-2 mb-1",children:[t.jsx("div",{className:"text-sm font-semibold text-white leading-tight",children:d.customer_name_snapshot}),t.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded border font-semibold flex-shrink-0 ${E8[d.status]}`,children:nd[d.status]})]}),t.jsx("div",{className:"text-xs text-muted",children:lo[d.system_type]}),t.jsx("div",{className:"text-xs text-muted mt-1 truncate",children:d.service_address_snapshot}),d.assigned_technician&&t.jsxs("div",{className:"text-xs text-accent mt-1",children:["ð§ ",d.assigned_technician.full_name]}),!d.assigned_technician&&t.jsx("div",{className:"text-xs text-amber mt-1",children:"â Unassigned"})]},d.id))})]},a):null})})]})}function PV({allJobs:e,onJobClick:n}){const r=new Date,[s,i]=g.useState(new Date(r.getFullYear(),r.getMonth(),1)),[o,a]=g.useState(null),l=s.getFullYear(),d=s.getMonth(),c=new Date(l,d,1).getDay(),f=new Date(l,d+1,0).getDate(),p=new Date(l,d,0).getDate(),u=[];for(let _=c-1;_>=0;_--)u.push({date:new Date(l,d-1,p-_),isCurrentMonth:!1});for(let _=1;_<=f;_++)u.push({date:new Date(l,d,_),isCurrentMonth:!0});const h=42-u.length;for(let _=1;_<=h;_++)u.push({date:new Date(l,d+1,_),isCurrentMonth:!1});const y=g.useMemo(()=>{const _=new Map;return e.forEach(j=>{if(!j.scheduled_date)return;const C=j.scheduled_date.split("T")[0];_.has(C)||_.set(C,[]),_.get(C).push(j)}),_},[e]);function m(_){return`${_.getFullYear()}-${String(_.getMonth()+1).padStart(2,"0")}-${String(_.getDate()).padStart(2,"0")}`}function b(_){return _.getFullYear()===r.getFullYear()&&_.getMonth()===r.getMonth()&&_.getDate()===r.getDate()}const A=o?y.get(m(o))||[]:[],v=e.filter(_=>{if(!_.scheduled_date)return!1;const j=new Date(_.scheduled_date);return j.getFullYear()===l&&j.getMonth()===d}),x=v.filter(_=>!_.assigned_technician_id&&_.status==="scheduled");return t.jsxs("div",{className:"flex gap-4 flex-1 overflow-hidden",children:[t.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden",children:[t.jsxs("div",{className:"flex items-center justify-between mb-4 flex-shrink-0",children:[t.jsxs("div",{className:"flex items-center gap-3",children:[t.jsx("button",{onClick:()=>i(new Date(l,d-1,1)),className:"text-muted hover:text-white text-lg w-8 h-8 flex items-center justify-center rounded-lg hover:bg-surface transition-colors",children:"â"}),t.jsxs("h2",{className:"text-base font-bold text-white w-44 text-center",children:[i3[d]," ",l]}),t.jsx("button",{onClick:()=>i(new Date(l,d+1,1)),className:"text-muted hover:text-white text-lg w-8 h-8 flex items-center justify-center rounded-lg hover:bg-surface transition-colors",children:"â"}),t.jsx("button",{onClick:()=>i(new Date(r.getFullYear(),r.getMonth(),1)),className:"text-xs px-3 py-1.5 bg-surface border border-border rounded-lg text-muted hover:text-white transition-colors",children:"Today"})]}),t.jsxs("div",{className:"flex items-center gap-4 text-xs",children:[t.jsxs("span",{className:"text-muted",children:[v.length," installs this month"]}),x.length>0&&t.jsxs("span",{className:"px-2 py-1 bg-amber/20 text-amber rounded-lg font-semibold",children:["â ",x.length," unassigned"]})]})]}),t.jsx("div",{className:"grid grid-cols-7 gap-2 mb-2 flex-shrink-0",children:TV.map(_=>t.jsx("div",{className:"text-xs font-bold text-muted uppercase tracking-wide text-center py-1",children:_},_))}),t.jsx("div",{className:"grid grid-cols-7 gap-2 flex-1 overflow-y-auto",children:u.map((_,j)=>t.jsx(RV,{date:_.date,isCurrentMonth:_.isCurrentMonth,isToday:b(_.date),jobs:y.get(m(_.date))||[],onJobClick:n,onDayCl
757ick:C=>a(S=>S&&m(S)===m(C)?null:C),selected:!!o&&m(o)===m(_.date)},j))})]}),o&&t.jsx(EV,{date:o,jobs:A,onJobClick:n,onClose:()=>a(null)})]})}function qV({jobsByStatus:e,searchQuery:n,onJobClick:r}){const[s,i]=g.useState("ready_to_schedule"),o=[{status:"ready_to_schedule",color:"#a855f7",bg:"rgba(168,85,247,0.15)",border:"rgba(168,85,247,0.4)"},{status:"scheduled",color:"#0d7ea3",bg:"rgba(13,126,163,0.15)",border:"rgba(13,126,163,0.4)"},{status:"in_progress",color:"#22d3ee",bg:"rgba(34,211,238,0.15)",border:"rgba(34,211,238,0.4)"},{status:"waiting_for_stock",color:"#f59e0b",bg:"rgba(245,158,11,0.15)",border:"rgba(245,158,11,0.4)"},{status:"complete",color:"#22c55e",bg:"rgba(34,197,94,0.15)",border:"rgba(34,197,94,0.4)"}],a=(e==null?void 0:e[s])||[],l=n?a.filter(d=>{var c;return d.customer_name_snapshot.toLowerCase().includes(n.toLowerCase())||d.phone_snapshot.includes(n)||d.service_address_snapshot.toLowerCase().includes(n.toLowerCase())||(((c=d.ticket)==null?void 0:c.ticket_number)??"").toLowerCase().includes(n.toLowerCase())}):a;return t.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden"},children:[t.jsx("div",{style:{display:"flex",gap:6,overflowX:"auto",flexShrink:0,marginBottom:12,paddingBottom:2},children:o.map(({status:d,color:c,bg:f,border:p})=>{const u=((e==null?void 0:e[d])||[]).length,h=s===d;return t.jsxs("button",{onClick:()=>i(d),style:{flexShrink:0,display:"flex",alignItems:"center",gap:6,padding:"8px 14px",borderRadius:10,border:`1px solid ${h?p:"#1e3a4f"}`,background:h?f:"rgba(255,255,255,0.02)",color:h?c:"#475569",cursor:"pointer",fontSize:12,fontWeight:h?700:500,boxShadow:h?`0 0 12px ${c}20`:"none"},children:[t.jsx("span",{children:nd[d]}),u>0&&t.jsx("span",{style:{background:h?c+"30":"rgba(255,255,255,0.06)",color:h?c:"#64748b",borderRadius:20,padding:"1px 6px",fontSize:11,fontWeight:700},children:u})]},d)})}),t.jsx("div",{style:{flex:1,overflowY:"auto"},children:l.length===0?t.jsx("div",{style:{textAlign:"center",padding:"48px 0",color:"#64748b",fontSize:13},children:"No jobs"}):t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:l.map(d=>t.jsx(F0,{job:d,onClick:r},d.id))})})]})}function DV({allJobs:e,onJobClick:n}){const r=new Date,[s,i]=g.useState(new Date(r.getFullYear(),r.getMonth(),1)),[o,a]=g.useState(null),l=s.getFullYear(),d=s.getMonth(),c=new Date(l,d,1).getDay(),f=new Date(l,d+1,0).getDate(),p=new Date(l,d,0).getDate(),u=[];for(let _=c-1;_>=0;_--)u.push({date:new Date(l,d-1,p-_),isCurrentMonth:!1});for(let _=1;_<=f;_++)u.push({date:new Date(l,d,_),isCurrentMonth:!0});const h=42-u.length;for(let _=1;_<=h;_++)u.push({date:new Date(l,d+1,_),isCurrentMonth:!1});const y=g.useMemo(()=>{const _=new Map;return e.forEach(j=>{if(!j.scheduled_date)return;const C=j.scheduled_date.split("T")[0];_.has(C)||_.set(C,[]),_.get(C).push(j)}),_},[e]);function m(_){return`${_.getFullYear()}-${String(_.getMonth()+1).padStart(2,"0")}-${String(_.getDate()).padStart(2,"0")}`}function b(_){return _.getFullYear()===r.getFullYear()&&_.getMonth()===r.getMonth()&&_.getDate()===r.getDate()}const A=e.filter(_=>{if(!_.scheduled_date)return!1;const j=new Date(_.scheduled_date);return j.getFullYear()===l&&j.getMonth()===d}),v=A.filter(_=>!_.assigned_technician_id&&_.status==="scheduled"),x=o?y.get(m(o))||[]:[];return t.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:10,flexShrink:0},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[t.jsx("button",{onClick:()=>i(new Date(l,d-1,1)),style:{background:"none",border:"none",color:"#64748b",fontSize:18,cursor:"pointer",width:32,height:32,display:"flex",alignItems:"center",justifyContent:"center",borderRadius:8},children:"â"}),t.jsxs("span",{style:{fontWeight:700,fontSize:14,color:"#e2e8f0",minWidth:130,textAlign:"center"},children:[i3[d]," ",l]}),t.jsx("button",{onClick:()=>i(new Date(l,d+1,1)),style:{background:"none",border:"none",color:"#64748b",fontSize:18,cursor:"pointer",width:32,height:32,display:"flex",alignItems:"center",justifyContent:"center",borderRadius:8},children:"â"})]}),t.jsx("button",{onClick:()=>{i(new Date(r.getFullYear(),r.getMonth(),1)),a(null)},style:{fontSize:11,padding:"4px 10px",background:"#1e3a4f",border:"1px solid #1e3a4f",borderRadius:6,color:"#94a3b8",curs
757or:"pointer"},children:"Today"})]}),v.length>0&&t.jsxs("div",{style:{marginBottom:8,padding:"6px 12px",background:"rgba(245,158,11,0.1)",border:"1px solid rgba(245,158,11,0.3)",borderRadius:8,fontSize:12,color:"#f59e0b",fontWeight:600,flexShrink:0},children:["â ",v.length," unassigned · ",A.length," installs this month"]}),t.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(7, 1fr)",gap:2,marginBottom:4,flexShrink:0},children:["S","M","T","W","T","F","S"].map((_,j)=>t.jsx("div",{style:{fontSize:10,fontWeight:700,color:"#475569",textAlign:"center",padding:"3px 0",textTransform:"uppercase",letterSpacing:"0.04em"},children:_},j))}),t.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(7, 1fr)",gap:2,flexShrink:0},children:u.map((_,j)=>{const C=m(_.date),S=y.get(C)||[],T=!!o&&m(o)===C,L=b(_.date);return t.jsxs("div",{onClick:()=>a(E=>E&&m(E)===C?null:_.date),style:{minHeight:40,borderRadius:8,cursor:"pointer",border:`1px solid ${T?"#22d3ee":L?"#0d7ea3":S.length>0?"#1e3a4f":"#1a2535"}`,background:T?"rgba(34,211,238,0.08)":L?"rgba(13,126,163,0.12)":_.isCurrentMonth?"#162232":"rgba(22,34,50,0.4)",padding:"4px 2px",display:"flex",flexDirection:"column",alignItems:"center",gap:2,opacity:_.isCurrentMonth?1:.35,boxShadow:L?"0 0 0 2px rgba(13,126,163,0.4)":T?"0 0 0 2px rgba(34,211,238,0.4)":"none"},children:[t.jsx("span",{style:{fontSize:11,fontWeight:L?800:600,color:L?"#fff":_.isCurrentMonth?"#cbd5e1":"#475569",width:20,height:20,display:"flex",alignItems:"center",justifyContent:"center",borderRadius:"50%",background:L?"#0d7ea3":"transparent"},children:_.date.getDate()}),S.length>0&&t.jsx("div",{style:{display:"flex",gap:2,flexWrap:"wrap",justifyContent:"center"},children:S.slice(0,3).map((E,R)=>t.jsx("span",{style:{width:5,height:5,borderRadius:"50%",background:E.status==="scheduled"?"#0d7ea3":E.status==="in_progress"?"#22d3ee":E.status==="waiting_for_stock"?"#f59e0b":"#22c55e"}},R))})]},j)})}),t.jsx("div",{style:{flex:1,overflowY:"auto",marginTop:14},children:o?t.jsxs(t.Fragment,{children:[t.jsxs("div",{style:{fontSize:12,fontWeight:700,color:"#64748b",textTransform:"uppercase",letterSpacing:"0.08em",marginBottom:10},children:[o.toLocaleDateString("en-US",{weekday:"long",month:"short",day:"numeric"})," · ",x.length," job",x.length!==1?"s":""]}),x.length===0?t.jsx("div",{style:{textAlign:"center",padding:"24px 0",color:"#475569",fontSize:13},children:"No installs scheduled"}):t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:x.map(_=>t.jsx(F0,{job:_,onClick:n},_.id))})]}):t.jsx("div",{style:{textAlign:"center",padding:"20px 0",color:"#334155",fontSize:13},children:"Tap a day to see jobs"})})]})}function OV(){Ee();const e=w0(),{data:n,isLoading:r,error:s}=z8(),[i,o]=g.useState(null),[a,l]=g.useState(""),[d,c]=g.useState("board"),f=g.useMemo(()=>Object.values(n||{}).flat(),[n]),p=f.length;return r?t.jsx("div",{className:"flex items-center justify-center h-full",children:t.jsx("div",{className:"text-muted text-sm",children:"Loading dispatch board..."})}):s?t.jsx("div",{className:"flex items-center justify-center h-full",children:t.jsx("div",{className:"text-red text-sm",children:"Failed to load dispatch board."})}):e?t.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[t.jsxs("div",{style:{flexShrink:0,marginBottom:4},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:10},children:[t.jsxs("div",{children:[t.jsx("div",{style:{fontWeight:800,fontSize:18,color:"#e2e8f0"},children:"Dispatch Board"}),t.jsxs("div",{style:{fontSize:12,color:"#64748b",marginTop:2},children:[p," job",p!==1?"s":""," total"]})]}),t.jsxs("div",{style:{display:"flex",alignItems:"center",background:"#162232",border:"1px solid #1e3a4f",borderRadius:8,padding:3},children:[t.jsx("button",{onClick:()=>c("board"),style:{padding:"6px 10px",borderRadius:6,border:"none",cursor:"pointer",fontSize:12,fontWeight:600,background:d==="board"?"#0d7ea3":"transparent",color:d==="board"?"#fff":"#64748b"},children:"â ¿ Board"}),t.jsx("button",{onClick:()=>c("calendar"),style:{padding:"6px 10px",borderRadius:6,border:"none",cursor:"pointer",fontSize:12,fontWeight:600,background:d==="calendar"?"#0d7ea3":"transparent",color:d==="calendar"?"#fff":"#64748b"},children:"ð
Cal"})]})]}),t.jsx(NV,{allJobs:f}),d==="board"&&t.jsx("input",{type:"text",value:a,onChange:u=>l(u.target.value),placeholder:"Search jobs...",style:{width:"100%",boxSizing:"border-box",background:"#162232",border:"1px solid #1e3a4f",borderRadius:8,color:"#e2e8f0",padding:"10px 14px",fontSize:13,outline:"none",marginBottom:10}})]}),d==="board"&&t.jsx(qV,{jobsByStatus:n||{},searchQuery:a,onJobClick:o}
757),d==="calendar"&&t.jsx(DV,{allJobs:f,onJobClick:o}),i&&t.jsx(mj,{job:i,onClose:()=>o(null)})]}):t.jsxs("div",{className:"flex flex-col h-full",children:[t.jsxs("div",{className:"flex items-center justify-between mb-4 flex-shrink-0",children:[t.jsxs("div",{children:[t.jsx("h1",{className:"text-xl font-bold text-white",children:"Dispatch Board"}),t.jsxs("p",{className:"text-sm text-muted mt-0.5",children:[p," job",p!==1?"s":""," total"]})]}),t.jsxs("div",{className:"flex items-center gap-3",children:[t.jsxs("div",{className:"flex items-center bg-surface border border-border rounded-lg p-1",children:[t.jsx("button",{onClick:()=>c("board"),className:`px-3 py-1.5 rounded-md text-xs font-semibold transition-all ${d==="board"?"bg-accent text-white":"text-muted hover:text-white"}`,children:"â ¿ Board"}),t.jsx("button",{onClick:()=>c("calendar"),className:`px-3 py-1.5 rounded-md text-xs font-semibold transition-all ${d==="calendar"?"bg-accent text-white":"text-muted hover:text-white"}`,children:"ð
Calendar"})]}),d==="board"&&t.jsx("input",{type:"text",value:a,onChange:u=>l(u.target.value),placeholder:"Search jobs...",className:"bg-card border border-border rounded-lg px-3 py-2 text-sm text-slate-200 placeholder-muted focus:outline-none focus:border-accent w-48 transition-colors"})]})]}),t.jsx(zV,{allJobs:f}),d==="board"&&t.jsx("div",{className:"flex gap-4 overflow-x-auto flex-1 pb-4",children:VU.map(u=>{const h=(n==null?void 0:n[u])||[],y=a?h.filter(m=>{var b;return m.customer_name_snapshot.toLowerCase().includes(a.toLowerCase())||m.phone_snapshot.includes(a)||m.service_address_snapshot.toLowerCase().includes(a.toLowerCase())||(((b=m.ticket)==null?void 0:b.ticket_number)??"").toLowerCase().includes(a.toLowerCase())}):h;return t.jsxs("div",{className:`kanban-col bg-surface border-t-2 ${kV[u]} rounded-xl flex-shrink-0`,children:[t.jsxs("div",{className:"flex items-center justify-between px-3 py-2.5 border-b border-border",children:[t.jsx("span",{className:"text-xs font-bold text-slate-300 uppercase tracking-wide",children:nd[u]}),t.jsx("span",{className:"text-xs bg-card border border-border rounded-full px-2 py-0.5 text-muted font-semibold",children:y.length})]}),t.jsx("div",{className:"flex flex-col gap-2 p-2 overflow-y-auto max-h-[calc(100vh-340px)]",children:y.length===0?t.jsx("div",{className:"text-center py-6 text-xs text-muted",children:"No jobs"}):y.map(m=>t.jsx(F0,{job:m,onClick:o},m.id))})]},u)})}),d==="calendar"&&t.jsx(PV,{allJobs:f,onJobClick:o}),i&&t.jsx(mj,{job:i,onClose:()=>o(null)})]})}const Pm=[{key:"scheduled",label:"Scheduled",color:"#60a5fa",bg:"rgba(96,165,250,0.08)",border:"rgba(96,165,250,0.3)"},{key:"in_progress",label:"In Progress",color:"#22d3ee",bg:"rgba(34,211,238,0.08)",border:"rgba(34,211,238,0.3)"},{key:"waiting_for_stock",label:"Waiting for Stock",color:"#fbbf24",bg:"rgba(251,191,36,0.08)",border:"rgba(251,191,36,0.3)"},{key:"complete",label:"Completed",color:"#4ade80",bg:"rgba(74,222,128,0.08)",border:"rgba(74,222,128,0.3)"}],IV={scheduled:"#60a5fa",in_progress:"#22d3ee",waiting_for_stock:"#fbbf24",complete:"#4ade80",ready_to_schedule:"#a78bfa"};function LV(){const{user:e,role:n}=Ee(),r=gt(),{data:s,isLoading:i,error:o}=z8(),[a,l]=g.useState("");if(i)return t.jsx("div",{className:"flex items-center justify-center h-full",children:t.jsx("div",{style:{color:"#64748b",fontSize:"14px"},children:"Loading jobs..."})});if(o)return t.jsx("div",{className:"flex items-center justify-center h-full",children:t.jsx("div",{style:{color:"#f87171",fontSize:"14px"},children:"Failed to load jobs."})});const d=Object.values(s||{}).flat().filter(h=>h.job_type==="standard_install"),c=(yt.viewAllInstallJobs(n)?d:d.filter(h=>h.assigned_technician_id===(e==null?void 0:e.id))).filter(h=>!a||(h.customer_name_snapshot||"").toLowerCase().includes(a.toLowerCase())||(h.phone_snapshot||"").includes(a)),f=c.filter(h=>h.status!=="complete").length,p=c.filter(h=>h.status==="complete").length,u={};for(const h of Pm)u[h.key]=[];for(const h of c)u[h.status]?u[h.status].push(h):h.status==="ready_to_schedule"&&u.scheduled.push(h);for(const h of Pm)u[h.key].sort((y,m)=>h.key==="complete"?(m.completed_at||"").localeCompare(y.completed_at||""):y.scheduled_date&&m.scheduled_date?y.scheduled_date.localeCompare(m.scheduled_date):y.scheduled_date?-1:1);return t.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%"}
757,children:[t.jsxs("div",{style:{marginBottom:"16px",flexShrink:0},children:[t.jsx("h1",{style:{color:"#e2e8f0",fontWeight:700,fontSize:"20px"},children:n==="technician"?"My Installations":"All Installations"}),t.jsxs("p",{style:{color:"#64748b",fontSize:"13px",marginTop:"2px"},children:[f," active job",f!==1?"s":"",p>0&&` · ${p} completed`]})]}),t.jsx("div",{style:{marginBottom:"14px",flexShrink:0},children:t.jsx("input",{type:"text",placeholder:"Search by customer name or phone...",value:a,onChange:h=>l(h.target.value),style:{width:"100%",maxWidth:"360px",background:"#162232",border:"1px solid #1e3a4f",borderRadius:"8px",color:"#e2e8f0",padding:"8px 12px",fontSize:"13px",outline:"none"}})}),t.jsx("div",{style:{display:"flex",gap:"12px",flex:1,overflowX:"auto",overflowY:"hidden",paddingBottom:"8px"},children:Pm.map(h=>{const y=u[h.key]||[];return t.jsxs("div",{style:{minWidth:"220px",flex:"1 1 220px",display:"flex",flexDirection:"column",background:h.bg,border:`1px solid ${h.border}`,borderRadius:"12px",overflow:"hidden"},children:[t.jsxs("div",{style:{padding:"10px 14px",borderBottom:`1px solid ${h.border}`,display:"flex",alignItems:"center",justifyContent:"space-between",flexShrink:0},children:[t.jsx("span",{style:{color:h.color,fontWeight:700,fontSize:"12px",textTransform:"uppercase",letterSpacing:"0.06em"},children:h.label}),t.jsx("span",{style:{background:h.bg,border:`1px solid ${h.border}`,color:h.color,borderRadius:"20px",padding:"1px 8px",fontSize:"11px",fontWeight:700},children:y.length})]}),t.jsx("div",{style:{flex:1,overflowY:"auto",padding:"8px"},children:y.length===0?t.jsx("div",{style:{color:"#334155",fontSize:"12px",textAlign:"center",padding:"20px 8px"},children:"No jobs"}):t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:y.map(m=>t.jsx(WV,{job:m,accentColor:IV[m.status]||h.color,onClick:()=>r(`/installations/${m.id}`)},m.id))})})]},h.key)})})]})}function WV({job:e,accentColor:n,onClick:r}){const s=e.scheduled_date?new Date(e.scheduled_date+"T00:00:00").toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric"}):"Not scheduled";return t.jsxs("div",{onClick:r,style:{background:"#162232",border:"1px solid #1e3a4f",borderLeft:`3px solid ${n}`,borderRadius:"8px",padding:"10px 12px",cursor:"pointer",transition:"background 0.15s"},onMouseEnter:i=>i.currentTarget.style.background="#1a2d45",onMouseLeave:i=>i.currentTarget.style.background="#162232",children:[t.jsx("div",{style:{color:"#e2e8f0",fontWeight:700,fontSize:"13px",marginBottom:"2px"},children:e.customer_name_snapshot}),e.phone_snapshot&&t.jsx("div",{style:{color:"#64748b",fontSize:"11px",marginBottom:"6px"},children:e.phone_snapshot}),t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"4px"},children:[t.jsx("span",{style:{background:"rgba(100,116,139,0.15)",border:"1px solid rgba(100,116,139,0.25)",color:"#94a3b8",borderRadius:"4px",padding:"1px 6px",fontSize:"10px",fontWeight:600,whiteSpace:"nowrap"},children:lo[e.system_type]||e.system_type}),t.jsxs("span",{style:{color:"#475569",fontSize:"10px",whiteSpace:"nowrap"},children:["ð
",s]})]}),e.status==="in_progress"&&t.jsx("div",{style:{marginTop:"6px",fontSize:"10px",fontWeight:600,color:"#22d3ee"},children:"â In progress â tap to continue"})]})}const xj="job-files";async function B0(e,n,r){const s=Date.now(),i=n.name.replace(/[^a-zA-Z0-9._-]/g,"_"),o=`${r}/${e}/${s}_${i}`,{error:a}=await w.storage.from(xj).upload(o,n,{cacheControl:"3600",upsert:!1});if(a)throw new Error(`Upload failed: ${a.message}`);const{data:l}=w.storage.from(xj).getPublicUrl(o);return l.publicUrl}async function U0(e,n,r){const i=await(await fetch(n)).blob(),o=new File([i],`${r}_signature.png`,{type:"image/png"});return B0(e,o,"signatures")}function $V(e){const n={};for(const r of e)n[r.section]||(n[r.section]=[]),n[r.section].push(r);return n}function MV({jobId:e}){Ee();const n=rt(),{data:r,isLoading:s}=LU(e),{mutateAsync:i}=FU(),{mutateAsync:o}=BU(),{mutateAsync:a}=UU();if(s)return t.jsx("p",{className:"text-sm text-muted text-center py-8",children:"Loading checklist..."});if(!(r!=null&&r.length))return t.jsx("p",{className:"text-sm text-muted text-center py-8",children:"No checklist items for this job."});const l=$V(r),d=r.filter(y=>y.is_required).length,c=r.filter(y=>y.is_required&&y.completed).length,f=d>0?Math.round(c/d*100):0;async function p(y){y.completed?await o({itemId:y.id,jobId:e}):await i({itemId:y.id,jobId:e}),n.invalidateQueries({queryKey:["job_completion",e]}
757)}async function u(y){await a({itemId:y.id,jobId:e}),n.invalidateQueries({queryKey:["job_completion",e]})}async function h(y,m){try{const b=await B0(e,m,"checklist-evidence"),{error:A}=await w.from("job_checklist_items").update({photo_url:b}).eq("id",y.id);if(A)throw new Error(A.message);n.invalidateQueries({queryKey:["jobs","checklist",e]}),n.invalidateQueries({queryKey:["job_completion",e]})}catch(b){alert("Photo upload failed: "+b.message)}}return t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{children:[t.jsxs("div",{className:"flex items-center justify-between text-xs text-muted mb-1.5",children:[t.jsxs("span",{children:[c,"/",d," required items"]}),t.jsxs("span",{className:"font-semibold",children:[f,"%"]})]}),t.jsx("div",{className:"h-2 bg-surface rounded-full overflow-hidden",children:t.jsx("div",{className:`h-full rounded-full transition-all ${f===100?"bg-green":"bg-accent"}`,style:{width:`${f}%`}})})]}),Object.entries(l).map(([y,m])=>t.jsxs("div",{children:[t.jsx("h4",{className:"text-xs font-bold text-slate-300 uppercase tracking-wide mb-2 border-b border-border pb-1",children:HU[y]||y}),t.jsx("div",{className:"space-y-1",children:m.map(b=>t.jsx(FV,{item:b,onToggle:()=>p(b),onVerify:()=>u(b),onPhotoUpload:A=>h(b,A)},b.id))})]},y))]})}function FV({item:e,onToggle:n,onVerify:r,onPhotoUpload:s}){const i=g.useRef(null);function o(a){var d;const l=(d=a.target.files)==null?void 0:d[0];l&&l.type.startsWith("image/")&&s(l),i.current&&(i.current.value="")}return t.jsxs("div",{className:`flex items-start gap-2.5 p-2 rounded-lg transition-colors ${e.completed?"bg-green/5":"hover:bg-surface"}`,children:[t.jsx("button",{onClick:n,className:`w-5 h-5 rounded border-2 flex-shrink-0 mt-0.5 flex items-center justify-center transition-colors ${e.completed?"bg-green border-green text-white":"border-muted hover:border-accent"}`,children:e.completed&&t.jsx("span",{className:"text-xs",children:"â"})}),t.jsxs("div",{className:"flex-1 min-w-0",children:[t.jsxs("div",{className:`text-sm ${e.completed?"text-muted line-through":"text-slate-200"}`,children:[e.item_text,e.is_required&&!e.completed&&t.jsx("span",{className:"text-red-400 text-xs ml-1",children:"*"})]}),t.jsxs("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:[e.requires_photo&&(e.photo_url?t.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-green/10 text-green",children:"ð· Photo attached"}):t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:()=>{var a;return(a=i.current)==null?void 0:a.click()},className:"text-xs px-2 py-1 rounded bg-amber/10 text-amber hover:bg-amber/20 transition-colors font-medium",children:"ð· Upload Photo"}),t.jsx("input",{ref:i,type:"file",accept:"image/*",className:"hidden",onChange:o})]})),e.requires_tech_verification&&(e.tech_verified?t.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-green/10 text-green",children:"â
Verified"}):t.jsx("button",{onClick:r,className:"text-xs px-1.5 py-0.5 rounded bg-accent/10 text-accent hover:bg-accent/20 transition-colors",children:"Verify"})),e.completed_at&&t.jsx("span",{className:"text-xs text-muted",children:new Date(e.completed_at).toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit"})})]}),e.photo_url&&t.jsx("div",{className:"mt-1.5",children:t.jsx("img",{src:e.photo_url,alt:"Evidence",className:"w-20 h-20 object-cover rounded-lg border border-border"})})]})]})}const BV=[{value:"before_install",label:"Before Install"},{value:"after_install",label:"After Install"},{value:"equipment",label:"Equipment"},{value:"plumbing",label:"Plumbing"},{value:"general",label:"General"}],yj={pending:{label:"Pending Review",bg:"rgba(251,191,36,0.15)",text:"#fbbf24"},approved:{label:"Approved",bg:"rgba(74,222,128,0.15)",text:"#4ade80"},rejected:{label:"Rejected",bg:"rgba(248,113,113,0.15)",text:"#f87171"}};function UV({jobId:e}){var z;const{user:n,role:r}=Ee(),s=rt(),{data:i,isLoading:o}=$U(e),a=g.useRef(null),[l,d]=g.useState(!1),[c,f]=g.useState("general"),[p,u]=g.useState(""),[h,y]=g.useState(null),[m,b]=g.useState(""),[A,v]=g.useState(!1),[x,_]=g.useState(null),[j,C]=g.useState("all"),S=yt.managePhotos(r);async function T(P){var M;const D=(M=P.target.files)==null?void 0:M[0];if(D){if(!D.type.startsWith("image/")){u("Only image files are allowed");return}u(""),d(!0);try{const k=await B0(e,D,"photos"),{error:q}=await w.from("job_photos").insert({job_id:e,photo_url:k,caption:D.name,category:c,uploaded_by:n==null?void 0:n.id,review_status:"pending"});if(q)throw new Error(q.message);s.invalidateQueries({queryKey:et.photos(e)}),s.invalidateQueries({queryKey:["job_completion",e]}
757)}catch(k){u(`Upload failed: ${k.message}`)}finally{d(!1),a.current&&(a.current.value="")}}}async function L(P,D){v(!0);try{const{error:M}=await w.from("job_photos").update({review_status:D,reviewed_by:n==null?void 0:n.id,reviewed_at:new Date().toISOString(),review_notes:m||null}).eq("id",P);if(M)throw new Error(M.message);s.invalidateQueries({queryKey:et.photos(e)}),y(null),b("")}catch(M){u(`Review failed: ${M.message}`)}finally{v(!1)}}if(o)return t.jsx("p",{className:"text-sm text-muted text-center py-8",children:"Loading photos..."});const E=i||[],R=E.filter(P=>(P.review_status||"pending")==="pending").length,N=E.filter(P=>P.review_status==="rejected").length,O=j==="all"?E:E.filter(P=>(P.review_status||"pending")===j);return t.jsxs("div",{className:"space-y-4",children:[S&&E.length>0&&t.jsxs("div",{className:"flex items-center gap-3 text-xs",children:[t.jsx("span",{className:"text-gray-400",children:"Filter:"}),[{value:"all",label:`All (${E.length})`},{value:"pending",label:`Pending (${R})`,color:"#fbbf24"},{value:"approved",label:`Approved (${E.length-R-N})`,color:"#4ade80"},{value:"rejected",label:`Rejected (${N})`,color:"#f87171"}].map(P=>t.jsx("button",{onClick:()=>C(P.value),className:`px-2 py-1 rounded text-xs font-medium transition-colors ${j===P.value?"bg-gray-700 text-white":"text-gray-500 hover:text-gray-300"}`,children:P.label},P.value))]}),S&&R>0&&t.jsxs("div",{className:"rounded-lg px-4 py-2.5 text-sm font-semibold flex items-center gap-2",style:{backgroundColor:"rgba(251,191,36,0.12)",border:"1px solid rgba(251,191,36,0.3)",color:"#fbbf24"},children:[t.jsx("span",{children:"ð"}),t.jsxs("span",{children:[R," photo",R!==1?"s":""," pending review"]})]}),t.jsxs("div",{className:"border-2 border-dashed border-border rounded-xl p-4",children:[t.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[t.jsx("select",{value:c,onChange:P=>f(P.target.value),className:"bg-surface border border-border rounded-lg px-2 py-1.5 text-xs text-slate-200 focus:outline-none focus:border-accent",children:BV.map(P=>t.jsx("option",{value:P.value,children:P.label},P.value))}),t.jsx("button",{onClick:()=>{var P;return(P=a.current)==null?void 0:P.click()},disabled:l,className:"text-xs px-3 py-1.5 bg-accent hover:bg-sky-400 disabled:opacity-50 text-white font-semibold rounded-lg transition-colors",children:l?"Uploading...":"ð· Upload Photo"})]}),t.jsx("input",{ref:a,type:"file",accept:"image/*",capture:"environment",className:"hidden",onChange:T}),p&&t.jsx("div",{className:"text-xs text-red-400 mt-2",children:p})]}),O.length>0?t.jsx("div",{className:"grid grid-cols-2 gap-3",children:O.map(P=>{var k;const D=P.review_status||"pending",M=yj[D]||yj.pending;return t.jsxs("div",{className:`bg-card border rounded-lg overflow-hidden ${D==="rejected"?"border-red-700/40":D==="approved"?"border-green-700/40":"border-border"}`,children:[t.jsxs("div",{className:"relative group cursor-pointer",onClick:()=>_(P.photo_url),children:[t.jsx("img",{src:P.photo_url,alt:P.caption||"Job photo",className:"w-full aspect-square object-cover",onError:q=>{q.target.className="w-full aspect-square bg-surface"}}),t.jsx("div",{className:"absolute top-2 right-2",children:t.jsx("span",{className:"text-[10px] px-2 py-0.5 rounded font-semibold",style:{backgroundColor:M.bg,color:M.text},children:M.label})})]}),t.jsxs("div",{className:"p-2",children:[t.jsx("div",{className:"text-xs text-slate-300 capitalize",children:(k=P.category)==null?void 0:k.replace(/_/g," ")}),t.jsx("div",{className:"text-xs text-muted mt-0.5",children:new Date(P.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}),P.review_notes&&t.jsx("div",{className:"text-xs mt-1 italic",style:{color:M.text},children:P.review_notes}),S&&D==="pending"&&t.jsxs("div",{className:"flex gap-1.5 mt-2",children:[t.jsx("button",{onClick:q=>{q.stopPropagation(),L(P.id,"approved")},className:"flex-1 text-[10px] py-1 rounded font-semibold transition-colors",style:{backgroundColor:"rgba(74,222,128,0.15)",color:"#4ade80",border:"1px solid rgba(74,222,128,0.3)"},children:"â Approve"}),t.jsx("button",{onClick:q=>{q.stopPropagation(),y(P)},className:"flex-1 text-[10px] py-1 rounded font-semibold transition-colors",style:{backgroundColor:"rgba(248,113,113,0.15)",color:"#f87171",border:"1px solid rgba(248,113,113,0.3)"},children:"â Reject"})]}),D!=="pending"&&P.reviewed_at&&t.jsxs("div",{className:"text-[10px] text-gray-500 mt-1",children:["Reviewed ",new Date(P.reviewed_at).toLocaleDateString("en-US",{month:"short",day:"numeric"})]})]})]},P.id)})}):t.jsx("p",{className:"text-sm text-muted text-center py-4",children:j!=="all"?`No ${j} photos.`:"No photos uploaded yet."}),h&&t.jsx("div",{className:"fixed inset-0 bg-black/60 flex items-center justify-center p-4 z-50",children:t.jsxs("div",{className:"bg-gray-900 border border-gray-700 rounded-xl w-full max-w-sm p-5",children:[t.jsx("h3",{className:"font-bold text-white mb-2",children:"Reject Photo"}),t.jsxs("p",{className:"text-xs text-gray-400 mb-3",children:[(z=h.category)==null?void 0:z.replace(/_/g," ")," â uploaded ",new Date(h.created_at).toLocaleDateString()]}),t.jsx("img",{src:h.photo_url,className:"w-full h-32 object-cover rounded mb-3"}),t.jsx("label",{className:"block text-xs text-gray-400 mb-1",children:"Reason for rejection (required)"}),t.jsx("textarea",{value:m,onChange:P=>b(P.target.value),placeholder:"Photo is blurry, wrong angle, wrong category...",rows:2,className:"w-full bg-gray-800 border border-gray-700 text-white text-sm rounded-lg px-3 py-2 focus:ring-red-500 focus:border-red-500 resize-none"}),t.jsxs("div",{className:"flex gap-2 mt-4",children:[t.jsx("button",{onClick:()=>{y(null),b("")},className:"flex-1 py-2 text-sm text-gray-400 hover:text-white transition-colors",children:"Cancel"}),t.jsx("button",{onClick:()=>L(h.id,"rejected"),disabled:!m.trim()||A,className:"flex-1 py-2 text-sm font-semibold rounded-lg disabled:opacity-50 transition-colors",style:{backgroundColor:"rgba(248,113,113,0.2)",color:"#f87171",border:"1px solid rgba(248,113,113,0.3)"},children:A?"Rejecting...":"Reject Photo"})]})]})}),x&&t.jsxs("div",{className:"fixed inset-0 bg-black/90 z-50 flex items-center justify-center p-8 cursor-pointer",onClick:()=>_(null),children:[t.jsx("img",{src:x,alt:"Photo",className:"max-w-full max-h-full object-contain rounded-lg"}),t.jsx("button",{className:"absolute top-6 right-6 text-white text-2xl hover:text-gray-300",onClick:()=>_(null),children:"Ã"})]})]})}function H0({onCapture:e,onClear:n,width:r=400,height:s=150}){const i=g.useRef(null),[o,a]=g.useState(!1),[l,d]=g.useState(!1);g.useEffect(()=>{const y=i.current;if(!y)return;const m=y.getContext("2d");m&&(m.fillStyle="#1e293b",m.fillRect(0,0,r,s),m.strokeStyle="#ffffff",m.lineWidth=2,m.lineCap="round",m.lineJoin="round")},[r,s]);function c(y){const b=i.current.getBoundingClientRect();return"touches"in y?{x:y.touches[0].clientX-b.left,y:y.touches[0].clientY-b.top}:{x:y.clientX-b.left,y:y.clientY-b.top}}function f(y){var A;y.preventDefault();const m=(A=i.current)==null?void 0:A.getContext("2d");if(!m)return;a(!0);const b=c(y);m.beginPath(),m.moveTo(b.x,b.y)}function p(y){var A;if(!o)return;y.preventDefault();const m=(A=i.current)==null?void 0:A.getContext("2d");if(!m)return;const b=c(y);m.lineTo(b.x,b.y),m.stroke(),d(!0)}function u(){a(!1),l&&i.current&&e(i.current.toDataURL("image/png"))}function h(){const y=i.current;if(!y)return;const m=y.getContext("2d");m&&(m.fillStyle="#1e293b",m.fillRect(0,0,r,s),d(!1),n())}return t.jsxs("div",{children:[t.jsx("div",{className:"text-xs text-muted mb-1.5",children:"Sign below:"}),t.jsx("div",{className:"border border-border rounded-lg overflow-hidden",style:{width:r,maxWidth:"100%"},children:t.jsx("canvas",{ref:i,width:r,height:s,className:"cursor-crosshair touch-none w-full",style:{height:s},onMouseDown:f,onMouseMove:p,onMouseUp:u,onMouseLeave:u,onTouchStart:f,onTouchMove:p,onTouchEnd:u})}),t.jsxs("div",{className:"flex items-center justify-between mt-1.5",children:[t.jsx("button",{onClick:h,className:"text-xs text-muted hover:text-white transition-colors",children:"Clear signature"}),l&&t.jsx("span",{className:"text-xs text-green",children:"â Signature captured"})]})]})}const qm=[{key:"system_operation",label:"System operation explained to customer"},{key:"bypass_valve",label:"Bypass valve location and operation shown"},{key:"regeneration_schedule",label:"Regeneration schedule explained"},{key:"salt_maintenance",label:"Salt maintenance requirements discussed"},{key:"filter_schedule",label:"Filter replacement schedule provided"},{key:"warranty_info",label:"Warranty information reviewed with customer"},{key:"emergency_shutoff",label:"Emergency shutoff procedure demonstrated"},{key:"water_quality",label:"Water quality test results reviewed"},{key:"contact_info",label:"Service contact information provided"},{key:"customer_questions",label:"All customer questions answered"}];function HV({jobId:e,formType:n,onSubmit:r,isPending:s}){const[i,o]=g.useState({}),[a,l]=g.useState(""),[d,c]=g.useState(""),[f,p]=g.useState(null),[u,h]=g.useState(""),[y,m]=g.useState(!1),b=qm.every(j=>i[j.key]),A=b&&a.trim()&&f;function v(j){o(C=>({...C,[j]:!C[j]}))}async function x(){if(!b){h("All checklist items must be checked");return}if(!a.trim()){h("Customer name is required");return}if(!f){h("Customer signature is required");return}h(""),m(!0);try{let j=null;try{j=await U0(e,f,n)}catch(S){console.warn("Signature upload failed, using reference:",S),j=`local_signature_${a.trim()}_${Date.now()}`}const C={checklist_items:qm.map(S=>({key:S.key,label:S.label,checked:!!i[S.key]})),customer_name:a.trim(),customer_notes:d.trim()||null,signature_captured:!0,submitted_at:new Date().toISOString()};await r(C,j)}catch(j){h(j.message)}finally{m(!1)}}const _=s||y;return t.jsxs("div",{className:"space-y-4",children:[t.jsx("div",{className:"text-xs text-muted",children:"Complete each item with the customer present. All items and signature are required."}),t.jsx("div",{className:"space-y-1",children:qm.map(j=>t.jsxs("div",{onClick:()=>v(j.key),className:`flex items-center gap-2.5 p-2 rounded-lg cursor-pointer transition-colors ${i[j.key]?"bg-green/5":"hover:bg-surface"}`,children:[t.jsx("div",{className:`w-5 h-5 rounded border-2 flex-shrink-0 flex items-center justify-center transition-colors ${i[j.key]?"bg-green border-green text-white":"border-muted"}`,children:i[j.key]&&t.jsx("span",{className:"text-xs",children:"â"})}),t.jsx("span",{className:`text-sm ${i[j.key]?"text-muted line-through":"text-slate-200"}`,children:j.label})]},j.key))}),t.jsxs("div",{children:[t.jsxs("label",{className:"block text-xs font-semibold text-muted uppercase tracking-wide mb-1.5",children:["Customer Name ",t.jsx("span",{className:"text-red-400",children:"*"})]}),t.jsx("input",{type:"text",value:a,onChange:j=>l(j.target.value),placeholder:"Full legal name",className:"w-full bg-surface border border-border rounded-lg px-3 py-2.5 text-sm text-slate-200 placeholder-muted focus:outline-none focus:border-accent"})]}),t.jsxs("div",{children:[t.jsx("label",{className:"block text-xs font-semibold text-muted uppercase tracking-wide mb-1.5",children:"Notes (optional)"}),t.jsx("textarea",{value:d,onChange:j=>c(j.target.value),placeholder:"Any special instructions...",rows:2,className:"w-full bg-surface border border-border rounded-lg px-3 py-2.5 text-sm text-slate-200 placeholder-muted focus:outline-none focus:border-accent resize-none"})]}),t.jsxs("div",{children:[t.jsxs("label",{className:"block text-xs font-semibold text-muted uppercase tracking-wide mb-1.5",children:["Customer Signature ",t.jsx("span",{className:"text-red-400",children:"*"})]}),t.jsx(H0,{onCapture:p,onClear:()=>p(null)})]}),u&&t.jsx("div",{className:"text-xs text-red-400 bg-red-500/10 border border-red-500/20 rounded-lg px-3 py-2",children:u}),t.jsx("button",{onClick:x,disabled:!A||_,className:"w-full py-2.5 bg-green-500 hover:bg-green-400 disabled:opacity-40 disabled:cursor-not-allowed text-white font-semibold rounded-lg text-sm transition-colors",children:_?"Submitting...":"Complete Handover"})]})}const Dm=[{key:"ro_operation",label:"RO system operation explained to customer"},{key:"faucet_usage",label:"RO faucet usage demonstrated"},{key:"tank_fill_time",label:"Initial tank fill time explained (2-4 hours)"},{key:"filter_schedule",label:"Filter replacement schedule reviewed"},{key:"membrane_schedule",label:"Membrane replacement schedule reviewed"},{key:"tds_reading",label:"TDS reading shown and explained to customer"},{key:"drain_connection",label:"Drain connection location shown"},{key:"warranty_info",label:"Warranty information provided"},{key:"contact_info",label:"Service contact information provided"},{key:"customer_questions",label:"All customer questions answered"}];function VV({jobId:e,formType:n,onSubmit:r,isPending:s}){const[i,o]=g.useState({}),[a,l]=g.useState(""),[d,c]=g.useState(""),[f,p]=g.useState(null),[u,h]=g.useState(""),[y,m]=g.useState(!1),A=Dm.every(_=>i[_.key])&&a.trim()&&d.trim()&&f;function v(_){o(j=>({...j,[_]:!j[_]}))}async function x(){if(!A){h("All items, TDS reading, customer name, and signature required");return}h(""),m(!0);try{let _=null;try{_=await U0(e,f,n)}catch{_=`local_signature_${a.trim()}_${Date.now()}`}await r({checklist_items:Dm.map(j=>({key:j.key,label:j.label,checked:!!i[j.key]})),customer_name:a.trim(),tds_reading:d.trim(),signature_captured:!0,submitted_at:new Date().toISOString()},_)}catch(_){h(_.message)}finally{m(!1)}}return t.jsxs("div",{className:"space-y-4",children:[t.jsx("div",{className:"text-xs text-muted",children:"Guardian RO ZPS-RO800 â Complete with customer present."}),t.jsx("div",{className:"space-y-1",children:Dm.map(_=>t.jsxs("div",{onClick:()=>v(_.key),className:`flex items-center gap-2.5 p-2 rounded-lg cursor-pointer transition-colors ${i[_.key]?"bg-green/5":"hover:bg-surface"}`,children:[t.jsx("div",{className:`w-5 h-5 rounded border-2 flex-shrink-0 flex items-center justify-center ${i[_.key]?"bg-green border-green text-white":"border-muted"}`,children:i[_.key]&&t.jsx("span",{className:"text-xs",children:"â"})}),t.jsx("span",{className:`text-sm ${i[_.key]?"text-muted line-through":"text-slate-200"}`,children:_.label})]},_.key))}),t.jsxs("div",{children:[t.jsxs("label",{className:"block text-xs font-semibold text-muted uppercase tracking-wide mb-1.5",children:["Final TDS Reading ",t.jsx("span",{className:"text-red-400",children:"*"})]}),t.jsx("input",{type:"text",value:d,onChange:_=>c(_.target.value),placeholder:"e.g., 12 ppm",className:"w-full bg-surface border border-border rounded-lg px-3 py-2.5 text-sm text-slate-200 placeholder-muted focus:outline-none focus:border-accent"})]}),t.jsxs("div",{children:[t.jsxs("label",{className:"block text-xs font-semibold text-muted uppercase tracking-wide mb-1.5",children:["Customer Name ",t.jsx("span",{className:"text-red-400",children:"*"})]}),t.jsx("input",{type:"text",value:a,onChange:_=>l(_.target.value),placeholder:"Full legal name",className:"w-full bg-surface border border-border rounded-lg px-3 py-2.5 text-sm text-slate-200 placeholder-muted focus:outline-none focus:border-accent"})]}),t.jsxs("div",{children:[t.jsxs("label",{className:"block text-xs font-semibold text-muted uppercase tracking-wide mb-1.5",children:["Customer Signature ",t.jsx("span",{className:"text-red-400",children:"*"})]}),t.jsx(H0,{onCapture:p,onClear:()=>p(null)})]}),u&&t.jsx("div",{className:"text-xs text-red-400 bg-red-500/10 border border-red-500/20 rounded-lg px-3 py-2",children:u}),t.jsx("button",{onClick:x,disabled:!A||s||y,className:"w-full py-2.5 bg-green-500 hover:bg-green-400 disabled:opacity-40 disabled:cursor-not-allowed text-white font-semibold rounded-lg text-sm transition-colors",children:s||y?"Submitting...":"Complete RO Handover"})]})}function ZV(e){if(!e||!e.trim())return"Customer name is required for signature";const n=e.trim();if(n.length<3)return"Name is too short â enter the customer's full name";
757if(!/^[a-zA-Z\s\-'.]+$/.test(n))return"Name contains invalid characters â please enter the customer's real name";const r=n.split(/\s+/).filter(s=>s.length>0);return r.length<2?"Please enter the customer's full name (first and last)":r.some(s=>s.length<2)?"Each name part must be at least 2 characters":null}function KV({jobId:e}){const{data:n,isLoading:r}=N8(e),{data:s}=WU(e),{mutateAsync:i,isPending:o}=R8(),[a,l]=g.useState(null),[d,c]=g.useState(null);if(r)return t.jsx("p",{className:"text-sm text-muted text-center py-8",children:"Loading forms..."});const f=(n||[]).filter(h=>h.form_type==="whole_home_handover"||h.form_type==="ro_handover");if(f.length===0)return t.jsx("p",{className:"text-sm text-muted text-center py-8",children:"No customer handover forms required for this job."});const p=new Map((s||[]).map(h=>[h.form_type,h]));async function u(h,y,m){const b=ZV(y.customer_name);if(b){c(b);return}c(null),await i({jobId:e,formType:h,responseData:y,signatureUrl:m}),l(null)}return t.jsxs("div",{className:"space-y-4",children:[d&&t.jsxs("div",{className:"rounded-lg px-4 py-2.5 text-sm font-semibold flex items-center gap-2",style:{backgroundColor:"rgba(248,113,113,0.12)",border:"1px solid rgba(248,113,113,0.3)",color:"#f87171"},children:[t.jsx("span",{children:"â ï¸"}),t.jsx("span",{children:d})]}),f.map(h=>{var A;const y=p.get(h.form_type),m=h.status==="completed",b=a===h.form_type;return t.jsxs("div",{className:`border rounded-xl p-4 ${m?"border-green/30 bg-green/5":"border-border"}`,children:[t.jsxs("div",{className:"flex items-center justify-between mb-2",children:[t.jsx("h4",{className:"text-sm font-bold text-white",children:P8[h.form_type]}),t.jsx("span",{className:`text-xs px-2 py-0.5 rounded-full font-semibold ${m?"bg-green/20 text-green":"bg-amber/20 text-amber"}`,children:m?"Completed":"Pending"})]}),m?t.jsxs("div",{className:"text-xs text-muted space-y-1",children:[t.jsxs("div",{children:["Completed ",h.completed_at?new Date(h.completed_at).toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}):""]}),h.signature_verified?t.jsx("div",{className:"text-green",children:"â
Customer signature verified"}):h.requires_signature?t.jsx("div",{className:"text-amber",children:"â ï¸ Signature not yet verified"}):null,((A=y==null?void 0:y.response_data)==null?void 0:A.customer_name)&&t.jsxs("div",{children:["Signed by: ",y.response_data.customer_name]})]}):b?t.jsxs("div",{className:"mt-3",children:[h.form_type==="whole_home_handover"&&t.jsx(HV,{jobId:e,formType:h.form_type,onSubmit:(v,x)=>u(h.form_type,v,x),isPending:o}),h.form_type==="ro_handover"&&t.jsx(VV,{jobId:e,formType:h.form_type,onSubmit:(v,x)=>u(h.form_type,v,x),isPending:o}),t.jsx("button",{onClick:()=>{l(null),c(null)},className:"w-full mt-2 py-1.5 text-xs text-muted hover:text-white transition-colors",children:"Cancel"})]}):t.jsxs("div",{children:[t.jsxs("p",{className:"text-xs text-muted mb-3",children:[h.requires_signature&&"âï¸ Customer signature required. ","Complete this form with the customer present."]}),t.jsx("button",{onClick:()=>{l(h.form_type),c(null)},className:"text-xs px-3 py-1.5 bg-accent hover:bg-sky-400 text-white font-semibold rounded-lg transition-colors",children:"Start Handover"})]})]},h.id)})]})}function YV({jobId:e,formType:n,onSubmit:r,isPending:s}){const[i,o]=g.useState(""),[a,l]=g.useState(""),[d,c]=g.useState(!1),[f,p]=g.useState(!1),[u,h]=g.useState(null),[y,m]=g.useState(""),[b,A]=g.useState(!1),v=i.trim()&&d&&f&&u;async function x(){if(!v){m("All acknowledgments, customer name, and signature required");return}m(""),A(!0);try{let _=null;try{_=await U0(e,u,n)}catch{_=`local_consent_sig_${i.trim()}_${Date.now()}`}await r({customer_name:i.trim(),countertop_material:a.trim()||null,acknowledge_risk:!0,authorize_work:!0,signature_captured:!0,consent_date:new Date().toISOString()},_)}catch(_){m(_.message)}finally{A(!1)}}return t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{className:"bg-amber/10 border border-amber/30 rounded-xl p-3",children:[t.jsx("div",{className:"text-sm font-bold text-amber mb-1",children:"â ï¸ Drilling Authorization Required"}),t.jsx("div",{className:"text-xs text-slate-300",children:"Must be obtained BEFORE drilling. Customer must be present and sign."})]}),t.jsxs("div",{className:"bg-surface border border-border rounded-lg p-3",children:[t.jsx("div",{className:"text-xs font-semibold text-slate-300 mb-2",children:"CONSENT AGREEMENT"}),t.jsx("div",{className:"text-xs text-muted leading-relaxed",children:"I hereby authorize Zenith Pure Solutions LLC to drill a new hole in my countertop
757/sink area for RO faucet installation. I understand this is permanent and cannot be undone without professional repair."})]}),t.jsxs("div",{children:[t.jsxs("label",{className:"block text-xs font-semibold text-muted uppercase tracking-wide mb-1.5",children:["Customer Name ",t.jsx("span",{className:"text-red-400",children:"*"})]}),t.jsx("input",{type:"text",value:i,onChange:_=>o(_.target.value),placeholder:"Full legal name",className:"w-full bg-surface border border-border rounded-lg px-3 py-2.5 text-sm text-slate-200 placeholder-muted focus:outline-none focus:border-accent"})]}),t.jsxs("div",{children:[t.jsx("label",{className:"block text-xs font-semibold text-muted uppercase tracking-wide mb-1.5",children:"Countertop Material (optional)"}),t.jsx("input",{type:"text",value:a,onChange:_=>l(_.target.value),placeholder:"Granite, Quartz...",className:"w-full bg-surface border border-border rounded-lg px-3 py-2.5 text-sm text-slate-200 placeholder-muted focus:outline-none focus:border-accent"})]}),t.jsx("div",{className:"space-y-2",children:[{state:d,toggle:()=>c(!d),text:"I understand this is permanent and accept the risks."},{state:f,toggle:()=>p(!f),text:"I authorize Zenith Pure Solutions to proceed with drilling."}].map((_,j)=>t.jsxs("div",{onClick:_.toggle,className:`flex items-start gap-2.5 p-3 rounded-lg border cursor-pointer transition-colors ${_.state?"border-amber/50 bg-amber/5":"border-border"}`,children:[t.jsx("div",{className:`w-5 h-5 rounded border-2 flex-shrink-0 mt-0.5 flex items-center justify-center ${_.state?"bg-amber border-amber text-white":"border-muted"}`,children:_.state&&t.jsx("span",{className:"text-xs",children:"â"})}),t.jsx("div",{className:"text-sm text-slate-200",children:_.text})]},j))}),t.jsxs("div",{children:[t.jsxs("label",{className:"block text-xs font-semibold text-muted uppercase tracking-wide mb-1.5",children:["Customer Signature ",t.jsx("span",{className:"text-red-400",children:"*"})]}),t.jsx(H0,{onCapture:h,onClear:()=>h(null)})]}),y&&t.jsx("div",{className:"text-xs text-red-400 bg-red-500/10 border border-red-500/20 rounded-lg px-3 py-2",children:y}),t.jsx("button",{onClick:x,disabled:!v||s||b,className:"w-full py-2.5 bg-amber hover:bg-amber-400 disabled:opacity-40 disabled:cursor-not-allowed text-white font-semibold rounded-lg text-sm transition-colors",children:s||b?"Saving...":"Record Drilling Consent"})]})}function XV({jobId:e}){const{data:n,isLoading:r}=N8(e),{mutateAsync:s,isPending:i}=R8(),[o,a]=g.useState(null);if(r)return t.jsx("p",{className:"text-sm text-muted text-center py-8",children:"Loading..."});const l=(n||[]).filter(c=>c.form_type==="ro_drilling_consent");if(l.length===0)return t.jsx("p",{className:"text-sm text-muted text-center py-8",children:"No consent forms required for this job type."});async function d(c,f,p){await s({jobId:e,formType:c,responseData:f,signatureUrl:p}),a(null)}return t.jsx("div",{className:"space-y-4",children:l.map(c=>{const f=c.status==="completed",p=o===c.form_type;return t.jsxs("div",{className:`border rounded-xl p-4 ${f?"border-green/30 bg-green/5":"border-amber/30 bg-amber/5"}`,children:[t.jsxs("div",{className:"flex items-center justify-between mb-2",children:[t.jsx("h4",{className:"text-sm font-bold text-white",children:P8[c.form_type]}),t.jsx("span",{className:`text-xs px-2 py-0.5 rounded-full font-semibold ${f?"bg-green/20 text-green":"bg-amber/20 text-amber"}`,children:f?"Signed":"Required"})]}),f?t.jsxs("div",{className:"text-xs text-muted",children:["Consent recorded ",c.completed_at?new Date(c.completed_at).toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}):"",t.jsx("div",{className:"text-green mt-1",children:"â
Customer signature captured"})]}):p?t.jsxs("div",{className:"mt-3",children:[t.jsx(YV,{jobId:e,formType:c.form_type,onSubmit:(u,h)=>d(c.form_type,u,h),isPending:i}),t.jsx("button",{onClick:()=>a(null),className:"w-full mt-2 py-1.5 text-xs text-muted hover:text-white transition-colors",children:"Cancel"})]}):t.jsxs("div",{children:[t.jsx("p",{className:"text-xs text-slate-300 mb-3",children:"â ï¸ This consent must be obtained BEFORE drilling begins. Customer must be present."}),t.jsx("button",{onClick:()=>a(c.form_type),className:"text-xs px-3 py-1.5 bg-amber hover:bg-amber-400 text-white font-semibold rounded-lg transition-colors",children:"Start Consent Form"})]})]},c.id)})})}function GV({jobId:e,jobStatus:n,installFee:r,monthlyAmount:s,planPrice:i,customerName:o,completedBy:a,serials:l,onCompleted:d}){var j,C,S,T,L,E;const[c,f]=g.useState(!1),[p,u]=g.useState(!1),[h,y]=g.useState(null),m=r!=null&&r>0,b=s!=null&&s>0,A=i!=null&&i>0,v=(r??0)+(s??0)+(i??0),x=v>0,_=async()=>{f(!0);try{const R=await fetch("/api/installations/complete",{method:"POST",headers:await At(),body:JSON.stringify({job_id:e,completed_by:a,serials:l||{}})}),N=await R.json();if(!R.ok)throw new Error(N.error||"Failed to complete installation");y(N),u(!1),d==null||d(N)}catch(R){y({success:!1,error:R.message})}finally{f(!1)}};if(h)if(h.success){const R=h.charge_status,N=h.rental_charge;return t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[t.jsx("div",{style:{display:"flex",alignItems:"center",gap:6,color:"#4ade80",fontSize:13,fontWeight:600},children:"â
Installation Marked Complete"}),R==="charged"&&t.jsxs("span",{style:{fontSize:12,padding:"4px 10px",borderRadius:6,backgroundColor:"rgba(34,197,94,0.12)",color:"#4ade80",border:"1px solid rgba(34,197,94,0.25)"},children:["ð³ Install fee $",(C=(j=h.charge_details)==null?void 0:j.amount)==null?void 0:C.toFixed(2)," charged to â¢â¢â¢â¢",(S=h.charge_details)==null?void 0:S.last_four]}),(N==null?void 0:N.status)==="charged"&&t.jsxs("span",{style:{fontSize:12,padding:"4px 10px",borderRadius:6,backgroundColor:"rgba(34,197,94,0.12)",color:"#4ade80",border:"1px solid rgba(34,197,94,0.25)"},children:["ð³ First month $",(T=N.amount)==null?void 0:T.toFixed(2)," charged"]}),R==="failed"&&t.jsxs("span",{style:{fontSize:12,padding:"4px 10px",borderRadius:6,backgroundColor:"rgba(239,68,68,0.12)",color:"#f87171",border:"1px solid rgba(239,68,68,0.25)"},children:["â ï¸ Charge failed: ",(L=h.charge_details)==null?void 0:L.error," â retry manually"]}),R==="skipped"&&t.jsx("span",{style:{fontSize:12,padding:"4px 10px",borderRadius:6,backgroundColor:"rgba(251,191,36,0.12)",color:"#fbbf24",border:"1px solid rgba(251,191,36,0.25)"},children:((E=h.charge_details)==null?void 0:E.reason)||"No install fee"})]})}else return t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[t.jsxs("span",{style:{color:"#f87171",fontSize:13},children:["â ",h.error]}),t.jsx("button",{onClick:()=>{y(null),u(!1)},style:{color:"#64748b",fontSize:12,background:"none",border:"none",cursor:"pointer",textDecoration:"underline"},children:"Try again"})]});return p?t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8,padding:"12px 14px",borderRadius:8,background:"#1a2a36",border:"1px solid rgba(34,197,94,0.3)"},children:[t.jsx("div",{style:{color:"#e2e8f0",fontSize:13,fontWeight:600},children:"Mark this installation as complete?"}),x?t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[t.jsxs("div",{style:{color:"#94a3b8",fontSize:12},children:["The following will be charged to ",t.jsx("strong",{style:{color:"#e2e8f0"},children:o}),"'s card on file:"]}),m&&t.jsxs("div",{style:{color:"#94a3b8",fontSize:12,paddingLeft:8},children:["⢠Install fee: ",t.jsxs("strong",{style:{color:"#e2e8f0"},children:["$",r.toFixed(2)]})]}),b&&t.jsxs("div",{style:{color:"#94a3b8",fontSize:12,paddingLeft:8},children:["⢠First month rental: ",t.jsxs("strong",{style:{color:"#e2e8f0"},children:["$",s.toFixed(2)]})]}),A&&t.jsxs("div",{style:{color:"#94a3b8",fontSize:12,paddingLeft:8},children:["⢠First month service plan: ",t.jsxs("strong",{style:{color:"#e2e8f0"},children:["$",i.toFixed(2)]})]}),m&&b&&t.jsxs("div",{style:{color:"#e2e8f0",fontSize:12,paddingLeft:8,fontWeight:700,borderTop:"1px solid rgba(255,255,255,0.08)",paddingTop:4,marginTop:2},children:["Total today: $",v.toFixed(2)]})]}):t.jsx("div",{style:{color:"#94a3b8",fontSize:12},children:"No charges for this job."}),t.jsxs("div",{style:{display:"flex",gap:8,marginTop:4},children:[t.jsx("button",{onClick:_,disabled:c,style:{fontSize:13,padding:"9px 18px",borderRadius:8,fontWeight:600,cursor:c?"not-allowed":"pointer",backgroundColor:"#16a34a",color:"#ffffff",border:"1px solid #22c55e",opacity:c?.6:1,whiteSpace:"nowrap",display:"flex",alignItems:"center",gap:6},children:c?"â³ Processingâ¦":x?`â
Complete & Charge $${v.toFixed(2)}`:"â
Complete"}),t.jsx("button",{onClick:()=>u(!1),disabled:c,style:{fontSize:13,padding:"9px 18px",borderRadius:8,fontWeight:600,cursor:"pointer",backgroundColor:"transparent",color:"#94a3b8",border:"1px solid rgba(148,163,184,0.3)",whiteSpace:"nowrap"},children:"Cancel"})]})]}):t.jsxs("button",{onClick:()=>u(!0),style:{fontSize:13,padding:"9px 18px",borderRadius:8,fontWeight:600,cursor:"pointer",backgroundColor:"rgba(34,197,94,0.15)",color:"#4ade80",border:"1px solid rgba(34,197,94,0.3)",whiteSpace:"nowrap",display:"flex",alignItems:"center",gap:6},children:["â
Mark Complete",x?` & Charge $${v.toFixed(2)}`:""]})}const JV=[{key:"photos",label:"Photos",icon:"ð·"},{key:"handover",label:"Handover",icon:"ð¤"},{key:"consents",label:"Consents",icon:"ð"},{key:"activity",label:"Activity",icon:"ð"}],QV={ro:"Reverse Osmosis",softener:"Water Softener",whole_home_filter:"Whole Home Filter",replacement_filter:"Replacement Filter",accessory:"Accessory",service:"Service"};function bj(e){return e?new Date(e).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit"}):"â"}function eZ(){const[e,n]=g.useState(window.innerWidth<768);return g.useEffect(()=>{const r=()=>n(window.innerWidth<768);return window.addEventListener("resize",r),()=>window.removeEventListener("resize",r)},[]),e}function tZ(){const{jobId:e}=di(),n=gt(),{user:r,profile:s}=Ee(),i=rt(),o=eZ(),{data:a,isLoading:l,error:d}=OU(e||""),{mutateAsync:c,isPending:f}=ng(),[p,u]=g.useState(null),[h,y]=g.useState("photos"),[m,b]=g.useState(""),[A,v]=g.useState({}),x=p||a,{data:_}=Ae({queryKey:["job_completion",x==null?void 0:x.id],queryFn:()=>C8(x.id),enabled:!!(x!=null&&x.id)&&(x==null?void 0:x.status)==="in_progress",staleTime:5e3,refetchInterval:1e4}),{data:j}=Ae({queryKey:["job_customer",x==null?void 0:x.id],queryFn:async()=>
757{if(!(x!=null&&x.lead_id))return null;const{data:P}=await w.from("customers").select("id, full_name").eq("lead_id",x.lead_id).maybeSingle();return P},enabled:!!(x!=null&&x.id)&&(x==null?void 0:x.status)==="complete"}),{data:C}=Ae({queryKey:["job_install_fee",x==null?void 0:x.id],queryFn:async()=>{const P=await fetch("/api/installations/preview-charges",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({job_id:x.id})}),D=await P.json();if(!P.ok)throw new Error(D.error||"Failed to preview charges");return{installFee:D.install_fee??0,monthlyAmount:D.monthly_amount??0,planPrice:D.plan_price??0,customerName:(x==null?void 0:x.customer_name_snapshot)||"Customer"}},enabled:!!(x!=null&&x.id)&&((x==null?void 0:x.status)==="in_progress"||(x==null?void 0:x.status)==="scheduled"),staleTime:3e4}),{data:S}=Ae({queryKey:["job_install_products",x==null?void 0:x.id],queryFn:async()=>{if(!(x!=null&&x.lead_id))return[];const{data:P}=await w.from("quotes").select("id").eq("lead_id",x.lead_id).in("status",["accepted","signed"]).order("created_at",{ascending:!1}).limit(1).maybeSingle();if(!P)return[];const{data:D}=await w.from("document_line_items").select("product_catalog_id, description, quantity").eq("quote_id",P.id).eq("item_type","product").order("sort_order",{ascending:!0});if(!(D!=null&&D.length))return[];const M=D.map(q=>q.product_catalog_id).filter(Boolean);let k=new Map;if(M.length>0){const{data:q}=await w.from("product_catalog").select("id, name, category, sku").in("id",M);k=new Map((q||[]).map($=>[$.id,$]))}return D.filter(q=>q.product_catalog_id&&k.has(q.product_catalog_id)).map(q=>{const $=k.get(q.product_catalog_id);return{product_catalog_id:q.product_catalog_id,name:$.name,category:$.category,sku:$.sku,quantity:q.quantity||1}})},enabled:!!(x!=null&&x.id)&&!!(x!=null&&x.lead_id),staleTime:6e4}),T=(_==null?void 0:_.ready)===!0,L=g.useCallback(P=>{u(P),i.invalidateQueries({queryKey:et.board()}),i.invalidateQueries({queryKey:et.activity(P.id)}),i.invalidateQueries({queryKey:["job_completion",P.id]})},[i]);async function E(P){if(x){b("");try{const D=await c({jobId:x.id,newStatus:P,currentJob:x});L(D)}catch(D){b(D.message)}}}function R(P){i.invalidateQueries({queryKey:et.detail(x.id)}),i.invalidateQueries({queryKey:et.board()}),i.invalidateQueries({queryKey:et.activity(x.id)}),i.invalidateQueries({queryKey:["job_completion",x.id]}),i.invalidateQueries({queryKey:["job_customer",x.id]}),x&&u({...x,status:"complete",completed_at:new Date().toISOString()})}if(l)return t.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",padding:24},children:t.jsx("div",{style:{color:"#64748b",fontSize:14},children:"Loading installation..."})});if(d||!x)return t.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",padding:24},children:t.jsxs("div",{style:{textAlign:"center"},children:[t.jsx("div",{style:{color:"#f87171",fontSize:14,marginBottom:8},children:"Failed to load installation."}),t.jsx("button",{onClick:()=>n("/installations"),style:{color:"#22d3ee",fontSize:13,background:"none",border:"none",cursor:"pointer",textDecoration:"underline"},children:"â Back to list"})]})});const N=s==null?void 0:s.role,O=yt.completeJobs(N),z=o?"12px 20px":"9px 18px";return t.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[t.jsxs("div",{style:{flexShrink:0,padding:o?"10px 12px":"12px 16px",borderBottom:"1px solid #1e3a4f",background:"#0f1923"},children:[t.jsx("button",{onClick:()=>n("/installations"),style:{color:"#64748b",fontSize:12,background:"none",border:"none",cursor:"pointer",marginBottom:8,display:"flex",alignItems:"center",gap:4,padding:0},children:"â Back to Installations"}),t.jsxs("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:12,flexWrap:"wrap"},children:[t.jsxs("div",{style:{minWidth:0,flex:1},children:[t.jsx("h1",{style:{color:"#e2e8f0",fontWeight:700,fontSize:o?16:18,margin:0,lineHeight:1.3},children:x.customer_name_snapshot}),t.jsx("div",{style:{color:"#64748b",fontSize:13,marginTop:2,wordBreak:"break-word"},children:x.service_address_snapshot}),(x.phone_snapshot||x.email_snapshot)&&t.jsxs("div",{style:{color:"#64748b",fontSize:12,marginTop:2},children:[x.phone_snapshot,x.email_snapshot&&` · ${x.email_snapshot}`]})]}),t.jsxs("div",{style:{textAlign:"right",flexShrink:0},children:[t.jsx("div",{className:`stage-badge border ${E8[x.status]}`,children:nd[x.status]}),t.jsx("div",{style:{color:"#64748b",fontSize:11,marginTop:4},children:lo[x.system_type]})]})]})]}),t.jsxs("div",{style:{flexShrink:0,padding:o?"8px 12px":"10px 16px",borderBottom:"1px solid #1e3a4f",dis
757play:"flex",flexWrap:"wrap",gap:8,alignItems:"center",flexDirection:o?"column":"row",background:"#0f1923"},children:[x.status==="scheduled"&&t.jsx("button",{onClick:()=>E("in_progress"),disabled:f,style:{fontSize:o?14:13,padding:z,borderRadius:8,fontWeight:600,cursor:"pointer",backgroundColor:"rgba(6,182,212,0.15)",color:"#22d3ee",border:"1px solid rgba(6,182,212,0.3)",opacity:f?.5:1,whiteSpace:"nowrap",...o?{alignSelf:"stretch",textAlign:"center"}:{}},children:"ð§ Start Installation"}),x.status==="in_progress"&&O&&t.jsx("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap",...o?{width:"100%"}:{}},children:T?t.jsx(GV,{jobId:x.id,jobStatus:x.status,installFee:(C==null?void 0:C.installFee)??null,monthlyAmount:(C==null?void 0:C.monthlyAmount)??null,planPrice:(C==null?void 0:C.planPrice)??null,customerName:(C==null?void 0:C.customerName)||x.customer_name_snapshot||"Customer",completedBy:r==null?void 0:r.id,serials:A,onCompleted:R}):t.jsxs(t.Fragment,{children:[t.jsx("button",{disabled:!0,style:{fontSize:o?14:13,padding:z,borderRadius:8,fontWeight:600,backgroundColor:"rgba(148,163,184,0.1)",color:"#94a3b8",border:"1px solid rgba(148,163,184,0.2)",cursor:"not-allowed",opacity:.7,whiteSpace:"nowrap"},title:"Complete all requirements first",children:"â
Mark Complete"}),_&&t.jsxs("span",{style:{color:"#fbbf24",fontSize:12},children:["Checklist incomplete (",_.completed,"/",_.total,")"]})]})}),x.status==="complete"&&t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap",...o?{width:"100%"}:{}},children:[t.jsxs("div",{style:{color:"#4ade80",fontSize:13,fontWeight:600},children:["â
Complete â ",bj(x.completed_at)]}),x.install_fee_charged&&t.jsx("span",{style:{fontSize:11,padding:"3px 8px",borderRadius:6,backgroundColor:"rgba(34,197,94,0.12)",color:"#4ade80",border:"1px solid rgba(34,197,94,0.25)"},children:"ð³ Install fee charged"}),x.install_fee_charge_status==="failed"&&t.jsx("span",{style:{fontSize:11,padding:"3px 8px",borderRadius:6,backgroundColor:"rgba(239,68,68,0.12)",color:"#f87171",border:"1px solid rgba(239,68,68,0.25)"},children:"â ï¸ Install fee charge failed"}),x.install_fee_charge_status==="skipped"&&t.jsx("span",{style:{fontSize:11,padding:"3px 8px",borderRadius:6,backgroundColor:"rgba(251,191,36,0.12)",color:"#fbbf24",border:"1px solid rgba(251,191,36,0.25)"},children:"No card â fee not charged"}),j&&t.jsxs("button",{onClick:()=>n(`/customers/${j.id}`),style:{fontSize:12,padding:"7px 14px",borderRadius:8,fontWeight:600,cursor:"pointer",backgroundColor:"rgba(56,189,248,0.12)",color:"#38bdf8",border:"1px solid rgba(56,189,248,0.25)",whiteSpace:"nowrap"},children:["ð¤ ",j.full_name]})]}),t.jsxs("div",{style:{display:"flex",gap:8,marginLeft:o?0:"auto",flexWrap:"wrap",alignItems:"center"},children:[x.scheduled_at&&t.jsxs("span",{style:{color:"#64748b",fontSize:12},children:["ð
",new Date(x.scheduled_at).toLocaleDateString("en-US",{month:"short",day:"numeric"})]}),x.started_at&&t.jsxs("span",{style:{color:"#64748b",fontSize:12},children:["Started ",bj(x.started_at)]})]})]}),m&&t.jsxs("div",{style:{flexShrink:0,margin:"8px 16px",borderRadius:8,padding:"10px 14px",color:"#fbbf24",background:"rgba(245,158,11,0.12)",border:"1px solid rgba(245,158,11,0.3)",fontSize:13,fontWeight:600},children:["â ï¸ ",m]}),t.jsxs("div",{style:{flex:1,overflowY:"auto",overflowX:"hidden"},children:[!1,x.lead_id&&t.jsx("div",{style:{padding:"12px 16px 0"},children:t.jsx($0,{leadId:x.lead_id,defaultExpanded:!0,title:"Site Visit Photos (from sales visit)"})}),S&&S.length>0&&t.jsx("div",{style:{padding:"12px 16px 0"},children:t.jsxs("div",{style:{background:"#162232",border:"1px solid #1e3a4f",borderRadius:14,overflow:"hidden"},children:[t.jsxs("div",{style:{padding:"10px 16px",borderBottom:"1px solid #1e3a4f",display:"flex",alignItems:"center",gap:8},children:[t.jsx("span",{style:{fontSize:14},children:"ð¦"}),t.jsx("span",{style:{color:"#e2e8f0",fontWeight:700,fontSize:13},children:"Products Being Installed"}),t.jsxs("span",{style:{color:"#4ade80",fontSize:11,fontWeight:600},children:[S.length," item",S.length!==1?"s":""]})]}),S.map((P,D)=>t.jsxs("div",{style:{padding:"10px 16px",borderBottom:D<S.length-1?"1px solid rgba(255,255,255,0.04)":"none"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[t.jsxs("div",{style:{minWidth:0,flex:1},children:[t.jsx("div",{style:{color:"#e2e8f0",fontSize:13,fontWeight:600},children:P.name}),t.jsxs("div",{style:{display:"flex",gap:8,marginTop:2},children:[P.category&&t.jsx("span",{style:{color:"#64748b",fontSize:11},children:QV[P.category]||P.category}),P.sku&&t.jsx("span",{style:{color:"#475569",fontSize:11,fontFamily:"monospace"},children:P.sku})]})]}),t.jsxs("span",{style:{color:"#94a3b8",fontSize:12,fontWeight:600,flexShrink:0},children:["à ",P.quantity]})]}),(x.status==="in_progress"||x.status==="scheduled")&&P.product_catalog_id&&t.jsxs("div",{style:{marginTop:8,display:"flex",alignItems:"center",gap:8},children:[t.jsx("label",{style:{fontSize:11,fontWeight:600,color:"#64748b",textTransform:"uppercase",letterSpacing:"0.06em",flexShrink:0},children:"Serial #"}),t.jsx("input",{type:"text",value:A[P.product_catalog_id]||"",onChange:M=>v(k=>({...k,[P.product_catalog_id]:M.target.value}
757)),placeholder:"Enter serial number (optional)",style:{flex:1,background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:8,padding:"6px 10px",fontSize:12,color:"#e2e8f0",outline:"none",fontFamily:"monospace"}})]})]},D))]})}),(x.status==="in_progress"||x.status==="scheduled")&&t.jsx("div",{style:{padding:"12px 16px 0"},children:t.jsx(MV,{jobId:x.id})}),t.jsxs("div",{style:{padding:"16px 16px 0"},children:[t.jsx("div",{style:{display:"flex",overflowX:"auto",borderBottom:"1px solid #1e3a4f",scrollbarWidth:"none",WebkitOverflowScrolling:"touch",gap:0},children:JV.map(P=>t.jsxs("button",{onClick:()=>y(P.key),style:{flexShrink:0,padding:o?"12px 16px":"10px 18px",fontSize:13,fontWeight:600,cursor:"pointer",background:"none",border:"none",borderBottom:h===P.key?"2px solid #22d3ee":"2px solid transparent",color:h===P.key?"#22d3ee":"#64748b",transition:"color 0.15s",whiteSpace:"nowrap",display:"flex",alignItems:"center",gap:6},children:[t.jsx("span",{style:{fontSize:14},children:P.icon}),P.label]},P.key))}),t.jsxs("div",{style:{paddingTop:16,paddingBottom:32,minHeight:300},children:[h==="photos"&&t.jsx(UV,{jobId:x.id}),h==="handover"&&t.jsx(KV,{jobId:x.id}),h==="consents"&&t.jsx(XV,{jobId:x.id}),h==="activity"&&t.jsx(s3,{jobId:x.id})]})]})]})]})}const Fe={all:["customers"],list:()=>[...Fe.all,"list"],detail:e=>[...Fe.all,e],addresses:e=>[...Fe.all,e,"addresses"],primaryAddr:e=>[...Fe.all,e,"primary_address"],systems:e=>[...Fe.all,e,"systems"],warranties:e=>[...Fe.all,e,"warranties"],rentals:e=>[...Fe.all,e,"rentals"],rentalSys:e=>[...Fe.all,e,"rental_systems"],payments:e=>[...Fe.all,e,"payments"],plans:e=>[...Fe.all,e,"plans"],requirements:e=>[...Fe.all,e,"requirements"],schedules:e=>[...Fe.all,e,"schedules"],completions:e=>[...Fe.all,e,"completions"],proofs:e=>[...Fe.all,e,"proofs"],buyouts:e=>[...Fe.all,e,"buyouts"],activity:e=>[...Fe.all,e,"activity"],catalog:()=>["product_catalog"]};function nZ(){return Ae({queryKey:Fe.list(),queryFn:GF,staleTime:3e4})}function rZ(e){return Ae({queryKey:Fe.detail(e),queryFn:()=>JF(e),enabled:!!e})}function o3(e){return Ae({queryKey:Fe.primaryAddr(e),queryFn:()=>ba("customer",e),enabled:!!e})}function V0(e){return Ae({queryKey:Fe.systems(e),queryFn:()=>f8(e),enabled:!!e})}function sZ(e){return Ae({queryKey:Fe.warranties(e),queryFn:()=>eB(),enabled:!!e})}function ig(e){return Ae({queryKey:Fe.rentals(e),queryFn:()=>tB(e),enabled:!!e})}function iZ(e){return Ae({queryKey:Fe.payments(e),queryFn:()=>nB(e),enabled:!!e})}function a3(e){return Ae({queryKey:Fe.plans(e),queryFn:()=>rB(e),enabled:!!e})}function oZ(e){return Ae({queryKey:Fe.requirements(e),queryFn:()=>sB(),enabled:!!e})}function l3(e){return Ae({queryKey:Fe.schedules(e),queryFn:()=>iB(e),enabled:!!e})}function aZ(e){return Ae({queryKey:Fe.completions(e),queryFn:()=>oB(),enabled:!!e})}function lZ(e){return Ae({queryKey:Fe.proofs(e),queryFn:()=>aB(),enabled:!!e})}function dZ(e,n){return Ae({queryKey:[...Fe.activity(e),n??null],queryFn:()=>lB(e,n),enabled:!!e})}const Aj=[{value:"missed_payment",label:"Missed Payment",description:"Autopay failed or payment is overdue. Needs immediate follow-up.",requiresText:!1,requiresDate:!1,optionalText:!1,note:"Check billing tab and confirm payment method is still valid."},{value:"no_recent_contact",label:"No Recent Contact",description:"Customer has gone quiet and is not responding to calls or messages.",requiresText:!1,requiresDate:!0,optionalText:!1,note:"A follow-up task will be created on the re-engage date."},{value:"considering_cancellation",label:"Considering Cancellation",description:"Customer has expressed intent to cancel or is unhappy with the agreement.",requiresText:!0,requiresDate:!1,optionalText:!1,optionalTextPlaceholder:"Required â describe the situation and what was discussed",note:"Flag for admin review. Consider a retention call or offer."},{value:"service_complaint",label:"Service Complaint",description:"Customer is unhappy with service quality, response time, or equipment.",requiresText:!0,requiresDate:!1,optionalText:!1,optionalTextPlaceholder:"Required â describe the complaint clearly",note:"Escalate to admin. Document complaint for service improvement tracking."}];function vj({onSubmit:e,onCancel:n,isPending:r=!1}){const[s,i]=g.useState(""),[o,a]=g.useState(""),[l,d]=g.useState(""),[c,f]=g.useState({}),p=Aj.find(v=>v.value===s)??null,u=new Date;u.setDate(u.getDate()+1);const h=u.toISOString().split("T")[0];function y(){const v={};return s||(v.code="Please select a reason"),p!=null&&p.requiresText&&o.trim().length<5&&(v.text="Required â please describe the situation (at least 5 characters)"),p!=null&&p.requiresDate&&!l&&(v.date="Re-engage date is required for this reason"),p!=null&&p.requiresDate&&l&&l<h&&(v.date="Re-engage date must be in the future"),f(v),Object.keys(v).length===0}function m(){!y()||!p||e({reasonCode:p.value,reasonLabel:p.label,freeText:o.trim()||null,reEngageDate:l||null})}const b={width:"100%",boxSizing:"border-box",background:"rgba(255,255,255,0.05)",border:"1px solid #1e3a4f",borderRadius:10,padding:"9px 14px",color:"#e2e8f0",fontSize:13,outline:"none",fontFamily:"inherit"},A={...b,border:"1px solid rgba(251,191,36,0.6)"};return t.jsxs("div",{style:{position:"fixed",inset:0,zIndex:50,display:"flex",alignItems:"center",justifyContent:"center",padding:16},children:[t.jsx("div",{style:{position:"absolute",inset:0,background:"rgba(0,0,0,0.65)"},onClick:n}),t.jsxs("div",{style:{position:"relative",width:"100%",maxWidth:440,background:"#162232",border:"1px solid #1e3a4f",borderRadius:20,padding:"24px 24px 20px",boxShadow:"0 24px 60px rgba(0,0,0,0.5)"},children:[t.jsxs("div",{style:{marginBottom:20},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,marginBottom:4},children:[t.jsx("span",{style:{fontSize:20},children:"â ï¸"}),t.jsx("h3",{style:{color:"#e2e8f0",fontWeight:800,fontSize:16,margin:0},children:"Mark as At Risk"})]}),t.jsx("p",{style:{color:"#64748b",fontSize:12,margin:0},children:"Select the reason this customer is at risk. This feeds into retention reporting."})]}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:14},children:[t.jsxs("div",{children:[t.jsxs("label",{style:{display:"block",fontSize:11,fontWeight:700,color:"#64748b",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:8},children:["At Risk Reason ",t.jsx("span",{style:{color:"#fbbf24"},children:"*"})]}),t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:Aj.map(v=>{const x=s===v.value;return t.jsx("button",{onClick:()=>{i(v.value),a(""),d(""),f({})},style:{width:"100%",textAlign:"left",cursor:"pointer",padding:"10px 14px",borderRadius:10,background:x?"rgba(251,191,36,0.08)":"rgba(255,255,255,0.03)",border:`1px solid ${x?"rgba(251,191,36,0.4)":"rgba(255,255,255,0.06)"}`,transition:"all 0.12s"},children:t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[t.jsx("div",{style:{width:16,height:16,borderRadius:"50%",flexShrink:0,border:`2px solid ${x?"#fbbf24":"#334155"}`,background:x?"#fbbf24":"transparent",display:"flex",alignItems:"center",justifyContent:"center",transition:"all 0.12s"},children:x&&t.jsx("div",{style:{width:6,height:6,borderRadius:"50%",background:"#0f1923"}})}),t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexWrap:"wrap"},children:[t.jsx("span",{style:{fontSize:13,fontWeight:600,color:x?"#fbbf24":"#e2e8f0"},children:v.label}),v.requiresText&&t.jsx("span",{style:{fontSize:9,padding:"1px 6px",borderRadius:8,background:"rgba(251,191,36,0.15)",color:"#fbbf24",fontWeight:700,textTransform:"uppercase",letterSpacing:"0.05em"},children:"Requires note"}),v.requiresDate&&t.jsx("span",{style:{fontSize:9,padding:"1px 6px",borderRadius:8,background:"rgba(167,139,250,0.15)",color:"#a78bfa",fontWeight:700,textTransform:"uppercase",letterSpacing:"0.05em"},children:"Requires date"})]}),t.jsx("div",{style:{fontSize:11,color:"#475569",marginTop:2,lineHeight:1.4},children:v.description})]})]})},v.value)})}),c.code&&t.jsx("p",{style:{fontSize:11,color:"#fbbf24",marginTop:6},children:c.code})]}),(p==null?void 0:p.requiresText)&&t.jsxs("div",{children:[t.jsxs("label",{style:{display:"block",fontSize:11,fontWeight:700,color:"#64748b",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:6},children:["Description ",t.jsx("span",{style:{color:"#fbbf24"},children:"* Required"})]}),t.jsx("textarea",{value:o,onChange:v=>{a(v.target.value),f(x=>({...x,text:""}))},placeholder:p.optionalTextPlaceholder??"Describe the situation clearly...",rows:3,style:{...c.text?A:b,resize:"none"},autoFocus:!0}),c.text?t.jsx("p",{style:{fontSize:11,color:"#fbbf24",marginTop:4},children:c.text}):t.jsxs("p",{style:{fontSize:11,color:"#64748b",marginTop:4},children:[o.trim().length,"/5 minimum characters"]})]}),(p==null?void 0:p.requiresDate)&&t.jsxs("div",{children:[t.jsxs("label",{style:{display:"block",fontSize:11,fontWeight:700,color:"#64748b",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:6},children:["Re-Engage Date ",t.jsx("span",{style:{color:"#fbbf24"},children:"* Required"})]}),t.jsx("input",{type:"date",value:l,min:h,onChange:v=>{d(v.target.value),f(x=>({...x,date:""}))},style:c.date?A:b}),c.date?t.jsx("p",{style:{fontSize:11,color:"#fbbf24",marginTop:4},children:c.date}):t.jsx("p",{style:{fontSize:11,color:"#64748b",marginTop:4},children:"A follow-up task will be created on this date."})]}),(p==null?void 0:p.note)&&t.jsxs("div",{style:{background:"rgba(251,191,36,0.06)",border:"1px solid rgba(251,191,36,0.2)",borderRadius:10,padding:"8px 12px",display:"flex",gap:8,alignItems:"flex-start"},children:[t.jsx("span",{style:{fontSize:14,flexShrink:0},children:"ð¡"}),t.jsx("p",{style:{fontSize:12,color:"#94a3b8",margin:0,lineHeight:1.5},children:p.note})]})]}),t.jsxs("div",{style:{display:"flex",gap:10,marginTop:20},children:[t.jsx("button",{onClick:n,style:{flex:1,padding:"10px 0",borderRadius:10,fontSize:13,color:"#64748b",background:"rgba(255,255,255,0.04)",border:"1px solid #1e3a4f",cursor:"pointer"},children:"Cancel"}),t.jsx("button",{onClick:m,disabled:r||!s,style:{flex:1,padding:"10px 0",borderRadius:10,fontSize:13,fontWeight:700,color:"#0f1923",background:r||!s?"rgba(251,191,36,0.3)":"#fbbf24",border:"none",cursor:r||!s?"not-allowed":"pointer",opacity:r?.7:1},children:r?"Saving...":"Mark At Risk"})]})]})]})}const Pp=[{key:"active",label:"Active",icon:"â",color:"#4ade80",bg:"rgba(34,197,94,0.08)",border:"rgba(34,197,94,0.25)",headerBg:"rgba(34,197,94,0.15)"},{key:"service_due",label:"Service Due",icon:"ð§",color:"#fbbf24",bg:"rgba(245,158,11,0.08)",border:"rgba(245,158,11,0.25)",headerBg:"rgba(245,158,11,0.15)"},{key:"renewal_due",label:"Renewal Due",icon:"â»",color:"#60a5fa",bg:"rgba(59,130,246,0.08)",border:"rgba(59,130,246,0.25)",headerBg:"rgba(59,130,246,0.15)"},{key:"upsell",label:"Upsell",icon:"â",color:"#c084fc",bg:"rgba(168,85,247,0.08)",border:"rgba(168,85,247,0.25)",headerBg:"rgba(168,85,247,0.15)"},{key:"at_risk",label:"At Risk",icon:"â ",color:"#f87171",bg:"rgba(239,68,68,0.08)",border:"rgba(239,68,68,0.25)",headerBg:"rgba(239,68,68,0.15)"},{key:"inactive",label:"Inactive",icon:"â",color:"#94a3b8",bg:"rgba(148,163,184,0.05)",border:"rgba(148,163,184,0.15)",headerBg:"rgba(148,163,184,0.1)"}];function _j({c:e,onClick:n,accentColor:r,borderColor:s,onMarkAtRisk:i}){var l;const[o,a]=g.useState(!1);return t.jsxs("div",{onClick:n,onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),style:{background:o?`linear-gradient(135deg, ${r}0d 0%, #0f1923 100%)`:"linear-gradient(135deg, #0f1923 0%, #111e2e 100%)",border:`1px solid ${s}`,borderLeft:`3px solid ${r}`,borderRadius:10,padding:"12px 12px 10px",cursor:"pointer",transition:"all 0.15s",marginBottom:8,transform:o?"translateY(-1px)":"translateY(0)",boxShadow:o?`0 4px 16px ${r}20`:"none"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[t.jsx("div",{style:{width:36,height:36,borderRadius:"50%",flexShrink:0,background:`${r}20`,border:`2px solid ${r}55`,display:"flex",alignItems:"center",justifyContent:"center",color:r,fontWeight:800,fontSize:14,textTransform:"uppercase"},children:((l=e.full_name)==null?void 0:l.charAt(0))||"?"}),t.jsxs("div",{style:{minWidth:0,flex:1},children:[t.jsx("div",{style:{color:"#f1f5f9",fontWeight:700,fontSize:13,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:e.full_name}),e.phone&&t.jsx("div",{style:{color:"#64748b",fontSize:11,marginTop:1},children:e.phone}),e.customer_number&&t.jsx("div",{style:{color:"#0d7ea3",fontSize:10,fontFamily:"monospace",marginTop:1},children:e.customer_number})]}),i&&o&&t.jsx("button",{onClick:d=>{d.stopPropagation(),i(d)},title:"Mark as At Risk",style:{flexShrink:0,padding:"3px 8px",borderRadius:6,background:"rgba(239,68,68,0.12)",border:"1px solid rgba(239,68,68,0.3)",color:"#f87171",fontSize:11,fontWeight:700,cursor:"pointer",whiteSpace:"nowrap"},children:"â At Risk"})]}),(e.service_address||e.email)&&t.jsxs("div",{style:{marginTop:8,paddingTop:8,borderTop:`1px solid ${r}18`},children:[e.service_address&&t.jsxs("div",{style:{color:"#475569",fontSize:11,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",marginBottom:e.email?3:0},children:["ð ",e.service_address]}),e.email&&t.jsxs("div",{style:{color:"#475569",fontSize:11,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:["â ",e.email]})]})]})}function cZ(){const e=gt(),n=w0(),{data:r,isLoading:s,error:i,refetch:o}=nZ(),[a,l]=g.useState(""),[d,c]=g.useState("active"),[f,p]=g.useState(null),[u,h]=g.useState(!1);async function y(v){if(f){h(!0);try{if(await w.from("customers").update({lifecycle_stage:"at_risk",at_risk_reason_code:v.reasonCode,at_risk_reason_label:v.reasonLabel,at_risk_notes:v.freeText,at_risk_flagged_at:new Date().toISOString()}).eq("id",f.id),v.reEngageDate){const{error:x}=await w.from("follow_ups").insert({entity_type:"customer",entity_id:f.id,title:`Re-engage: ${f.full_name} (At Risk â ${v.reasonLabel})`,notes:v.freeText||`Customer marked at risk: ${v.reasonLabel}`,due_at:v.reEngageDate,status:"pending",priority:"high"});x&&console.warn("[#261] follow_ups insert failed:",x.message)}p(null),o==null||o()}catch(x){console.error("At risk update failed:",x)}finally{h(!1)}}}if(s)return t.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%"},children:t.jsx("div",{style:{color:"#64748b",fontSize:14},children:"Loading customers..."})});if(i)return t.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%"},children:t.jsx("div",{style:{color:"#f87171",fontSize:14},children:"Failed to load customers."})});const m=r||[],b={};for(const v of Pp)b[v.key]=[];for(const v of m)b[v.lifecycle_stage]?b[v.lifecycle_stage].push(v):b.inactive=[...b.inactive||[],v];const A=v=>{if(!a)return v;const x=a.toLowerCase();return v.filter(_=>_.full_name.toLowerCase().includes(x)||_.phone.includes(x)||(_.service_address||"").toLowerCase().includes(x)||(_.email||"").toLowerCase().includes(x)||(_.customer_number||"").toLowerCase().includes(x))};if(n){const v=Pp.find(_=>
757_.key===d),x=A(b[d]||[]);return t.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[t.jsxs("div",{style:{flexShrink:0,paddingBottom:12},children:[t.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:10},children:t.jsxs("div",{children:[t.jsx("h1",{style:{color:"#e2e8f0",fontWeight:700,fontSize:18,margin:0},children:"Customers"}),t.jsxs("div",{style:{color:"#64748b",fontSize:12,marginTop:1},children:[m.length," total"]})]})}),t.jsx("input",{type:"text",value:a,onChange:_=>l(_.target.value),placeholder:"Search name, phone, address, account #â¦",style:{width:"100%",boxSizing:"border-box",background:"#162232",border:"1px solid #1e3a4f",borderRadius:8,color:"#e2e8f0",padding:"9px 14px",fontSize:13,outline:"none"}})]}),t.jsx("div",{style:{flexShrink:0,display:"flex",gap:6,overflowX:"auto",paddingBottom:10,scrollbarWidth:"none"},children:Pp.map(_=>{const j=A(b[_.key]||[]).length,C=d===_.key;return t.jsxs("button",{onClick:()=>c(_.key),style:{flexShrink:0,display:"flex",alignItems:"center",gap:5,padding:"7px 12px",borderRadius:20,border:`1px solid ${C?_.color:_.border}`,background:C?`${_.color}20`:"#0c1a26",color:C?_.color:"#64748b",fontSize:12,fontWeight:C?700:500,cursor:"pointer",transition:"all 0.15s"},children:[t.jsx("span",{style:{fontSize:13},children:_.icon}),t.jsx("span",{children:_.label}),t.jsx("span",{style:{background:C?`${_.color}30`:"#1e3a4f",color:C?_.color:"#64748b",borderRadius:10,padding:"1px 6px",fontSize:11,fontWeight:700},children:j})]},_.key)})}),t.jsx("div",{style:{flex:1,overflowY:"auto",minHeight:0},children:x.length===0?t.jsx("div",{style:{textAlign:"center",padding:"48px 12px",color:"#334155",fontSize:13},children:a?"No matches":"No customers"}):x.map(_=>t.jsx(_j,{c:_,accentColor:v.color,borderColor:v.border,onClick:()=>e(`/customers/${_.id}`),onMarkAtRisk:v.key!=="at_risk"?()=>p(_):void 0},_.id))}),f&&t.jsx(vj,{onSubmit:y,onCancel:()=>p(null),isPending:u})]})}return t.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[t.jsxs("div",{style:{flexShrink:0,display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"0 0 16px 0",flexWrap:"wrap"},children:[t.jsxs("div",{children:[t.jsx("h1",{style:{color:"#e2e8f0",fontWeight:700,fontSize:20,margin:0},children:"Customers"}),t.jsxs("div",{style:{color:"#64748b",fontSize:13,marginTop:2},children:[m.length," total"]})]}),t.jsx("input",{type:"text",value:a,onChange:v=>l(v.target.value),placeholder:"Search name, phone, address, account #â¦",style:{background:"#162232",border:"1px solid #1e3a4f",borderRadius:8,color:"#e2e8f0",padding:"9px 14px",fontSize:13,outline:"none",width:240,flexShrink:0}})]}),t.jsx("div",{style:{flex:1,display:"flex",gap:12,overflowX:"auto",overflowY:"hidden",minHeight:0,scrollbarWidth:"thin",scrollbarColor:"#1e3a4f transparent"},children:Pp.map(v=>{const x=A(b[v.key]||[]);return t.jsxs("div",{style:{flex:"1 1 0",minWidth:200,display:"flex",flexDirection:"column",background:"#0c1a26",border:`1px solid ${v.border}`,borderRadius:12,overflow:"hidden"},children:[t.jsxs("div",{style:{background:v.headerBg,padding:"12px 14px",borderBottom:`1px solid ${v.border}`,display:"flex",alignItems:"center",justifyContent:"space-between",flexShrink:0,borderTop:`3px solid ${v.color}`},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:7},children:[t.jsx("span",{style:{fontSize:16},children:v.icon}),t.jsx("span",{style:{color:v.color,fontWeight:800,fontSize:14,letterSpacing:"0.01em"},children:v.label})]}),t.jsx("div",{style:{background:v.color+"25",color:v.color,border:`1px solid ${v.color}40`,borderRadius:20,padding:"3px 10px",fontSize:12,fontWeight:800,minWidth:26,textAlign:"center"},children:x.length})]}),t.jsx("div",{style:{flex:1,overflowY:"auto",padding:"10px",scrollbarWidth:"thin",scrollbarColor:"#1e3a4f transparent"},children:x.length===0?t.jsx("div",{style:{textAlign:"center",padding:"32px 12px",color:"#334155",fontSize:12},children:a?"No matches":"No customers"}):x.map(_=>t.jsx(_j,{c:_,accentColor:v.color,borderColor:v.border,onClick:()=>e(`/customers/${_.id}`),onMarkAtRisk:v.key!=="at_risk"?()=>p(_):void 0},_.id))})]},v.key)})}),f&&t.jsx(vj,{onSubmit:y,onCancel:()=>p(null),isPending:u})]})}const d3={active:"Active",service_due:"Service Due",renewal_due:"Renewal Due",upsell:"Upsell",at_risk:"At Risk"},uZ={active:"bg-green/20 text-green border-green/30",service_due:"bg-
757amber/20 text-amber border-amber/30",renewal_due:"bg-purple/20 text-purple border-purple/30",upsell:"bg-accent/20 text-accent border-accent/30",at_risk:"bg-red/20 text-red border-red/30"},jj={sediment_filter_replacement:"Sediment Filter",ro_pre_post_filter_replacement:"RO Pre/Post Filters",ro_membrane_replacement:"RO Membrane",uv_bulb_replacement:"UV Bulb",annual_maintenance:"Annual Maintenance",maintenance_plan_renewal:"Maintenance Plan Renewal"};function pZ(e){const n=new Date;n.setHours(0,0,0,0);const r=new Date(e+"T00:00:00");return Math.floor((r.getTime()-n.getTime())/864e5)}function hZ(e){return new Date(e+"T00:00:00").toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}function fZ({customerId:e,customerName:n,userId:r}){const[s,i]=g.useState(!1),[o,a]=g.useState([]),[l,d]=g.useState(!0),[c,f]=g.useState(!1),p=g.useCallback(async()=>{d(!0);try{const m=await jE(e);a(m.filter(b=>!b.completed_at))}catch{a([])}finally{d(!1)}},[e]);g.useEffect(()=>{p()},[p]);async function u(m){try{await fd(m),await p()}catch{}}async function h(m){try{await Bf({...m,customer_id:e}),f(!1),await p()}catch{}}const y=o.length;return t.jsxs("div",{style:{background:"#162232",border:"1px solid #1e3a4f",borderRadius:14,overflow:"hidden"},children:[t.jsxs("button",{onClick:()=>i(m=>!m),style:{width:"100%",display:"flex",alignItems:"center",gap:8,padding:"10px 14px",background:"transparent",border:"none",cursor:"pointer",textAlign:"left"},children:[t.jsx("span",{style:{fontSize:13},children:"ð"}),t.jsx("span",{style:{color:"#94a3b8",fontWeight:700,fontSize:12,textTransform:"uppercase",letterSpacing:"0.06em",flex:1},children:"Follow-Ups"}),y>0&&t.jsx("span",{style:{background:"rgba(248,113,113,0.15)",color:"#f87171",borderRadius:20,padding:"1px 8px",fontSize:11,fontWeight:700},children:y}),t.jsx("span",{style:{color:"#64748b",fontSize:12},children:s?"â²":"â¼"})]}),s&&t.jsxs("div",{style:{padding:"0 14px 12px"},children:[l?t.jsx("div",{style:{color:"#64748b",fontSize:12,padding:"8px 0"},children:"Loadingâ¦"}):o.length===0?t.jsx("div",{style:{color:"#64748b",fontSize:12,padding:"8px 0"},children:"No open follow-ups."}):t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8,marginBottom:10},children:o.map(m=>{const b=pZ(m.due_date),A=b<0,v=b===0,x=A?"#f87171":v?"#fbbf24":b<=3?"#fb923c":"#94a3b8",_=A?`${Math.abs(b)}d overdue`:v?"Due today":b===1?"Tomorrow":`In ${b}d`;return t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:10,padding:"8px 12px"},children:[t.jsx("button",{onClick:()=>u(m.id),title:"Mark complete",style:{width:18,height:18,borderRadius:4,flexShrink:0,border:"2px solid #475569",background:"transparent",cursor:"pointer"},onMouseEnter:j=>{j.currentTarget.style.borderColor="#4ade80",j.currentTarget.style.background="rgba(74,222,128,0.15)"},onMouseLeave:j=>{j.currentTarget.style.borderColor="#475569",j.currentTarget.style.background="transparent"}}),t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexWrap:"wrap"},children:[t.jsxs("span",{style:{fontSize:13,color:"#e2e8f0",fontWeight:600},children:[Xl[m.task_type]||"ð"," ",m.title]}),t.jsx("span",{style:{fontSize:10,fontWeight:700,color:"#60a5fa",background:"rgba(96,165,250,0.15)",padding:"2px 6px",borderRadius:6},children:Vi[m.task_type]||"Task"})]}),m.notes&&t.jsx("div",{style:{fontSize:11,color:"#64748b",marginTop:2},children:m.notes})]}),t.jsxs("div",{style:{textAlign:"right",flexShrink:0},children:[t.jsx("div",{style:{fontSize:11,fontWeight:600,color:x},children:_}),t.jsx("div",{style:{fontSize:10,color:"#475569",marginTop:1},children:hZ(m.due_date)})]})]},m.id)})}),t.jsx("button",{onClick:()=>f(!0),style:{padding:"6px 14px",borderRadius:8,fontSize:12,fontWeight:700,background:"rgba(13,126,163,0.1)",color:"#22d3ee",border:"1px solid rgba(13,126,163,0.25)",cursor:"pointer"},children:"+ Add Follow-Up"})]}),c&&t.jsx(t0,{onClose:()=>f(!1),onCreate:h,userId:r})]})}const c3={month:"short",day:"numeric",year:"numeric"};function dn(e){if(!e)return"â";const n=e.length===10?`${e}T12:00:00`:e,r=new Date(n);return Number.isNaN(r.getTime())?"â":r.toLocaleDateString("en-US",c3)}function sr(e){if(!e)return"â";const n=new Date(e);return Number.isNaN(n.getTime())?"â":n.toLocaleDateString("en-US",c3)}async function gZ(e){const{data:n}=await w.from("customer_service_plans").select("id, status, price_monthly, billing_interval, plan_id, next_billing_date").eq("customer_id",e).eq("status","active").maybeSingle();return n}async function mZ(e){if(!e)return null;const{data:n}=await w.from("leads").select("source, created_at, assigned_rep_id").eq("id",e).maybeSingle();return n}async function xZ(e){if(!e)return null;const{data:n}=await w.from("profiles").select("full_name").eq("id",e).maybeSingle();return(n==null?void 0:n.full_name)||null}const yZ={website_form:"Website Form",landing_page:"Landing Page",google_ads:"Google Ads",facebook_ads:"Facebook Ads",referral:"Referral",door_knock:"Door Knock",home_show:"Home Show",phone_call:"Phone Call",other:"Other"},bZ={phone:"ð Phone",email:"âï¸ Email",sms:"ð¬ SMS",mail:"ð¬ Mail"};function AZ({customer:e}){const n=rt(),{data:r}=V0(e.id),{data:s}=ig(e.id),{data:i}=o3(e.id),{data:o}=Ae({queryKey:["active-service-plan",e.id],queryFn:()=>gZ(e.id)}),{data:a}=Ae({queryKey:["lead-origin",e.lead_id],queryFn:()=>mZ(e.lead_id),enabled:!!e.lead_id}),{data:l}=Ae({queryKey:["rep-name",a==null?void 0:a.assigned_rep_id],queryFn:()=>xZ((a==null?void 0:a.assigned_rep_id)||null),enabled:!!(a!=null&&a.assigned_rep_id)}),[d,c]=g.useState(!1),f=(r||[]).filter(m=>m.is_active!==!1),p=f.filter(m=>m.commercial_type==="purchase").length,u=f.filter(m=>m.commercial_type==="rental").length,h=(s||[]).find(m=>m.status==="active"),y=(()=>
757{if(!i)return"â";const m=[i.address_line1,i.address_line2,i.city,i.state,i.zip].filter(Boolean);return m.length>0?m.join(", "):"â"})();return t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[t.jsxs("div",{className:"bg-card border border-border rounded-xl p-3 text-center",children:[t.jsx("div",{className:"text-2xl font-bold text-white",children:f.length}),t.jsx("div",{className:"text-xs text-muted",children:"Installed Systems"}),t.jsxs("div",{className:"text-xs mt-1",children:[p>0&&t.jsxs("span",{style:{color:"#4ade80"},children:[p," purchased"]}),p>0&&u>0&&t.jsx("span",{className:"text-muted",children:" · "}),u>0&&t.jsxs("span",{style:{color:"#fbbf24"},children:[u," rented"]})]})]}),t.jsxs("div",{className:"bg-card border border-border rounded-xl p-3 text-center",children:[t.jsx("div",{className:"text-2xl font-bold text-white",children:d3[e.lifecycle_stage]||e.lifecycle_stage}),t.jsx("div",{className:"text-xs text-muted",children:"Lifecycle Status"})]})]}),h&&t.jsxs("div",{className:"rounded-xl p-3",style:{backgroundColor:"rgba(245,158,11,0.06)",border:"1px solid rgba(245,158,11,0.2)"},children:[t.jsx("div",{className:"text-xs font-bold uppercase tracking-wide mb-2",style:{color:"#fbbf24"},children:"Active Rental Contract"}),t.jsxs("div",{className:"text-sm text-slate-200 mb-1",children:["$",Number(h.monthly_amount).toFixed(2),"/month · ",h.payments_made||0," payments made"]}),t.jsxs("div",{className:"text-xs text-muted space-y-0.5",children:[h.contract_number&&t.jsxs("div",{children:["Contract · ",h.contract_number]}),t.jsxs("div",{className:"flex gap-3",children:[h.start_date&&t.jsxs("span",{children:["Start: ",dn(h.start_date)]}),h.end_date?t.jsxs("span",{children:["Ends: ",dn(h.end_date)]}):t.jsx("span",{children:"End date: â"})]}),h.total_paid>0&&t.jsxs("div",{children:["Total paid: $",Number(h.total_paid).toLocaleString()]})]}),h.rental_risk_status&&t.jsxs("div",{className:"text-xs font-semibold mt-2",style:{color:"#f87171"},children:["â ï¸ Risk: ",h.rental_risk_status.replace(/_/g," ")]})]}),o?t.jsxs("div",{className:"rounded-xl p-3",style:{backgroundColor:"rgba(34,197,94,0.06)",border:"1px solid rgba(34,197,94,0.2)"},children:[t.jsx("div",{className:"text-xs font-bold uppercase tracking-wide mb-1",style:{color:"#4ade80"},children:"Service Plan"}),t.jsx("div",{className:"text-sm text-slate-200",children:"Active Plan"}),t.jsxs("div",{className:"text-xs text-muted",children:["$",Number(o.price_monthly||0).toFixed(2),"/mo",o.next_billing_date&&` · Next billing ${dn(o.next_billing_date)}`]})]}):t.jsxs("div",{className:"rounded-xl p-3",style:{backgroundColor:"rgba(148,163,184,0.06)",border:"1px solid rgba(148,163,184,0.15)"},children:[t.jsx("div",{className:"text-xs font-bold uppercase tracking-wide mb-1 text-muted",children:"Service Plan"}),t.jsx("div",{className:"text-sm text-muted",children:"No active service plan"})]}),t.jsxs("div",{className:"bg-card border border-border rounded-xl p-4 space-y-3",children:[t.jsx("div",{className:"text-xs font-bold text-slate-300 uppercase tracking-wide",children:"Contact Information"}),t.jsx(zo,{label:"Phone",value:e.phone||"â"}),e.email&&t.jsx(zo,{label:"Email",value:e.email}),t.jsxs("div",{className:"flex items-start justify-between gap-4",children:[t.jsx("span",{className:"text-xs text-muted uppercase tracking-wide flex-shrink-0",children:"Service Address"}),t.jsxs("div",{className:"flex items-start gap-2",children:[t.jsx("span",{className:"text-sm text-slate-300 text-right",children:y}),t.jsx("button",{onClick:()=>c(!0),style:{fontSize:11,padding:"2px 8px",borderRadius:6,border:"1px solid rgba(13,126,163,0.4)",background:"rgba(13,126,163,0.12)",color:"#0d7ea3",cursor:"pointer",flexShrink:0},children:"Edit"})]})]}),t.jsx(zo,{label:"Customer Since",value:sr(e.created_at)}),l&&t.jsx(zo,{label:"Sales Rep",value:l}),e.preferred_contact_method&&t.jsx(zo,{label:"Preferred Contact",value:bZ[e.preferred_contact_method]||e.preferred_contact_method})]}),t.jsxs("div",{className:"bg-card border border-border rounded-xl p-4 space-y-3",children:[t.jsx("div",{className:"text-xs font-bold text-slate-300 uppercase tracking-wide",children:"Communication Consent"}),t.jsx("div",{className:"space-y-2",children:t.jsx(vZ,{label:"Marketing Contact",enabled:e.do_not_contact!==!0}
757)}),e.do_not_contact===!0?t.jsx("div",{className:"text-xs text-muted italic",children:"Customer opted out of marketing contact. Excluded from all campaigns."}):t.jsx("div",{className:"text-xs text-muted italic",children:"No explicit consent record on file. Verify before any marketing communications."})]}),e.lead_id&&t.jsxs("div",{className:"bg-card border border-border rounded-xl p-4 space-y-3",children:[t.jsx("div",{className:"text-xs font-bold text-slate-300 uppercase tracking-wide",children:"Lead History"}),t.jsx(zo,{label:"Converted",value:sr(e.created_at)}),a?t.jsx(t.Fragment,{children:a.source&&t.jsx(zo,{label:"Lead Source",value:yZ[a.source]||a.source})}):t.jsx("div",{className:"text-xs text-muted italic",children:"No source tracking data on original lead"})]}),t.jsx(fZ,{customerId:e.id,customerName:e.full_name||"",userId:null}),t.jsx(ru,{entityType:"customer",entityId:e.id,section:"general",visibilityDefault:"all",visibilitySelectorMode:"collapsed",title:"Customer Notes"}),d&&t.jsx(x8,{entityType:"customer",entityId:e.id,displayName:e.full_name,initial:{first_name:e.first_name,last_name:e.last_name,phone:e.phone,email:e.email},onClose:()=>c(!1),onSaved:()=>{n.invalidateQueries({queryKey:Fe.detail(e.id)}),n.invalidateQueries({queryKey:Fe.primaryAddr(e.id)}),n.invalidateQueries({queryKey:Fe.addresses(e.id)})}})]})}function zo({label:e,value:n}){return t.jsxs("div",{className:"flex items-start justify-between gap-4",children:[t.jsx("span",{className:"text-xs text-muted uppercase tracking-wide flex-shrink-0",children:e}),t.jsx("span",{className:"text-sm text-slate-300 text-right",children:n})]})}function vZ({label:e,enabled:n}){return t.jsxs("div",{className:"flex items-center gap-2 rounded-lg px-3 py-2",style:{backgroundColor:n?"rgba(74,222,128,0.08)":"rgba(148,163,184,0.06)",border:`1px solid ${n?"rgba(74,222,128,0.2)":"rgba(148,163,184,0.15)"}`},children:[t.jsx("span",{style:{color:n?"#4ade80":"#64748b",fontSize:14},children:n?"â":"â"}),t.jsxs("div",{children:[t.jsx("div",{className:"text-xs font-semibold",style:{color:n?"#4ade80":"#64748b"},children:e}),t.jsx("div",{className:"text-xs text-muted",children:n?"Opted in":"Not opted in"})]})]})}const _Z={rental:"Rental",purchase:"Purchased",financed:"Financed"},wj={rental:{bg:"rgba(245,158,11,0.15)",color:"#fbbf24"},purchase:{bg:"rgba(34,197,94,0.15)",color:"#4ade80"},financed:{bg:"rgba(56,189,248,0.15)",color:"#38bdf8"}};function Sj(e){return e?`$${Number(e).toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}`:null}function Tl(e){if(!e)return null;const n=new Date(e),r=new Date,s=Math.floor((n.getTime()-r.getTime())/(1e3*60*60*24));if(s<0)return{label:`Expired ${dn(e)}`,color:"#f87171",bg:"rgba(239,68,68,0.15)",daysLeft:s,expired:!0};let i;const o=new Date,a=new Date(e);let l=a.getFullYear()-o.getFullYear(),d=a.getMonth()-o.getMonth(),c=a.getDate()-o.getDate();if(c<0){d-=1;const u=new Date(a.getFullYear(),a.getMonth(),0);c+=u.getDate()}d<0&&(l-=1,d+=12),l>0&&d>0?i=`${l}y ${d}mo remaining`:l>0?i=`${l} year${l>1?"s":""} remaining`:d>0?i=`${d} month${d>1?"s":""} remaining`:i=`${c} day${c!==1?"s":""} remaining`;const f=s<90?"#fbbf24":"#4ade80",p=s<90?"rgba(245,158,11,0.15)":"rgba(34,197,94,0.15)";return{label:i,color:f,bg:p,daysLeft:s,expired:!1}}function jZ(e,n,r){const s=Tl(e),i=Tl(n),o=!s&&!i?Tl(r):null,a=[s,i,o].some(c=>c&&!c.expired),l=[s,i,o].some(c=>c&&c.expired);return s||i||o?a?{label:"Valid",bg:"rgba(34,197,94,0.15)",color:"#4ade80"}:l?{label:"Expired",bg:"rgba(239,68,68,0.15)",color:"#f87171"}:{label:"Valid",bg:"rgba(34,197,94,0.15)",color:"#4ade80"}:{label:"No Warranty",bg:"rgba(148,163,184,0.15)",color:"#94a3b8"}}function wZ({customerId:e}){const{data:n,isLoading:r}=V0(e),{profile:s}=Ee(),i=rt(),[o,a]=g.useState(null),l=yt.editSaltReminders(s==null?void 0:s.role);function d(u){var h;return((h=u==null?void 0:u.product_catalog)==null?void 0:h.category)==="softener"}async function c(u,h){a(u.id);try{await QF(u.id,h),await i.invalidateQueries({queryKey:Fe.systems(e)})}catch(y){alert("Failed to update salt reminders: "+y.message)}a(null)}if(r)return t.jsx("p",{className:"text-sm text-muted text-center py-8",children:"Loading systems..."});if(!(n!=null&&n.length))return t.jsx("p",{className:"text-sm text-muted text-center py-8",children:"No installed systems."});const f=n.filter(u=>u.is_active!==!1),p=n.filter(u=>u.is_active===!1);return t.jsxs("div",{className:"space-y-3",children:[f.length===0&&t.jsx("p",{className:"text-sm text-muted text-center py-4",children:"No active systems."}),f.map(u=>{const h=u.commercial_type||"purchase",y=h==="rental",m=h==="financed",b=wj[h]||wj.purchase,A=_Z[h]||h,v=Tl(u.parts_warranty_expires_at),x=Tl(u.labour_warranty_expires_at),_=!v&&!x?Tl(u.warranty_expires_at):null,j=jZ(u.parts_warranty_expires_at,u.labour_warranty_expires_at,u.warranty_expires_at);return t.jsxs("div",{className:"bg-card border border-border rounded-xl p-4",children:[t.jsxs("div",{className:"flex items-center justify-between mb-3",children:[t.jsx("h4",{className:"text-sm font-bold text-white",children:u.system_name||"â"}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full font-semibold",style:{backgroundColor:b.bg,color:b.color},children:A}),t.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full font-semibold",style:{backgroundColor:j.bg,color:j.color},children:j.label})]})]}),(y||m)&&u.monthly_rental_snapshot&&t.jsx("div",{className:"flex items-center gap-4 bg-amber-500/10 border border-amber-500/20 rounded-lg px-3 py-2 mb-3",children:t.jsxs("div",{children:[t.jsxs("div",{style:{fontSize:10,
757color:"#fbbf24",fontWeight:700,textTransform:"uppercase",letterSpacing:"0.06em"},children:["Monthly ",m?"Payment":"Rental"]}),t.jsxs("div",{style:{fontSize:14,fontWeight:700,color:"#fcd34d"},children:[Sj(u.monthly_rental_snapshot),"/mo"]})]})}),!y&&!m&&u.retail_price_snapshot&&t.jsx("div",{style:{display:"flex",alignItems:"center",gap:16,background:"#0a2a3a",border:"1px solid #1e3a4f",borderRadius:10,padding:"10px 14px",marginBottom:12},children:t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:10,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.06em",color:"#4ade80"},children:"Purchase Price"}),t.jsx("div",{style:{fontSize:15,fontWeight:700,color:"#ffffff"},children:Sj(u.retail_price_snapshot)})]})}),(v||x||_)&&t.jsxs("div",{style:{background:"rgba(15,23,42,0.6)",border:"1px solid rgba(30,58,79,0.8)",borderRadius:10,padding:"12px 14px",marginBottom:12},children:[t.jsx("div",{style:{fontSize:10,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.06em",color:"#94a3b8",marginBottom:8},children:"Warranty Coverage"}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[v&&t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12},children:[t.jsxs("span",{style:{fontSize:12,color:"#cbd5e1",display:"flex",alignItems:"center",gap:6},children:[t.jsx("span",{children:"ð©"}),t.jsx("span",{children:"Parts"})]}),t.jsx("span",{style:{fontSize:11,fontWeight:700,padding:"3px 9px",borderRadius:12,color:v.color,background:v.bg},children:v.label})]}),x&&t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12},children:[t.jsxs("span",{style:{fontSize:12,color:"#cbd5e1",display:"flex",alignItems:"center",gap:6},children:[t.jsx("span",{children:"ð·"}),t.jsx("span",{children:"Labour"})]}),t.jsx("span",{style:{fontSize:11,fontWeight:700,padding:"3px 9px",borderRadius:12,color:x.color,background:x.bg},children:x.label})]}),_&&!v&&!x&&t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12},children:[t.jsx("span",{style:{fontSize:12,color:"#cbd5e1"},children:"General"}),t.jsx("span",{style:{fontSize:11,fontWeight:700,padding:"3px 9px",borderRadius:12,color:_.color,background:_.bg},children:_.label})]})]})]}),t.jsxs("div",{className:"grid grid-cols-2 gap-x-4 gap-y-1.5 text-xs",children:[u.serial_number&&t.jsx(qp,{label:"Serial",value:u.serial_number}),t.jsx(qp,{label:"Installed",value:dn(u.install_date)}),d(u)&&t.jsxs("div",{className:"col-span-2 mt-2 pt-2 border-t border-slate-700/50",children:[t.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[t.jsx("input",{type:"checkbox",checked:u.salt_reminders_enabled===!0,disabled:!l||o===u.id,onChange:C=>c(u,C.target.checked),className:"accent-sky-400"}),t.jsx("span",{className:"text-xs text-slate-200",children:"Salt reminders â text + email every 2 months"})]}),t.jsx("p",{className:"text-[10px] text-slate-500 mt-1 ml-5",children:"Reminders run from the install date. Enrolling a system installed more than 2 months ago will send on the next run."})]}),u.parts_warranty_expires_at&&t.jsx(qp,{label:"Parts Expires",value:dn(u.parts_warranty_expires_at)}),u.labour_warranty_expires_at&&t.jsx(qp,{label:"Labour Expires",value:dn(u.labour_warranty_expires_at)})]}),u.returned_at&&t.jsxs("div",{className:"mt-2 text-xs text-muted",children:["Returned: ",sr(u.returned_at),u.return_condition&&` â ${u.return_condition}`]})]},u.id)}),p.length>0&&t.jsxs("div",{className:"mt-4",children:[t.jsx("div",{className:"text-xs font-bold text-muted uppercase tracking-wide mb-2",children:"Inactive / Removed Systems"}),p.map(u=>t.jsx("div",{className:"bg-card/50 border border-border/50 rounded-xl p-3 opacity-60 mb-2",children:t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx("span",{className:"text-sm text-slate-400",children:u.system_name||"â"}),t.jsx("span",{className:"text-xs text-muted",children:u.returned_at?`Returned ${sr(u.returned_at)}`:"Removed"})]})},u.id))]})]})}function qp({label:e,value:n}){return t.jsxs("div",{children:[t.jsxs("span",{className:"text-muted",children:[e,": "]}),t.jsx("span",{className:"text-slate-300",children:n})]})}async function SZ(e){try{const n=new Date().toISOString().split("T")[0],r=new Date(Date.now()-30*864e5).toISOString(),s=new Date(Date.now()+60*864e5).toISOString().split("T")[0],{data:i}=await w.from("customers").select("lifecycle_stage, created_at").eq("id",e).single();if(!i)return"active";const{data:o}=await w.from("payment_transactions").select("id").eq("customer_id",e).eq("status","failed").gte("created_at",r).limit(1),a=(o||[]).length>0,{data:l}=await w.from("customer_service_plans").select("id").eq("customer_id",e).eq("status","payment_failed").limit(1),d=(l||[]).length>0,{data:c}=await w.from("customer_service_plans").select("id, status, next_service, next_fulfillment_date").eq("customer_id",e).in("status",["active","pending_payment_method"]),f=(c||[]).some(x=>x.status!=="active"?!1:!!(x.next_service&&x.next_service<=n||x.next_fulfillment_date&&x.next_fulfillment_date<=n)),p=(c||[]).some(x=>x.status==="active"),{data:u}=await w.from("contracts").select("id, end_date").eq("customer_id",e).eq("status","active"),h=(u||[]).length>0,y=(u||[]).some(x=>x.end_date?x.end_date<=s&&x.end_date>=n:!1),{data:m}=await w.from("installed_systems").select("id").eq("customer_id",e).eq("is_active",!0).limit(1),b=(m||[]).length>0,A=!h&&!p&&!b;let v;return a||d?v="at_risk":f?v="service_due":y?v="renewal_due":A?v="inactive":b&&!p&&h?v="upsell":v="active",v!==i.lifecycle_stage&&(await w.from("customers").update({lifecycle_stage:v,updated_at:new Date().toISOString()}).eq("id",e),await Tt({customer_id:e,event_type:"lifecycle_changed",title:`Lifecycle: ${i.lifecycle_stage||"unknown"} â ${v}`,actor_id:null,actor_name:"System",metadata:{from:i.lifecycle_stage,to:v}}).then(()=>{}).catch(()=>{})),v}catch(n){return console.error("[lifecycleService] Error updating lifecycle for",e,n),"active"}}
757async function kZ(e,n,r,s){const{data:i,error:o}=await w.from("contracts").select("id, customer_id, tenant_id, branch_id").eq("id",e).single();if(o||!i)throw new Error("Contract not found for payment");const a=new Date(r+"T00:00:00").toISOString(),{error:l}=await w.from("payment_transactions").insert({customer_id:i.customer_id,contract_id:i.id,amount:n,currency:"usd",status:"succeeded",payment_type:"monthly_rental",stripe_payment_intent_id:null,processed_at:a,failure_reason:null,tenant_id:i.tenant_id,branch_id:i.branch_id,tax_amount:0});if(l)throw new Error(`Payment recording failed: ${l.message}`);await Tt({customer_id:i.customer_id,event_type:"rental_payment_received",title:`Rental payment received: $${n.toFixed(2)}`,metadata:{contract_id:e,amount:n,payment_date:r},actor_id:s.actor_id,actor_name:s.actor_name||null}).then(()=>{}).catch(()=>{}),await SZ(i.customer_id)}function CZ({contract:e,customerId:n,onClose:r,onCompleted:s}){const{user:i,profile:o}=Ee(),a=rt(),[l,d]=g.useState(String(e.monthly_amount||"")),[c,f]=g.useState(new Date().toISOString().split("T")[0]),[p,u]=g.useState(!1),[h,y]=g.useState("");async function m(){if(!(!i||!l||!c)){u(!0),y("");try{await kZ(e.id,Number(l),c,{actor_id:i.id,actor_name:o==null?void 0:o.full_name}),a.invalidateQueries({queryKey:Fe.rentals(n)}),a.invalidateQueries({queryKey:Fe.payments(e.id)}),a.invalidateQueries({queryKey:Fe.activity(n)}),a.invalidateQueries({queryKey:Fe.detail(n)}),s()}catch(b){y(b.message)}finally{u(!1)}}}return t.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60",onClick:r,children:t.jsxs("div",{className:"bg-card border border-border rounded-xl p-5 w-full max-w-sm shadow-xl",onClick:b=>b.stopPropagation(),children:[t.jsx("h3",{className:"text-sm font-bold text-white mb-1",children:"Record Payment"}),t.jsxs("p",{className:"text-xs text-muted mb-4",children:["Contract ",e.contract_number||"â"]}),t.jsxs("div",{className:"mb-3",children:[t.jsx("label",{className:"text-xs font-semibold text-slate-300 uppercase tracking-wide block mb-1",children:"Amount"}),t.jsx("input",{type:"number",value:l,onChange:b=>d(b.target.value),step:"0.01",placeholder:"0.00",className:"w-full bg-surface border border-border rounded-lg px-3 py-2 text-sm text-white placeholder-muted focus:outline-none focus:border-accent"})]}),t.jsxs("div",{className:"mb-4",children:[t.jsx("label",{className:"text-xs font-semibold text-slate-300 uppercase tracking-wide block mb-1",children:"Payment Date"}),t.jsx("input",{type:"date",value:c,onChange:b=>f(b.target.value),className:"w-full bg-surface border border-border rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-accent"})]}),h&&t.jsx("div",{className:"mb-3 text-xs rounded-lg px-3 py-2",style:{color:"#f87171",backgroundColor:"rgba(239,68,68,0.1)",border:"1px solid rgba(239,68,68,0.2)"},children:h}),t.jsxs("div",{className:"flex gap-2",children:[t.jsx("button",{onClick:r,disabled:p,className:"flex-1 text-xs px-3 py-2 rounded-lg border border-border text-muted hover:text-slate-300 transition-colors",children:"Cancel"}),t.jsx("button",{onClick:m,disabled:p||!l,className:"flex-1 text-xs px-3 py-2 rounded-lg font-semibold transition-colors disabled:opacity-50",style:{backgroundColor:"rgba(34,197,94,0.15)",color:"#4ade80",border:"1px solid rgba(34,197,94,0.3)"},children:p?"Recording...":"Record Payment"})]})]})})}function Gt(e){return e==null?"â":new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}).format(Number(e))}function TZ(e){return e?new Date(e).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):"â"}const zZ={buyout_rental_credit_pct:50,buyout_install_credit_pct:100,buyout_credit_cap_pct:50};function NZ({contract:e,customerId:n,calculation:r,onClose:s,onInvoiceGenerated:i}){const{profile:o}=Ee(),[a,l]=g.useState(null),[d,c]=g.useState([]),[f,p]=g.useState([]),[u,h]=g.useState(zZ),[y,m]=g.useState(0),[b,A]=g.useState(0),[v,x]=g.useState(!0),[_,j]=g.useState({}),[C,S]=g.useState({}),[T,L]=g.useState("none"),[E,R]=g.useState(""),[N,O]=g.useState(""),[z,P]=g.useState(!1),[D,M]=g.useState(null),[k,q]=g.useState(""),[$,I]=g.useState(!1),[B,J]=g.useState(!1),[ae,te]=g.useState(!1),[U,W]=g.useState(!1),[G,V]=g.useState(!1);g.useEffect(()=>{async function ke(){x(!0);try{if(o!=null&&o.tenant_id){const{data:_e}=await w.from("tenants").select("buyout_rental_credit_pct, buyout_install_credit_pct, buyout_credit_cap_pct").eq("id",o.tenant_id).single();_e&&h({buyout_rental_credit_pct:Number(_e.buyout_rental_credit_pct)||50,buyout_install_credit_pct:Number(_e.buyout_install_credit_pct)||100,buyout_credit_cap_pct:Number(_e.buyout_credit_cap_pct)||50})}const{data:Pe}=await w.from("installed_systems").select("*").eq("customer_id",n).eq("commercial_type","rental").eq("is_active",!0).limit(1).maybeSingle();l(Pe);try{const _e=e.quote_id||e.source_quote_id||null;if(_e){const{data:je}=await w.from("document_line_items").select("product_id, quantity").eq("quote_id",_e).eq("item_type","product").not("product_id","is",null);if(je&&je.length>0){const Be=je.map(Vn=>Vn.product_id),{data:Je}=await w.from("product_catalog").select("id, retail_price").in("id",Be),bt=(Je||[]).reduce((Vn,fr)=>{const Ca=je.find(is=>is.product_id===fr.id);return Vn+(Number(fr.retail_price)||0)*((Ca==null?void 0:Ca.quantity)||1)},0);bt>0?m(bt):Pe!=null&&Pe.retail_price_snapshot&&m(Number(Pe.retail_price_snapshot)||0)}}}catch(_e){console.error("retail price fetch error (non-fatal):",_e),Pe!=null&&Pe.retail_price_snapshot&&m(Number(Pe.retail_price_snapshot)||0)}if(e.quote_id){const{data:_e}=await w.from("quotes").select("install_fee").eq("id",e.quote_id).single();_e!=null&&_e.install_fee&&A(Number(_e.install_fee)||0)}const{data:nt}=await w.from("customer_service_plans").select("id, price_monthly, billing_interval, status, plan_id").eq("customer_id",n).eq("status","active"),ue=nt||[];let fe={};const le=ue.map(_e=>
757_e.plan_id).filter(Boolean);if(le.length>0){const{data:_e}=await w.from("service_plans").select("id, name").in("id",le);for(const je of _e||[])fe[je.id]=je.name}const ce=ue.map(_e=>({..._e,plan_name:fe[_e.plan_id]||"Service Plan"}));c(ce);const xe={};ce.forEach(_e=>{xe[_e.id]=!0}),j(xe);const{data:ve}=await w.from("service_plans").select("id, name, price_monthly, billing_interval, fulfillment_type").eq("is_active",!0).order("name");p(ve||[])}catch(Pe){console.error("ExecuteBuyoutModal load error:",Pe)}finally{x(!1)}}ke()},[n,o==null?void 0:o.tenant_id,e.quote_id]);const ee=y||Number(a==null?void 0:a.retail_price_snapshot)||Number(r.current_retail_total)||0,re=Number(r.payments_made_count)||0,Q=Number(e.monthly_amount)||0,oe=b||Number(r.install_fee)||0,ge=re*Q*(u.buyout_rental_credit_pct/100),be=oe*(u.buyout_install_credit_pct/100),we=Math.max(0,ee-ge-be),F=parseFloat(E)||0,K=T==="flat"?Math.max(0,F):T==="discount"?Math.max(0,we-F):we,Z=N.trim(),ie=T==="none"?!0:F>0&&Z.length>=10&&(T==="flat"||F<=we);let Y="";T!=="none"&&(F<=0?Y="Enter an amount greater than $0":T==="discount"&&F>we?Y=`Discount cannot exceed calculated balance (${Gt(we)})`:Z.length<10&&(Y=`Reason required â at least 10 characters (${Z.length}/10)`));function X(){const ke=[];return a&&ke.push({description:`${a.system_name||"Water System"}${a.serial_number?` (${a.serial_number})`:""}`,quantity:1,unit_price:ee,total:ee,item_type:"buyout_product"}),ge>0&&ke.push({description:`Rental Payment Credit (${re} payments à ${u.buyout_rental_credit_pct}%)`,quantity:1,unit_price:-ge,total:-ge,item_type:"credit"}),be>0&&ke.push({description:`Installation Fee Credit (${u.buyout_install_credit_pct}%)`,quantity:1,unit_price:-be,total:-be,item_type:"credit"}),d.filter(Pe=>_[Pe.id]).forEach(Pe=>{ke.push({description:`${Pe.plan_name} â Continuing after buyout`,quantity:1,unit_price:Number(Pe.price_monthly)||0,total:0,item_type:"service_plan",billing_interval:Pe.billing_interval})}),Object.entries(C).forEach(([Pe,{price:nt,billing_interval:ue}])=>{const fe=f.find(le=>le.id===Pe);fe&&ke.push({description:`${fe.name} â New plan added at buyout`,quantity:1,unit_price:nt,total:0,item_type:"service_plan",billing_interval:ue})}),ke}const H=d.filter(ke=>!_[ke.id]),de=Object.entries(C).map(([ke,{price:Pe,billing_interval:nt}])=>{const ue=f.find(fe=>fe.id===ke);return{plan_id:ke,price:Pe,billing_interval:nt,name:ue==null?void 0:ue.name}});async function pe(){if(T!=="none"){const ke=T==="flat"?`Flat buyout price: ${Gt(F)} (vs calculated ${Gt(we)})`:`Discount: â${Gt(F)}`;if(!window.confirm(`Apply admin adjustment? 758 759${ke} 760Final balance due: ${Gt(K)} 761 762Reason: ${Z} 763 764This will be logged for audit. Continue?`))return}P(!0),q("");try{const ke=T==="none"?null:{mode:T,amount:F,reason:Z,original_calculated:we,final_amount:K,adjusted_by:(o==null?void 0:o.id)||null,adjusted_by_name:(o==null?void 0:o.full_name)||"Admin",adjusted_at:new Date().toISOString()},Pe=await fetch("/api/stripe/buyout-invoice",{method:"POST",headers:await At(),body:JSON.stringify({contract_id:e.id,customer_id:n,calculation_id:r.id,line_items:X(),subtotal:we,total:K,notes:`Equipment buyout â Contract ${e.contract_number}`,plans_to_cancel:H.map(ue=>ue.id),plans_to_activate:de,tenant_buyout_config:u,adjustment:ke})}),nt=await Pe.json();if(!Pe.ok)throw new Error(nt.error||"Invoice generation failed");M(nt),i==null||i()}catch(ke){q(ke.message)}finally{P(!1)}}async function Ne(){if(D){I(!0);try{if(!(await fetch("/api/email/send-buyout",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({invoiceId:D.invoice_id,senderName:(o==null?void 0:o.full_name)||"Water Treatment Solutions",paymentLinkUrl:D.payment_link_url,systemName:a==null?void 0:a.system_name})})).ok)throw new Error("Email send failed");te(!0)}catch(ke){alert("Email failed: "+ke.message)}finally{I(!1)}}}async function Ie(){var ue;const{data:ke}=await w.from("customers").select("phone, full_name").eq("id",n).single(),Pe=((ue=ke==null?void 0:ke.phone)==null?void 0:ue.replace(/\D/g,""))||"",nt=encodeURIComponent(`Hi ${(ke==null?void 0:ke.full_name)||"there"}, your equipment buyout invoice is ready. Click here to pay ${Gt(K)}: ${D==null?void 0:D.payment_link_url}`);window.open(`sms:${Pe}?body=${nt}`,"_blank"),W(!0)}function Ze(){D!=null&&D.payment_link_url&&(navigator.clipboard.writeText(D.payment_link_url),V(!0),setTimeout(()=>V(!1),2e3))}if(v)return t.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center",style:{backgroundColor:"rgba(0,0,0,0.75)"},children:t.jsx("div",{style:{color:"#64748b",fontSize:14},children:"Loading buyout details..."})});const ht=(ke,Pe,nt)=>{const ue=T===ke;return t.jsx("button",{onClick:()=>{L(ke),ke==="none"&&(R(""),O(""))},style:{flex:1,padding:"8px 10px",borderRadius:8,fontSize:12,fontWeight:700,cursor:"pointer",background:ue?`${nt}26`:"rgba(255,255,255,0.02)",border:`1px solid ${ue?`${nt}66`:"#334155"}`,color:ue?nt:"#64748b"},children:Pe},ke)};return t.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4",style:{backgroundColor:"rgba(0,0,0,0.8)"},children:t.jsxs("div",{className:"w-full max-w-2xl max-h-[92vh] overflow-y-auto rounded-2xl flex flex-col",style:{backgroundColor:"#1e293b",border:"1px solid #334155"},children:[t.jsxs("div",{className:"flex items-center justify-between px-6 py-4 flex-shrink-0",style:{borderBottom:"1px solid #334155",background:"#162232"},children:[t.jsxs("div",{children:[t.jsx("h2",{className:"text-lg font-bold text-white",children:"Execute Buyout"}),t.jsxs("p",{className:"text-sm mt-0.5",style:{color:"#94a3b8"},children:["Contract ",e.contract_number," · ",(a==null?void 0:a.system_name)||"Water System"]})]}),t.jsx("button",{onClick:s,style:{color:"#64748b",fontSize:22,background:"none",border:"none",cursor:"pointer",lineHeight:1},children:"â"})]}),t.jsxs("div",{className:"p-6 space-y-6",children:[t.jsxs("div",{style:{display:"flex",gap:8,flexWrap:"wrap"},children:[t.jsxs("span",{style:{fontSize:11,padding:"3px 10px",borderRadius:20,background:"rgba(14,165,233,0.1)",border:"1px solid rgba(14,165,233,0.25)",color:"#0ea5e9",fontWeight:600},children:["Rental credit: ",u.buyout_rental_credit_pct,"%"]}),t.jsxs("span",{style:{fontSize:11,padding:"3px 10px",borderRadius:20,background:"rgba(74,222,128,0.1)",border:"1px solid rgba(74,222,128,0.25)",color:"#4ade80",fontWeight:600},children:["Install credit: ",u.buyout_install_credit_pct,"%"]}),t.jsxs("span",{style:{fontSize:11,padding:"3px 10px",borderRadius:20,background:"rgba(168,85,247,0.1)",border:"1px solid rgba(168,85,247,0.25)",color:"#c084fc",fontWeight:600},children:["Credit cap: ",u.buyout_credit_cap_pct,"% of retail"]}),ee>0&&t.jsxs("span",{style:{fontSize:11,padding:"3px 10px",borderRadius:20,background:"rgba(251,191,36,0.1)",border:"1px solid rgba(251,191,36,0.25)",color:"#fbbf24",fontWeight:600},children:["ð Retail from invoice: ",Gt(ee)]}),ee===0&&t.jsx("span",{style:{fontSize:11,padding:"3px 10px",borderRadius:20,background:"rgba(239,68,68,0.1)",border:"1px solid rgba(239,68,68,0.25)",color:"#f87171",fontWeight:600},children:"â No retail price found â set product retail price in catalog"})]}),t.jsxs("div",{style:{background:"rgba(14,165,233,0.06)",border:"1px solid rgba(14,165,233,0.25)",borderRadius:14,padding:20},children:[t.jsx("p",{style:{fontSize:11,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.08em",color:"#0ea5e9",margin:"0 0 16px"},children:"ð Buyout Statement"}),a&&t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",marginBottom:12,paddingBottom:12,borderBottom:"1px solid rgba(14,165,233,0.15)"},children:[t.jsxs("div",{children:[t.jsx("div",{style:{color:"#e2e8f0",fontSize:14,fontWeight:600},children:a.system_name}),a.serial_number&&t.jsx("div",{style:{color:"#64748b",fontSize:11,fontFamily:"monospace",marginTop:2},children:a.serial_number}),a.warranty_expires_at&&t.jsxs("div",{style:{color:"#60a5fa",fontSize:11,marginTop:4},children:["ð¡ Warranty until ",TZ(a.warranty_expires_at)]})]}),t.jsx("div",{style:{color:"#e2e8f0",fontSize:15,fontWeight:700},children:Gt(ee)})]}),ge>0&&t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:8},children:[t.jsxs("span",{style:{color:"#94a3b8",fontSize:13},children:["Rental credit (",re," à ",Gt(Q),"/mo à ",u.buyout_rental_credit_pct,"%)"]}),t.jsxs("span",{style:{color:"#4ade80",fontSize:13,fontWeight:600},children:["â ",Gt(ge)]})]}),be>0&&t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:8},children:[t.jsxs("span",{style:{color:"#94a3b8",fontSize:13},children:["Install fee credit (",u.buyout_install_credit_pct,"%)"]}),t.jsxs("span",{style:{color:"#4ade80",fontSize:13,fontWeight:600},children:["â ",Gt(be)]})]}),T!=="none"&&ie&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{style:{borderTop:"1px solid rgba(14,165,233,0.15)",marginTop:12,paddingTop:10,display:"flex",justifyContent:"space-between"},children:[t.jsx("span",{style:{color:"#64748b",fontSize:12},children:"Calculated balance"}),t.jsx("span",{style:{color:"#94a3b8",fontSize:13,textDecoration:"line-through"},children:Gt(we)})]}),t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginTop:6},children:[t.jsx("span",{style:{color:"#fbbf24",fontSize:13,fontWeight:600},children:T==="flat"?"â Flat negotiated amount":"â Admin discount applied"}),t.jsx("span",{style:{color:"#fbbf24",fontSize:13,fontWeight:600},children:T==="discount"?`â ${Gt(F)}`:Gt(F)})]})]}),t.jsxs("div",{style:{borderTop:"1px solid rgba(14,165,233,0.2)",marginTop:12,paddingTop:14,display:"flex",justifyContent:"space-between",alignItems:"center"},children:[t.jsx("span",{style:{fontSize:16,fontWeight:700,color:"#e2e8f0"},children:"Balance Due"}),t.jsx("span",{style:{fontSize:26,fontWeight:800,color:"#0ea5e9"},children:Gt(K)})]})]}),t.jsxs("div",{style:{background:"rgba(251,191,36,0.06)",border:"1px solid rgba(251,191,36,0.25)",borderRadius:14,padding:20},children:[t.jsx("p",{style:{fontSize:11,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.08em",color:"#fbbf24",margin:"0 0 12px"},children:"â Admin Adjustment (optional)"}),t.jsxs("div",{style:{display:"flex",gap:6,marginBottom:12},children:[ht("none","None","#64748b"),ht("flat","Flat Amount","#fbbf24"),ht("discount","Discount Off","#c084fc")]}),T!=="none"&&t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[t.jsxs("div",{children:[t.jsx("label",{style:{display:"block",fontSize:11,color:"#64748b",fontWeight:600,marginBottom:4},children:T==="flat"?"Final negotiated buyout price ($)":"Discount amount ($)"}),t.jsx("input",{type:"number",step:"0.01",min:"0",value:E,onChange:ke=>R(ke.target.value),placeholder:T==="flat"?"150.00":"50.00",style:{width:"100%",padding:"10px 14px",borderRadius:8,background:"#0f1923",border:"1px solid #334155",color:"#e2e8f0",fontSize:14,outline:"none",boxSizing:"border-box"}}),T==="flat"&&t.jsxs("p",{style:{margin:"4px 0 0",fontSize:11,color:"#64748b"},children:["Replaces calculated balance of ",Gt(we)]}),T==="discount"&&t.jsxs("p",{style:{margin:"4px 0 0",fontSize:11,color:"#64748b"},children:["Subtracted from calculated balance of ",Gt(we)]})]}),t.jsxs("div",{children:[t.jsx("label",{style:{display:"block",fontSize:11,color:"#64748b",fontWeight:600,marginBottom:4},children:"Reason (required â audit trail) *"}),t.jsx("textarea",{value:N,onChange:ke=>O(ke.target.value),rows:2,placeholder:"e.g., Customer loyalty discount, competitor price match, partial damage waiver",style:{width:"100%",padding:"10px 14px",borderRadius:8,background:"#0f1923",border:"1px solid #334155",color:"#e2e8f0",fontSize:13,outline:"none",boxSizing:"border-box",resize:"none",fontFamily:"inherit"}}),t.jsxs("p",{style:{margin:"4px 0 0",fontSize:11,color:Z.length>=10?"#4ade80":"#64748b"},children:[Z.length,"/10 characters minimum"]})]}),Y&&t.jsx("div",{style:{padding:"8px 12px",borderRadius:8,background:"rgba(239,68,68,0.1)",border:"1px solid rgba(239,68,68,0.25)",color:"#f87171",fontSize:12},children:Y})]})]}),t.jsxs("div",{style:{background:"rgba(168,85,247,0.06)",border:"1px solid rgba(168,85,247,0.25)",borderRadius:14,padding:20},children:[t.jsx("p",{style:{fontSize:11,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.08em",color:"#c084fc",margin:"0 0 14px"},children:"ð§ Service Plans After Buyout"}),d.length>0&&t.jsxs("div",{className:"space-y-2 mb-4",children:[t.jsx("p",{style:{fontSize:11,color:"#64748b",margin:"0 0 8px",fontWeight:600},children:"CURRENT ACTIVE PLANS"}),d.map(ke=>t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",borderRadius:10,background:_[ke.id]?"rgba(74,222,128,0.08)":"rgba(239,68,68,0.08)",border:`1px solid ${_[ke.id]?"rgba(74,222,128,0.2)":"rgba(239,68,68,0.2)"}`},children:[t.jsxs("div",{children:[t.jsx("div",{style:{color:"#e2e8f0",fontSize:13,fontWeight:600},children:ke.plan_name}),t.jsxs("div",{style:{color:"#64748b",fontSize:11,marginTop:2},children:[Gt(ke.price_monthly),"/",ke.billing_interval]})]}),t.jsxs("div",{style:{display:"flex",gap:6},children:[t.jsx("button",{onClick:()=>j(Pe=>({...Pe,[ke.id]:!0})),style:{padding:"4px 12px",borderRadius:8,fontSize:11,fontWeight:700,cursor:"pointer",background:_[ke.id]?"rgba(74,222,128,0.2)":"rgba(255,255,255,0.04)",border:`1px solid ${_[ke.id]?"rgba(74,222,128,0.4)":"#334155"}`,color:_[ke.id]?"#4ade80":"#64748b"},children:"â Keep"}),t.jsx("button",{onClick:()=>j(Pe=>({...Pe,[ke.id]:!1})),style:{padding:"4px 12px",borderRadius:8,fontSize:11,fontWeight:700,cursor:"pointer",background:_[ke.id]?"rgba(255,255,255,0.04)":"rgba(239,68,68,0.2)",border:`1px solid ${_[ke.id]?"#334155":"rgba(239,68,68,0.4)"}`,color:_[ke.id]?"#64748b":"#f87171"},children:"â Cancel"})]})]},ke.id))]}),t.jsx("p",{style:{fontSize:11,color:"#64748b",margin:"0 0 8px",fontWeight:600},children:"ADD NEW PLANS"}),t.jsx("div",{className:"space-y-2",children:f.filter(ke=>!d.some(Pe=>Pe.plan_id===ke.id)).map(ke=>{var nt;const Pe=!!C[ke.id];return t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",borderRadius:10,background:Pe?"rgba(168,85,247,0.1)":"rgba(255,255,255,0.02)",border:`1px solid ${Pe?"rgba(168,85,247,0.3)":"#1e3a4f"}`},children:[t.jsxs("div",{children:[t.jsx("div",{style:{color:"#e2e8f0",fontSize:13,fontWeight:600},children:ke.name}),t.jsxs("div",{style:{color:"#64748b",fontSize:11,marginTop:2},children:[Gt(ke.price_monthly),"/",ke.billing_interval," · ",(nt=ke.fulfillment_type)==null?void 0:nt.replace(/_/g," ")
764]})]}),t.jsx("button",{onClick:()=>{S(Pe?ue=>{const fe={...ue};return delete fe[ke.id],fe}:ue=>({...ue,[ke.id]:{price:ke.price_monthly,billing_interval:ke.billing_interval}}))},style:{padding:"4px 12px",borderRadius:8,fontSize:11,fontWeight:700,cursor:"pointer",background:Pe?"rgba(168,85,247,0.2)":"rgba(255,255,255,0.04)",border:`1px solid ${Pe?"rgba(168,85,247,0.4)":"#334155"}`,color:Pe?"#c084fc":"#64748b"},children:Pe?"â Added":"+ Add"})]},ke.id)})}),(H.length>0||de.length>0)&&t.jsxs("div",{style:{marginTop:12,padding:"10px 12px",borderRadius:10,background:"rgba(251,191,36,0.08)",border:"1px solid rgba(251,191,36,0.25)"},children:[t.jsx("p",{style:{margin:0,fontSize:11,fontWeight:700,color:"#fbbf24"},children:"Plan changes on payment:"}),H.map(ke=>t.jsxs("p",{style:{margin:"4px 0 0",fontSize:11,color:"#f87171"},children:["â Cancel: ",ke.plan_name]},ke.id)),de.map(ke=>t.jsxs("p",{style:{margin:"4px 0 0",fontSize:11,color:"#4ade80"},children:["â Activate: ",ke.name]},ke.plan_id))]})]}),D?t.jsxs("div",{style:{background:"rgba(74,222,128,0.06)",border:"1px solid rgba(74,222,128,0.25)",borderRadius:14,padding:20},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:16},children:[t.jsx("span",{style:{fontSize:18},children:"â
"}),t.jsxs("div",{children:[t.jsx("div",{style:{color:"#4ade80",fontWeight:700,fontSize:14},children:"Invoice Generated"}),t.jsxs("div",{style:{color:"#94a3b8",fontSize:11},children:["Invoice ",D.invoice_number," · ",Gt(K)," due"]})]})]}),t.jsxs("div",{style:{background:"rgba(255,255,255,0.03)",border:"1px solid #1e3a4f",borderRadius:10,padding:"10px 14px",marginBottom:14},children:[t.jsx("p",{style:{margin:"0 0 6px",fontSize:11,fontWeight:700,color:"#64748b",textTransform:"uppercase",letterSpacing:"0.06em"},children:"Payment Link"}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[t.jsx("span",{style:{color:"#0ea5e9",fontSize:12,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:D.payment_link_url}),t.jsx("button",{onClick:Ze,style:{flexShrink:0,padding:"4px 12px",borderRadius:8,fontSize:11,fontWeight:700,cursor:"pointer",background:G?"rgba(74,222,128,0.15)":"rgba(14,165,233,0.15)",border:`1px solid ${G?"rgba(74,222,128,0.3)":"rgba(14,165,233,0.3)"}`,color:G?"#4ade80":"#0ea5e9"},children:G?"â Copied":"Copy"}),t.jsx("a",{href:D.payment_link_url,target:"_blank",rel:"noopener noreferrer",style:{flexShrink:0,padding:"4px 12px",borderRadius:8,fontSize:11,fontWeight:700,cursor:"pointer",textDecoration:"none",background:"rgba(255,255,255,0.04)",border:"1px solid #334155",color:"#94a3b8"},children:"Open â"})]})]}),t.jsxs("div",{style:{display:"flex",gap:10},children:[t.jsx("button",{onClick:Ne,disabled:$||ae,style:{flex:1,padding:"12px 16px",borderRadius:10,fontSize:13,fontWeight:700,cursor:$||ae?"not-allowed":"pointer",opacity:ae?.7:1,background:ae?"rgba(74,222,128,0.15)":"rgba(14,165,233,0.15)",border:`1px solid ${ae?"rgba(74,222,128,0.3)":"rgba(14,165,233,0.3)"}`,color:ae?"#4ade80":"#0ea5e9"},children:$?"â³ Sending...":ae?"â Email Sent":"ð§ Send Email"}),t.jsx("button",{onClick:Ie,disabled:U,style:{flex:1,padding:"12px 16px",borderRadius:10,fontSize:13,fontWeight:700,cursor:U?"not-allowed":"pointer",opacity:U?.7:1,background:U?"rgba(74,222,128,0.15)":"rgba(34,197,94,0.15)",border:`1px solid ${U?"rgba(74,222,128,0.3)":"rgba(34,197,94,0.3)"}`,color:U?"#4ade80":"#22c55e"},children:U?"â SMS Opened":"ð¬ Send SMS"})]}),t.jsx("p",{style:{textAlign:"center",margin:"12px 0 0",fontSize:11,color:"#475569"},children:"Ownership transfers automatically when Stripe payment is received."})]}):t.jsxs("div",{children:[k&&t.jsx("div",{style:{marginBottom:12,padding:"10px 14px",borderRadius:10,background:"rgba(239,68,68,0.1)",border:"1px solid rgba(239,68,68,0.25)",color:"#f87171",fontSize:13},children:k}),t.jsx("button",{onClick:pe,disabled:z||ee===0||!ie,style:{width:"100%",padding:"14px 20px",borderRadius:12,fontSize:15,fontWeight:700,cursor:z||ee===0||!ie?"not-allowed":"pointer",opacity:z||ee===0||!ie?.5:1,background:"linear-gradient(135deg, #0ea5e9, #0369a1)",color:"#fff",border:"none",boxShadow:ee>0?"0 4px 20px rgba(14,165,233,0.3)":"none"},children:z?"â³ Generating Invoice...":ee===0?"â Set product retail price to continue":ie?`ð Generate Buyout Invoice â ${Gt(K)}`:"â Complete adjustment fields to continue"}),t.jsx("p",{style:{textAlign:"center",margin:"8px 0 0",fontSize:11,color:"#475569"},children:"Creates a formal invoice + Stripe payment link. Ownership transfers automatically when payment is received."})]})]}),t.jsx("div",{className:"flex justify-end px-6 py-4 flex-shrink-0",style:{borderTop:"1px solid #334155"},children:t.jsx("button",{onClick:s,style:{padding:"8px 20px",borderRadius:8,fontSize:13,fontWeight:600,cursor:"pointer",background:"rgba(255,255,255,0.04)",border:"1px solid #334155",color:"#94a3b8"},children:D?"Close":"Cancel"})})]})})}
764function Zd(e){return e==null?"$0.00":`$${Number(e).toLocaleString("en-US",{minimumFractionDigits:2})}`}function RZ(e,n){if(!e||!n)return"â";const r=new Date(e),s=new Date(n),i=Math.round((s.getTime()-r.getTime())/(1e3*60*60*24*30.44));return i>0?String(i):"â"}function EZ({customerId:e}){const{data:n,isLoading:r}=ig(e);return r?t.jsx("p",{className:"text-sm text-muted text-center py-8",children:"Loading rental contracts..."}):n!=null&&n.length?t.jsx("div",{className:"space-y-4",children:n.map(s=>t.jsx(PZ,{contract:s,customerId:e},s.id))}):t.jsx("p",{className:"text-sm text-muted text-center py-8",children:"No rental contracts for this customer."})}function PZ({contract:e,customerId:n}){var C;Ee();const r=rt(),{data:s}=iZ(e.id),[i,o]=g.useState(!1),[a,l]=g.useState(!1),[d,c]=g.useState(""),[f,p]=g.useState(!1),u=e.status==="active",h=u?"#4ade80":e.status==="completed"?"#38bdf8":"#94a3b8",y=!!e.bought_out_at,m=RZ(e.start_date,e.end_date),b=s||[],A=b.filter(S=>S.status==="succeeded"),v=A.length,x=A.reduce((S,T)=>S+(parseFloat(T.amount)||0),0),_=((C=A[0])==null?void 0:C.payment_date)||null;function j(){r.invalidateQueries({queryKey:Fe.rentals(n)}),r.invalidateQueries({queryKey:Fe.payments(e.id)}),r.invalidateQueries({queryKey:Fe.systems(n)}),r.invalidateQueries({queryKey:Fe.activity(n)}),r.invalidateQueries({queryKey:Fe.detail(n)})}return t.jsxs("div",{className:"bg-card border border-border rounded-xl p-4",children:[t.jsxs("div",{className:"flex items-center justify-between mb-3",children:[t.jsxs("div",{children:[t.jsxs("div",{className:"text-sm font-bold text-white",children:["Contract ",e.contract_number||"â"]}),t.jsxs("div",{className:"text-xs text-muted",children:[m," month term"]})]}),t.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full font-semibold capitalize",style:{backgroundColor:`${h}20`,color:h},children:e.status})]}),t.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-2 text-xs mb-3",children:[t.jsx(No,{label:"Monthly",value:Zd(e.monthly_amount)}),t.jsx(No,{label:"Payments Made",value:String(v)}),t.jsx(No,{label:"Total Paid",value:Zd(x)}),t.jsx(No,{label:"Install Fees",value:Zd(0)}),t.jsx(No,{label:"Start Date",value:dn(e.start_date)}),t.jsx(No,{label:"End Date",value:dn(e.end_date)}),_&&t.jsx(No,{label:"Last Payment",value:dn(_)})]}),u&&!y&&t.jsxs("div",{className:"flex flex-wrap gap-2 mb-3",children:[t.jsx("button",{onClick:()=>l(!0),className:"text-xs px-3 py-1.5 rounded-lg font-semibold transition-colors",style:{backgroundColor:"rgba(34,197,94,0.12)",color:"#4ade80",border:"1px solid rgba(34,197,94,0.25)"},children:"ð³ Record Payment"}),t.jsx("button",{onClick:()=>p(!0),className:"text-xs px-3 py-1.5 rounded-lg font-semibold transition-colors",style:{backgroundColor:"rgba(56,189,248,0.12)",color:"#38bdf8",border:"1px solid rgba(56,189,248,0.25)"},children:"ð§® Calculate Buyout"})]}),d&&t.jsx("div",{className:"mb-3 text-xs rounded-lg px-3 py-2",style:{color:"#f87171",backgroundColor:"rgba(239,68,68,0.1)",border:"1px solid rgba(239,68,68,0.2)"},children:d}),y?t.jsxs("div",{className:"rounded-lg p-3 mb-3",style:{backgroundColor:"rgba(34,197,94,0.08)",border:"1px solid rgba(34,197,94,0.2)"},children:[t.jsx("div",{className:"text-xs font-bold uppercase tracking-wide mb-1",style:{color:"#4ade80"},children:"Buyout Complete"}),t.jsxs("div",{className:"text-xs text-muted",children:["Completed ",sr(e.bought_out_at)]}),e.buyout_amount&&t.jsxs("div",{className:"text-xs text-slate-300 mt-0.5",children:["Buyout amount: ",Zd(e.buyout_amount)]})]}):u?t.jsx("div",{className:"rounded-lg p-3 mb-3",style:{backgroundColor:"rgba(148,163,184,0.06)",border:"1px solid rgba(148,163,184,0.15)"},children:t.jsx("div",{className:"text-xs text-muted",children:'No buyout calculation yet. Click "Calculate Buyout" to see the price.'})}):null,b.length>0&&t.jsxs("div",{children:[t.jsxs("button",{onClick:()=>o(!i),className:"text-xs hover:underline",style:{color:"#38bdf8"},children:[i?"Hide":"Show"," payment history (",b.length,")"]}),i&&t.jsx("div",{className:"mt-2 space-y-1 max-h-48 overflow-y-auto",children:b.map((S,T)=>t.jsxs("div",{className:"flex items-center justify-between text-xs py-1.5 border-b border-border/50 last:border-0",children:[t.jsx("span",{className:"text-muted",children:dn(S.payment_date)}),t.jsx("span",{className:"text-slate-300",children:Zd(S.amount)}),t.jsx("span",{style:{color:S.status==="succeeded"?"#4ade80":S.status==="failed"?"#f87171":"#94a3b8"},children:S.status})]},S.id||T))})]}),a&&t.jsx(CZ,{contract:e,customerId:n,onClose:()=>l(!1),onCompleted:()=>{l(!1),j()}}),f&&t.jsx(NZ,{contract:e,customerId:n,calculation:{id:e.id,current_retail_total:e.buyout_amount||0,payments_made_count:Math.max(0,A.filter(S=>Math.abs(parseFloat(S.amount)-Number(e.monthly_amount))<.1).length),install_fee:0},onClose:()=>p(!1),onInvoiceGenerated:()=>{p(!1),j()}})]})}function No({label:e,value:n}){return t.jsxs("div",{children:[t.jsxs("span",{className:"text-muted",children:[e,": "]}),t.jsx("span",{className:"text-slate-300",children:n})]})}async function u3(e){return"unknown"}function kj(e,n){const r=new Date(e+"T00:00:00");return r.setMonth(r.getMonth()+n),r.toISOString().split("T")[0]}function Cj(){return new Date().toISOString().split("T")[0]}async function qZ(e,n){const{data:r}=await w.from("compliance_requirements").select("*").eq("id",e).single();if(!r)return;
764const s=kj(n,r.interval_months),i=kj(s,r.grace_period_months);await w.from("service_schedule_items").insert({compliance_requirement_id:e,installed_system_id:r.installed_system_id,customer_id:r.customer_id,due_date:s,grace_expiry_date:i,status:"upcoming"})}async function DZ(e,n,r,s,i){const{data:o}=await w.from("service_schedule_items").select("*").eq("id",e).single();if(!o)throw new Error("Schedule item not found");const{data:a,error:l}=await w.from("service_completions").insert({service_schedule_item_id:e,compliance_requirement_id:o.compliance_requirement_id,installed_system_id:o.installed_system_id,customer_id:o.customer_id,completed_date:Cj(),completed_by:n,purchased_through_zenith:r,cost:s,notes:i}).select("id").single();if(l)throw new Error(`Completion failed: ${l.message}`);return await w.from("service_schedule_items").update({status:"completed",service_completion_id:a.id,completed_at:new Date().toISOString()}).eq("id",e),await qZ(o.compliance_requirement_id,Cj()),await u3(o.installed_system_id),a.id}function OZ({scheduleItem:e,customerId:n,requirementLabel:r,onClose:s,onCompleted:i}){const{user:o}=Ee(),a=rt(),[l,d]=g.useState(!0),[c,f]=g.useState(""),[p,u]=g.useState(""),[h,y]=g.useState(!1),[m,b]=g.useState("");async function A(){if(o){y(!0),b("");try{await DZ(e.id,o.id,l,c?Number(c):void 0,p||void 0),a.invalidateQueries({queryKey:Fe.schedules(n)}),a.invalidateQueries({queryKey:Fe.completions(n)}),a.invalidateQueries({queryKey:Fe.warranties(n)}),a.invalidateQueries({queryKey:Fe.requirements(n)}),a.invalidateQueries({queryKey:Fe.activity(n)}),a.invalidateQueries({queryKey:Fe.detail(n)}),i()}catch(v){b(v.message)}finally{y(!1)}}}return t.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60",onClick:s,children:t.jsxs("div",{className:"bg-card border border-border rounded-xl p-5 w-full max-w-md
764shadow-xl",onClick:v=>v.stopPropagation(),children:[t.jsx("h3",{className:"text-sm font-bold text-white mb-1",children:"Complete Service"}),t.jsx("p",{className:"text-xs text-muted mb-4",children:r}),t.jsxs("div",{className:"mb-3",children:[t.jsx("label",{className:"text-xs font-semibold text-slate-300 uppercase tracking-wide block mb-2",children:"Purchase Source"}),t.jsxs("div",{className:"flex gap-2",children:[t.jsx("button",{onClick:()=>d(!0),className:"flex-1 text-xs px-3 py-2 rounded-lg border font-semibold transition-colors",style:l?{backgroundColor:"rgba(34,197,94,0.15)",color:"#4ade80",borderColor:"rgba(34,197,94,0.4)"}:{backgroundColor:"transparent",color:"#94a3b8",borderColor:"rgba(148,163,184,0.2)"},children:"â Through Zenith"}),t.jsx("button",{onClick:()=>d(!1),className:"flex-1 text-xs px-3 py-2 rounded-lg border font-semibold transition-colors",style:l?{backgroundColor:"transparent",color:"#94a3b8",borderColor:"rgba(148,163,184,0.2)"}:{backgroundColor:"rgba(245,158,11,0.15)",color:"#fbbf24",borderColor:"rgba(245,158,11,0.4)"},children:"External Purchase"})]}),!l&&e.must_purchase_through_zenith&&t.jsx("div",{className:"text-xs mt-1.5",style:{color:"#f87171"},children:"â ï¸ This requirement must be purchased through Zenith â warranty may be voided."})]}),t.jsxs("div",{className:"mb-3",children:[t.jsx("label",{className:"text-xs font-semibold text-slate-300 uppercase tracking-wide block mb-1",children:"Cost (optional)"}),t.jsx("input",{type:"number",value:c,onChange:v=>f(v.target.value),placeholder:"0.00",step:"0.01",className:"w-full bg-surface border border-border rounded-lg px-3 py-2 text-sm text-white placeholder-muted focus:outline-none focus:border-accent"})]}),t.jsxs("div",{className:"mb-4",children:[t.jsx("label",{className:"text-xs font-semibold text-slate-300 uppercase tracking-wide block mb-1",children:"Notes (optional)"}),t.jsx("textarea",{value:p,onChange:v=>u(v.target.value),rows:2,placeholder:"Service details, receipt #, etc.",className:"w-full bg-surface border border-border rounded-lg px-3 py-2 text-sm text-white placeholder-muted focus:outline-none focus:border-accent resize-none"})]}),m&&t.jsx("div",{className:"mb-3 text-xs rounded-lg px-3 py-2",style:{color:"#f87171",backgroundColor:"rgba(239,68,68,0.1)",border:"1px solid rgba(239,68,68,0.2)"},children:m}),t.jsxs("div",{className:"flex gap-2",children:[t.jsx("button",{onClick:s,disabled:h,className:"flex-1 text-xs px-3 py-2 rounded-lg border border-border text-muted hover:text-slate-300 transition-colors",children:"Cancel"}),t.jsx("button",{onClick:A,disabled:h,className:"flex-1 text-xs px-3 py-2 rounded-lg font-semibold transition-colors disabled:opacity-50",style:{backgroundColor:"rgba(34,197,94,0.15)",color:"#4ade80",border:"1px solid rgba(34,197,94,0.3)"},children:h?"Completing...":"Mark Complete"})]})]})})}async function IZ(e,n,r,s,i){const{data:o}=await w.from("compliance_requirements").select("customer_id").eq("id",e).single();if(!o)throw new Error("Requirement not found");const{data:a,error:l}=await w.from("compliance_proofs").insert({compliance_requirement_id:e,service_completion_id:null,customer_id:o.customer_id,proof_url:n,proof_type:r,submitted_by:s.actor_id,review_status:"pending"}).select("id").single();if(l)throw new Error(`Proof submission failed: ${l.message}`);return await Tt({customer_id:o.customer_id,event_type:"proof_submitted",title:"Compliance proof submitted",metadata:{proof_id:a.id,requirement_id:e,proof_type:r},actor_id:s.actor_id,actor_name:s.actor_name||null}).then(()=>{}).catch(()=>{}),a.id}async function LZ(e,n,r,s){const{data:i}=await w.from("compliance_proofs").select("compliance_requirement_id, customer_id").eq("id",e).single();if(!i)throw new Error("Proof not found");await w.from("compliance_proofs").update({review_status:n,reviewed_by:r.actor_id,reviewed_at:new Date().toISOString(),review_notes:s||null}).eq("id",e);const{data:o}=await w.from("compliance_requirements").select("installed_system_id").eq("id",i.compliance_requirement_id).single();o&&await u3(o.installed_system_id),await Tt({customer_id:i.customer_id,event_type:"proof_reviewed",title:`Proof ${n}${s?": "+s:""}`,metadata:{proof_id:e,status:n},actor_id:r.actor_id,actor_name:r.actor_name||null}).then(()=>{}).catch(()=>{})}function WZ({requirementId:e,customerId:n,requirementLabel:r,onClose:s,onCompleted:i}){const{user:o,profile:a}=Ee(),l=rt(),[d,c]=g.useState(""),[f,p]=g.useState("receipt"),[u,h]=g.useState(!1),[y,m]=g.useState("");async function b(){if(!(!o||!d.trim())){h(!0),m("");try{await IZ(e,d.trim(),f,{actor_id:o.id,actor_name:a==null?void 0:a.full_name}
764),l.invalidateQueries({queryKey:Fe.proofs(n)}),l.invalidateQueries({queryKey:Fe.activity(n)}),i()}catch(A){m(A.message)}finally{h(!1)}}}return t.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60",onClick:s,children:t.jsxs("div",{className:"bg-card border border-border rounded-xl p-5 w-full max-w-md shadow-xl",onClick:A=>A.stopPropagation(),children:[t.jsx("h3",{className:"text-sm font-bold text-white mb-1",children:"Submit Compliance Proof"}),t.jsx("p",{className:"text-xs text-muted mb-4",children:r}),t.jsxs("div",{className:"mb-3",children:[t.jsx("label",{className:"text-xs font-semibold text-slate-300 uppercase tracking-wide block mb-1",children:"Proof Type"}),t.jsxs("select",{value:f,onChange:A=>p(A.target.value),className:"w-full bg-surface border border-border rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-accent",children:[t.jsx("option",{value:"receipt",children:"Receipt"}),t.jsx("option",{value:"invoice",children:"Invoice"}),t.jsx("option",{value:"photo",children:"Photo"}),t.jsx("option",{value:"service_record",children:"Service Record"}),t.jsx("option",{value:"other",children:"Other"})]})]}),t.jsxs("div",{className:"mb-4",children:[t.jsx("label",{className:"text-xs font-semibold text-slate-300 uppercase tracking-wide block mb-1",children:"Proof URL"}),t.jsx("input",{type:"url",value:d,onChange:A=>c(A.target.value),placeholder:"https://... (link to receipt, photo, or document)",className:"w-full bg-surface border border-border rounded-lg px-3 py-2 text-sm text-white placeholder-muted focus:outline-none focus:border-accent"}),t.jsx("p",{className:"text-xs text-muted mt-1",children:"Paste a link to the uploaded proof document or image."})]}),y&&t.jsx("div",{className:"mb-3 text-xs rounded-lg px-3 py-2",style:{color:"#f87171",backgroundColor:"rgba(239,68,68,0.1)",border:"1px solid rgba(239,68,68,0.2)"},children:y}),t.jsxs("div",{className:"flex gap-2",children:[t.jsx("button",{onClick:s,disabled:u,className:"flex-1 text-xs px-3 py-2 rounded-lg border border-border text-muted hover:text-slate-300 transition-colors",children:"Cancel"}),t.jsx("button",{onClick:b,disabled:u||!d.trim(),className:"flex-1 text-xs px-3 py-2 rounded-lg font-semibold transition-colors disabled:opacity-50",style:{backgroundColor:"rgba(56,189,248,0.15)",color:"#38bdf8",border:"1px solid rgba(56,189,248,0.3)"},children:u?"Submitting...":"Submit Proof"})]})]})})}function Kd(e){return e?new Date(e).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):"â"}function $Z(e){return Math.floor((new Date(e).getTime()-Date.now())/864e5)}const Tj={upcoming:{color:"#94a3b8",label:"Upcoming"},due_soon:{color:"#fbbf24",label:"Due Soon"},overdue:{color:"#f87171",label:"Overdue"},completed:{color:"#4ade80",label:"Completed"},skipped:{color:"#94a3b8",label:"Skipped"}};function MZ({customerId:e}){const{data:n,isLoading:r}=a3(e),{data:s,isLoading:i}=oZ(e),{data:o,isLoading:a}=l3(e),{data:l}=aZ(e),[d,c]=g.useState(null),[f,p]=g.useState(null);if(r||i||a)return t.jsx("p",{className:"text-sm text-muted text-center py-8",children:"Loading maintenance data..."});const h=(n||[]).find(v=>v.status==="active"),y=(o||[]).length>0,m=(s||[]).length>0,b=s||[];function A(v){var _;const x=b.find(j=>j.id===v);return x?jj[x.requirement_type]||((_=x.requirement_type)==null?void 0:_.replace(/_/g," ")):"Scheduled Service"}return t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{className:"bg-card border border-border rounded-xl p-4",children:[t.jsxs("div",{className:"flex items-center justify-between mb-2",children:[t.jsx("h4",{className:"text-xs font-bold text-slate-300 uppercase tracking-wide",children:"Annual Maintenance Plan"}),h?t.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full font-semibold",style:{backgroundColor:"rgba(34,197,94,0.15)",color:"#4ade80"},children:"Active"}):t.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full font-semibold",style:{backgroundColor:"rgba(239,68,68,0.15)",color:"#f87171"},children:"No Active Plan"})]}),h?t.jsxs("div",{className:"text-xs text-muted space-y-1",children:[t.jsxs("div",{children:["Price
764: ",h.included_in_rental?"Included in Rental":`$${h.price_snapshot}/year`]}),t.jsxs("div",{children:["Renewal: ",Kd(h.renewal_date)]}),t.jsxs("div",{children:["Auto-renew: ",h.auto_renew?"Yes":"No"]})]}):t.jsx("div",{className:"text-xs text-muted",children:"No active maintenance plan. Some warranties require an active plan to remain valid."})]}),t.jsxs("div",{children:[t.jsx("h4",{className:"text-xs font-bold text-slate-300 uppercase tracking-wide mb-3",children:"Service Schedule"}),y?t.jsx("div",{className:"space-y-2",children:o.map(v=>{const x=v.due_date?$Z(v.due_date):0,_=Tj[v.status]||Tj.upcoming,j=A(v.compliance_requirement_id),C=v.status!=="completed"&&v.status!=="skipped";return t.jsxs("div",{className:"bg-card border border-border rounded-xl p-3",children:[t.jsxs("div",{className:"flex items-center justify-between mb-1",children:[t.jsx("span",{className:"text-sm font-medium text-white",children:j}),t.jsx("span",{className:"text-xs font-semibold",style:{color:_.color},children:v.status==="overdue"?`Overdue (${Math.abs(x)}d)`:v.status==="due_soon"?`Due in ${x}d`:v.status==="completed"?"Completed":v.status==="skipped"?"Skipped":v.due_date?`In ${x}d`:_.label})]}),t.jsxs("div",{className:"text-xs text-muted space-y-0.5",children:[t.jsxs("div",{children:["Due: ",Kd(v.due_date)]}),v.grace_expiry_date&&v.status==="overdue"&&t.jsxs("div",{style:{color:"#f87171"},children:["Grace expires: ",Kd(v.grace_expiry_date)," â warranty will void"]}),v.completed_at&&t.jsxs("div",{children:["Completed: ",Kd(v.completed_at)]})]}),C&&t.jsxs("div",{className:"flex gap-2 mt-2",children:[t.jsx("button",{onClick:()=>c({item:v,label:j}),className:"text-xs px-3 py-1.5 rounded-lg font-semibold transition-colors",style:{backgroundColor:"rgba(34,197,94,0.12)",color:"#4ade80",border:"1px solid rgba(34,197,94,0.25)"},children:"â Mark Complete"}),v.compliance_requirement_id&&t.jsx("button",{onClick:()=>p({requirementId:v.compliance_requirement_id,label:j}),className:"text-xs px-3 py-1.5 rounded-lg font-semibold transition-colors",style:{backgroundColor:"rgba(56,189,248,0.12)",color:"#38bdf8",border:"1px solid rgba(56,189,248,0.25)"},children:"ð Upload Proof"})]})]},v.id)})}):t.jsx("p",{className:"text-sm text-muted text-center py-4",children:"No service schedule items."})]}),m&&t.jsxs("div",{children:[t.jsx("h4",{className:"text-xs font-bold text-slate-300 uppercase tracking-wide mb-3",children:"Compliance Requirements"}),t.jsx("div",{className:"space-y-2",children:b.map(v=>{var x;return t.jsxs("div",{className:"bg-card border border-border rounded-xl p-3",children:[t.jsxs("div",{className:"flex items-center justify-between mb-1",children:[t.jsx("span",{className:"text-sm font-medium text-white",children:jj[v.requirement_type]||((x=v.requirement_type)==null?void 0:x.replace(/_/g," "))}),t.jsxs("span",{className:"text-xs text-muted",children:["Every ",v.interval_months," months"]})]}),t.jsxs("div",{className:"flex flex-wrap gap-2 mt-1 text-xs",children:[v.must_purchase_through_zenith&&t.jsx("span",{className:"px-1.5 py-0.5 rounded",style:{backgroundColor:"rgba(56,189,248,0.1)",color:"#38bdf8"},children:"Must purchase through Zenith"}),v.affects_warranty&&t.jsx("span",{className:"px-1.5 py-0.5 rounded",style:{backgroundColor:"rgba(245,158,11,0.1)",color:"#fbbf24"},children:"Affects warranty"}),v.requires_active_plan&&t.jsx("span",{className:"px-1.5 py-0.5 rounded",style:{backgroundColor:"rgba(168,85,247,0.1)",color:"#c084fc"},children:"Requires active plan"})]})]},v.id)})})]}),(l||[]).length>0&&t.jsxs("div",{children:[t.jsx("h4",{className:"text-xs font-bold text-slate-300 uppercase tracking-wide mb-3",children:"Recent Service Completions"}),t.jsx("div",{className:"space-y-1",children:l.slice(0,10).map(v=>t.jsxs("div",{className:"flex items-center justify-between text-xs py-2 border-b border-border/50 last:border-0",children:[t.jsxs("div",{children:[t.jsx("span",{className:"text-slate-300",children:A(v.compliance_requirement_id)}),v.purchased_through_zenith&&t.jsx("span",{className:"text-muted ml-2",children:"(via Zenith)"}),v.purchased_through_zenith===!1&&t.jsx("span",{className:"ml-2",style:{color:"#fbbf24"},children:"(external)"})]}),t.jsx("div",{className:"text-muted",children:Kd(v.completed_date)})]},v.id))})]}),d&&t.jsx(OZ,{scheduleItem:d.item,customerId:e,requirementLabel:d.label,onClose:()=>c(null),onCompleted:()=>c(null)}),f&&t.jsx(WZ,{requirementId:f.requirementId,customerId:e,requirementLabel:f.label,onClose:()=>p(null),onCompleted:()=>p(null)})]})}function zj(){const e=new Date,n=r=>String(r).padStart(2,"0");return e.getFullYear()+"-"+n(e.getMonth()+1)+"-"+n(e.getDate())+"T"+n(e.getHours())+":"+n(e.getMinutes())}function p3(e){return new Date(e).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit"})}function FZ(e){const n=Date.now()-new Date(e).getTime(),r=Math.floor(n/6e4);if(r<1)return"Just now";if(r<60)return`${r}m ago`;const s=Math.floor(r/60);if(s<24)return`${s}h ago`;const i=Math.floor(s/24);return i<7?`${i}d ago`:p3(e)}const BZ={customer_created:"ð¤",system_installed:"ð§",warranty_change:"ð¡ï¸",lifecycle_change:"ð",payment_recorded:"ð³",buyout_completed:"ð ",consent_submitted:"ð",handover_submitted:"ð",rental_risk_change:"â ï¸",service_completed:"â
",proof_submitted:"ð",proof_reviewed:"ð",maintenance_plan_created:"ð
",service_plan_activated:"ð",lead_created:"â¨",stage_changed:"â¡ï¸",chase_synced:"ð",booking_advanced:"ð",quote_sent:"ð",quote_signed:"âï¸",call_logged:"ð",sms_sent:"ð¬",sms_received:"ð©",email_sent:"âï¸",site_visit_completed:"ð "},UZ={customer_created:"#4ade80",system_installed:"#38bdf8",warranty_change:"#fbbf24",lifecycle_change:"#c084fc",payment_recorded:"#4ade80",buyout_completed:"#4ade80",rental_risk_change:"#f87171",service_plan_activated:"#38bdf8",lead_created:"#4ade80",stage_changed:"#c084fc",chase_synced:"#94a3b8",booking_advanced:"#38bdf8",quote_sent:"#fbbf24",quote_signed:"#4ade80",sms_sent:"#60a5fa",sms_received:"#4ade80",email_sent:"#60a5fa"};function HZ({customerId:e,leadId:n}){const{data:r,isLoading:s}
764=dZ(e,n),{user:i,profile:o}=Ee(),a=rt(),[l,d]=g.useState(!1),[c,f]=g.useState("outbound"),[p,u]=g.useState(""),[h,y]=g.useState(zj()),[m,b]=g.useState(!1),[A,v]=g.useState(null);async function x(){if(v(null),!p.trim()){v("Enter the message text.");return}b(!0);try{await m8({entityType:"customer",entityId:e,direction:c,body:p,occurredAt:new Date(h).toISOString(),actorId:(i==null?void 0:i.id)||null,actorName:(o==null?void 0:o.full_name)||null}),d(!1),u(""),y(zj()),f("outbound"),a.invalidateQueries({predicate:j=>Array.isArray(j.queryKey)&&j.queryKey.includes(e)})}catch(j){v((j==null?void 0:j.message)||"Could not save. Try again.")}finally{b(!1)}}const _=r||[];return t.jsxs("div",{className:"space-y-0",children:[t.jsx("div",{className:"flex justify-end pb-3",children:t.jsx("button",{onClick:()=>d(!0),style:{fontSize:12,fontWeight:600,padding:"5px 10px",borderRadius:6,color:"#60a5fa",backgroundColor:"rgba(96,165,250,0.12)",border:"1px solid rgba(96,165,250,0.35)"},children:"+ Log a text"})}),l&&t.jsx("div",{style:{position:"fixed",inset:0,zIndex:60,backgroundColor:"rgba(2,6,23,0.72)",display:"flex",alignItems:"center",justifyContent:"center",padding:16},onClick:()=>{m||d(!1)},children:t.jsxs("div",{onClick:j=>j.stopPropagation(),style:{width:"100%",maxWidth:460,borderRadius:12,padding:18,backgroundColor:"#0f172a",border:"1px solid #1e3a4f"},children:[t.jsx("div",{style:{fontSize:15,fontWeight:600,color:"#e2e8f0"},children:"Log a text message"}),t.jsx("div",{style:{fontSize:12,color:"#94a3b8",marginTop:4},children:"For texts sent or received outside the CRM."}),t.jsx("div",{style:{display:"flex",gap:8,marginTop:14},children:["outbound","inbound"].map(j=>t.jsx("button",{onClick:()=>f(j),style:{flex:1,fontSize:12,fontWeight:600,padding:"7px 0",borderRadius:6,color:c===j?"#0f172a":"#94a3b8",backgroundColor:c===j?"#60a5fa":"rgba(148,163,184,0.10)",border:"1px solid "+(c===j?"#60a5fa":"rgba(148,163,184,0.25)")},children:j==="outbound"?"I texted them":"They texted me"},j))}),t.jsx("textarea",{value:p,onChange:j=>u(j.target.value),rows:5,placeholder:"Paste or type what was said...",style:{width:"100%",marginTop:12,fontSize:13,lineHeight:1.5,padding:"9px 10px",borderRadius:8,resize:"vertical",color:"#e2e8f0",backgroundColor:"rgba(15,23,42,0.85)",border:"1px solid #1e3a4f"}}),t.jsxs("div",{style:{marginTop:12},children:[t.jsx("div",{style:{fontSize:11,color:"#94a3b8",marginBottom:4},children:"When did this happen?"}),t.jsx("input",{type:"datetime-local",value:h,onChange:j=>y(j.target.value),style:{width:"100%",fontSize:13,padding:"8px 10px",borderRadius:8,color:"#e2e8f0",backgroundColor:"rgba(15,23,42,0.85)",border:"1px solid #1e3a4f"}})]}),A&&t.jsx("div",{style:{marginTop:10,fontSize:12,color:"#f87171"},children:A}),t.jsxs("div",{style:{display:"flex",gap:8,marginTop:16},children:[t.jsx("button",{onClick:()=>d(!1),disabled:m,style:{flex:1,fontSize:13,fontWeight:600,padding:"8px 0",borderRadius:8,color:"#94a3b8",backgroundColor:"rgba(148,163,184,0.10)",border:"1px solid rgba(148,163,184,0.25)"},children:"Cancel"}),t.jsx("button",{onClick:x,disabled:m,style:{flex:1,fontSize:13,fontWeight:600,padding:"8px 0",borderRadius:8,color:"#0f172a",backgroundColor:m?"#475569":"#60a5fa",border:"1px solid "+(m?"#475569":"#60a5fa")},children:m?"Saving...":"Save to timeline"})]})]})}),s&&t.jsx("p",{className:"text-sm text-muted text-center py-8",children:"Loading activity..."}),!s&&_.length===0&&t.jsx("p",{className:"text-sm text-muted text-center py-8",children:"No activity recorded yet."}),_.map((j,C)=>{var R;const S=BZ[j.event_type]||"ð",T=UZ[j.event_type]||"#94a3b8",L=j.entity_type==="lead",E=(R=j.metadata)==null?void 0:R.body;return t.jsxs("div",{className:"flex gap-3 py-3 border-b border-border/50 last:border-0",children:[t.jsxs("div",{className:"flex flex-col items-center pt-0.5",children:[t.jsx("div",{className:"text-sm",children:S}),C<_.length-1&&t.jsx("div",{className:"w-px flex-1 mt-1",style:{backgroundColor:"rgba(148,163,184,0.15)"}})]}),t.jsxs("div",{className:"flex-1 min-w-0",children:[t.jsxs("div",{className:"flex items-start justify-between gap-2",children:[t.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[t.jsx("div",{className:"text-sm font-medium",style:{color:T},children:j.title}),L&&t.jsx("span",{style:{fontSize:9,fontWeight:700,letterSpacing:"0.06em",textTransform:"uppercase",color:"#94a3b8",backgroundColor:"rgba(148,163,184,0.12)",border:"1px solid rgba(148,163,184,0.2)",borderRadius:4,padding:"1px 5px",flexShrink:0},children:"Lead"})]}),t.jsx("div",{className:"text-xs text-muted whitespace-nowrap flex-shrink-0",title:p3(j.created_at),children:FZ(j.created_at)})]}),j.actor_name&&t.jsxs("div",{className:"text-xs text-muted mt-0.5",children:["by ",j.actor_name]}),E&&t.jsx("div",{className:"mt-1.5 whitespace-pre-wrap",style:{fontSize:12,lineHeight:1.5,color:"#cbd5e1",backgroundColor:"rgba(15,23,42,0.5)",border:"1px solid #1e3a4f",borderRadius:8,padding:"8px 10px"},children:E}),j.metadata&&Object.keys(j.metadata).length>0&&t.jsx(VZ,{metadata:j.metadata})]})]},j.id||C)})]})}function VZ({metadata:e}){const n=[];return e.from&&e.to&&!e.body&&n.push(`${e.from} â ${e.to}`),e.system_type&&n.push(`System: ${String(e.system_type).replace(/_/g," ")}`),e.ownership_type&&n.push(`Type: ${e.ownership_type}`),e.buyout_price&&n.push(`Buyout: $${Number(e.buyout_price).toLocaleStr
764ing()}`),e.amount&&n.push(`Amount: $${Number(e.amount).toFixed(2)}`),e.reason&&n.push(e.reason),e.days_late&&n.push(`${e.days_late} days late`),e.body&&e.to&&n.push(`to ${e.to}`),n.length===0?null:t.jsx("div",{className:"text-xs text-muted mt-1",children:n.join(" · ")})}function ZZ({proof:e,customerId:n,onClose:r,onCompleted:s}){var y;const{user:i,profile:o}=Ee(),a=rt(),[l,d]=g.useState(""),[c,f]=g.useState(!1),[p,u]=g.useState("");async function h(m){if(i){f(!0),u("");try{await LZ(e.id,m,{actor_id:i.id,actor_name:o==null?void 0:o.full_name},l||void 0),a.invalidateQueries({queryKey:Fe.proofs(n)}),a.invalidateQueries({queryKey:Fe.warranties(n)}),a.invalidateQueries({queryKey:Fe.activity(n)}),a.invalidateQueries({queryKey:Fe.detail(n)}),s()}catch(b){u(b.message)}finally{f(!1)}}}return t.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60",onClick:r,children:t.jsxs("div",{className:"bg-card border border-border rounded-xl p-5 w-full max-w-md shadow-xl",onClick:m=>m.stopPropagation(),children:[t.jsx("h3",{className:"text-sm font-bold text-white mb-1",children:"Review Compliance Proof"}),t.jsxs("p",{className:"text-xs text-muted mb-4",children:[(y=e.proof_type)==null?void 0:y.replace(/_/g," ")," â submitted ",new Date(e.submitted_at).toLocaleDateString()]}),e.proof_url&&t.jsx("div",{className:"mb-3 p-3 bg-surface border border-border rounded-lg",children:t.jsxs("a",{href:e.proof_url,target:"_blank",rel:"noopener noreferrer",className:"text-xs font-medium break-all",style:{color:"#38bdf8"},children:["ð ",e.proof_url]})}),t.jsxs("div",{className:"mb-4",children:[t.jsx("label",{className:"text-xs font-semibold text-slate-300 uppercase tracking-wide block mb-1",children:"Review Notes (optional)"}),t.jsx("textarea",{value:l,onChange:m=>d(m.target.value),rows:2,placeholder:"Reason for acceptance or rejection...",className:"w-full bg-surface border border-border rounded-lg px-3 py-2 text-sm text-white placeholder-muted focus:outline-none focus:border-accent resize-none"})]}),p&&t.jsx("div",{className:"mb-3 text-xs rounded-lg px-3 py-2",style:{color:"#f87171",backgroundColor:"rgba(239,68,68,0.1)",border:"1px solid rgba(239,68,68,0.2)"},children:p}),t.jsxs("div",{className:"flex gap-2",children:[t.jsx("button",{onClick:r,disabled:c,className:"text-xs px-3 py-2 rounded-lg border border-border text-muted hover:text-slate-300 transition-colors",children:"Cancel"}),t.jsx("button",{onClick:()=>h("rejected"),disabled:c,className:"flex-1 text-xs px-3 py-2 rounded-lg font-semibold transition-colors disabled:opacity-50",style:{backgroundColor:"rgba(239,68,68,0.15)",color:"#f87171",border:"1px solid rgba(239,68,68,0.3)"},children:c?"...":"â Reject"}),t.jsx("button",{onClick:()=>h("accepted"),disabled:c,className:"flex-1 text-xs px-3 py-2 rounded-lg font-semibold transition-colors disabled:opacity-50",style:{backgroundColor:"rgba(34,197,94,0.15)",color:"#4ade80",border:"1px solid rgba(34,197,94,0.3)"},children:c?"...":"â Accept"})]})]})})}const ju="data:image/png;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/4gHYSUNDX1BST0ZJTEUAAQEAAAHIAAAAAAQwAABtbnRyUkdCIFhZWiAH4AABAAEAAAAAAABhY3NwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAA9tYAAQAAAADTLQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAlkZXNjAAAA8AAAACRyWFlaAAABFAAAABRnWFlaAAABKAAAABRiWFlaAAABPAAAABR3dHB0AAABUAAAABRyVFJDAAABZAAAAChnVFJDAAABZAAAAChiVFJDAAABZAAAAChjcHJ0AAABjAAAADxtbHVjAAAAAAAAAAEAAAAMZW5VUwAAAAgAAAAcAHMAUgBHAEJYWVogAAAAAAAAb6IAADj1AAADkFhZWiAAAAAAAABimQAAt4UAABjaWFlaIAAAAAAAACSgAAAPhAAAts9YWVogAAAAAAAA9tYAAQAAAADTLXBhcmEAAAAAAAQAAAACZmYAAPKnAAANWQAAE9AAAApbAAAAAAAAAABtbHVjAAAAAAAAAAEAAAAMZW5VUwAAACAAAAAcAEcAbwBvAGcAbABlACAASQBuAGMALgAgADIAMAAxADb/2wBDAAUDBAQEAwUEBAQFBQUGBwwIBwcHBw8LCwkMEQ8SEhEPERETFhwXExQaFRERGCEYGh0dHx8fExciJCIeJBweHx7/2wBDAQUFBQcGBw4ICA4eFBEUHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh7/wAARCAYbBhsDASIAAhEBAxEB/8QAHQABAAICAwEBAAAAAAAAAAAAAAcIBgkBBAUDAv/EAFsQAQABAgQBBQcOCAsHAwUAAwABAgMEBQYRBwgSITFBExg3UVaU0RQXIlVhcXR1gZGhsbPTMkJSVHOVstIVIzM0NTZicoKSwSRDU5OitMIWY+ElRYTD8ERG8f/EABoBAQADAQEBAAAAAAAAAAAAAAADBAUCAQb/xAA4EQEAAgECAggDBwMFAQEBAAAAAQIDBBEUMQUSEyEyUVJxM0FhFSJCgZGh8AaxwSM0YtHhQ5Lx/9oADAMBAAIRAxEAPwC5YAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOKqoppmqqYimI3mZnogHLxdR6u0ppuqinUWp8lyequN6Yx+PtWJqj3OfVG6r/FXj5rXiHra7wy4C4au7XzqqMRnVvbnVRE7V1W6p9jbtR1d1npmZjm7dE1dvSPI0yvE1TmnEjWebZzmt+e6YiMFXFFM19vOu3Iqruf3tqZBP1vitwuuV00W+JOjq66p2pppzzDTMz/nZZhMThsZhreKwmItYixcjnW7tquKqK48cTHRMK85vyOeEuLwdVrBXdQZdf
76466b1vG017T7sV0zEx80+6jHPuFHGXk7d11Xw21Pd1Bp+xPdcdgZtVREUR11XcPzpiumI666JiqI3n2MbyC7Ii3k7caMh4v6brxGFtxl+d4KKYzDLqq+dNvfquUT+Nbnx9cT0T2TMpAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA8LXeq8n0Vpu9qDPrl23gbNduiuq1am5VE11RTT0R09cwjnvleFnthmX6vuPtyvvAXmnwrB/wDcW1GV7TaamWszZT1GotitEQvB3yvCz2wzL9X3DvleFfthmf6vuehR9zuscBj85V+Nv5Qu/wB8rws9sMz/AFfc9B3yvCz2wzP9X3PQpBu43k4DH5ycbfyheDvlOFnthmf6vueg75ThZ7YZn+r7noUf3k3OBx+cnG38oXg75XhZ7YZn+r7noO+V4We2GZ/q+56FH93O/uveAx+cnG38oXf75XhZ7YZn+r7noO+V4We2GZ/q+56FINzd5wGPzk42/lC7/fK8K/bDM/1fc9B3yvCz2wzP9X3PQpBuHAY/OTjb+ULv98rws9sMz/V9z0HfK8LPbDM/1fc9CkG8m5wGPzk42/lC7/fK8LPbDM/1fc9B3yvCz2wzP9X3PQpBuRJwGPzk42/lC7/fK8LPbDM/1fc9B3yvCz2wzP8AV9z0KQG5wGPzk42/lC7/AHyvCz2wzP8AV9z0HfK8LPbDM/1fc9CkBucDj85ONv5Qu/3ynCz2wzP9X3PQd8pws9sMy/V9xSDc3OAx+cnG38oXf75XhZ7YZn+r7noO+U4We2GZ/q+56FIB7wGPzk42/lC7/fKcLPbDM/1fc9D92OUfwwv37dixjM1uXbtdNu3RRl1yaq6qp2imI26ZmZiIhR35ehbPko8H5yuzY15qXD7Y29RFeWYW5T02KJj+Vq/tVRPRHZHT1z0Q5tNhxV3mZS4dRly22iIWMw9zu1i3e5ldvn0xVza42qp37Jjsl+wZy+AAMH4j8VdGaAxuGwWo8wu28Vibc3aLNizVdrijfbnTEdUTMTETPXtPifXi/wAQcr4daTu5xjoi9irkzbwWEiraq/c26vcpjrmeyPkUD1Tn2aamz7F55nOJnE47F18+7XPV7lMR2UxHREdkLem03a99uStqNRGLujmuZ3ynCz2wzP8AV9z0HfK8LPbDMv1fcUg6Rc4DH5yqcbfyhd/vleFnthmX6vueg75XhZ7YZn+r7noUgHnAY/OTjb+ULv8AfK8LPbDM/wBX3PQd8rws9sMz/V9z0KQby43e8Bj85ONv5QvB3yvCz2wzP9X3PQd8rws9sMz/AFfc9CkESby84HH5ycbfyhd/vleFnthmX6vueg75XhZ7YZl+r7ikG5ucBj85ONv5Qu/HKU4WT/8AcMz/AFfc9CUNLZ5l+pdPYHPsqrrrwWOtRds1V0TTVNM+OJ6mtGmemGwTk8eBPSfxdR/qrarTVxViYWdNqLZZmJZ6rpy7+IWL0tw1wuk8mu10Zrqi7Vhpm3Ps6cNTt3WI27a5qoo92KqvEsWqBym7VOZ8tfhblWLmmvB02cDd7lX+DM+rL0z8/c6YUltnfCfD8NeTVoTK8o1lneEyvUmdWYxePvXLVdyq7XG29umqimfYW9+bEds71fjSzrTvHjhJqHO8JkuTazwuLzDGXItYezTh70TXVPZvNER88vF5V/D3SGqOGOf6mz3KPVebZFkuLu5biPVN2juFUUTVE82iqKavZUxPsonqQZyA+HukNQZFmmsc3yj1TnmTZpEYDFeqbtHcf4qKvwKaooq6Zn8KJBZDTHHThPqbPsJkOR6zwmMzLGV9zw9iLF6mblW0ztE1URHVE9rsa14z8MdGZ/dyHU2rcLl2ZWqKa7mHqs3a6qYqjeneaaZjpiYnra1NH05hpqzknEjA86qMrz+3RVHVEXKIovUR/iim5E/3Xt8b8fd1tqjUvE2muurL8yz+vBYCqqNufat245u+/VMW+49HuyCaOM2X2OBvGvS/GPQMTOldRf7Rcw9iJpt1U1xTVdtRE7bU3KKoroifwaonaI5sLw5fi8Pj8Bh8dg7tN7DYm1Tds3KequiqImmY9+JhV3lOZbYx3Ig01i7sRz8uweUYi1M/lTaptT9F2U2cni9XiOBOhrlyZmr+AsJTvPiptU0x9EAzwAEWcqPO83yDhVdzDJMxxOX4uMbZoi9h7k0V82ZneN4VM9dTiP5bZ553V6Vo+WF4Gr3w+x9cqVNbRUrOPvj5svWXtGTulmXrqcR/LbPPO6vSeupxH8ts887q9LDRc7OnkqdpfzZl66nEfy2zzzur0nrqcR/LbPPO6vSw0Ozp5HaX82ZeupxH8ts887q9J66nEfy2zzzur0sNDs6eR2l/NmXrqcR/LbPPO6vSeupxH8ts887q9LDQ7OnkdpfzZl66nEfy2zzzur0nrqcR/LbPPO6vSw0Ozp5HaX82ZeupxH8ts887q9J66nEfy2zzzur0sNDs6eR2l/NmXrqcR/LbPPO6vSeupxH8ts887q9LDQ7OnkdpfzZl66nEfy2zzzur0rUck3Ps61Fw0xeOz3M8VmOKpzW7apu4i5NdUURbtTFO89m8z86rnB7hzm/EbUlOAwUVYfAWJirHY2ad6bNHijx1z07R8vVEyvVpDTmUaT0/hciyTC04bB4enamOuqurtrqntqmemZUNbbHFepEd69o63metM9z1wGY0RSrjZxE11lXFbUWX5bqzN8JhLGMmi1ZtYmqmiiNo6IjsXVUC5QHhm1T8Oq+qF7QVibzv5KWttMUjZ1vXU4j+W2eed1ek9dTiP5bZ553V6WGjU7Onkze0v5sy9dTiP5bZ553V6T11OI/ltnnndXpYaHZ08jtL+bMvXU4j+W2eed1ek9dTiP5bZ553V6WGh2dPI7S/mzL11OI/ltnnndXpPXU4j+W2eed1elhodnTyO0v5sy9dTiP5bZ553V6T11OI/ltnnndXpYaHZ08jtL+bMvXU4j+W2eed1ek9dTiP5bZ553V6WGh2dPI7S/mzL11OI/ltnnndXpetozibxBxWsMlw2I1jnV2zdzCxRcoqxVUxVTNymJiY8Uwjd7Wg/wCvOQfGeG+1peWx02nue1yW3jvbHgHzzeHXzOuq3luKroqmmqmzXNMx1xO0uw6ub/0VjP0Ff7MvY5vJ5KB+upxH8ts887q9J66nEfy2zzzur0sNH0PZ08mD2l/NmlritxIt3KblOtc6maZiYirE1VR0eOJ6J96Vt+A3FbAcRck7hiZtYXUGEoj1XhonaLkdXdbfjpntj8WZ28UzRR6Om86zPTud4XOcnxdzCY7C18+1co7PHEx2xMdExPRMTshz6auSu0d0psOotjtvPfDZOI+4JcTss4j6e7tR3PC5xhqYjHYPf8Gfy6O2aJ+jqnxzILFvWaTtLXraLRvAA5dAAAAAAKR8X+I2vMt4oakwGA1bnGGwuHzG7bs2beJqppopiroiI7IYr66nEfy2zzzur0ueOPhf1X8aXv2pYY38eOvUjuYV726097MvXU4j+W2eed1eldDgVmOPzbhLp7Mczxd7GYy/h5qu3rtXOrrnn1RvM9vRDX6vxyc/Anpj4LV9pWqa6tYpG0fNa0VrTed5+SQAGW0wAFEtc8TOIGE1rnuFw2sc6s2LOZYi3bt0YqqKaKYuVRERHiiIeN66nEfy2zzzur0vK4ieEDUXxrivtanhPoK46dWO5g2yW3nvZl66nEfy2zzzur0rxcLcXisw4a6Zx2Nv3MRisRlWGu3rtyrequuq1TM1TPbMy11thvB3wT6S+JsJ9lSpa+tYrG0LmitM2neWVgMxpChGo+J/EOxqHMrNnWed0W7eLu00U04uqIpiK5iIhfdrZ1V/WfNfht79uWhoKxM23hQ11piK7SyD11OI/ltnnndXpPXU4j+W2eed1elho0uzp5M/tL+bMvXU4j+W2eed1ek9dTiP5bZ553V6WGh2dPI7S/mzL11OI/ltnnndXpPXU4j+W2eed1elhodnTyO0v5sy9dTiP5bZ553V6T11OI/ltnnndXpYaHZ08jtL+bMvXU4j+W2eed1ek9dTiP5bZ553V6WGh2dPI7S/mzL11OI/ltnnndXpPXU4j+W2eed1elhodnTyO0v5sy9dTiP5bZ553V6T11OI/ltnnndXpYaHZ08jtL+bMvXU4j+W2eed1ek9dTiP5bZ553V6WGh2dPI7S/mvjybM3zPPOD+U5lnGOxGOxt25iIrv365qrq2vVxG8z4oiISOivkoeAzJP0mJ+3uJUYWaNslvdt4e/HX2AESRSrjZxE11lXFbUWX5bqzN8JhLGMmi1ZtYmqmiiNo6IjsYd66nEfy2zzzur0uzygPDNqn4dV9UMEb+PHXqR3fJh5L26897MvXU4j+W2eed1elcrk+5nmGc8H8gzLNcZfxuNv27s3b96uaq69r1yI3mfciI+RQNfDkyeAzTX6O99vcVddWsY42j5rOitabzvPySQAymmAAAAAAAAq7yuNaas05xEy7BZDqHMctw1zKbd2u1h780U1VzevRNUxHbtTEfIhv11OI/ltnnndXpSLy2vCjlfxJa+3voIbempWcVZmGNqL2jJO0sy9dTiP5bZ553V6Vl+SFqPPtSaUzrEZ/m+MzO9Zx1NFuvE3ZrmmnucTtG/ZupstpyHv6mZ/wDGNP2cONZSsYpmId6S9pyxEysIAx2sAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAiLlfeAvNPheD/7i2oyvNyvvAXmnwvB/wDcW1GGtoPhz7szXeOPZyAuqQAAAAAAA9AAAAADteABs9AAAABzDhKvJ34U4jiLqGcVjYrtaewFyPVl2I2m9XtExZpnxzvE1T2RPjmHF7xSvWl3Sk3t1YZZyV+EMalxlrWmo8PE5Phbu+Cw1dHRi7lP4879HMpn55jxR03CiNo2h8cFhcPgsHZweEsW7GHsW6bdq1bp5tNFMRtEREdURD7MPNmnLbeWzixRjrtAAiSDyNY6jyrSenMZn2c4mmxg8LRNVUz11z2UUx21TPREPSxuJw+Cwd/GYu9RZw9i3Vdu3K52poopjeapnsiIiZUV5Q/FTEcRtRxYwU3LOnsBXMYOzVO03attpvVR456YiOyJ8cyn0+CcttvkhzZoxV3+bGuK+vM14hasu55mcdxtxHc8Jhaat6cPa7KY8cz1zPbPyMR+VwNutYrG0Ma1ptO8uflPlcOXTwcAAAAAA5cAOY64bBeTx4E9J/F1H+rX1T+FDYLyePAnpP4uo/1UNf4I917Q+KWeqd8uzD4zSfFvh3xUw9mu7ZwVduxc26orw9/u9NE/3oruf5ZXEYZxq4f5dxN4dZlpPMK4s1X6YuYXEc3nTh79PTRciPf6JjtpmqO1lNJ+OI1irXnBLPcPpeu
7641j6s+yK9GXVRXFNN7u1me5zzp6IiedHWjjkZcNNX8NdDZ/lersBaweKxmPi9Ypt4ii7FVHcqad96ZmI6YlEfJ54v5twS1DiOEPF2zfwWX4a9VGCxtVNVcYTnTv2R7KxXO9VNUdUzPZPsbo5bjsFmeAs4/LsZh8ZhL9EV2b9i5Fy3cpnqmmqOiY94FM9J8nHX9HJ11fpHOMowtnPsRmuFzDKbfqy1VTXVbjmVb1RO1PsKrkdMx1vxrDk38QLnJ90XpTJ8owt7PMLmOMx2b2/Vlqimiq7tTRtVNW1XsKKI6JnqXXR1xn4yaK4WZRdv55mNq/mk25nC5VYrirEX6tujePxKZ/Lq6PFvPRIQByzs7vac4A6D4X3eb/DuKsYP1XhrdXPqpow9mKJjo697s0xE9vMq2Wg4W5He0zw10zp3E7eqMtyrDYW9t1d0otU01f9USqpyc9G6p42cXauOHEKzNGVYO/FeV4eaZi3duUT/F024n/dWp6d/xq47Z5654AAI75Q+ks51rw5uZHkVuzcxlWKtXYpu3Iop5tMzv0z76tfe48TvzHLvPaV2BYxaq+KvVqr5dNTJbrSpP3uPE78xy7z2k73Hid+Y5d57SuwJePy/RHwWP6qT97jxO/Mcu89pO9x4nfmOXee0rsBx+X6HBY/qpP3uPE78xy7z2k73Hid+Y5d57SuwHH5focFj+qk/e48TvzHLvPaTvceJ35jl3ntK7Acfl+hwWP6qT97jxO/Mcu89pO9x4nfmOXee0rsK6cprjT/BdOJ0XpHF/7fVE28xx1qr+bx22qJj8fxz+L1R0/gyYtVmy26tYhxk02HHXrTurHqTKMRkOd4rKMXfwt7EYWvud2cNdi5RFUdcRVHRMx1Tt2vOBpwzZGXcKtA5zxC1NbyjK6O52KNq8Zi6qd6MPb3658cz2U9s+5EzHX4baJzrXmprOSZNa6Z9liL9UfxeHt79NdU/VHbPQvdw40XkuhNM2cjyWztTT7K/fqj+MxFzbprqnx+51RHRCrqdTGKNo5rOn085Z3nk++hNJ5NovTeHyHI8P3LD2Y3rrnprvVz111z21T6IjaIiHugxpmZneWvEREbQAPHooFygPDNqn4dV9UL+qBcoDwzap+HVfVC/0f459lHXeCPdggDWZaStIcEteaq05hM/yjCYKvA4uKptVXMVTRVPNqmmd4nq6aZet3uPE78xy7z2lZDkyeAzTX6O99vcSQysmtyVvMRs1Mejx2rEypP3uPE78xy7z2k73Hid+Y5d57SuwOOPy/R1wWP6qT97jxO/Mcu89pO9x4nfmOXee0rsBx+X6HBY/qpP3uPE78xy7z2k73Hid+Y5d57SuwHH5focFj+qk/e48TvzHLvPaTvceJ35jl3ntK7Acfl+hwWP6qT97jxO/Mcu89pelpXk+8SMv1PlWPxOCy+LGGxtm9cmMZTMxTTXEz0e9C4w8nXZZ8nsaLHHmAKa2Orm/9FYz9BX+zLtOrm/9FYz9BX+zL2ObyeTWiA+kfPAAPX0fqPN9J6hwue5Jiq
764sPjMPVvE9dNdPbRVHbTMdEwvXwf4i5RxF01TmGCmmxjrMRTjsHNW9Vivxx46J6dp/1iYa/Xv6C1bnOitS4fPcjxHcsRanauirpovUT10Vx20z9HRMbTESranTxlju5rOnzzinv5NjIxPhbrzJuIOmbecZVXzLtO1GLwtVW9eHubfgz448VXbHu7xGWMS1ZrO0titotG8ADx6AAAA19ccfC/qv40vftSwxmfHHwv6r+NL37UsMfRY/BHswMnikX45OfgT0x8Fq+0rUHX45OfgT0x8Fq+0rU+kPhx7reh8c+yQAGS1AAGuTiJ4QNRfGuK+1qeE93iJ4QNRfGuK+1qeE+jp4YfP25yNhvB3wT6S+JsJ9lS15NhvB3wT6S+JsJ9lSo9IeGF3QeKWVgMppimee8nniVi87x+Ls4LL5tXsTcuUTONpiebVVMx9a5gmw57Yt+qhy4a5duspP3uPE78xy7z2k73Hid+Y5d57SuwJ+Py/RDwWP6qT97jxO/Mcu89pO9x4nfmOXee0rsBx+X6HBY/qpP3uPE78xy7z2k73Hid+Y5d57SuwHH5focFj+rWrn+V4vJM7x2T4+mmnF4G/Xh70U1c6IromYnae3ph0WWcZPC1qz44xX2tTE2tWd6xLLtG0zAk7THAviBqPIMHnmWYTA14PGW4u2aq8XTTVNPux2IxX+5P/gZ0t8Bp+uVfVZrYqxNU+mxVy2mLKw97jxO/Mcu89pO9x4nfmOXee0rsCjx+X6LvBY/qpP3uPE78xy7z2k73Hid+Y5d57SuwHH5focFj+qk/e48TvzHLvPaTvceJ35jl3ntK7Acfl+hwWP6sF4DaZzXR/C/Lcgzq3at47D13puU27kV0xFV2qqOmPcmGdAqWtNrTafmtVrFYiIAHLpQLlAeGbVPw6r6oYIzvlAeGbVPw6r6oYI+hxeCPZg5PHPuL4cmTwGaa/R3vt7ih6+HJk8Bmmv0d77e4q9IfDj3WdD8SfZJADIaoAAAAAAACn3La8KOV/Elr7e+ghO/La8KOV/Elr7e+ghvab4VWJqPi2FtOQ9/UzP/AIxp+zhUtbTkPf1Mz/4xp+zhHrfgy70fxYWEAYrYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAARDyv8AwF5p8Lwf/cW1GtpbOM3yzLs3wNWBzXAYXH4WuYqqs4m1TcomYneJmmqJjomIl4vrf6E8jNPfq2z+6uafVRhrtsq59N2tt92uHaTafE2Pet/oTyM09+rbP7p63+hPIzT36ttfup/tCPSg4GfU1w7T4nO0tjvrf6E8jNPfq21+6et/oTyM09+rbX7p9oR6TgZ9TXDtPic7T4mx31v9C+Rmnv1ba/dPW/0J5Gae/Vtr90+0I9JwM+pri2nxG0+Jsd9b/QnkZp79W2v3T1v9CeRmnv1ba/dPtCPScDPqa4tp8RtPibHfW/0J5Gae/Vtr909b/QnkZp79W2v3T7Qj0nAz6muLafEbS2O+t/oTyM09+rbX7p63+hPIzT36ttfun2hHpOBn1NcW0+I2nxNjvrf6E8jNPfq21+6et/oTyM09+rbX7p9oR6TgZ9TXFtJtLY763+hPIzT36ts/uop5Q+ccPOHOQxhMBo3Tt3UWOon1Hb/gyzMWKeqb1e9PVE9Uds+5Euqa3r26sVeW0cVjebKcbS4fu5VNy5VXXMTVVMzM7bdM+8/K+ouHIA4cj2NG6bzXVmpMHkGTWO7YzFV82nffm0R211TETtTHXMvJmIjeXsRMztD1+Eugc24h6ss5Ll0dzs07XMZiZjenD2t+mqfHM9UR2z70r+6Q07lWlNO4PIclw0YfBYWjm0U9tU9c1VT21TO8zPuvE4ScP8p4d6UtZNl216/XPdMZi5p2qxF3bpqnr2iOqI36I+VmLF1OonLbu5NfT4IxV+oArLAD8X7Vu/Zrs3aIrt3KZprpnqmJjaYBUTlV8Xo1Bjb2iNOYir+CsLcmnH4iiqYjFXaZ/k48dFM9fjn3I6a9y2Izws4bTO86E05+r7foPWr4a+QenP1db9DQxavHjr1YhRyaW+S3WmWu4bEfWr4a+QenP1db9B61fDXyE05+rrfoScfXyR8Dbza7tiYbEfWr4a+QenP1db9B61fDXyD05+rrfoOPr5HA282u7bpNmxH1q+GvkHpz9XW/QetXw18g9Ofq636Dj6+RwNvNru2NmxH1q+GvkHpz9X2/QetZw28hNOfq636Dj6+RwNvNru2GxH1rOG3kJpz9XWvQetXw18hNOfq636Dj6+RwNvNru2GxH1rOG3kJpz9XW/QetZw18hNOfq616Dj6+RwNvNrvpjphsE5PHgT0n8XUfXLuxws4bR//AKJpz9XWvQyfKsvwOVZdYy7LcJZweDw9HMs2LNEUUW6fFER0RCvqdTGWsRELGn084pmZl2QFNaYTxa4WaM4oZNGX6qyyLty3ExhsbZmKMThpn8ivaej+zMTTPbCtlXJa4t6LzWu5ws4pUYXBV1c+aL2Kv4KufFFdNuK6Lnvzt7y5ICoeZcJeVvmmH9S4vixl1u1NPNmbOaX7M7e7VbsRVL2uFnJAyDKs0oz3iJndzVWP5/dZwlNNVGGmvx3Kpma7vT09PNie2JWiAfPCYfD4TC2sLhLFrD4ezRFFq1aoimiimI2imIjoiIjsh9AAAAAAAAAAAABCHKQ4y29H4W7pnTd+i5qG/Rtdu07TGBomOuf/AHJjqjs657InvHjtkt1auMmSuOvWs6PKW40U6cs39I6VxUTnVynm4zFW5/mdM/i0z/xJj/L7/VUWqqqqqaqpmqqZ3mZnpmX6vXbl69XevXK7l25VNVddc71VTPTMzM9cvw3MOGuKu0MbNmtltvI97QWks51rqTD5FkeH7riLs7111dFFmiOuuueymPp6IjeZiHx0dpvN9W6hw2RZHhasRjMRVtEdVNFPbXVPZTHbP+q9fCDh1lHDrTdOXYGIv469EVY7GzTtVfr/ANKY6dqez35mXGp1EYo7ubvT6ecs9/J2eFmgsm4faZt5RlVHdL1W1eLxdVO1eIubfhT4ojsp7I93eZywGJa02neWxWsVjaAB49AAFAuUB4ZtU/Dqvqhf1QLlAeGbVPw6r6oX+j/HPso67wR7sEAazLXw5MngM01+jvfb3EkI35MngM01+jvfb3EkPns3xLe8t7D8OvtAAjSAAAAAAAAAADq5v/RWM/QV/sy7Tq5v/RWM/QV/sy9jm8nk1ogPpHzwzfjBw6zXh5qGMHiudfy/ExNzA4zm7Rdo8U+KuneImPenqmGENimuNI5PrfSFzIc6s8+zdoiq3cpj2di5EexuUT2TH0xvE9Eyq6jP2Nq+UrODD2tbecNdYynibobOtAalu5NnFremd68NiaI/i8Rb36Kqf9Y64n52LLNbRaN4V5iaztLJ+Gmt860FqazneT3d9vYYjD1T/F4i3v00Vf6T2T0r3cO9ZZLrrTNjPclvc63X7G9Zqn+MsXO2iuOyY+mNpjra6mY8JuIGccPNTUZrltU3cNc2oxmDqq2oxFvfq9yqOn
764arsnxxMxNXU6aMsbxzWdNqJxTtPJsHHiaI1Rk+sdOYbPsjxMXsLfjpieiu1XHXRXHZVHi+WN4mJe2xpiYnaWvExMbwAPHoADX1xx8L+q/jS9+1LDGZ8cfC/qv40vftSwx9Fj8EezAyeKRfjk5+BPTHwWr7StQdfjk5+BPTHwWr7StT6Q+HHut6Hxz7JAAZLUAAa5OInhA1F8a4r7Wp4T3eInhA1F8a4r7Wp4T6Onhh8/bnI2G8HfBPpL4mwn2VLXk2G8HfBPpL4mwn2VKj0h4YXdB4pZWAymmAAAAAAAA158ZPC1qz44xX2tTE2WcZPC1qz44xX2tTE30WPwwwL+KRf7k/+BnS3wGn65UBX+5P/gZ0t8Bp+uVPpDwR7reh8c+zOgGS1AAAAAAAAFAuUB4ZtU/DqvqhgjO+UB4ZtU/Dqvqhgj6HF4I9mDk8c+4vhyZPAZpr9He+3uKHr4cmTwGaa/R3vt7ir0h8OPdZ0PxJ9kkAMhqgAAAAAAAKfctrwo5X8SWvt76CE78trwo5X8SWvt76CG9pvhVYmo+LYW05D39TM/8AjGn7OFS1tOQ9/UzP/jGn7OEet+DLvR/FhYQBitgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB4Gv9W5RonS+K1BnN3mWLEbUUUzHPvVz+DRTE9cz6Z7HsRMztDyZiI3l5PGLiJlXDnStea42O74y9vbwOEpq2qv3NvH2UxvEzPZHjmYhQbVOe5rqbP8XnmdYqrFY7F1865cqn5IpiOymI2iI7Ih63E7Wuba91Zic+zWuY50zRhsPFUzRh7W/RRT/rPbPSxdtabTxirvPNk6jP2k7RycSOdhZVnEGznZ+qaZqqimmJmZnaIiOmZB9ctwOKzLMcNl+BsXMRisTdptWbVuN6q66p2iIj317OT/wswnDjTnPxXcsRn+NpicbiaafwI64tUT+TT4/xpjfo6IjGOTBwhp0jl1vVeoLETnuMtR3GzVT04K3VHV0/j1RPT4o6PHvOjJ1ep689SvJqaXT9SOtbmAKK4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAinlAcXMHw9ymcvy6q1idR4u3vh7M9NOHpno7rXH1R2z7kS7pS17dWrm94pHWl0+UTxhw+hMvqyPJLtu/qTE2+jqqpwdEx+HVH5U/i0z789G0TS7GYnEYzF3cXi79y/iL1c3Lt25VNVVdUzvMzM9czL6ZnjsZmeYX8wzDE3cTi8Rcm5evXKt6q6p6ZmZdZt4MFcNdo5sXNmnLbeeQ9LTOR5pqTPMLkuTYSvFY7FV8y3bp+mZnsiI6ZmeiIh8sjyrMc8zfDZTlOEuYvG4q5FuzZtxvNUz9UdszPRERMyvFwJ4V5dw5yPn3e54rPsXRHqzFxHRTHX3K3v1URPb11T0z2RHmo1EYa/V1gwTlt9Ha4KcMsr4cae7ha5mJzfE0xOOxvN6a5/Ip8VEdkdvXPuZ+DEtabzvLYrWKxtAA5dAAAACgXKA8M2qfh1X1Qv6oFygPDNqn4dV9UL/R/jn2Udd4I92CANZlrm8nrXei8o4O5Bl2aaqybBYyzbuxdsX8ZRRXRveuTG8TO8dExPys+9c3h35b6e/WFv0tego30NbWmd+a7XW2rWI25Nhfrm8O/LfT36wt+k9c3h35b6e/WFv0teg5+z6ebrj7eTYX65vDvy309+sLfpPXN4d+W+nv1hb9LXoH2fTzOPt5Nhfrm8O/LfT36wt+k9c3h35b6e/WFv0tegfZ9PM4+3k2F+ubw78t9PfrC36WR5VmOAzXL7OYZZjLGMwd6Jm1fsVxXRXG+28THRPTEtaK+vJu8COmfg9z7WtX1OlrhrExKfT6mctpiYSGApLgAA6ub/ANFYz9BX+zLtOrm/9FYz9BX+zL2ObyeTWiA+kfPDZphv5vb/ALkfU1ltmmG/m9v+5H1M3pH8P5/4aOg/F+THOJmh8l19pq7kucWtp6asNiaI/jMPc26Kqf8AWOqYUS4jaLzrQmpb2R51Z2rp9lYv0xPc8Rb36K6J8XudcT0S2KMT4p6CyXiDpq5lGbUcy7TvXhMXTTvcw9zb8KPHE9tPbHu7TFfTamcU7TyT6jTxljeObXmMg1/pDOtEakv5FnmH7nft+yt3Kem3fo7K6J7Yn6J3idpiWPtmJiY3hkTExO0s74M8Ss14c6jjGYbn4nLMRMU47Bc7ou0/lU+KuOyfknolenSuf5VqfIcLneS4ujFYLE0c6iuOuJ7aao7KonomOyWttI/AzilmPDjPvZ90xWR4quPVuEiers7pRv1VxHyVR0T2TFPVabtI61ea3ptT2c9W3JfEdHIc3y7Pcnwub5Ti7eLwOKtxcs3aJ6Ko/wBJjqmJ6YmJiXeY8xs1oncABr644+F/Vfxpe/alhjM+OPhf1X8aXv2pYY+ix+CPZgZPFIvxyc/Anpj4LV9pWoOvxyc/Anpj4LV9pWp9IfDj3W9D459kgAMlqAANcnETwgai+NcV9rU8J7vETwgai+NcV9rU8J9HTww+ftzkbDeDvgn0l8TYT7KlrybDeDvgn0l8TYT7KlR6Q8MLug8UsrAZTTAAAAAAAAa8+Mnha1Z8cYr7WpibLOMnha1Z8cYr7Wpib6LH4YYF/FIv9yf/AAM6W+A0/XKgK/3J/wDAzpb4DT9cqfSHgj3W9D459mdAMlqAAAAAAAAKBcoDwzap+HVfVDBGd8oDwzap+HVfVDBH0OLwR7MHJ459xfDkyeAzTX6O99vcUPfa3isVboii3ib1FMdUU1zEQ41GHtq9XfZ3gzdlbfbdsyGs/wBW4z87xH/Mk9W4z87xH/MlT+zv+X7LfH/8f3bMBrP9W4z87xH/ADJPVuM/O8R/zJPs7/l+xx//AB/dswGs/wBW4z87xH/Mk9W4z87xH/Mk+zv+X7HH/wDH92zAaz/VuM/O8R/zJPVuM/O8R/zJPs7/AJfscf8A8f3bMBrP9W4z87xH/Mk9W4z87xH/ADJPs7/l+xx//H9038trwo5X8SWvt76CH7u3bt6rnXbldyqI23qqmZ2fhfxU6lIr5KOS/XtNhbTkPf1Mz/4xp+zhUtbTkPf1Mz/4xp+zhBrfgym0fxYWEAYrYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAfm9ct2bVd27XTbt0RNVVVU7RTEdczIOrnmaYDJMoxWbZpibeGwWFtzcvXa52immP/wC6lDuOXEzMOI+p5xVUXMNlOFmqjL8JNX4NO/8AKVR1c+raN/F1bztvOScpHi3XrzNv4FyWuu3pzBXN6J5388uR/vZj8mPxY/xdsREN7NfSabqR17c2XqtR1p6leT8j9bGy8pPyS/WxsD87LQ8lTg9t6m19qfDdPRcyrCXaPmv1RPb+TH+LxbYpyZOD06ux9vVWorFdOQYWvfD2aqdoxtymfd67cTvv45jbslcmI2jaGbrNTt/p1/No6TT/AI7fkAMxoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAI/42cTsr4caf7tc5mKzjE0zGBwe/4U/l17dMUR9PVHjjqtZvO0ObWisby6nHfirl/DnI+5WO54rP8AF0T6jwszvFEdXdbnipieqOuqY2jtmKP53mmYZ3m2JzbNcXcxeNxVybl69cneapn6o7IiOiI6IfTUud5pqPPMVnWc4uvF47FV8+5cq+iIjsiI6IiOiIh5zb0+CMNfqx8+ecs/QdnK8BjM0zHD5dl2Gu4rF4i5FuzZt071V1T1REPxg8NiMbi7OEwli5fxF6uLdq1bpmqquqZ2iIiOuZldHk78H8PoPLqc6zq3bv6kxNv2U9FVODon/d0T+V+VV8kdG8z7nz1w13nm8w4Zy22jk7nADhJg+HuUer8wptYnUeLt7Yi9HTTYpnp7lbnxeOe2fciEqgxL3te3Ws2aUikdWABw6AAAAAAFAuUB4ZtU/Dqvqhf1QLlAeGbVPw6r6oX+j/HPso67wR7sEAazLBaTgrwQ0Jqvhhk2oM3sZhVjcXRcm7NvFTTT7G7XTG0bdHRTDMu9u4Z/m2aeez6FS2tx1mYndbro8loiYUpF1u9u4Z/m2aeez6DvbuGf5tmnns+hzx2L6veCyfRSkXW727hn+bZp57PoO9u4Z/m2aeez6DjsX1OCyfRSkXW727hn+bZp57PoO9u4Z/m2aeez6DjsX1OCyfRSlfXk3eBHTPwe59rW8DvbuGf5tmnns+hJukcgy/S2nMHkGVU3KcFg6ZotRcr51W01TV0z29MyrarU0y1iKrOm098Vpmz1QFBdAAHVzf8AorGfoK/2Zdp1c3/orGfoK/2ZexzeTya0QH0j54bNMN/N7f8Acj6msts0w383t/3I+pm9I/h/P/DR0H4vyfQBmNFh3Frh7k3ETTdWWZlTFnFWt6sFjKad68PX/rTPRvT2+5MRMUU1xpXOdG6jxGRZ5hps4qzO9NUdNF2iequie2mfTE7TEw2OMI4wcOMn4jacnAY2KcPj7ETVgcbTTvVZr8U+Oiejen5euIlb0upnFPVtyVdTp4yRvHNr+Hsay01nGktQ4nIs8wtWHxmHnp7aa6eyume2meyf9d3jtmJiY3hkTExO0pU4AcWsbw8zj1Fj6ruJ07i7keqbEdM2Kp6O60R4/HHbHuxC7eV4/BZpl2HzHLsTaxWExNuLlm9bq3prpnqmJa0Ew8nbjBiNB5jTkudXLl7TeJueyjpqqwdc/wC8pj8n8qn5Y6d4mlq9L1/v15rml1PU+7bkuuPlg8Th8ZhLWLwl+3fw96iLlq7bqiqmumY3iYmOuJh9WQ1Wvrjj4X9V/Gl79qWGMz44+F/Vfxpe/alhj6LH4I9mBk8Ui/HJz8CemPgtX2lag6/HJz8CemPgtX2lan0h8OPdb0Pjn2SAAyWoAA1ycRPCBqL41xX2tTwnu8RPCBqL41xX2tTwn0dPDD5+3ORsN4O+CfSXxNhPsqWvJsN4O+CfSXxNhPsqVHpDwwu6DxSysBlNMAAAAAAABrz4yeFrVnxxivtamJss4yeFrVnxxivtamJvosfh
764hgX8Ui/3J/8AAzpb4DT9cqAr/cn/AMDOlvgNP1yp9IeCPdb0Pjn2Z0AyWoAAAAAAAAoFygPDNqn4dV9UMEZ3ygPDNqn4dV9UMEfQ4vBHswcnjn3AWN4Scn7TusuHeU6lxud5rh8RjablVduzFvmU825VRG29Mz1UwZctcUb2MeK2Sdqq5C3HesaS8o87+a1+6d6xpLyjzv5rX7qDjcXmm4PL5Kji3HesaS8o87+a1+6d6xpLyjzv5rX7pxuLzODy+So4tx3rGkvKPO/mtfunesaS8o87+a1+6cbi8zg8vkqOLcd6xpLyjzv5rX7p3rGkvKPO/mtfunG4vM4PL5Kji3HesaS8o87+a1+6d6xpLyjzv5rX7pxuLzODy+So4kblAcP8u4c6wweS5ZjcVjLN/L6MVVXiObzoqm5cp2jmxEbbUR86OVmlovWLQr2rNZ2kW05D39TM/wDjGn7OFS1tOQ9/UzP/AIxp+zhW1vwZWNH8WFhAGK2AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABU7lT8XpzbEYnQunL8fwfZr5uY4q3VvGIqjrtUzH4kT1z2zG3VE75XypOME5LYv6J0ziojM7tHNzHE26unDUTEfxdMx1VzE9M/ix7s9FTGlo9N/9Lfkz9XqNvuVcS4cjTZrjY2cmwONkocn/hXieImoe7Yym9Y0/g6onF4imNu61dcWaJntntnsj3Zh4XCLh/mvEPVNvKcDFyzhLc0147GRRvTh7cz83OnaYpjtmJ7IlfLSGncr0rp3CZDk9juODwtHNoiZ3qqnrmqqe2qZ3mZUtXqezjq15rul0/XnrW5O/l2CwmXYCxgMDh7eHwuHtxbtWqI2popiNoiH3BjtUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABiXFXX2TcPdM3M3zSvul+vejB4SmravEXNuqPFEdtXZHjmYifa1m07Q8taKxvLrcYeI2UcOdN1ZhjZpv4+9E04HBRVtVer8c+KiOjefk65iFFNYajzfVmoMTnueYqrEYzEVbzPVTRT2UUx2Ux1RD7671ZnOtNSYjPc8xHdcRdnaiiOiizRHVRRHZTHpmd5mZeC29Np4xR382PqM85Z+g/di1dv3qLNm3Xdu3KopooopmaqqpnaIiI65l+aKaq6ooopmqqqdoiI3mZW85NXBenTVmzq3VWGic7uU87CYW5G/qOmY/Cqj/iTH+WPd327zZq4q7y4w4py22h3eThwataNwlvUuo7FFzUN+j+KtVbTGBomOqP8A3Jjrns6o7ZmbgYeTJbJbrWbOPHXHXq1AHDsAAAAAAAAUC5QHhm1T8Oq+qF/VAuUB4ZtU/Dqvqhf6P8c+yjrvBHuwQBrMtfDkyeAzTX6O99vcSQjfkyeAzTX6O99vcSQ+ezfEt7y3sPw6+0ACNIAAAAAAAAAAOrm/9FYz9BX+zLtOrm/9FYz9BX+zL2ObyeTWiA+kfPDZphv5vb/uR9TWW2aYb+b2/wC5H1M3pH8P5/4aOg/F+T6AMxogAMD4z8M8p4j6enC4jmYbNMPEzgcbFPTbq/Jq8dE9sfLHSoxqvT+baXz7FZHneErwuNw1XNronqqjsqpntpmOmJbI0e8beF+V8R8h7nV3PC5zhqZnBY3m9U9fc69umaJ+iemO2JuaXUzjnq25Kmp03aR1q81CR6OpcjzTTmd4rJc5wlzCY7C18y5br+iYntiY6YmOiYl5zYid++GTMbJw5N3GW5o/F29M6kv1V6ev17Wb1U7zga5nr/RzPXHZ1x273Gs3Ld61Res3KbluumKqK6Z3iqJ6YmJ7YayVh+S/xj/ge9Y0TqnFf/TblXMy/F3Kv5tVPVbqn8iZ6p/Fn3J9jn6vS9b79Oa9pdTt9yyK+OPhf1X8aXv2pYYzPjh4X9V/Gl79qWGL2PwR7KeTxSL8cnPwJ6Y+C1faVqDr8cnPwJ6Y+C1faVqfSHw491vQ+OfZIADJagADXJxE8IGovjXFfa1PCe7xE8IGovjXFfa1PCfR08MPn7c5Gw3g74J9JfE2E+ypa8mw3g74J9JfE2E+ypUekPDC7oPFLKwGU0wAAAAAAAGvPjJ4WtWfHGK+1qYmyzjJ4WtWfHGK+1qYm+ix+GGBfxSL/cn/AMDOlvgNP1yoCv8Acn/wM6W+A0/XKn0h4I91vQ+OfZnQDJagAAAAAAACgXKA8M2qfh1X1QwRnfKA8M2qfh1X1QwR9Di8EezByeOfcXw5MngM01+jvfb3FD18OTJ4DNNfo7329xV6Q+HHus6H4k+ySAGQ1QAAAAAAAFPuW14Ucr+JLX299BCd+W14Ucr+JLX299BDe03wqsTUfFsLach7+pmf/GNP2cKlrach7+pmf/GNP2cI9b8GXej+LCwgDFbAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAiLlG8WLWgslnKMqrouaix9qZsx1xhrc9Hdao8fXzYnrmPFEsh41cSMu4c6Xqxt3ueIzTERNGAwk1bTcr7aqu2KKd95n3o65US1DnGZZ/nWKzjN8TVicbi7k3L1yejeZ7IjsiOqI7IiF3SabtJ61uSpqtR2cdWvN08Teu4nEXcRfuV3b12uq5cuVzvVXVM7zVM9szMzO75mw2GSAdo8Ht6H0vm2sNT4TIMmsTdxWIq6atvY2qI/CrrnspiPn6IjpmHQybLMdnGaYbLMswt3FYzE1xbs2bcb1V1T2f/PYvTwK4ZYLh1pmLVfMxGdYuIrx2Jjx9lujxUU/TO8+9W1OojFX6rOnwTlt9Ht8L9D5RoDStjI8qpmuY9nicRXEc/EXZjprnxe5HZG0MpBiWtNp3lsRERG0ADx6IA5RXHLEaUzKjTWjr2GrzW1VFeOxNdMXaLEbdFqI6ufPRM79UdG289GQ8o7ixa0Hkv8EZRdt3NRY63Pco339S25iY7rVHj/JieuenqhSfEXbl+/cvXrlVy7cqmuuuqd5qqmd5mZ7Zmendf0mm6/378lLVajqfdrzSx3xfFH21wHmFB3xnFH20wHmFCI3GzQ4fF6YUOIy+pLvfGcUfbXL/ADCg74zij7aZf5hQiLY2OHxemDiMvqS73xnFH20wHmFB3xnFH20wHmFCItjY4fF6YOIy+pLvfGcUfbTAeYUHfGcUfbTL/MKERbGxw+L0wcRl9SXe+M4o+2mX+YUHfGcUfbTAeYUIi2Njh8Xpg4jL6ku98ZxR9tMv8woO+M4o+2mA8woRFsbHD4vTBxGX1Jd74zij7aYDzCg74zij7a5f5hQiLY2OHxemDiMvqS73xnFH20y/zCg74zij7a4DzChEcQHD4vTBxGX1JcjlGcUfbXL/ADCg74zijH/3TAeYUIj2Njh8Xpg4jL6kud8ZxR9tMB5hQ/VvlF8UZriP4Uy/r7cBQiHZ+7MfxtPvk6fF6YdV1GTePvNm4DAbQAAAAAAAAAADwde6tybRWm8RnueYjuWHtRtRRT013q56qKI7ap+jpmdoiZexEzO0PJmIjeXw4k61yXQemb2d5zd6I9jYsUz/ABmIubdFFMfXPVEdKiPEfWmda71NezzOr29VXsbFimZ7nh7e/RRTHi93tnpl2OKevc54g6muZvmtfc7NO9GEwlNW9vD29/wY8cz21ds+5tEYk2dNpoxRvPNkajUTlnaOQCc+TdkHD7BYm1q7W+p8jt4m1XvgMuvYqje3VE/ytyN+vf8ABpnq657E+S8Urugx069tmd8mbgt/BVOH1pq7Cf8A1CqIuZfgrtP83jsu1xP4/ij8Xr6/wbFMO9dLhz5bZF55R6T10uHPltkXnlHpYuWcmW3WtDZxxjx16sSzEYd66XDny2yLzyj0nrpcOfLbIvPKPSj7O/k77SnmzEYd66XDny2yLzyj0nrpcOfLbIvPKPSdnfyO0p5sxGHeulw58tsi88o9J66XDny2yLzyj0nZ38jtKebMRh3rpcOfLbIvPKPSeulw58tsi88o9J2d/I7SnmzEYd66XDny2yLzyj0smybNMuznLbOZZTjbGNwV7fuV+zXFVFe0zE7THXtMTHyPJpaOcPYtWeUu2A5dCgXKA8M2qfh1X1Qv6oFygPDNqn4dV9UL/R/jn2Udd4I92CA
764NZlr4cmTwGaa/R3vt7iSEI8nzX+icn4PZBlua6pynBYyzRdi7YvYmmmuje9cmN4mejomJ+VnvrpcOfLbIvPKPSwcuO05Ld3zluYr1ile/5MxGHeulw58tsi88o9J66XDny2yLzyj0o+zv5O+0p5sxGHeulw58tsi88o9J66XDny2yLzyj0nZ38jtKebMRh3rpcOfLbIvPKPSeulw58tsi88o9J2d/I7SnmzEYd66XDny2yLzyj0nrpcOfLbIvPKPSdnfyO0p5sxGHeulw58tsi88o9L6YbiXw/wATibWGw+scku3rtcUW6KcXRM1VTO0REb9cydnfyO0r5stAcOx1c3/orGfoK/2Zdp1c3/orGfoK/wBmXsc3k8mtEB9I+eGzTDfze3/cj6msts0w383t/wByPqZvSP4fz/w0dB+L8n0AZjRAAAARvx04VZbxGyTn2+54TPcLRPqPFzHRV29zubddEz8tMzvHbE0dz/KMyyHOMTlGb4S5hMdha5ou2rkdNM/6xMdMTHRMTEw2VIw488Jsv4i5P6pwsWsLqHC0TGFxMxtF2OvuVzx0z2T10zO/VvE3dLquz+7bkp6nTdf71eaiw7mdZZmGTZricqzTCXcJjcNcm3es3I2qpqj/APuvqmOl02vzZT6Yi9exF6q9iLtd27V+FXXVM1T78y+YPXgvxyc/Anpj4LV9pWoOvxyc/Anpj4LV9pWodIfDj3XtD459kgAMlqAANcnETwgai+NcV9rU8J7vETwgai+NcV9rU8J9HTww+ftzkbDeDvgn0l8TYT7KlrybDeDvgn0l8TYT7KlR6Q8MLug8UsrAZTTAAAAAAAAa8+Mnha1Z8cYr7WpibLOMnha1Z8cYr7Wpib6LH4YYF/FIv9yf/Azpb4DT9cqAr/cn/wADOlvgNP1yp9IeCPdb0Pjn2Z0AyWoAAAAAAAAoFygPDNqn4dV9UMEZ3ygPDNqn4dV9UMEfQ4vBHswcnjn3F8OTJ4DNNfo7329xQ9fDkyeAzTX6O99vcVekPhx7rOh+JPskgBkNUAAAAAAABT7lteFHK/iS19vfQQnflteFHK/iS19vfQQ3tN8KrE1HxbC2nIe/qZn/AMY0/ZwqWtpyHv6mZ/8AGNP2cI9b8GXej+LCwgDFbAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAxziNrLKNC6WxGfZxdiKLfsLFmKoivEXZ/Bt0b9cztM+5ETPVEvU1DnGW5Bk2KzjN8XawmCwtubl27cnaIiOyPHM9URHTM9EKI8Z+I2Z8RdUVY/EROHy7D728BhN+i1R21VeOurrmfejsWdNp5y2+ivqM8Yq/V4vELV2b631Ric/zmuJv3vY27VEzzLFuPwaKd+yN59+Zme1jzndw24iKxtDGtM2neQB68H6tW67t2m1bt1V11zFNNFNMzNUz0RERHTMz4nELQ8lfhD3GmxrzU2FnulVMV5VhbtP4Ef8AHqie2fxY7I6e2Nos2WMVetKXDinLbaGW8mvhHb0XllOos9sb6ixdvaKKv/8ADtz+JH9ufxp+SOqd5pBhZMlslutZt0pFK9WABw6GAcbeJeW8OdNVYiubWIzfE01U5fg5q2muqPx6tumKKd43n3o65etxP1xlGgdLXs7zW5FVX4GGw0VbV4i7PVRT9cz2REyodr3Veca01Nic+zq9FeIvTtTRTvzLNG8823RE9VMb/wCs9Mrel03azvPJV1OojFG0c3nZ/m2YZ7nGKzfNcVXisbi7k3L12rrqmfqiI2iI7IiIdFyNmI27oZEzvO8uDZyPXj87Gzk2BxsbP1sA42HIDjY2c7GwPzs5c7APy52cgONj5HOxIOJHOxsDiH0sx/G0++/D6Wf5Wn33k8nVecNmgD5t9AAAAAAAAAAA8jWOpMo0lp7E57nmKpw+Dw9O8z11V1dlFMdtU9kf6KKcX+Iub8RdSVZjjpqsYGzM04HBRVvTYo/1qno3q7feiIezyj9c51qriJmeWYy53LLsmxt7B4TDUT7GOZXNE3J8dVXN39yOiPdjBsaTTRjjrTzZOq1E3nqxyAF1TAAAAAAAAAAAAF7uS/4CtN/3cR/3F1RFe7kv+ArTf93Ef9xdUdf8OPdd0PxJ9klAMhqigXKA8M2qfh1X1Qv6oFygPDNqn4dV9UL/AEf459lHXeCPdggDWZYAAAAAAAAAA9rQf9ecg+M8N9rS8V7Wg/685B8Z4b7WlzblLqvOGx4B84+gHVzf+isZ+gr/AGZdp1c3/orGfoK/2ZexzeTya0QH0j54bNMN/N7f9yPqay2zTDfze3/cj6mb0j+H8/8ADR0H4vyfQBmNEAAAAABFXH/hHguIWVTmGX02sLqPC29rF6einEUx/urk+LxVdk+5upLmuX43KsyxGXZjhbuFxeGuTbvWblO1VFUdcTDZeiPlCcH8Lr7Lqs2yii1h9SYa3tbrn2NOLpj/AHdc+P8AJq7OqejqvaXVdT7luSlqdN1/vV5qRj75hg8Vl+Ov4HHYe7hsVYrm3dtXKebVRVE7TExPVL4Ndli/HJz8CemPgtX2lag6/HJz8CemPgtX2lah0h8OPdd0Pjn2SAAyWoAA1ycRPCBqL41xX2tTwnu8RPCBqL41xX2tTwn0dPDD5+3ORsN4O+CfSXxNhPsqWvJsN4O+CfSXxNhPsqVHpDwwu6DxSysBlNMAAAAAAABrz4yeFrVnxxivtamJss4yeFrVnxxivtamJvosfhhgX8Ui/wByf/Azpb4DT9cqAr/cn/wM6W+A0/XKn0h4I91vQ+OfZnQDJagAAAAAAACgXKA8M2qfh1X1QwRnfKA8M2qfh1X1QwR9Di8EezByeOfcXw5MngM01+jvfb3FD18OTJ4DNNfo7329xV6Q+HHus6H4k+ySAGQ1QAAAAAAAFPuW14Ucr+JLX299BCd+W14Ucr+JLX299BDe03wqsTUfFsLach7+pmf/ABjT9nCpa2nIe/qZn/xjT9nCPW/Bl3o/iwsIAxWwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPljMTh8HhbuLxd63Yw9mia7ly5VFNNFMRvMzM9URD6z0RvKpHKh4v/w9i72jNNYumrKLFXNx2JtTv6quRP4FM9tumY6dvwp9yOmXDhnLbaEWXLGKvWljPKI4sX9fZ1/BmWVzb07gbszh4iJicTXHR3Wrfs6+bHZE79c9ESTPS5nplw3aUilerVi3vN7daQB24ASlyfuFeJ4hag9U423dtaewVceq70ex7tV1xaonxz0bzHVE+OYcXvFK9azulJvbqwyXkycIJ1Tjreq9SYWunJMLcirC2a42jG3Inrnx24mOn8qejqiVwKaYppimmIiIjaIjsfHLsHhcvwFjA4Kxbw+Gw9um3atW42popiNoiIfdh5805bby2sOKMVdoAEKUeNrPUuUaR07is9zvE02MJh6d/wC1cq7KKY7apnoiHezrM8Bk2U4rNc0xVvC4LC25u3rtydoopiN5n/465Ua47cUMw4iaiq7nXcsZHhK5jA4Xq37O61x21z9EdHjmbGnwTmt9EGfNGKu/zeRxZ1/m3ELU9eb5jPccPRE28HhKZ9jYt79Xu1T2z2+9EMOJG3WsVjaGNa02neQB05HpZBkWc5/i6sJkuWYrML9FHdKreHtTXMU77bztHV0w403kuZ6hzvC5Nk+ErxWOxVfMtWqe2e2ZnsiI3mZnqiF7ODHDfK+HWmacHYinEZniIivH4uY6blf5MeKiOnaPlnplW1GojDH1WdPp5yz9FMPWz4geR+deaV+g9bPiB5H5z5pX6GwraPEbR4lP7Qv5LfA085a9fWz4geSGc+aV+g9bPX/kfnPmlfobCto8RtHiPtC/kcDTzlr19bPX/khnPmlfoPWz1/5H5z5pX6GwraPEbR4j7Qv5HA085a9vWz1/5H5z5pX6COGev/JDOfNK/Q2E7R4jaPEfaF/I4GnnLXr62ev/ACQznzSv0OfWz1/5H5z5pX6GwnaPEbR4j7Qv5HA085a9vWz1/wCSGc+aV+g9bPX/AJIZz5pX6GwnaPEbR4j7Qv5HA085a9vWz1/5IZz5pX6D1s9f+SGc+aV+hsJ2jxG0eI+0L+RwNPOWvb1s9f8AkhnPmlfoPWz1/wCSGc+aV+hsJ2jxG0eI+0L+RwNPOWvb1s+IHkhnPmlfofq1w01/FymZ0hnO2/5pX6GwfaPEbR4nn2hfyexoaRO+8gCgugAAAAAAAAAIZ1DycND55n+Y51i811FRiMwxV3FXabWIsxRTXcrmqYpibUztvM7bzLod65w/9uNT+c2PuU6iaNTlj8SGdPjn5IK71zh/7can85sfcneucP8A241P5zY+5TqPeJy+o4fF6UFd65w/9uNT+c2PuTvXOH/txqfzmx9
764ynUOJy+o4fF6UFd65w/8AbjU/nNj7k71zh/7can85sfcp1DicvqOHxelBXeucP/bjU/nNj7k71zh/7can85sfcp1DicvqOHxelBXeucP/AG41P5zY+5O9c4f+3Gp/ObH3KdQ4nL6jh8XpQV3rnD/241P5zY+5O9c4f+3Gp/ObH3KdQ4nL6jh8XpQV3rnD/wBuNT+c2PuTvXOH/txqfzmx9ynUOJy+o4fF6UFd65w/9uNT+c2PuUs6D0xgNG6TwOmsrvYm9hMFFcW68TVTVcnnV1VzvNMRHXVPZHQ9wcXzXvG1p3dUxUpO9YAEaQRBrDk9aL1RqbH6gzDM9QWsVjrs3btFi/ZiiJ27Im1M7dHbMpfHdMlqTvWdnF6VvG1oQV3rnD/241P5zY+5O9c4f+3Gp/ObH3KdRJxOX1OOHxelBXeucP8A241P5zY+5O9c4f8Atxqfzmx9ynUOJy+o4fF6UFd65w/9uNT+c2PuTvXOH/txqfzmx9ynUOJy+o4fF6UFd65w/wDbjU/nNj7k71zh/wC3Gp/ObH3KdQ4nL6jh8XpQV3rnD/241P5zY+5O9c4f+3Gp/ObH3KdQ4nL6jh8XpQV3rnD/ANuNT+c2PuTvXOH/ALcan85sfcp1DicvqOHxelBXeucP/bjU/nNj7l2so5NOhcszXCZlYzbUlV7CX6L9uK8RZmmaqKoqiJ2tRO28JrDicvqOHxeQAgTD8Ym1Tfw9yxXMxTcomiZjr2mNn7AQV3rnD/241P5zY+5O9c4f+3Gp/ObH3KdRPxOX1IeHxelBXeucP/bjU/nNj7lOlFMUUU0R1UxtDkR3y3v4p3d0x1p4YAHDsAAAAAAABHHE7gxo3iBmtrNc1jHYLHUUcy5fwFyiiq9HZz+dRVEzHVE9E7dHVEbYj3rnD/241P5zY+5TqJq58lY2iUVsGO07zCCu9c4f+3Gp/ObH3KXdF6dwWk9L4DTuXXcRdwmBtzbtV36oquTEzM9MxER29kQ9gc3y3vG1p3e0xUpO9YAEaQABCuc8mvQua5xjc0xGbajpvYzEXMRcpt4izFMVV1TVMRvamdt58bqd65w/9uNT+c2PuU6ificsfiQ8Pi8kFd65w/8AbjU/nNj7lMumspw2Qaey7I8HXduYbL8Nbw1qq7MTXVTRTFMTVMREb7R2RD0BxfLe/dad3VMVKeGABGkAAAAAAAAQ3qbk56I1BqLMc8xmaaht4nMMTcxN2m1iLMUU1V1TVMUxNqZ23ntmXnd65w/9uNT+c2PuU6iaNRlju6yGdPjn5IK71zh/7can85sfcpf0fkOD0vpnAafy+5fu4XA2otWq79UTXMb9sxERv09kQ9Yc3y3vG1p3dUxUpO9YAEaQAAAAAAABEGsOT1ovVGpsfqDMMz1BaxWOuzdu0WL9mKInbsibUzt0dsy8nvXOH/txqfzmx9ynUTRqMsRtFkM6fHM7zCCu9c4f+3Gp/ObH3KWtC6ZwGjtKYHTeWXsTewmCpqpt14iqmq5POrqrneaYiOuqeyHtjm+a942tO7qmKlJ3rAAjSAAAAAAAAI34pcGtMcRc/wAPnWd4/OMPiLGFpwtNODvW6aJoiuqqJmKrdU771z2+JiXeucP/AG41P5zY+5TqJq58lY2iUVsGO07zCCu9c4f+3Gp/ObH3KROFfDrJOHGWYzL8jxWY4i1i70Xrk4y5RVVFUU7dHNop6OhmI8tmyXja0lcNKzvEACJKAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAh3lG8W7ehsqnJcjxFqvUeKo9j0RV6ktz/ALyqOrnT+LE+/wBUdPeOk5LdWrm94pHWli3Kk4wU5dhr+h9L42PV1yOZmWKtzv3Cieu1TP5cx1z2RO3RM7xVOX6xF25fvV3r1yq5crqmquuqd6qpmd5mZ7Zfhu4cMYq9WGLmyzltvIBCVCA93Q+ls31jqTC5DkuHm7ir87zVPRRaoiY51yueymN/9I6Zh5MxEby9iJmdoetwh4fZpxE1TRlOC51jCW47pjcXzfY2Lf1TVPVEfL1RK+OlMgyrS+Q4XI8lwsYbBYWjmW6N95nxzVM9M1TPTMz1y8vhjojKNBaWsZJlVvnVR7PE4iqPZ4i7PXXV9UR2RtDKGJqdROW3dybOnwRir9QBWWB88Tes4bD3MRiLtFqzbpmuuuurammmOmZmZ6ofSZ2jeVTOU/xinO797RmlsZVGV255mYYm30eqa4npt0z+RG0bz+NPR1R0y4cNsturCPLljFXeWO8o7i5e1xm1WSZJiK6NN4S5PN2jm+rLkTt3Se3mx+LHR17zG+20OdrmZcN3Hjrjr1asTJknJbrSAO3A+2CwuJxuLs4TCWLmIxF6uKLVq3Tzqq6p6IiI7Zl86aZmYiImd/Et9yZeD0aZwtvVupcLTOd36P8AZLFfT6jtz2zHZcqj/LE7dcyhz5q4q7ymw4Zy22hkPJ64T4fh9k1WPzKmi9qLG0R6ouRVzqcPR19yo7OvrmOufciErgwr3m9utZtUpFI2gAcugAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGM8StaZRoPSuIz7N7m8URzbFin8PEXZj2NFPuz4+qI3mep7ETadoeTMRG8vF43cS8t4daZqv1VW7+cYqmqjL8JM7zVVt+HVHZRT0b+PoiOtRXPM2zDO82xOa5ri7mLxuKuTcvXq+uqqfoiOzaOqIelr7Vmca01Pis+zq/z796dqLdPRRZtx+DbpjsiI+ed5npmWPtvTaeMVfqx9RnnLbu5BsCyrAP3YtXL12m1aoquXK5immimN5qmeiIiO2QdnJcsx2c5thMpyzDV4nG4u7TZsWqOuqqqdo6+iI8cz0RG8z0L0cCuGeB4daZi3XFu/nWLpirH4mOnp64t0+Kmn6Z6fexvk18I6NF5TTqDP8ADUVaixluJiirafUVuY/Ajs58/jT7m0dETMzQyNXqevPUrya2l0/Zx1rcwBRXAGBcaM+1Zlenv4P0RkWOzPO8dTVTbvWbcdzwlG3TcqqqmKed0xzae2enqjp6rXrTs8mdo3RnypOL9WVW7+h9M4iqnHXKObmOLt1fyFEx/JUzH48x1z2RPjnoqj0dERG0QkO9wc4sYm9Xfu6PzO7duVTVXXcxFmaqqpneZmZubzMz2u3hOAnFXEWYu/8ApbuO87c27jsPTV83Pls4eyw12i0MjLGXLbeayjASr3vvFXyds/rCx++d77xV8nbP6wsfvpe3x+qP1R9hk9KKnMRvKVJ5PvFXs07Z/WFj99nfBfk85xRqeMy4gZfh7OAwc012sH3ei96qr6fwubMxFEdG8T+F1dW+/NtTjrG+72umyWnbZ2eS3we7pNjXGqsDTNraLmVYW7G+879F6qmfk5sfL4ln3FFNNFEUUUxTTTG0REbREOWNly2y260tfFjjHXqwAIkgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD5YvE4fB4W7isVet2LFmia7ly5VFNNFMRvMzM9UA6epc7yzTmR4vOs4xVOGwWFo5925V9ERHbMztER2zKiPGXiJmfETVNeYYiq5Zy+zM0YDCTPRao3657JrnomZ+Tqh73KE4sX+IOdxgssuXrOncHV/s9uYmmcRX/xa46/7sT1R2bzKKGxpNN2cda3NlarUdeerXkOJcuF1SHLiHMdYELS8ljhB6mow+u9T4PbEVRz8qwt2P5OP+NVT+VP4sT1RO/XttifJi4QTqbG29W6lwczkeHr3wti50eq7kT1zHbbif8ANPR1RO9vqaaaaYppiIpiNoiOqGbrNT/86/m0dJp/x2/JyAzGiA62Px+By+zN7HYyxhrcddV25FMfSRG/J5MxEby7IwTNuKOn8LM0YKjE46qN+mmjmUfPV0/QxXM+LGcXpmnL8Dg8JT+VXvdq/wBI+iVmmky2+TPy9LaXH+Lf27//ABMor1jdc6pxVUzXm96iPFaiKI+iHlYjOs3v/wAtmeNr9+/VP+qeOj7/ADlRv/UGKPDSf5+qzUzEdcxDp3c2yu1O13MsHR
764/ev0x/qrHcmblXOuTz6vHV0y/MU0x1U0x8iSOjo+dv2QW/qGflj/f/AMWfsZnlt+JmzmGEuxHRM0XqZ2+aX2t4jD3Kubbv2q6vFTXEyq1MU1ddNM+/BzaIneKKfmPs6PV+zyP6ht88f7/+LVCrtjGYuxERYxV+1EdUUXKqdvml38PqXUGH27lnOPp26v4+qfrlxPR1vlZNX+oKfip+6yYgHCcQ9WYfb/6n3WI7Ltqmr/SJezgeLOdW5iMZl2BxER1zb51uZ+mqPoR20GWOXesU6c0tue8fl/0mURvg+LWWV7Risrxdrxzbqpr+vZ72W8QtJ42Yp/hOMNXM7c3E0VW/pmOb9KC2ny151XcfSGmycrx/b+7Kh1sLj8Di6YqwuNw1+meqbV2mqJ+aXZQzGy3ExPfAAPQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAfm5XRbt1XLldNFFMb1VVTtEQxPOOJOjcsuTauZxbxN2J25mFpm7vPv0xzfpd0x3vO1Y3RZc2PFG+S0R7suGGYfiDZxXTg9J6rxFuemLlGXxFE/LNUO7a1ddqqiLmktTWqZ/GqwlExHyU1zP0OpwZI5wjjV4bcp/aWTDo5fm2Cx1XMt1XbV3/hYizXZr/wAtcRM+/HQ7yOYmOaxW0WjeJAHj0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAmYiJmZiIjrlUblQ8X/wD1Bi7ujtM42f4HsV7Y7EW52jF3In8CJ/IpmOuPwpjxR05dypeME5Zav6H0vjNsdcpmjM8VanpsUzH8lTPZXMdcx1RO3RM9FUeiI2joiOxpaPTf/S35M/V6j8FfzczO8uDdxu02a5cG5AOYSlyfuFeJ4iZ/OIx1u5a09gqo9WXoq5s3qujazRMdO8x0zMdUe7MMf4R8P824hapt5VgKZtYW3tcxuKmN6bFvfr92qemIjx+5Er56U0/lWl8gwuR5LhacNgsLRzaKI65nrmqZ7apneZntmVLV6ns46tea5pdP1561uTvYHCYbA4KzgsHYt2MPYoi3atW6dqaKYjaIiOyH2BjtYfLF36MNh6r9yK6qaeyiiaqp96I6ZdfNc3yrKbPdszzLCYK3+VfvU0b+9vPSxDNOLWisFFXc8fdxlUdUWLNUxPyztCXHhyZPDWZQZdRixeO0Q7WY4rXOb1V2soy+xkmGnoi/jbkVXqo8cUU86Kfl+h4nrXYnGXpv5xqK9ib1U71VRbmZ+eqZeVmPHXA0TMZfp/EX+nrv4im3G3yRU8HF8cdQ3IrjDZVlmHid+bNXPuTH0xH0NDHpdXEfcrFf0YubU9H3nfLeb/rt+20M/s8J8ipj+Ox+YXJ9yqin/wAXYnhZpjsqzCPev/8Awie7xk1lXtzbmBt9P4uG9My693i7rauuaox+HpjxU4ajb6UvBayfxfuh4zouOWP9v/UvTwr01/xsx/50fuvzc4U6cqj2GJzGif0tM/XSiSzxd1tRciqrHYeuI/Fqw1O0/Ns7dHGfV9MxvGXVdPbh5/0qeTotZH4v3I1nRc//AD/b/wBSJc4SZbNM9zzbF0zt0b0Uz6HSv8Iapj+IzumJ/t4f0VMaw3HTPKa98TkmXXafFbuV25+eec9XCcd7FW/qvTV230R02sXFe/z0w5nBrq/yHXW6Iv8AT/8AT5Y7hVqGz04bEYDFRv1RXVRV80xt9LwsZonVOEiZu5LiJiO23NNyP+mZZ9geNOkr/RiLeYYWf7VmKv2Zl7+X8RtFY2qKaNQYSzVM7RGImbX01REOe11dPFT9ns9H9HZfBk2/OP8AKCMZg8Vg6ubi8New8/8Au0TT9b4dm60OHxOCx2H5+Hv4fFWa466K4rpqj5Oh4+Y6L0vjpmq9k2Forn8ezT3Of+nYr0hHK1UeToC3PHeJ9/5KuwmnH8KcivRM4XF43C1dnsorj5pjf6WOZhwmze1MzgsxwmKp7Irpm1V/5R9KeusxW+ajk6I1dPw7+yORkuO0JqvB7zVlN29EdtmqK/oid/oeBi8Ji8Hc7njMLfw1f5N63NE/SsVyVtyndRyYcmPx1mPeHyt11W6udRVNM+OmdpexluqtRZdtGEznGUUx1U1190p+areHjD2a1tzhzTJek71nb2Z3gOKeo7MRTibeDxUR21W5oqn5p2+h7mD4u2+iMZkte3bVZvxP0VRH1ooEFtJht+Fdp0pq6cr/AK96c8BxP0viYju1zF4OZjfa7Ymfpo3e1hNXaZxXRZzrBzPiquc2fp2VyOnsnoQW6PxzymVynT2ojxRErSYfE4bE087D4i1ep8dFcVfU+qq9EzbuRct+wrjpiqnomPlh6mF1JqDDU82xneY0R4vVNUx80yit0dPystU/qCv46fpKygr7Y19q21Mf/V7le3ZXbon/AEdyzxM1VbmediMNc9yuxH+myOdBk84WK9PaeecT+3/adhCVvirqSmveuxl1ceLuNUf+T7euzn35hln+Sv8Aec8DlSR03pZ+c/omcQpe4rair25mHy6349rVU/XU61/ibqm5TtTewtv3aLEf6zJGhyvJ6c0sef6J0dLM82yzLKOdmGPw+Gjbf+MuREz8iAcdrDU+Niab2dYummeuLdfc4/6dnb0norOtR3acTFNWGwlyd6sXeiZ58eOmOuv6vdd8FFI3yW2Q/bVstupgxzM/X+f5SXd15azDMaMr0vgbmZYmuem9XE27NuO2qd+mYj3o9xmOGpvU4eim/cpuXYpjn1U082Jnt2jseZpfT2WadwPqbL7O1VW03btXTXcnxzP+nU9dUyTTfakdzV09M0R1s098/KOUACNZAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEdcSOKOX6cquZdlVNvMM0p6Ko33tWZ/tTHXP9mPlmHncb9f3Mot1adya9zMfdo/2q9TPTYomOimPFVMdvZHuz0dHgjw+tep7OqM8sRcuV+zwVi5HRTHZdqjtmez5/Ftfw6elMfbZuXyjzY2p1uXNm4XS8/nPl/6+ORaN1fruqjM9aZri8Ll9c8+3hI9jVVHuUfg0R7sxMz4u1KGndKae0/bppyrKsPYrpjbu00867Pv1z0vaEGXU3yd3KPKOS5ptBiwfe528575B+L961Yt90vXKLdG8U86qdo3mYiI+WZiH7V10AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQ/yj+LVrQuTTk2S4iirUmNtz3PaIq9SW56O61b9HO/JieuenqhknGriPl3DrS9WNuzRfzTERNGAwm/Tcr/Kq8VFPXM+9HXMKJahznMtQZ1is4zfF3MXjsXcm5eu19sz2RHVER1REdERERC7pNN2k9a3JU1Wo7OOrXm6eJvXcRfuX792u7duVTXXXXVM1VVTO8zM9svkDYZIAPDZ7mhtL5vrDUuEyDJbHdcViKumZnai1RH4VdU9lMR0/RG8zEPPybLMdnGaYbLMsw1eKxmKuRbs2qI6a6p6o/wDnsXo4FcMcBw601TRcos388xdNNWPxVPT0/wDDomenmU9Pi3npnr6K2p1EYq/VZ0+Cctu/k9zhdofKdA6Vw+S5ZbpquREVYrE83avEXdumur6ojsjaHu5rm2WZVZ7tmWOw+Fo7O6VxEz70dc/I7dy5Rbomu5XTRTHXVVO0QwzHau4Z5NiaruL1Fp6jFbzFVdeLt3L3vTO81fIx4+/bed5a0/djavc6eY8RMdiaptaV0lnGbTvtTfuYeqzZnxTvVG+3v7MXzTA8adQc6b3csrsV9ViziKLURHuzTNVXzyyHGccuF2Et1VVaos3IpnbazYuVzPvbU9Lzr3KJ4V26OdTnWLuTvttRl97f6aYW8d7U8GL9YmVDJgjL8TNPtG0R/wB/uxWvgvq7E3ar2KzHLqrtU9NVd6uuqflmk9ZDUvbmOWf5q/3WU2+UVwrrpiqc6xlE+KrL72/0UuzheP8Awrx
764FzmU6iuUT47mCvUx880puN1kfL9lf7K0M/P8AdhdzgjqimnejHZXXPim5XH/i6eJ4NaztfydGX3/7mJ2/aiEpYXjNwyxFXNo1fgKJ32/jOdR+1EPZy7iFoXMNowmr8juVT1U+rrcVfNM7n2jqq84/YnoXR25b/qr7juGmuMHNc1afxF2ij8azct3N/eiKt5+Z4ONyPOcDVNOMynH4aY6+64euj64XDtXbV2nnWrlFynx0zvD9VU01RtVETHil1XpjJHirCG/9P4p8F5j9/wDpSraYqmmeiY64Fw8w0/kWYUzGOybL8TvExvdw1FU9PuzDFs04SaJxtVVdvL72Crntw+IriP8ALMzT9CzTpfHPirMKeT+n80eC0T+3/asonPNeBeDrpqnLM9vWatuim/ZiuPnp2Ydm/B/WWB3qsWMJmFEduHvbVf5a4p+jdbpr9Pflb9e5Qy9FarHzpv7d6PTefG9XN9N59lMTVmOUY3DUR1112aubH+LbZ5UdMbxtMeOFutotG8Tuo2pak7WjZ9cLiL+Fud0w165Yr6+dbqmmfnhkuU8RNZZZNMYfPcRcoj8S/EXaZ/zRM/NMMVcOb4qX8UbusebJj76WmPZMWT8c8wp5tObZLhr0fjV4auqiZ+Srf62Y5Pxi0fjZinF3MXl1c/8AHszVT89G/wBOytjmJUsnRmnvyjb2aOLprVY+c7+8LiZXn+R5pTE5dm+BxW/V3K/TVPzbvQu27d2iaLlFNdM9cVRvCltFdVFXOpqmmeyY63t5PrDVGUV01Zfn2YWop22oqvTco/y170/Qp36HnnS36tLH/UET3ZKfos9j9Jabx284jJsJMz+NTRzJ+enZjuZcK9O4iZqwt7HYKrsii5FdPzVRM/SjDLeNGrMPtGLowONiOua7PMmf8sxH0Mpyrjrgq5ppzTIcRa6t68NepuR7+1XN+tBOj1mPw9/5puM6Mz+OIj3j/MOxjeEeKiZnB5vZr6ejutqaZ2+SZeNjOGOqMPG9qzhcVH/tX4if+rZnOXcWdE4ymOdmF7C1dtN+xVG3yxvH0sgwOrtL42dsNqDLa6vyZxFMT80zu4nNqsfir+x9ndHZvBb9J/73QZjNJamwm/d8jx0bdMzRa7pHz07vNvZfjrP8tg8Rb/v2qqfrhZ6iui5TzqK6a6Z7aZ3hzVTT
764VG1URPvkdIW+dXFv6fxz4bz+n/8AFWKuirmz0T4hZ+9l+AvRMXsDhrm/Xz7VM/XDq1ad0/VO9WR5ZM+OcJb9DuOkY+dUM/0/f5Xj9Fadp8RtKxt3SGl7k71ZDl8T/ZsRT9T9YfSembEzNvIcu3nr52Hpq+uHX2hTycfYGXfxR+6uEztHT0P3ZtXb07Wbddyf7Mb/AFLK2shyO1VzrWTZdRV46cLRE/U7lrD4e1/JWLVv+7REOZ6Rj5Vd1/p+34r/ALK6ZfpbUeYVRGFyXG1RP41dvudPz1bQynKeFOdXqqaswxeFwlHbTTM3Kvo2j6UrZtnmTZTTvmWaYPCe5dvU0zPvRM7ywrUHGLSmXUVU4GcRml6I6Is0cyj5aqtvoiXkajU5u7HVL9maHT9+a+/5/wCI73tac4f6eyfmXKrFWOxNPT3XE7VbT7lMdEfNv7rJbOLwtzE3MJZvW67tqPZ0UzvzPf8AF7yOMmu691xT3XGVzpjJLkbzTYiYxN6meymqemmP7W0e5EpByXK8Dk+X28Bl9iLNi3HRG8zNU9s1TPTVM9sz0yq56zE/ftvb+38+jV0nU2/0qdWv6b/lz/OXdAVl0AAAAAAAABi3E/W2X6A0vOoMywmKxViL9FnueH5vP3q32n2UxG3Q9rWbTtDyZisbyykQD302jvJ7PvmtfvnfTaO8ns++a1++m4XL6UPE4vUn4QFTyptG7+y0/n8R7lNn9972n+Ubw1zW9TZxGKzHKaqp2icbhfY7+/bmuI9+didNlj8L2NRin8SXx1ssx+BzPA2sdluMw+Mwt6nnW71i5FdFceOJjol2UCYGIcWNfZbw505YzvNMHi8XZv4unC00YaKedFVVFdW886Yjbaifnhj3CjjTkHEXUd7I8ryrM8JftYSrFTXiYo5s001UU7exqmd964+ZJGK8160R3OJy0i3Vme9KACN2Ai3ipxs0/wAPdS0ZDmeVZnir9eGoxEV4eLfN5tU1REeyqid/Yy6pS152rDm960jeyUhiPCjXuW8RdOXs8yvB4vCWLWKqws0Ynm86aqaaKt/YzMbbVx8zLnlqzWdpe1tFo3gEZ8WeMuRcOM9wuUZrleZYu7icNGJprw0Uc2KZqqp2nnVR070yw3vptHeT2ffNa/fS10+S0bxCO2fHWdplPwgHvptHeT2ffNa/ffu1ypdFTVEXch1BRT46bdmr/wDZD3hcvpc8Ti9SexGekuOnDbUV+jDW87nLsTXO1NrMLc2d5/v9NH/UkymYqpiqmYmJjeJjtRWpak7WjZLW9bd9ZAYtxP1tl+gNLzqDMsJisVYi/RZ7nh+bz96t9p9lMRt0PK1m07Q9mYrG8spEA99No7yez75rX75302jvJ7PvmtfvpuFy+lDxOL1J+EA99No7yez75rX75302jvJ7PvmtfvnC5fScTi9SfhGvCXjFkXEfOMZlmVZZmOEuYXD93rqxMUc2Y50U7Rzap6elJSK9LUnayWt4vG9QBy6Hkayzy1pzTONzi7EVep7e9FE/j1zO1NPyzMfJu9dEHKXzOq3leVZRRVMRfu137kR4qIiKd/lqn5k+mxdrlrWVPX6jh9PfJHOI/dH3DvJr+ttfU/wjXVftzXVi8dXP41MTvMf4pmI96fcWfoppooiiimKaaY2iIjaIhE/Jsyumzp/Mc3qpjumJxEWaZ/sURv8ATNU/MllY6Ry9fL1Y5Qp9Cafs9N2k87d//X8+oDG+Iuq8LpHT9zHXObcxVzejC2Zn+Ur8c/2Y65+brmFKlJvaK15y1MuWuKk3vO0Qj/lEaq7nRh9MYK7MXedTiMXVTVtNO3TRT7+/svkp8bP+G2pbeqdK4bMOdHqqiO5Yqj8m5EdM+9PRMe+q1mOMxOY4+/jsbeqvYi/XNdyurrqmWScMdX39I6gpxE8+vAX9qMXajtp7Ko/tU9cfLHa3Mugjh4pXnH8l8lpumZ4ycl/Dbu9o+X/vvK0w+WDxOHxmEtYvC3aL1i9RFdu5TO8VUzG8TD6sHk+wiYmN4AB6AAAAAADHdda30xonL4xmo81s4OK9+5Wumq7dmPyaI6Z9/qjtmEHaj5VWCt3arentKX8RR+LexuIi3/0UxV+0lx4MmTwwivmpj8UrJio88qfV3dN405kcUeKe67/Pzv8AR72RcquiblNGeaQqpo/Gu4PF7zHvUVUx+0lnR5o+SONXin5rNDA9BcXdB60uW8NlWc02MdX1YPGR3G9M+KN/Y1T7lMyzxXtW1Z2tCetotG8SATMRG89EOXQIj4hcoHQ2lr9zBYK5dz7H25mKreCmO5UVeKq7PR/l5yK8w5VWoa7szl+lcrsW+yL9+5dn545v1LFNLlvG8QgvqcVZ2mVsBVbKOVXm1F2P4W0lgr9vtnC4mq1Mf5oq3TJw24zaI1zdt4PBY6vAZnX0RgsbEW665/sTvNNfvRO/uPL6bLSN5h7TUY7ztEpFAQJgedqfN7GQabzLPMTbuXbGX4W5irlFvbnVU0UzVMRv0b9CIdOcpLSmeahy3JcPkWdW72YYu1hbddyLXNpquVxTEztXvtvKSmK943rDi2WlJ2tKbwEbsAABinFPXOXcPtM059meExWKsVYijD8zD83nc6qKpifZTEbexl7Ws2naHlrRWN5ZWIr4W8b9P8QdTzkGWZTmmFvxh67/AD8RFvmbUzETHsapnfpSo9vS1J2tDyl63jesgDl0CMeLHGfIeHOocPkuaZXmWLvX8JTiqa8NFHNima66dp51UTvvRPzvc4TcQss4j5His2yrBYzCWsNiZw1VGJinnTVFNNW8c2Z6NqoSTivFetMdziMlZt1d+9mQIOz7lK6TyfPMflN/Is7uXcFibmGrroi1zaqqKppmY3r6t4eUx2yeGNy+StPFKcRAPfTaO8ns++a1++d9No7yez75rX76ThcvpR8Ti9SfhAPfTaO8ns++a1++d9No7yez75rX75wuX0nE4vUn4QrpLlGaW1JqbLshwuR5zZv4/EUYe3Xdi1zaZqnaJnauZ2TUjvjtSdrRskpkreN6yDD+LPEDLOHOn8NnOa4LGYuziMVThaaMNFPOiqaKqt550xG21EvA4Ucacg4i6jv5HleVZnhL1nCVYqqvExRzZpprop29jVM771x80vYxXmvWiO4nLSLdWZ70ngI3YPP1BnWU6fyu7mmd5hh8Bg7X4V69XFMb9kR45nsiOmUFav5UeQYO/XY0zkOKzXmztGIxNz1Pbn3aadpqmPf5spMeG+Twwjvlpj8UrCipFfKn1ZNzejTmSRR4pm7M/Pzv9GSaY5VOCu3qbWpNLXsNRM9N/A34ubf4Kojo/wAU+8mnR5ojkijV4p+ayY8LRmrtOaxyz+EdOZrYx9mNouRTO1dqZ7K6J9lTPvw91WmJidpWImJjeAGB8XuKGUcNbOW3M2y/HYyMwquU24wsUex5nN3350x+VD2tZtO0c3lrRWN5Z4Ip4a8d9H631DTkVizjcsxl2nfDxjIoim/V20UzTVPsu2Inr7ErPb0tSdrQUvW8b1kAcOgRDxE4+6b0VrDHaZzDJs2xGJwfc+fcsRb5lXPt01xtvVE9VUR1M94c6swWt9IYTUuX4bEYbDYqbkU27+3PjmV1UTvtMx10z2pLYr1rFpjucVy0tbqxPeyEHzxWIsYXDXMTir1uxYtUzXcuXKoppopjrmZnoiPdRu30EJa25Seickv3MLkuHxeoL9E7TXZmLVjfxc+rpn34pmPdR3juVTqOu5M4LS2U2aOyL165cn545v1LFdJltG+yvbVYq9262Iqjl3Kqz2i5E5jpPLcRR2xYxFdqfnmKkh6Q5SehM4uUYfN7eOyG9V0c6/R3Szv/AH6OmPfmmILaXLX5FdVit801jrZZj8DmeBtY7LcZh8Zhbsb271i5FdFce5MdEuyrrAAAAAAAAAAAAAAAAAAAAAAAAAAAx/iDq/J9EaXxOf51dqpsWY5tu3RG9d65P4NFMeOfmjpmeiHpZ/m+XZDk+KzfNsVRhcFhbc3L12rqpiPcjpmfFEdMqJcauJOZ8RtTVYu7N7D5Th5mnL8FVMbW6e2uqI666u3r26Ijojps6bTzmt9EGfPGKv1eJxF1hm+uNU4nPs3vVTXcnm2bMVb0Ye3H4NFMeKO2e2d5Y45cbNusRWNoY1rTad5cDk7HrlwQAJC4U8Q8Bw7tYjMsBpuzmWob0TRaxmLvTFrC29uqiimN5me2d46Oj3/Qz7j7xNzaqrbPaMuoq6qMDh6bcR7kTPOq+lFpKKcNJt1pjeUsZrxHVidoejnuf55ntya87zjMMymfzrE13Y+aqZiHmxM0xtT7GPFHQCSIiOSOZmeZv0uOlzsPXjgNjYeud5jqmYKpmqNqvZR4p6QHjtZZmOPyyvn5bjcTgat9+dhr1Vqd/H7GYZblPFviPlkxGH1jm1dMTvzb97u0T/n3YQObUrbnDuL2rylNGScpXiNgK6fVc5TmluI2mnEYWaKp/wAVFUdPySkLIeVZllyKac80li8NV214PFU3Y6/FVFMx88qqkIbaXFb5Jq6rLX5rx5JyheGOZVRTfzfEZbVP55hq6af81MTTHyykXJNRZBndiL+TZ3l2Y2p6q8LiaLsf9My1sRMx2v3Zu3LNyLlm5VbuR0xVRO0x8sK9uj6z4ZTV11vxQ2bsezfRGk81qqrxmQ4Gq5V13KLcW6/81O0qKZHxM19knN/g3V2bWYp22prv91o69/wbnOj6Ei6d5Teu8DRRbzfCZVm9Mbb11WpsXJ9+aJ5vzUoeDzY53pP+Es6nDlja8frG6ec34K6XxVNU4HE4/AXOzm1xcp+WKo3+mGIZnwOzyzMzgM3wOLpjfaLlFVmr3Pyo+l0sj5VGR3eZTnOmMww2/RVXhbtF2I+SrmykPTvHHhjndNEWdTWcJeq67WNtV2Konxb1RFM/JMpI1Osxc95/dXv0foc3KIj27kQZpwz1tgOdNWR3sRRG/ssNVTc+iJ3+hjGNy/H4G5NrHYLFYSuJ6ab9mq3P/VELhZdmeW5jbi5l+PwuLomN+dZvU1xt8kuxdt27tM0XbdFdM9cVRvCWnS+SPHVVyf0/inwXmP3/AOlLPd7HC3WY6O0rmG84vIMvuTPXMWIpn542ljmZ8H9E4yZqs4TF4Gqe3D4mr6q+dH0LNOl8U+KJhSv0Bnjw2iVaHKdcbwKwFU/7Fn+KojfqvWaa/pjmvFxfAzOqNvUuc5fdj+3RXR9W6zXpHT2/Ep36I1dfwb/nCJIkmd42npj3Ug4/g7rbDc6bGGwWMinq7jiYiav88UvGxPDvW+Hq5t3TWN9+3NFyP+mqU1dThtytH6q9tFqac6T+ksdwmLxOEiYwmJvYfed57lcmj6pezhda6tw0x3HUeZxtG0RXiKq4/wCrd172l9R2Zqi7kWZUTT174avo+h8f4Azz2ox/m1fodT2Vue0uaxnp4d4/VkNjifra1RFMZ3cr2nrrtUVT+y7lvi7rejrx+Hq9/C0ehilGns9rq2pyfMJnxRhq/Q7eF0ZqvFRM2NO5nXEdvqeqn69kNsOm+cR+yeufW8q2t+7I/Xh1r+d4PzWn0vzXxe1tVMTGPw9PuU4Wj/V1cBwq11i5jfJYw1MxvzsRiLdP0RVM/QyXLOBudXObOY5vgcPHRvTapquT9PNQXnQ059X+6zSvSeTl1v7f3Yze4oa2u0zH8NXKN+2i1RH/AIvJxmrdVZjM27+f5pd7p0TbpxFURV7nNpnafmTVkfBXTOEmK8yxGNzKqPxJr7lb+anp/wCpnOTacyHJoiMrynB4WY/Gt2o53+brV76/S4/h03/LZcp0Vrcvxcm0e8z/AOK8aa4XauzyqMRdwf8AB1q5O83sZvRXPu838Kfl2TBorhbp3T3csTiLf8KY+jaru9+mObTV46aOqNuyZ3n3WeEzERvM7RChn6QzZu7faPo1NL0Vp9PPW23nzkGCa34t6C0jbuU5lntm/i6OrCYP+OvVT4tqein36piECcQOUzn+ZWbuD0jl9GS26uiMXe5t2/Ee5T00Uz/mQY9NkycoXcmfHj5yszrLV+nN
764H5ZOYaizbD4Gz1UU11b13J/Jooj2VU+5EOxpDPsHqfTWBz/L6btOEx1qLtqLtO1XNmejeOxrszbNcyzjMKsdmuPxOOxVc+yu37s11T8s9nuL28nzwLaV+L6PrlLqNNGGkTv3o8Go7W0xt3M7AU1oAAAAAAQ1yxPA3c+MLH/kmVDXLE8Ddz4wsf8Akm0/xa+6LP8ADt7Kx8E9E4XX+ubensXjr2CtVYe5e7raoiqremI6Np99PHeq5D5WZn5vR6UZ8j3wzWPgF/6oXVXNXnyUybVlU0uGl6b2hXWeSrkO3RqzMt/g9HpYDxX5O+daRyLEZ9k+a0Z1gcLTNzE25sdyvWqI66ojeYqiI6Z6piOzrXIYxxUz7K9OaAznMc2v2rdn1Jct0UVzG96uqiYpt0x2zM9Hzz1Qgx6vN1o7902TS4urPdsqByceIWY6N11gcBXia6skzPEUYfF4eqr2FFVcxTTdiOyaZmN57Y3jxbXma3NH4HEZnq3KMvwtM1X8TjbNq3EeOquIbI0mvrEWiY+aPQ2mazEoL5bPgqy348tfYX0Xcinwr4/4lvfbWUo8tnwVZb8eWvsL6LuRT4V8f8S3vtrLvF/tZcZP9zC4oDNaIppyz/C5h/imz9pdXLU05Z/hcw/xTZ+0urmh+Kqa34SWeRT4KMf8dXvsbKckG8inwUY/46vfY2U5ItT8WyXT/CqqHy3fCPk/xRT9tdeVwC4N5bxJ07j80xudYvAV4XF+p6aLNqmqKo5lNW/T771eW74R8n+KKftrrPORB/ULPPjT/wDVQvTe1NLE1UopW+pmLOt3quQ+VmZ+b0el+L3JUyabcxZ1fj6K+ya8JRVEfJFUfWsYKXF5vUt8Li8lC+MfCbPuG1+xdxl+zmGWYquaLGNs0zTHOiN+ZXTP4NW0TMdMxMRO09E7SvyNtf5licfidC5pia8RhqMPOIy6q5VvNrmzEVWon8nad4js5s+N6PLN1jklel8Lo/C4qzis0qxtOIv27dUVep6KKao9lt1VTNUbR17b+5vinIt0xjsVrPG6ruWa6MvwWGqw9u5MbRXermPYx49qYmZ8W9PjXbWnJpptkU61jHqIii26GuWJ4G7nxhY/8kyoa5YngbufGFj/AMlDT/Fr7r+f4dvZWLgrovDa+11Z07i8bewVq5YuXZu2qYqqiaY322lPPeq5D5WZn5vR6UP8mLPMo09xWw+ZZ3mFjAYOnCXqJvXqubTEzT0Rutn67XDXy0yf/nr2qyZq32pyUtNjxWpvfmizvVch8rMz83o9J3quQ+VmZ+b0elKfrtcNfLTJ/wDnvR07r7RmocyjLck1Jl+Pxk0zXFmzd51U0x1zsrTn1Ed87/osRh088tv1Ypwd4N5bw2zrG5ngs6xePrxWH7hVRetU0xTHOirfo95KAK172vO9lilK0jaoA5dCAOUpc52sMvtc7eKcBE7eKZuV+iE7ZpgrOY5diMDiJri1ftzRVNFXNqjftieyY64lVPXOSZjp/UuJy7M7ly9cpnnW71czPdrc/g1bz7nzTEx2NPoulZydbfvj5MD+oMtq4Ip1e6Z5p84EU0U8M8vmnbeq5emrbx90qj6ohnKC+T/pbF4vEzqHF3b9vL7Fc+p7UVzFN67HXVMdsU/X70p0VtbWK5rbTuvdFZLX0tOtXbaNvfb5utmmOwuWZdiMwxt2LWGw9E3Llc9kR/r7iq+vtUYzVmoLuY4jnUWY9hhrO/Rat9ke/PXM+P5Ek8pDUNdPqPTOHuTFNVMYnFbT19MxRTPzTO391CzU6N00Vp2k85fP9Pa6cmTsK8o5/Wf/AAAaj55LHAfW85fjaNL5nd/2TEV/7JXVP8lcn8T3qp6vd99PKl9FVVFUV0VTTVTO8TE7TErV8Mc/q1JozBZjeqicTETZxG3/ABKeiZ+WNqvlYfSenis9rX58313QGunJWcF/ly9vL8mSoX49a4rou/8ApfKcRVRVRMV427bq2mJjpptxMfJM/JHjTFj7eIu4K9awmIpw2IromLd2q3z4oq26KubvG+3i3Vg4oaTxGk88t2MRmf8ACVWLtzfm9NuaKpmap33jeenft3Q9HY8dsu9p745Qs9OZs2PT7Y47p5z/AI/NOPCTWNGq9PxTia4jM8JEUYmnq5/iuR7k9vinf3GaIP4FaOx9fqXV2HzmMLR3Wu1VhosTX3a3E7VRM86Nt56uidpiJTgh1lKUyzFJ7v7LfRmXLl01bZY7/PzjzAFVoDxtcZ/h9K6QzTUOJo59vAYaq9zN9ufVEexp392raPleyxDjPp/Gap4XZ9keXxzsXiMNzrFG+3Proqprin5Zp2+V1SIm0RPJzeZis7c1HMZitTcS9e0Tfu14/Oc1xEW7dMztTTvPRTH5NFMfNELK6L5MWlcDhbdzVGYYzNsZMb3LdivuNiJ8Ubezn39438UKu6ZzjNdG6uwmcYS33HMcsxHO7lfonoqjeKqK6eiereJjon3lqdIcpvRmYWLdGosHjslxO3s6qaO72d/HE0+z+Tm/LLW1XaxERi5fRl6bspmZyc/qyuOA3CfuXc//AEnTt4/V2I3+fujF9TcmPQ+Pt1VZLjszye9+LHdIv2o9+mr2U/5oSFkvFLh3m/N9Q6xyeaqvwaL2IizVP+G5zZ+hluHv2MTZpvYe9bvWqummu3VFVM+9MM7tc1J75lf7LDeO6IU0x3Jw13hNW4LK7c4XE5dibu05nZq9hYojpmquidqonaOiOmJnaN1wdP5ZbybI8FlNnEYnEUYSzTai7ibs3Lle0bb1VT1zP/8Azod4MuovliIt8nuLBXFM9UVN5UXGDF5jmuL0RprF1Wctw1U2swxFqrarE3I6KrcTH4kdU/lTv2ddjOK2fXNMcOM+z2zVzb+FwVc2KvFdq9jRP+aqFCtC5Jc1VrfKMim5XE5hjKLVy5vvVFM1ezq9+I3lY0WKs75LfJBrMkxtSvzZxwY4J59xBtxml+9/BORRVtGKro51d+YnaYt09G+3VNU9ET49phYXKOTnwwwWHpt4rLsdmdcR03MTjblMz8luaY+hK2WYHCZZl2Gy7AWKMPhMNaptWbVEbRRRTG0RHyOwiy6vJee6doSY9LjpHfG8oX1Hya+HmYYaqnK6cxya/t7Cu1iJu0xPu03N5mPemPfVq4scMtR8Nc1tUZhtiMFeq/2TMLETFFcx07T20Vx17T8kzsv6xziVpbCaz0TmensXRRM4mzPcK6o/kr0RvRXHvVbfJvHa6w6u9LfeneHObS0tH3Y2lEPJa4vYrUm2jdT4mb2a2bc1YHFVz7LE0Ux00VT210x079sRO/TG82Ba29N5rjdNanwGcYXnW8Xl+KovUxvt001dNM+5PTE+5Mtj+DxFrF4SzirM72r1um5RPjpmN4+t7rcMUtExyk0eWb12nnDGuMHgn1b8S4v7GpRfhR4UtJ/HeD+3oXo4weCfVvxLi/salF+FHhS0n8d4P7ehNovh2Q6z4lWxIBmNEAAQpyzPBDa+NbP7FxNaFOWZ4IbXxrZ/YuJtP8Wvuh1HwrIb5Gvhgq+LL/7VC56mHI18MFXxZf8A2qFz02u+L+SLRfDAFNbU+5bXhRyv4ktfb30i8iLwc5x8b1fY2kdctrwo5X8SWvt76ReRF4Oc4+N6vsbTTyf7SGdj/wB1KfECah5M2SZxn+Y5vc1PmNqvHYq7iaqKbFExTNdc1TEe9unsUMeW+PwyvXx1yeKFdu9VyHyszPzej0oh5QPDDA8M8blGHwWaYnMIx9u7XVN63TTzOZNMdG395edVjlz/ANMaW+D4j9q2uaXUZL5Yi09ypqcGOmOZrDCeT7wmy/iZh85u47N8Vl85fXZppizbpq5/Pivfffxc36Uqd6rkPlZmfm9HpdPkLfzHVv6XCfVdWVeanUZKZZis9xp8GO2OJmEGaO5OGS6b1Vlmf2dS5hiLmX4mjEU2q7FEU1zTO+0zCcwU8mS2Sd7St0x1pG1YQPy2/BjlPx1b+xvIz5E/hWzH4ku/b2EmctvwY5T8dW/sbyM+RP4Vsx+JLv29hoYv9rKjk/3ULiPL1bn+XaX03js/za73LB4K1Ny5MddXZFMeOqZmIiPHMPUVv5b+oL1jKsh0zZuTTbxVy5i8RETtvFG1NEe7G9VU+/TCjhx9peKrubJ2dJsgviXrvUfEvVMYnGd1qoqudzy/L7O9VNqJnaKaYj8KuejeeuZ9zaImLhlyZKsTg7WY67zC/hqrlMVRl2DmmK6PcuXJiY39ymPlePyL9KYbNdX5lqbGWqblOUWqKMNFUbxF65zvZe/TTTV/miexbpd1OonHPZ4+7ZT0+CMkdpfv3RXb5PnCmmz3OrTt6urb+UqzC/zvor2+hg+vuTBlF/CXMTovNMRg8XTEzThcbV3S1X7kVxHOp9+ed8ixgq
764V1OWs79Zatp8do22a7srzHVvDPW1VdicRlOcYC5zL1mvqqjrmmuOquiY2nxTG0xPVK8nCXXOA4gaNw2fYOmLN7fuWLw++82L0RHOp92OmJifFMdu6IOWtpPDXshy3WWHtU04vDXoweJqiOmu1VEzRM/wB2qJj/ABsL5F2oL2B4hY3T9VyfU2aYOquKN/8Ae2vZRP8Almv6PEuZYjPh7SI74U8UzgzdnPKVwFauXT/MdJfpcX9VpZVWrl0/zHSX6XF/VaVdJ8av8+S1q/hSq/ZuXLN6i9ZuV27lFUVUV0TtVTMdMTEx1SuNybuMlvWOEt6Z1Hfot6hsUbWrtXRGOoiOuP8A3Ijrjt647YiIuTForJteZfrDI84t+xqw+HrsX6Yjn4e5E3Nq6f8AWO2N4R7rvSmouG+sP4Px83MPisPXF7B4yzM003aYn2Ny3V78e/E9DRy1pmmcc84Z+Kb4YjJHKWw4Q/yd+MGH15ltOS51ct2NSYa37KOimnGUR/vKI/K/Kpj346OiJgZGSlsdurZq0vF69aFFuVP4eNR//i/9raWW5KXgLyP9Jif+4uK08qfw8aj/APxf+1tLLclLwF5H+kxP/cXGhqf9tT8v7KOn/wBxb8/7pTVD5XfELH5nqy7ojAYiu1lWW8z1VTRO0Yi/MRV7Lx00xMREePefFtbxRrlQ6YzLIeLGaY7E2LnqLNbnqrCX9vY17xHPp38dNW8beLae2EGhis5O9NrZtGPuZBwN4B3ta5NZ1JqHMbuX5TfmfU9nD0x3e/TE7TVvO8UU7xMR0TM+5G0zOWXcn7hXhLUUXNP3cZXH+8v469vPyU1RH0IX4JcoKnSOn8LpnUuVXsXgMLE04fFYSY7rRRMzPNqoqmIqiN+uJjo7JTnkfHLhfm1NMUans4S5PXbxlquzzffqqjm/NKTUTqOtPPb6I8Eafqxy3+rzc35O/C7HWppw+U4zLa5/3mFxtyZj5Lk1R9CKNfcmDOcBZuYvR+bUZtRTEz6kxURavbeKmr8Gqff5q0GT59kec087KM5y7Madt98LiaLv7My9FXrqctJ5/qntp8V45fohrkucN8z0Tpy/meeXsTZzDM4iZwE3Ji3h6I6udTvtNye2euI6OjpTKCLJeclptKXHSKVisADh2AAAAAAAAAAAAAAAAAAAAAAAArRy48yx9qzpjKreKuUYHEeqL16zTO1NyujucUTPj2iuraPd95V+Vk+XNXM5rpW3O21NjFVR8tVr0K2tzRx/owxtXO+WXDhyTCyrONjZy4BxsOQHGxLlxIONjbocgONnGz9GwONjZyRAODZyA42HJsDjYhybA42cgDhyADmJlxsbA+uFxOIwt2LuGv3bFymd4rt1zTVE+/HSy7I+KnEbJdowGss35kRtFGIv+qKYjxRF3nbfIwwc2pW3OHdb2rylNWT8pXiHg9oxdOU5hEf8XDTTM/LRVH1MyyPlWV86Kc70dG3RvcwWN3n3fYV0x+0rIQhtpcVvklrqssfNdLK+Upw3xnNi/VnGAqqnbbEYPfb3d6Kqo2ZRlnGXhnj+bzNXZfYmqdojEVTZ/aiFBnMTMdUoZ0GOeUyljXXjnDZHlWocgzaiK8qzvLcdTPbhsVRcj/pmfHD02sjannc7m077777dL08v1Dn+X0zTgM9zTBxPXFjGXLcT80wino/ysljXx86tknQbx42vDDcQtdYa5NyzrDPIqmNvZY65VHzTLsxxQ4h+WWc+c1Ofs+/m64+nlLYN0e4dHuNfXrocQ/LLOfOanHrocQ/LLOfOaj7Pv5wcfTylsGfDGY3B4OmKsXirGHpnfabtyKIn52uzHaw1bjrddrGanzq/br6KqK8fdmmrp36Y523W8W/Xcv18+/XVdq8dc86fpdR0fPzs5nXx8qtgOZ8VeHOXxPd9Z5LVMRM82ziqbs9HuUbsMz7lJcO8upqpwf8ACma3Yj2MYfDRTTM+7Vcmno97dS+JmI236PEbJa6DHHOUdtdeeULD6j5Umf4iareQacwOAo/FuYm9Vfrn5IimI+lFGsOJuutV86jOdR42vDz0eprNfcbO3u0UbRV/i3YeLFMGOnKFe+fJfnLneRxs5hMhKY6YX65PngW0r8X0fXKg0dcL88n3wL6V+L6PrlQ6Q8Ee69ofHLOwGS1AAAAAABDXLE8Ddz4wsf8AkmVDXLE8Ddz4wsf+SbT/ABa+6LP8O3sp/pvOM6yPM4x+QY7FYLGxRNMXcNVMV82euOjsZR65nFPyr1B/zamUcj3wzWPgF/6oXVaGp1Fcd9pruz9PgtkpvFtlAo4lcVKvYxqvUMzPiu1vnTkHFHX2Ot13cu1Lnd3qovYqLlVFG/Zz7nsaY+WGwEQcbEeGkQn4OZ8VplBPJ84GVaNx9Gp9UXLN/OaaZjDYa1POt4XeNpqmr8avaZjo6I3nr6JidgVMmS2S3Wst48dcderVBfLZifWpy33M7tfYX0W8iqYjixj4mevJb0R/zrKduVHkF7P+DmaRhrc3L+X10Y6imI64omef81FVc/IqjwI1hZ0RxMy3OcZNUYCrnYbGTEbzTarjaav8M82rbt5q/p46+mtWOahnnq6iLTyX+HyweJw+MwtrF4S/bv4e9RFdq7bqiqmumY3iYmOuJfVmNIU05Z0xPF2xET1ZTZif89xcjEXrWHsXL9+7RatW6ZrrrrqiKaaYjeZmZ6oiFA+O+rbGtOJ+a5zgqpqwMVU4fCVT+NbtxzYq/wAU71f4l7QVmcm6nrbRGPZY3kVRMcJ8dv251e+xspyRnyZNP3tPcHcpt4q3NvEY7n465TMdMRcn2H/RFCTFfPMTktMJ8EbY6xKofLd8I+T/ABRT9tdRhojTev8AOsBfv6RwWcYjC27vMu1YO5VTTFe0TtO0x07TCT+W74R8n+KKftrrPORB/ULPPjT/APVQ0YyTj00WhnzjjJqJrKFP/QfGz2o1R/z6/wB58cXoTjNFiru+SaquW9ummKrle/yRM7r4itx1vTCxwVfVLXZp2vJdP59NvWulcyx/cq4i5g6sXVhKqf70cyapn3N6V3+DmqtH6o0har0bZowWDwm1qvARai3XhquvaaY6OnpnnRMxPT077on5cGUYSrTmQ59FiiMXbxlWEquxHsqqKqKq4pme2ImidvFvPjYdyJMZet8R83wEVzFi/lNVyqnfomqi7bimfkiur50ubbPh7TlMIsW+HN2fmt6hrlieBu58YWP/ACTKhrlieBu58YWP/JS0/wAWvuu5/h29lTuHmj811zqW3kGTXMLbxddqu7E4iuaaNqY3npiJn6Emd7FxE/PNP+dXPu3R5IPhowvwLEfsrsL2q1N8V+rVR02npkpvZTXvYuIn55p/zq592kDgFwT1foXiFaz/ADnEZTcwlGGu2pjDX66q96ojbomiI2+VYoVb6zJas1larpMdZiYAFVZAAGKcRtE4HWOEw1F65OHxOHuxNF+mnee5zMc+n5Y6vFMR7rKx3S9sdutWe9HlxUzUml43iXXy3BYXLsBYwGCs02cPYoi3bop6oiHYBxM798u4iIjaFe9eafzLVvGjNcpwd2xavU26Kqar9UxTTRTaonsiZ7fF2o4zDC3sDj8RgsREU3sPdqtXIid9qqZmJ+mE3cRa50lxZyfV9dM+oMXR3DFVRG+0xHNnf/DNMx4+bLEuOGlrmX53VqTBc29lWZ1Rci5RO8U3Ko3n5KumqJ92X0Wlz+Cs8pju945viekNH8XJHii07+098SjgBoMQTtyZ71yrIM2sTv3OjFU10+/VRtP7MIJWV4F5HdybQtq7iKJpv4+5OKmJjpppmIiiPmjf/Ez+krRGDafm2ugaWtq4tHKIndnivPKMxdN/XNjDUzE+psFRTV7lU1VVfVNKwlyui3bquXKopopiaqqpnaIiO1VTPsRiNacQ79zCRNVeY4yLdjeOqjeKaJn3qYjf3pZ/RlP9SbzyiG1/UGTbBXFHO0/z/CfODGEqwfDXKaK4mKrlFd2feqrqmPomGYuvluEtYDLsNgbEbWcNZos24/s0xER9EOwoZb9e8285bOnx9lirTyiIAHCUB18yxuGy7LsTmGNvU2cLhrVV69cq6qKKYmapn3oiQYRxH4QaJ13dqxeaZfXhcxqjacdg6ot3Z/vdE01+/VEz7qGdQclXH0TVXkGrMNeifwbeNw1Vvb366Jq3/wAsLE6R1dprVuCjF6dznCZhb23qpt1+zo/vUT7Kn5Yh7ixXPlxd0SgtgxZO/ZR7OuT1xQy7nTayfDZjRT11YTGUT80VzTVPzMPxOA15oLFxeu4bP9O3Zq6LsRdw8VT7lUbRV88tiL5YzDYbGYW5hcXh7WIw92nm3LV2iKqK48UxPRMJ66+3K0boLaGv4Z2VD4Z8pDU+T4qzg9XxGd5bMxTXfiiKMTajxxMbRXt4pjefyltsmzLA5xlWFzTLcRRicHirVN2zdo6qqZjeJ/8AhQzj1lWQZJxXzvLNNRRTl9m5Ttbt1b02rk0UzXRE+KKpmNuzq7Fp+SbGLjgllXqnncyb+I7hzv8Ah91q6vc53Oe6vFTqRkrG27zS5b9ecdp32ejylrFzEcDtS27UTNUWbVc7eKm9bqn6IlUrk84m1heNOl7t6YimrGdzjf8AKroqop+mqF7s/wAswudZHjsnxtM1YbHYe5h7sR182umaZ293pa8tTZPnGhta4jK8VNeHzHK8VE27tMbbzTMVUXKfcmNqo991opi2O2NzrImt63bGhgvBriRlHEPTVrFYe9atZrZtxGPwW/srVfVNUR20TPTE/JPTEs6Z9qzWdpX62i0bwOKqqaKZqqmKaYjeZmeiIcoX5TvFHA6W0vi9MZZiqLuf5jZmzVTbq3nC2qo2qrq8VUxMxTHX079nT7jxzktFYeZLxSs2lTvO79vFZ1jsVa/k72IuXKPemqZhsZ0lYuYbSmUYa9ExctYGzRXE9cTFumJUX4D6Kv644jZfl82Zqy/DVxisfXt7GLVExPNn3ap2pj39+yV+17X2jetYU9DWdpsxXjB4J9W/EuL+xqUX4UeFLSfx3g/t6F6OMHgn1b8S4v7GpRfhR4UtJ/HeD+3odaL4dnOs+JVsSAZjRAAEK8syJnhDb9zNLH7NxNSOeUnkF7UPB3OsPhbc3MThaKcZbpiN5nudUVVbe7zOelwTEZKzPmizRvjtEK68jaYjjDMTPXll+I+ehdBr54Latt6J4k5Vn+J504O3XNrFRTG89yriaap27dt+dt281f8Ay/GYXMMDYx2BxFrE4W/RFy1dt1
764RVTXTMbxMTHXCzr6zGSJV9DaJpMPuD83a6LVuq5crpoooiaqqqp2imI65mVFdU/wCW1MTxSyuInpjJLW//AD76R+RFE+txnE9n8L1fY2kCcoXV+G1pxQzDM8vud1y+xTThMJc7K6KN96o9yapqmPcmFoOSpp+9kPB7AV4m3Nu9md6vH1UzHTFNe1NE/LRRTPytPP8Ac00VnmzsM9bUTaErAMxoirHLn/pjS3wfEftW1p1WOXP/AExpb4PiP2ra1o/jQrav4UvS5C38x1b+lwn1XVlVauQt/MdW/pcJ9V1ZV5q/jW/nye6X4UACssIH5bfgxyn46t/Y3kZ8ifwrZj8SXft7CTOW34Mcp+Orf2N5GfIn8K2Y/El37ew08X+1lnZP91C4ip3LisXKdXaexMxPc68Bcopn3abm8/tQtih7lYaKv6q4dRmOX2Zu5hkldWJoopjequzMbXaY93aKav8ABt2qmlvFMsTK1qazbFMQxHkNYm1Vkmp8JEx3ajE2Lkx282qmuI+mmVj1CeAfED1vdd2sxxMV15Xi6PU2PopjeYomYmK4jtmmYifdjeO1evJ8ywGcZZYzPK8XZxmDxFEV2r1qrnU1x7k//wBsk1uOa5Ot8pR6PJFsfV+cO2D83rluzarvXrlNu3RTNVddU7RTEdczPZCmtoh5X+Js2ODGKtXJiK8RjcPbtRPbVFXP+qmpX/kmWLl3jhlNyiJmmzYxNdfuR3Gqn66od/lScTcLrbUOHybI73dclyuqra9T+Dib09E1x46Yjoie3eqeqYSDyLdFX8Hgcw1vjrM0erKPUmA50dNVuKom5X701U0xH92pqVjsdNPW+f8Alm2ntdRHV+SyCtXLp/mOkv0uL+q0sqrVy6f5jpL9Li/qtKmk+NX+fJa1fwpebyGP6Y1T8Hw/7VxPfFLQeS8QdNXMoza3zLtO9eExVNO9zD3Nvwo8cT209Ux7u0xAnIY/pjVPwfD/ALVxad1q7TXPMw50tYthiJa8dV6f1Pwz1tGExVV3A5lgrkXsLirMzFNyIn2Ny3V2xO31xPbC3nAHizguIeT+o8dVaw2osJRHqmxHRF6nq7rbjxeOPxZnxTDIeLPD7JuIem68rzKmLOKt71YPGU0714evx+7TPRvT2+5MRMUjzrLNV8LteU2b1V3Ls3y+5Fyxftz7G5T2V0z+NRVG8bT7sTHXCzE11dNp7rQrzFtLfeO+ssk5U/h41H/+L/2tpZbkpeAvI/0mJ/7i4p9xL1Vd1trPGamxGGow1/GW7EXbdE70xXRZot1THuTNEzEdm+3SuDyUvAXkf6TE/wDcXDVVmunrE/T+xpZi2e0x9f7pTeXqfT2Samym5lWfZbh8wwdzpm3dp6p8dMx00z7sTEvUY5jNdaRwWq6tLY3P8Fhc3i3Rc7her5m8VfgxFU+xmrt5u++0x0dLNrE7/daNpjbvQ5qnktafxd2u9pzUONyzeZmLOJtRiKI9yJiaaoj3+dKO875MvEDBTVVl+IyfNKPxYt4ibdc+/FdMRHzrlCxXWZa/PdXtpMVvls1+53ws4kaemb+N0nmtuLc7zdw1Hdqafd51qaoj33b0dxi4iaUxFNOGz/E4zD252qwmYTN+3MR+L7KedT/hmF91euWdkGmLej8Ln9eHw2Hz6rGUWrV23EU3MRRtPPirb8KIjad56uiN+nps49VGW0UvXmr5NNOKJvS3JIHBHitlXErKrvMs+oc3wlMTisHNXOjaeiK6J7aZn5YnonsmZFUp5H8YueM2H9T87uUYHEeqNurue0bb+5z+Z9C6ypqsUY8m1VnTZJyU3kAV1gAAAAAAAAAAAAAAAAAAAAAAABVnlyf0zpf4Nif2rSt653KP4V6i4i5hk1/I8RltmjA2b1F31XdromZrqomNubRV+TPiRL3sWv8A2w0751d+6a+mz464oiZ72XqMGS+SZiEFzBsnPvYdf+2OnfOrv3R3sOv/AGx0751d+6T8Ti9SHhcvpQZs4Tp3sOv/AGw0751d+6O9h1/7Y6d86u/dHE4vUcNl9KCxOnew6/8AbHTvnV37o72HX/thp3zq790cTi9RwuX0oLmHGyde9h1/7Yad86u/dOO9g1/7Yad86u/dHE4vUcNl9KC9jZOvew6/9sNO+dXfunHewa/9sdO+dXfujicXqOFy+lBe0GydO9g1/wC2GnfOrv3R3sGv/bHTvnV37o4nF6jhsvpQXsbdKdO9g1/7Y6d86u/dHewa/wDbDT3nV37o4nF6jhcvpQXsbJ072HX/AG5hp3zq790d7Dr/ANsNO+dXfujicXqOGy+lBexsnXvYdf8Athp3zq790d7Br/2x0751d+6OKxeo4XL6UFCde9h1/wC2GnfOrv3R3sOv/bDTvnV37o4nF6jhcvpQVsbJ172HX/tjp3zq790472HX/thp3zq790cTi9RwuX0oLE6d7Br/ANsNO+dXfujvYdf+2GnfOrv3RxOL1HC5fSgsTr3sOv8A2w0751d+6O9h1/7Yad86u/dHE4vUcLl9KCtnOydO9h1/7Y6d86u/dHew6/8AbDTvnV37o4nF6jhcvpQXsbJ072HX/thp3zq790d7Dr/2w0751d+6OJxeo4XL6UGQTCc+9h1/7Yae86u/dHexa/8AbDT3nV37o4rF6jhcvpQYJz72LX/thp7zq790572LX3thp7zq790cTi9RwuX0oLE6d7Fr72w0951d+6J5MWvvbDT3nV37o4rF6nnC5fSgwlOfexa+9sNPedXfujvYtfe2GnvOrv3RxWL1PeFy+lBewnTvYtfe2GnvOrv3R3sWvvbDT3nV37o4nF6nnDZfSguIcpz72LX3thp7zq790d7Fr/2w0751d+6OJxep7wuX0oM26TZOfexa/wDbHT3nV37o72LX/thp3zq790cTi9RwuX0oNmNzZOXexa/9sdO+dXfujvYtf+2GnfOrv3RxOL1HC5fSg6mOmF+OT74F9K/F9H1yrzHJj1/E/wBIad86u/dLOcLchxml+HuSafzCuzXisDhabN2qzVNVE1Rv1TMRMx8kKetzUvSIrO63pMN6WmbQyUBmr4AAAAAAhrlieBu58YWP/JMo7x36lot5OMlevWa+alXI98M1j4Bf+qF1Qd583a2622zjBi7KvV33AEKYABxXRTcoqorppqoqjaqmY3iY8Uqf8dOAub5DmOJzzR2Cu5jkt2qblWFs0zVewm/TMRT110eKY3mI6+rebgibDmtineEWXDXLG0tfOieJeudEUzhcjzvEYfDU1TzsJepi5aid+naiuJ5s79e20s6p5TXEaLXMnD5DVV+XOEr3+ivb6FrtQ6L0jqG5N3O9NZVj7s/729haJuf59ud9LHo4McL4r5//AKOwG/8Aer2+bnbLc6rDbvtTvVY02avdW3cqBrXipr/XFr+D81zm9XhbtUR6iwtuLVuud+iJimN6+nsqmUicCOAea5vmWGz7W2CuYDKbVUXLeBvU829ipjpiKqeuijx79M9W3Tus9p7R+ldPVc/I9O5Vl9zbbuljC0U1z79URvPzvccX1n3erjjZ1TSfe62Sd3FMRTTFNMRERG0RHY5BRXVQ+W74R8n+KKftrrPORB/ULPPjT/8AVQsALNtTvi7PZWrp9svabgCssoj5WmQ4vPOEN+vBWK793LcXaxs0UU71TREVUVTER4ouTM+5Eq7clvUeC03xdwVzML1NjD4+xcwNV2udqaKq9po3nsiaqaY+VeUWcep6mOccxvurZNP1skXidthDXLE8Ddz4wsf+SZRDjv1LRbyTZK9es182tbIs5zbIcwpzDJcxxOX4ummaYvYe5NFcRPXG8Mi9dHiN5bZ957X6WwcXp11Z50/n6KcaK0cr/wA/Vr49dHiN5bZ957X6T10eI3ltn3ntfpbBx5xtPR/P0e8Hb1/z9VZeSFrDVOo9ZZxhs+1BmOZ2bWXxct28Tfqrppq7pTG8RPbtMrNAqZskZLdaI2WsVJpXqzO4AiSAAAAPK1ZkOA1Lkd/KcwombVyN6a4/Ct1x1VU+7HpjtV91xlGr9OYTD5FnV7FYrT1i/wA+xXaiJtzG/j66Z2mdqap6OnbxrLuK6aa6JorpiqmY2mJjeJha02qth7tt4/nJna7o6mqjffq25b/TynzhU/Xd7S17NrVeksLicNgu4U90ovTMz3Ted9t5merbt63gU01V1RTTTNVUztERG8zK12P0NpDG1zXiNO5fzp65t2otzP8Al2drJdLadya53XLMmweGu/8AEptxNcf4p6WhXpSla7REzP1Yt/6fy5Mk2m0RE+Uf4/8AUN8L+FeOx+Ls5rqXDVYXAW5iujC3I2uX5jq50fi0+Pfpn6U+RERERERER1RAwHiVxJy3TFq7gcBVbxub7bRaid6LM+OuY7f7PX7yhfJl1mTk2cOHTdGYZmZ2j5z85/nk8zjzrGjK8oq05gbu+OxtG1+aZ/krM9cT7tXVt4t/HDyeT3pCu3NWrMfamnembeBpqjsnoquf+MfL7jzeHvDzM9VZnVqTVs36cLdr7rzLu8XMVP8A40f6dEdHSnazat2LNFmzbpt2rdMU0UUxtFMRG
7640REdkJ82WuDF2GOd5+cqekwZNZqOLzRtEeGP8v2AzW8AAMK426Zz/V/D3G6f09jsLg8TiqqYu1YjnRTctxO80b0xM07zEdO09G8drNR1W01mJh5asWjaWvrUeguIWhMZ6rx2TZpl82J3px2FmardPuxdtztHyzEvb09x44nZNbptRqCcwtU9VGOs03p+WuY58/5l6mN5zoLROc11XMz0nkuJu1dd2vB0c+f8URv9K9xtbRtkrupcHas/wCnbZV+jlRcQKbfNnKtNVVflThr2/0XWO6p4+cSs+w1eF/he1lli5G1dOX2YtVTH9+ZmuPkqhaf1mOF/P5//o7Ab/3q9vm52z3ci0JozI7lN3KdLZPhLtE703aMJR3SP8cxzvpecRgjvih2Gee6bqe8JuCmq9c5hZxePw2IynJJqiu9jcRRNNd2nti1TPTVM/lfgx456puxkeV4HJMnwmUZbYpsYPB2abNm3H4tNMbR78+72u4K+fUWzT38ljDgriju5iM+OfCTLOJGXUYi3cowOe4ajm4bFzTvTXT19zubdM079U9dMzvG/TEyYIqXtSetVJekXjaWvXUOm9c8M9QW7uNw2YZPi7Vf8RjbFcxRX/cuU9E9HZvv44Znk/KP4l4DD02r+JyzMZpjaK8VhI53y9zmnddLF4bD4vD14bF4e1iLFyNq7d2iKqao8UxPRLDcw4ScNcddm7f0ZlNNU9M9xtdyj5qJiF7jKXj/AFK7qXCXpP8Ap2VU1HyguJmc4avD0Zrh8rt1xtV6gw8W6pj3K6pqqj34mJeJw94Z614i5j3fA4O/GFu3Jqv5njOdFrpnpnnT011e5TvPj261zco4X8PMqu03sFo7J6blM7013MPF2aZ8cTXvsy+immimKKKYpppjaIiNoiCdZWkbY67PY0lrTvktuxHhTw/yXh5puMqyqmbt65MV4vF10xFzEV+OfFTHTtT2e7MzM5eCha02neV2tYrG0MV4weCfVvxLi/samvfA4rE4HG2Mbg79yxicPcpu2bturaqiumd6aonsmJiJbMhZ0+p7GJjbfdXz6ftZid9mvj10eI3ltn3ntfpPXR4jeW2fee1+lsHE3G09H8/RFwdvX/P1a+PXR4jeW2fee1+k9dHiN5bZ957X6WwcONp6P5+hwdvX/P1eHw9xOIxmgdO4zF3q7+Iv5Xhrl25XO9VddVqmZqme2Zmd3uTETExMRMT1xIKEzvO67EbRsqPx54CZrlOZYnUGisDXjspvVTcuYGzTvdwsz0zFNPXXR4tumOrbaN0XaK4i630NVXhsizrE4SzFc8/CXaYuWoq7fYVxMUz45jaWwl4WodHaU1DXNzO9OZVmFzbbut/C0VXI96rbePnXces+71ckbqd9J97rY52VQt8priNTa5lVjIa6tvw6sJXv9Fe30MQ1txa4ga0w85dmmdXIwd2ebODwluLVFe/ZMU9Nce5Myt56zHC/n8//ANHYDf8AvV7fNztmQ6e0ZpLT9cXMk03lWAux/vbOFopuf5tud9LqNTgr31p3ueGzW7rX7lXOBvATOM+zHD51rHBXstyW3VFynC3omi9i+2Keb10UeOZ2mY6uveLf2qKLVum1aopoooiKaaaY2imI6oiH6FXNmtlneVrDhrijaABClFWOXP8A0xpb4PiP2ra04lw5OyvFtkWbH2lJrurVyFv5jq39LhPqurKg8zZO0vNtnuLH2dIqAI0iB+W34Mcp+Orf2N5GfIn8K2Y/El37ewuILNdR1cU49la2n62WMm4ArLKsfHbk94i9jcRqPQNiiuLszcxGVRMUzTV1zVZ36Np6+Z2dnZEQjpjWGuuHWZXsNleYY/J71NX8fg79v2O/9q1XG2/u7bthTy8/07kGf2otZ5kuX5lRTG1MYrD0XOb73Ojo+Rdx6yYr1bxvCnk0kTPWpO0qjW+UzxHps9zqs5FXVt/KVYSvnfRXt9DC9acT9e65iMDm2c4i9hrlURTgsLRFu3VO/RE00R7Pp6uduuHXwa4YVXO6To7L9/FE1xHzRVsyLTukNK6dq52R6dyvLrm203LGGoprmPdq23n53carDXvrTvcTps1u61+5Vvgxye86z7F2M21ph72VZRTMVxhK/Y4nE+5MddunxzO1XiiN94t1gcLhsDgrOCwdi3h8NYt027Vq3TzaaKYjaIiOyIh9hVzZ7ZZ3stYsNcUbQK1cun+Y6S/S4v6rSyo5w5OzvFtnuXH2lJqqxyGP6Y1T8Hw/7VxacHubJ2t5ts8w4+zpFdxhPF/hzk/EXTk4DHRFjH2YmrBY2mneqxX4p8dE9G9P+sRLNhxW01neElqxaNpa4NZaazjSOocTkWeYWcPi7E+/Tcp7K6Z7aZ7J/wBd4XM5KXgLyP8ASYn/ALi4lMWc+qnLSKzCth00YrzaJFN+NXBviZc1VmmpasJTqC3jcRVem5gJmquimfwae5T7LoiIiObzuiI6VyBFhzWwzvCXNhrljaWvnINfcRNEXvUOAz3Ncu7j0Tg8RvVRR7ncrkTEfMzrAcpriNhrcU38PkWNmPxr2EriZ/yV0x9C3ucZLk2c2os5xlOAzG3HVRisPRdiPkqiWKYvg/wyxNc13NGZXTM/8KibcfNTMLU6rDfx0VeGy18N1bMx5TPEbFWZosWciwNUx0V2MJXNUf566o+hgsUcQeKuo4r5uZ6hx8+x58x/F2Yn3eii3T80LpZfwn4bYG5FyxovJ6qo6u7WIux81e7L8DhMJgcNThsFhbGFsUfg27NuKKafeiOg4vHT4dO97wuS/jsjTk/cKLPDjJr2Ix123is9x1MRirtH4FqiOmLVEz1xv0zPbO3ihKIKN7ze3WsuUpFI6sADl0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAATvtO3TPY8jHZ3XgZn1TkuazTHRz8PZi/E+9FEzV89MPXHtZiOcObRMx3Tsx6vWGVUU7zhc7535H8EYmJ/YedjNd3f5PLNIalx12eqasDVZt/LVV1fMzISRbHH4f3Q2x5rfj29o/7mUYY/CcVNU72rleD0vgK+iaKLvPvTT/ep3nf5aXraO4Yac0/cpxV6irNMdTO/dsTETTTPjpo6o9+d591nI7tqbzXq17o+n83RU0GKL9e+9rec9/6Ryj9ABXXQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAH//Z";function Nj(e){return e?new Date(e).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):"â"}function Ro(e){return e?new Date(e).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit"}):"â"}
764function Zt(e){return`$${Number(e).toLocaleString("en-US",{minimumFractionDigits:2})}`}function ir(){return new Date().toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric"})}const Rj={pending:{color:"#fbbf24",label:"Pending Review"},accepted:{color:"#4ade80",label:"Accepted"},rejected:{color:"#f87171",label:"Rejected"}},KZ={rental:"Rental Agreement",purchase:"Purchase Agreement",financing:"Financing Agreement"};function wu(e){return`<div style="background:#0a2540;padding:24px 32px;text-align:center;border-radius:8px 8px 0 0;"> 765 <img src="${e}" style="height:64px;max-width:320px;object-fit:contain;" alt="Zenith Pure Solutions" /> 766 <p style="color:#93c5fd;font-size:12px;margin-top:10px;">6951 E 30th St, Suite B · Indianapolis, IN 46219</p> 767 <p style="color:#93c5fd;font-size:12px;">(317) 690-4172 · zenithpuresolutions.com</p> 768 </div>`}const h3=` 769 * { box-sizing: border-box; margin: 0; padding: 0; } 770 body { font-family: Georgia, serif; color: #1a1a2e; background: white; padding: 40px; max-width: 800px; margin: 0 auto; } 771 .subheader { background: #f8fafc; border: 1px solid #e2e8f0; border-top: none; padding: 20px; text-align: center; } 772 .subheader h2 { font-size: 20px; font-weight: bold; } 773 .subheader .sub { color: #64748b; font-size: 13px; margin-top: 4px; } 774 .body-section { border: 1px solid #e2e8f0; border-top: none; padding: 24px; } 775 .body-section p { font-size: 13px; line-height: 1.7; color: #374151; margin-bottom: 12px; } 776 .body-section ul { margin: 12px 0 12px 20px; } 777 .body-section li { font-size: 13px; line-height: 1.7; color: #374151; margin-bottom: 6px; } 778 .body-section strong { color: #1a1a2e; } 779 .confirm-box { background: #f0fdf4; border: 1px solid #86efac; border-radius: 6px; padding: 14px 18px; margin: 16px 0; font-size: 13px; font-weight: 600; color: #166534; } 780 .info-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin: 16px 0; } 781 .info-item { background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 6px; padding: 12px 16px; } 782 .info-label { font-size: 10px; font-weight: bold; color: #94a3b8; text-transform: uppercase; letter-spacing: 1px; margin-bottom: 4px; } 783 .info-value { font-size: 14px; font-weight: 600; color: #1e293b; } 784 .sig-section { border: 2px solid #e2e8f0; border-radius: 8px; padding: 24px; margin-top: 24px; } 785 .sig-label { font-size: 10px; color: #94a3b8; font-weight: 600; text-transform: uppercase; letter-spacing: 1px; margin-bottom: 8px; } 786 .sig-img { max-height: 80px; background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 4px; padding: 8px; } 787 .sig-meta { font-size: 11px; color: #64748b; margin-top: 8px; } 788 .footer { margin-top: 32px; text-align: center; font-size: 10px; color: #94a3b8; border-top: 1px solid #e2e8f0; padding-top: 16px; } 789 .no-print { margin-bottom: 20px; text-align: center; } 790 @media print { .no-print { display: none !important; } body { padding: 20px; } } 791`,Su=` 792 <div class="no-print"> 793 <button onclick="window.print()" style="background:#0a2540;color:white;border:none;padding:10px 28px;border-radius:6px;font-size:14px;font-weight:600;cursor:pointer;"> 794 Print / Save as PDF 795 </button> 796 <p style="margin-top:8px;font-size:11px;color:#64748b;">Use your browser's "Save as PDF" option when printing</p> 797 </div> 798`,f3=` 799 <div class="footer"> 800 <p>Zenith Pure Solutions LLC · 6951 E 30th St, Suite B, Indianapolis, IN 46219</p> 801 <p>(317) 690-4172 · [email protected] · zenithpuresolutions.com</p> 802 </div> 803`;function zl(e){return Math.round((e||[]).reduce((n,r)=>n+(parseFloat(r==null?void 0:r.discount_amount)||0),0)*100)/100}function g3(e){const n=parseFloat(e==null?void 0:e.discount_amount)||0;return n>0?`<div style="font-size:12px;color:#16a34a;margin-top:2px;">${parseFloat(e.discount_pct)||0}% off: â${Zt(n)}</div>`:""}function YZ(e,n,r){const s=e.commercial_type==="rental",i=r.filter(f=>f.item_type!=="service_plan"),o=r.filter(f=>f.item_type==="service_plan"),a=i.map(f=>` 804 <tr> 805 <td style="padding:10px 16px;border-bottom:1px solid #f1f5f9;font-size:13px;color:#334155;"><strong>${f.description}</strong>${g3(f)}</td> 806 <td style="padding:10px 16px;border-bottom:1px solid #f1f5f9;text-align:center;font-size:13px;color:#64748b;">${f.quantity}</td> 807 <td style="padding:10px 16px;border-bottom:1px solid #f1f5f9;text-align:right;font-size:13px;color:#64748b;">${Zt(parseFloat(f.unit_price)||0)}${s?"/mo":""}</td> 808 <td style="padding:10px 16px;border-bottom:1px solid #f1f5f9;text-align:right;font-size:13px;font-weight:600;color:#0f172a;">${Zt(parseFloat(f.total??f.total_price)||0)}${s?"/mo":""}</td> 809 </tr>`).join(""),l=o.length>0?` 810 <div style="background:#fffbeb;border:1px solid #fcd34d;border-radius:8px;padding:16px;margin-top:16px;"> 811 <div style="font-size:11px;font-weight:700;color:#92400e;text-transform:uppercase;letter-spacing:0.06em;margin-bottom:10px;">Included Service Plans</div> 812 <table width="100%" cellpadding="0" cellspacing="0"> 813 ${o.map(f=>`<tr><td style="font-size:13px;color:#78350f;padding:4px 0;">${f.description}</td><td style="font-size:13px;color:#92400e;font-weight:600;text-align:right;padding:4px 0;">${Zt(parseFloat(f.unit_price)||0)}</td></tr>`).join("")} 814 </table> 815 </div>`:"",d=s?` 816 <table width="240" cellpadding="0" cellspacing="0" style="margin-left:auto;"> 817 <tr><td style="font-size:13px;color:#64748b;padding:4px 0;">Installation Fee (one-time)</td><td style="text-align:right;font-size:13px;font-weight:600;color:#0f172a;padding:4px 0;">${Zt(parseFloat(e.install_fee)||0)}</td></tr> 818 <tr style="border-top:2px solid #e2e8f0;"><td style="font-size:15px;font-weight:700;color:#0f172a;padding-top:8px;">Monthly Total</td><td style="text-align:right;font-size:16px;font-weight:800;color:#1e3a8a;padding-top:8px;">${Zt(parseFloat(e.monthly_rental_price)||parseFloat(e.monthly_amount)||0)}/mo</td></tr> 819 </table>`:` 820 <table width="240" cellpadding="0" cellspacing="0" style="margin-left:auto;"> 821 <tr><td style="font-size:13px;color:#64748b;padding:4px 0;">Subtotal</td><td style="text-align:right;font-size:13px;font-weight:600;color:#0f172a;padding:4px 0;">${Zt((parseFloat(e.subtotal)||0)+zl(r))}</td></tr> 822 ${zl(r)>0?`<tr><td style="font-size:13px;color:#16a34a;padding:4px 0;">Discount</td><td style="text-align:right;font-size:13px;font-weight:600;color:#16a34a;padding:4px 0;">â${Zt(zl(r))}</td></tr>`:""} 823 <tr><td style="font-size:13px;color:#64748b;padding:4px 0 10px;">${(parseFloat(e.subtotal)||0)>0?`Sales Tax (${Math.round((parseFloat(e.tax_amount)||0)/(parseFloat(e.subtotal)||1)*100)}%)`:"Sales Tax"}</td><td style="text-align:right;font-size:13px;font-weight:600;color:#0f172a;padding:4px 0 10px;">${Zt(parseFloat(e.tax_amount)||0)}</td></tr> 824 <tr style="border-top:2px solid #e2e8f0;"><td style="font-size:15px;font-weight:700;color:#0f172a;padding-top:8px;">Total</td><td style="text-align:right;font-size:17px;font-weight:800;color:#0f172a;padding-top:8px;">${Zt(parseFloat(e.total)||0)}</td></tr> 825 </table>`,c=e.signature_data||e.customer_signature?`<img src="${e.signature_data||e.customer_signature}" style="height:48px;max-width:260px;object-fit:contain;display:block;border-bottom:1px solid #334155;padding-bottom:6px;margin-bottom:8px;" alt="Customer signature" />`:`<div style="font-size:20px;font-style:italic;font-family:Georgia,serif;color:#0a2540;border-bottom:1px solid #334155;padding-bottom:6px;margin-bottom:8px;">${e.signed_name||(n==null?void 0:n.full_name)||""}</div>`;return`<!DOCTYPE html><html><head><meta charset="UTF-8"/> 826<title>${e.quote_number} â Zenith Pure Solutions</title> 827<style>* { box-sizing: border-box; margin: 0; padding: 0; } body { font-family: Georgia, serif; color: #1a1a2e; background: white; padding: 40px; max-width: 800px; margin: 0 auto; } @media print { .no-print { display: none !important; } body { padding: 20px; } }</style> 828</head><body> 829${Su} 830${wu(ju)} 831<div style="background:#0a2540;color:white;padding:16px 32px;border-top:1px solid rgba(255,255,255,0.1);"> 832 <table width="100%" cellpadding="0" cellspacing="0"><tr> 833 <td><div style="font-size:20px;font-weight:900;letter-spacing:1px;">QUOTATION # ${e.quote_number}</div></td> 834 <td style="text-align:right;vertical-align:top;"><div style="font-size:11px;color:#93c5fd;">6951 E 30th, Suite B · Indianapolis IN 46219</div></td> 835 </tr></table> 836</div> 837<div style="border:1px solid #e2e8f0;border-top:none;padding:20px 28px;"> 838 <table width="100%" cellpadding="0" cellspacing="0"><tr> 839 <td width="50%" style="vertical-align:top;"> 840 <div style="font-size:10px;font-weight:700;color:#64748b;text-transform:uppercase;letter-spacing:1px;margin-bottom:6px;">Bill To:</div> 841 <div style="font-size:13px;font-weight:600;color:#1e293b;">${(n==null?void 0:n.full_name)||""}</div> 842 <div style="font-size:12px;color:#64748b;">${(n==null?void 0:n.address)||""}</div> 843 <div style="font-size:12px;color:#64748b;">${[n==null?void 0:n.city,n==null?void 0:n.state,n==null?void 0:n.zip].filter(
843Boolean).join(", ")}</div> 844 </td> 845 <td width="50%" style="vertical-align:top;"> 846 <div style="font-size:10px;font-weight:700;color:#64748b;text-transform:uppercase;letter-spacing:1px;margin-bottom:6px;">Installation Address</div> 847 <div style="font-size:13px;font-weight:600;color:#1e293b;">${(n==null?void 0:n.full_name)||""}</div> 848 <div style="font-size:12px;color:#64748b;">${(n==null?void 0:n.address)||""}</div> 849 <div style="font-size:12px;color:#64748b;">${(n==null?void 0:n.phone)||""}</div> 850 </td> 851 </tr></table> 852</div> 853<div style="border:1px solid #e2e8f0;border-top:none;padding:14px 28px;background:#f8fafc;"> 854 <table width="100%" cellpadding="0" cellspacing="0"><tr> 855 <td><div style="font-size:10px;font-weight:700;color:#64748b;text-transform:uppercase;">Quotation Date</div><div style="font-size:13px;color:#1e293b;margin-top:2px;">${e.created_at?new Date(e.created_at).toLocaleDateString():ir()}</div></td> 856 <td><div style="font-size:10px;font-weight:700;color:#64748b;text-transform:uppercase;">Expiration</div><div style="font-size:13px;color:#dc2626;font-weight:600;margin-top:2px;">${e.valid_until?new Date(e.valid_until).toLocaleDateString():e.expires_at?new Date(e.expires_at).toLocaleDateString():"â"}</div></td> 857 <td><div style="font-size:10px;font-weight:700;color:#64748b;text-transform:uppercase;">Sales Consultant</div><div style="font-size:13px;color:#1e293b;margin-top:2px;">Kuldeep</div></td> 858 <td><div style="font-size:10px;font-weight:700;color:#64748b;text-transform:uppercase;">Type</div><div style="font-size:13px;color:#1e293b;margin-top:2px;">${s?"Rental":"Purchase"}</div></td> 859 </tr></table> 860</div> 861<div style="border:1px solid #e2e8f0;border-top:none;padding:16px 28px;"> 862 <table width="100%" cellpadding="0" cellspacing="0" style="border-collapse:collapse;margin-bottom:16px;"> 863 <thead><tr style="background:#f8fafc;"> 864 <th style="padding:10px 16px;text-align:left;font-size:11px;color:#94a3b8;font-weight:700;border-bottom:2px solid #e2e8f0;text-transform:uppercase;">Name and Description</th> 865 <th style="padding:10px 16px;text-align:center;font-size:11px;color:#94a3b8;font-weight:700;border-bottom:2px solid #e2e8f0;text-transform:uppercase;">Qty</th> 866 <th style="padding:10px 16px;text-align:right;font-size:11px;color:#94a3b8;font-weight:700;border-bottom:2px solid #e2e8f0;text-transform:uppercase;">Unit Price</th> 867 <th style="padding:10px 16px;text-align:right;font-size:11px;color:#94a3b8;font-weight:700;border-bottom:2px solid #e2e8f0;text-transform:uppercase;">Total</th> 868 </tr></thead> 869 <tbody>${a}</tbody> 870 </table> 871 <div style="background:#f8fafc;border-radius:8px;padding:16px 20px;margin-top:8px;">${d}</div> 872 ${l} 873</div> 874<div style="border:1px solid #e2e8f0;border-top:none;padding:20px 28px;"> 875 <div style="font-size:12px;font-weight:700;color:#475569;margin-bottom:10px;">CUSTOMER AUTHORIZATION</div> 876 <p style="font-size:11px;color:#64748b;line-height:1.7;margin-bottom:8px;">This is an estimate, not a final invoice or contract for services.</p> 877 <p style="font-size:11px;color:#64748b;line-height:1.7;margin-bottom:8px;">By approving this estimate, I authorize Zenith Pure Solutions to proceed as outlined and agree to pay the full amount for all services rendered.</p> 878 ${e.commercial_type==="purchase"?` 879 <div style="margin-top:20px;border:1px solid #e2e8f0;border-radius:8px;overflow:hidden;"> 880 <div style="background:#f8fafc;padding:10px 16px;font-size:11px;font-weight:700;color:#475569;text-transform:uppercase;letter-spacing:0.05em;border-bottom:1px solid #e2e8f0;">Direct Transfer / ACH Details</div> 881 <table width="100%" cellpadding="0" cellspacing="0" style="font-size:12px;"> 882 <tr style="border-bottom:1px solid #f1f5f9;"><td style="padding:9px 16px;font-weight:600;color:#374151;width:180px;">Bank Name</td><td style="padding:9px 16px;color:#64748b;">Old National Bank</td></tr> 883 <tr style="border-bottom:1px solid #f1f5f9;"><td style="padding:9px 16px;font-weight:600;color:#374151;">ACH ABA Number</td><td style="padding:9px 16px;color:#64748b;">086300012</td></tr> 884 <tr style="border-bottom:1px solid #f1f5f9;"><td style="padding:9px 16px;font-weight:600;color:#374151;">Account Number</td><td style="padding:9px 16px;color:#64748b;">0127726846</td></tr> 885 <tr style="border-bottom:1px solid #f1f5f9;"><td style="padding:9px 16px;font-weight:600;color:#374151;">Account Name</td><td style="padding:9px 16px;color:#64748b;">ZENITH PURE SOLUTIONS LLC</td></tr> 886 <tr><td style="padding:9px 16px;font-weight:600;color:#374151;">Phone Number</td><td style="padding:9px 16px;color:#64748b;">+1 (317) 690-4172</td></tr> 887 </table> 888 </div>`:""} 889</div> 890<div style="border:2px solid #e2e8f0;border-radius:8px;padding:28px;margin-top:20px;"> 891 <table width="100%" cellpadding="0" cellspacing="0"><tr> 892 <td width="48%" style="background:#f8fafc;border:1px solid #e2e8f0;border-radius:8px;padding:16px;"> 893 <div style="font-size:10px;color:#94a3b8;font-weight:600;text-transform:uppercase;letter-spacing:1px;margin-bottom:8px;">Zenith Pure Solutions LLC</div> 894 <div style="font-size:20px;font-style:italic;font-family:Georgia,serif;color:#0a2540;border-bottom:1px solid #334155;padding-bottom:6px;margin-bottom:8px;">Kuldeep Singh</div> 895 <div style="font-size:11px;color:#64748b;">Authorized Representative · ${ir()}</div> 896 </td> 897 <td width="4%"></td> 898 <td width="48%" style="background:#f8fafc;border:1px solid #e2e8f0;border-radius:8px;padding:16px;"> 899 <div style="font-size:10px;color:#94a3b8;font-weight:600;text-transform:uppercase;letter-spacing:1px;margin-bottom:8px;">Customer</div> 900 ${c} 901 <div style="font-size:11px;color:#64748b;">${(n==null?void 0:n.full_name)||""} · Signed ${e.signed_at?new Date(e.signed_at).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric"}):ir()}</div> 902 </td> 903 </tr></table> 904</div> 905<div style="margin-top:24px;text-align:center;font-size:10px;color:#94a3b8;border-top:1px solid #e2e8f0;padding-top:16px;"> 906 <p>Zenith Pure Solutions LLC · 6951 E 30th St, Suite B, Indianapolis, IN 46219</p> 907 <p style="margin-top:3px;">
907(317) 690-4172 · [email protected] · zenithpuresolutions.com</p> 908 <p style="margin-top:3px;font-style:italic;">Engineered for purity. Installed with care. Backed by Zenith Pure Solutions.</p> 909</div> 910</body></html>`}function XZ(e,n,r){const s=r.map(o=>` 911 <div class="section"> 912 <h3>${o.display_title||o.title||""}</h3> 913 <p>${(o.content||"").replace(/\[INSTALL_FEE\]/g,Zt(e.install_fee||0)).replace(/\[MONTHLY_AMOUNT\]/g,Zt(e.monthly_amount||0)).replace(/\n/g,"<br/>")}</p> 914 </div> 915 `).join(""),i=e.signature_data||e.customer_signature?`<img src="${e.signature_data||e.customer_signature}" style="height:48px;max-width:260px;object-fit:contain;display:block;border-bottom:1px solid #334155;padding-bottom:6px;margin-bottom:8px;" alt="Customer signature" />`:`<div class="sig-name">${e.signed_name||(n==null?void 0:n.full_name)||""}</div>`;return`<!DOCTYPE html><html><head><meta charset="UTF-8"/> 916<title>${e.agreement_number} â Zenith Pure Solutions</title> 917<style> 918 * { box-sizing: border-box; margin: 0; padding: 0; } 919 body { font-family: Georgia, serif; color: #1a1a2e; background: white; padding: 40px; max-width: 800px; margin: 0 auto; } 920 .subheader { background: #f8fafc; border: 1px solid #e2e8f0; border-top: none; padding: 20px; text-align: center; } 921 .subheader h2 { font-size: 22px; font-weight: bold; } 922 .subheader .agnum { color: #0a2540; font-size: 14px; font-weight: 600; margin-top: 6px; } 923 .parties { display: grid; grid-template-columns: 1fr 1fr; gap: 32px; padding: 20px; border: 1px solid #e2e8f0; border-top: none; } 924 .party-label { font-size: 10px; font-weight: bold; color: #94a3b8; text-transform: uppercase; letter-spacing: 1px; margin-bottom: 4px; } 925 .party-name { font-weight: bold; font-size: 14px; } 926 .party-address { font-size: 12px; color: #64748b; margin-top: 2px; } 927 .financials { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 8px; background: #eff6ff; border: 1px solid #bfdbfe; border-top: none; padding: 20px; text-align: center; } 928 .fin-label { font-size: 10px; color: #3b82f6; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px; } 929 .fin-value { font-size: 18px; font-weight: bold; color: #1e3a8a; margin-top: 4px; } 930 .notice { background: #fffbeb; border: 1px solid #fcd34d; border-top: none; padding: 12px 20px; text-align: center; font-size: 11px; font-weight: bold; color: #92400e; text-transform: uppercase; } 931 .intro { padding: 20px; border: 1px solid #e2e8f0; border-top: none; font-size: 13px; line-height: 1.6; } 932 .section { border: 1px solid #e2e8f0; margin-top: 16px; border-radius: 8px; overflow: hidden; } 933 .section h3 { background: #f8fafc; padding: 10px 20px; font-size: 13px; font-weight: bold; border-bottom: 1px solid #e2e8f0; } 934 .section p { padding: 16px 20px; font-size: 12px; line-height: 1.8; color: #374151; } 935 .signatures { border: 2px solid #e2e8f0; border-radius: 8px; padding: 32px; margin-top: 24px; } 936 .sig-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 24px; } 937 .sig-box { background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 8px; padding: 16px; } 938 .sig-party-label { font-size: 10px; color: #94a3b8; font-weight: 600; text-transform: uppercase; letter-spacing: 1px; margin-bottom: 8px; } 939 .sig-name { font-size: 22px; font-style: italic; font-family: Georgia, serif; color: #0a2540; border-bottom: 1px solid #334155; padding-bottom: 6px; margin-bottom: 8px; min-height: 36px; } 940 .sig-meta { font-size: 11px; color: #64748b; } 941 .footer { margin-top: 32px; text-align: center; font-size: 10px; color: #94a3b8; } 942 .no-print { margin-bottom: 20px; text-align: center; } 943 @media print { body { padding: 20px; } .no-print { display: none !important; } } 944</style> 945</head><body> 946 ${Su} 947 ${wu(ju)} 948 <div class="subheader"> 949 <div style="font-size:10px;font-weight:bold;color:#94a3b8;text-transform:uppercase;letter-spacing:2px;margin-bottom:4px;">Legal Agreement</div> 950 <h2>Residential Equipment Rental Agreement</h2> 951 <div class="agnum">${e.agreement_number}</div> 952 </div> 953 <div class="parties"> 954 <div><div class="party-label">Company</div><div class="party-name">Zenith Pure Solutions LLC</div><div class="party-address">6951 E 30th St, Suite B<br/>Indianapolis, IN 46219</div></div> 955 <div><div class="party-label">Customer</div><div class="party-name">${(n==null?void 0:n.full_name)||""}</div><div class="party-address">${(n==null?void 0:n.address)||""}<br/>${(n==null?void 0:n.city)||""}, ${(n==null?void 0:n.state)||""} ${(n==null?void 0:n.zip)||""}</div></div> 956 </div> 957 <div class="financials"> 958 <div><div class="fin-label">Monthly Payment</div><div class="fin-value">${Zt(e.monthly_amount||0)}/mo</div></div> 959 <div><div class="fin-label">Setup Fee (one-time)</div><div class="fin-value">${Zt(e.install_fee||0)}</div></div> 960 <div><div class="fin-label">Initial Term</div><div class="fin-value">36 months</div></div> 961 </div> 962 <div class="notice">By signing, you agree to all terms including the binding arbitration clause in Article IX.</div> 963 <div class="intro">This Agreement is entered into as of <strong>${ir()}</strong> between <strong>Zenith Pure Solutions LLC</strong> ("Company") and <strong>${(n==null?void 0:n.full_name)||""}</strong> ("Customer").</div> 964 ${s} 965 <div class="signatures"> 966 <div style="font-weight:bold;font-size:13px;margin-bottom:4px;">IN WITNESS WHEREOF</div> 967 <p style="font-size:11px;color:#64748b;margin-bottom:24px;">Executed as of ${ir()}.</p> 968 <div class="sig-grid"> 969 <div class="sig-box"><div class="sig-party-label">ZENITH PURE SOLUTIONS LLC</div><div class="sig-name">Kuldeep Singh</div><div class="sig-meta">Authorized Representative · ${ir()}</div></div> 970 <div class="sig-box"><div class="sig-party-label">CUSTOMER</div>${i}<div class="sig-meta">${(n==null?void 0:n.full_name)||""} · Signed ${e.signed_at?new Date(e.signed_at).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric"}):ir()}</div></div> 971 </div> 972 </div> 973 <div class="footer"><p>Zenith Pure Solutions LLC · 6951 E 30th St, Suite B, Indianapolis, IN 46219</p><p>
973(317) 690-4172 · [email protected] · zenithpuresolutions.com</p><p style="margin-top:6px;">Agreement ${e.agreement_number} · Generated ${ir()}</p></div> 974</body></html>`}function GZ(e,n,r){const s=r.length>0?r:e.line_items_snapshot||[],i=s.map(f=>` 975 <tr style="border-bottom:1px solid #f1f5f9;"> 976 <td style="padding:12px 24px;font-size:13px;color:#1e293b;">${f.description}${g3(f)}</td> 977 <td style="padding:12px 16px;font-size:13px;color:#64748b;text-align:center;">${f.quantity||1}</td> 978 <td style="padding:12px 16px;font-size:13px;color:#64748b;text-align:right;">${Zt(parseFloat(f.unit_price)||0)}</td> 979 <td style="padding:12px 24px;font-size:13px;font-weight:600;color:#0f172a;text-align:right;">${Zt(parseFloat(f.total)||parseFloat(f.total_price)||0)}</td> 980 </tr>`).join(""),o=parseFloat(e.subtotal)||0,a=parseFloat(e.tax_amount)||0,l=o>0?Math.round(a/o*100):0,d=parseFloat(e.total_amount||e.total)||0,c=e.signature_data||e.customer_signature?`<img src="${e.signature_data||e.customer_signature}" style="height:48px;max-width:260px;object-fit:contain;display:block;border-bottom:1px solid #334155;padding-bottom:6px;margin-bottom:8px;" alt="Customer signature" />`:`<div style="font-size:20px;font-style:italic;font-family:Georgia,serif;color:#0a2540;border-bottom:1px solid #334155;padding-bottom:6px;margin-bottom:8px;">${e.signed_name||(n==null?void 0:n.full_name)||""}</div>`;return`<!DOCTYPE html><html><head><meta charset="UTF-8"/> 981<title>${e.invoice_number} â Zenith Pure Solutions</title> 982<style>* { box-sizing: border-box; margin: 0; padding: 0; } body { font-family: Georgia, serif; color: #1a1a2e; background: white; padding: 40px; max-width: 800px; margin: 0 auto; } @media print { body { padding: 20px; } .no-print { display: none !important; } }</style> 983</head><body> 984 ${Su} 985 ${wu(ju)} 986 <div style="background:#0a2540;color:white;padding:16px 32px;border-top:1px solid rgba(255,255,255,0.1);"> 987 <table width="100%" cellpadding="0" cellspacing="0"><tr> 988 <td><div style="font-size:24px;font-weight:900;letter-spacing:1px;">INVOICE</div><div style="color:#93c5fd;font-size:13px;margin-top:2px;">${e.invoice_number}</div></td> 989 <td style="text-align:right;"><div style="font-size:32px;font-weight:900;">${Zt(d)}</div><div style="color:#93c5fd;font-size:11px;margin-top:2px;">Total Amount Due</div></td> 990 </tr></table> 991 </div> 992 <div style="display:grid;grid-template-columns:1fr 1fr;gap:32px;padding:20px 24px;border:1px solid #e2e8f0;border-top:none;"> 993 <div> 994 <div style="font-size:10px;font-weight:bold;color:#94a3b8;text-transform:uppercase;letter-spacing:1px;margin-bottom:4px;">Bill To</div> 995 <div style="font-weight:bold;font-size:14px;">${(n==null?void 0:n.full_name)||""}</div> 996 <div style="font-size:12px;color:#64748b;margin-top:2px;">${(n==null?void 0:n.address)||""}</div> 997 <div style="font-size:12px;color:#64748b;">${(n==null?void 0:n.city)||""}, ${(n==null?void 0:n.state)||""} ${(n==null?void 0:n.zip)||""}</div> 998 <div style="font-size:12px;color:#64748b;">${(n==null?void 0:n.phone)||""}</div> 999 </div> 1000 <div style="text-align:right;"> 1001 <div style="font-size:10px;font-weight:bold;color:#94a3b8;text-transform:uppercase;letter-spacing:1px;margin-bottom:4px;">From</div> 1002 <div style="font-weight:bold;font-size:14px;">Zenith Pure Solutions LLC</div> 1003 <div style="font-size:12px;color:#64748b;">
10036951 E 30th St, Suite B · Indianapolis, IN 46219</div> 1004 <div style="font-size:12px;color:#64748b;margin-top:8px;">Invoice Date: ${ir()}</div> 1005 <div style="font-size:12px;color:${e.paid_at?"#16a34a":"#dc2626"};font-weight:600;margin-top:4px;">${e.paid_at?"â Paid "+new Date(e.paid_at).toLocaleDateString():"Unpaid"}</div> 1006 </div> 1007 </div> 1008 <table style="width:100%;border-collapse:collapse;border:1px solid #e2e8f0;border-top:none;"> 1009 <thead><tr style="background:#f8fafc;border-bottom:1px solid #e2e8f0;"> 1010 <th style="padding:10px 24px;text-align:left;font-size:11px;font-weight:700;color:#94a3b8;text-transform:uppercase;">Description</th> 1011 <th style="padding:10px 16px;text-align:center;font-size:11px;font-weight:700;color:#94a3b8;text-transform:uppercase;">Qty</th> 1012 <th style="padding:10px 16px;text-align:right;font-size:11px;font-weight:700;color:#94a3b8;text-transform:uppercase;">Unit Price</th> 1013 <th style="padding:10px 24px;text-align:right;font-size:11px;font-weight:700;color:#94a3b8;text-transform:uppercase;">Amount</th> 1014 </tr></thead> 1015 <tbody>${i}</tbody> 1016 </table> 1017 <div style="background:#f8fafc;border:1px solid #e2e8f0;border-top:none;padding:16px 24px;"> 1018 <table width="240" cellpadding="0" cellspacing="0" style="margin-left:auto;"> 1019 <tr><td style="font-size:13px;color:#64748b;padding:4px 0;">Subtotal</td><td style="text-align:right;font-weight:600;color:#0f172a;font-size:13px;padding:4px 0;">${Zt(o+zl(s))}</td></tr> 1020 ${zl(s)>0?`<tr><td style="font-size:13px;color:#16a34a;padding:4px 0;">Discount</td><td style="text-align:right;font-weight:600;color:#16a34a;font-size:13px;padding:4px 0;">â${Zt(zl(s))}</td></tr>`:""} 1021 <tr><td style="font-size:13px;color:#64748b;padding:4px 0 8px;">${l>0?`Sales Tax (${l}%)`:"Sales Tax"}</td><td style="text-align:right;font-weight:600;color:#0f172a;font-size:13px;padding:4px 0 8px;">${Zt(a)}</td></tr> 1022 <tr style="border-top:2px solid #cbd5e1;"><td style="font-size:16px;font-weight:bold;color:#0f172a;padding-top:8px;">Total</td><td style="text-align:right;font-size:17px;font-weight:bold;color:#0f172a;padding-top:8px;">${Zt(d)}</td></tr> 1023 ${e.amount_paid?`<tr><td style="font-size:13px;color:#16a34a;font-weight:600;padding-top:6px;">Amount Paid</td><td style="text-align:right;font-size:13px;font-weight:600;color:#16a34a;padding-top:6px;">${Zt(parseFloat(e.amount_paid))}</td></tr>`:""} 1024 </table> 1025 </div> 1026 <div style="border:2px solid #e2e8f0;border-radius:8px;padding:28px 24px;margin-top:20px;"> 1027 <div style="font-weight:bold;font-size:13px;margin-bottom:4px;">Customer Authorization</div> 1028 <p style="font-size:11px;color:#64748b;margin-bottom:20px;">By signing, I authorize Zenith Pure Solutions to proceed and agree to the payment terms above.</p> 1029 <table width="100%" cellpadding="0" cellspacing="0"><tr> 1030 <td width="48%" style="background:#f8fafc;border:1px solid #e2e8f0;border-radius:8px;padding:16px;"> 1031 <div style="font-size:10px;color:#94a3b8;font-weight:600;text-transform:uppercase;letter-spacing:1px;margin-bottom:8px;">ZENITH PURE SOLUTIONS LLC</div> 1032 <div style="font-size:20px;font-style:italic;font-family:Georgia,serif;color:#0a2540;border-bottom:1px solid #334155;padding-bottom:6px;margin-bottom:8px;">Kuldeep Singh</div> 1033 <div style="font-size:11px;color:#64748b;">Authorized Representative · ${ir()}</div> 1034 </td> 1035 <td width="4%"></td> 1036 <td width="48%" style="background:#f8fafc;border:1px solid #e2e8f0;border-radius:8px;padding:16px;"> 1037 <div style="font-size:10px;color:#94a3b8;font-weight:600;text-transform:uppercase;letter-spacing:1px;margin-bottom:8px;">CUSTOMER</div> 1038 ${c} 1039 <div style="font-size:11px;color:#64748b;">${(n==null?void 0:n.full_name)||""} · Signed ${e.signed_at?new Date(e.signed_at).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric"}):ir()}</div> 1040 </td> 1041 </tr></table> 1042 </div> 1043 <div style="margin-top:28px;text-align:center;font-size:10px;color:#94a3b8;"> 1044 <p>Zenith Pure Solutions LLC · 6951 E 30th St, Suite B, Indianapolis, IN 46219</p> 1045 <p>
1045(317) 690-4172 · [email protected] · zenithpuresolutions.com</p> 1046 <p style="margin-top:4px;">Invoice ${e.invoice_number} · Generated ${ir()}</p> 1047 </div> 1048</body></html>`}function JZ(e,n){const r=e.response_data||{},s=r.customer_name||r.signed_name||"â",i=r.consent_date?new Date(r.consent_date).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric"}):ir(),o=r.job_reference||r.job_id||"â";return`<!DOCTYPE html><html><head><meta charset="UTF-8"/><title>RO Drilling Consent â ${s}</title><style>${h3}</style></head><body> 1049 ${Su}${wu(ju)} 1050 <div class="subheader"><div style="font-size:10px;font-weight:bold;color:#94a3b8;text-transform:uppercase;letter-spacing:2px;margin-bottom:4px;">Customer Acknowledgement</div><h2>Reverse Osmosis Drilling Consent Form</h2><div class="sub">Completed ${i}</div></div> 1051 <div class="body-section"> 1052 <div class="info-grid"> 1053 <div class="info-item"><div class="info-label">Customer Name</div><div class="info-value">${s}</div></div> 1054 <div class="info-item"><div class="info-label">Date Signed</div><div class="info-value">${i}</div></div> 1055 ${o!=="â"?`<div class="info-item"><div class="info-label">Job Reference</div><div class="info-value">${o}</div></div>`:""} 1056 </div> 1057 <p>I authorize <strong>Zenith Pure Solutions</strong> to drill a hole for installation of the RO faucet when an existing opening is not available.</p> 1058 <p>I understand and acknowledge that:</p> 1059 <ul> 1060 <li>Final pricing may vary if unforeseen material conditions or installation complexities are identified on site.</li> 1061 <li>Natural and manufactured sink or countertop materials may contain hidden variations or stress points.</li> 1062 <li>Minor cosmetic variations may occur despite proper installation methods.</li> 1063 <li>Zenith Pure Solutions is not responsible for pre-existing conditions and does not include repair or replacement of sinks, countertops, or cabinetry.</li> 1064 </ul> 1065 <div class="confirm-box">â I confirm that I am the property owner or have authorization to approve this work.</div> 1066 <div class="confirm-box">â I have read and understand the above terms and agree to the conditions stated in this Reverse Osmosis Drilling Consent Form.</div> 1067 </div> 1068 <div class="sig-section"> 1069 <div class="sig-label">Customer Signature</div> 1070 ${n?`<img src="${n}" class="sig-img" alt="Customer signature" />`:'<div style="height:60px;border-bottom:1px solid #334155;"></div>'} 1071 <div class="sig-meta">${s}
1071 · Signed ${i}</div> 1072 </div> 1073 ${f3} 1074</body></html>`}function QZ(e,n,r){const s=e.response_data||{},i=s.tds_reading||"â",o=s.submitted_at?new Date(s.submitted_at).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric",hour:"2-digit",minute:"2-digit"}):ir(),a=s.customer_name||s.signed_name||(r==null?void 0:r.full_name)||"â",l=s.job_reference||s.job_id||"â",d=Number(i)<50?"#166534":Number(i)<150?"#1e3a8a":"#7c2d12",c=Number(i)<50?"Excellent â pure water output":Number(i)<150?"Good â within healthy range":"Elevated â system may need service";return`<!DOCTYPE html><html><head><meta charset="UTF-8"/><title>RO Handover â ${a}</title> 1075 <style>${h3}.tds-box{background:#eff6ff;border:1px solid #bfdbfe;border-radius:8px;padding:20px;text-align:center;margin:16px 0;}.tds-label{font-size:11px;font-weight:bold;color:#3b82f6;text-transform:uppercase;letter-spacing:1px;}.tds-value{font-size:36px;font-weight:bold;margin-top:4px;}.tds-unit{font-size:14px;color:#64748b;margin-top:2px;}</style> 1076 </head><body> 1077 ${Su}${wu(ju)} 1078 <div class="subheader"><div style="font-size:10px;font-weight:bold;color:#94a3b8;text-transform:uppercase;letter-spacing:2px;margin-bottom:4px;">Installation Record</div><h2>Reverse Osmosis System Handover</h2><div class="sub">Completed ${o}</div></div> 1079 <div class="body-section"> 1080 <div class="info-grid"> 1081 <div class="info-item"><div class="info-label">Customer</div><div class="info-value">${a}</div></div> 1082 <div class="info-item"><div class="info-label">Handover Date</div><div class="info-value">${o}</div></div> 1083 ${r!=null&&r.address?`<div class="info-item"><div class="info-label">Service Address</div><div class="info-value">${r.address}${r.city?", "+r.city:""}</div></div>`:""} 1084 ${l!=="â"?`<div class="info-item"><div class="info-label">Job Reference</div><div class="info-value">${l}</div></div>`:""} 1085 </div> 1086 <div class="tds-box"><div class="tds-label">Post-Install TDS Reading</div><div class="tds-value" style="color:${d};">${i}</div><div class="tds-unit">ppm (parts per million)</div><div style="font-size:12px;color:#64748b;margin-top:6px;">${c}</div></div> 1087 <p style="margin-top:16px;"><strong>System Handover Checklist â Completed at Installation:</strong></p> 1088 <ul> 1089 <li>RO system installed and tested â all connections checked for leaks</li> 1090 <li>TDS meter reading taken and recorded (${i} ppm post-filter)</li> 1091 <li>Customer shown faucet operation, tank fill time, and daily output expectations</li> 1092 <li>Filter replacement schedule explained (annual â Zenith will contact you)</li> 1093 <li>Emergency shutoff valve location demonstrated</li> 1094 <li>Customer questions answered before technician departure</li> 1095 </ul> 1096 <div class="confirm-box" style="margin-top:20px;">â Customer confirms the system was demonstrated and is operating correctly at time of handover.</div> 1097 </div> 1098 <div class="sig-section"> 1099 <div class="sig-label">Customer Signature</div> 1100 ${n?`<img src="${n}" class="sig-img" alt="Customer signature" />`:'<div style="height:60px;border-bottom:1px solid #334155;"></div>'} 1101 <div class="sig-meta">${a} · Signed ${o}</div> 1102 </div> 1103 ${f3} 1104</body></html>`}function Yd(e,n){if(/iPhone|iPad|iPod|Android/i.test(navigator.userAgent)){const i=new Blob([e],{type:"text/html"}),o=URL.createObjectURL(i);window.open(o,"_blank")||(window.location.href=o),setTimeout(()=>URL.revokeObjectURL(o),6e4);return}const s=window.open("","_blank");if(s)s.document.write(e),s.document.close(),setTimeout(()=>s.print(),600);else{const i=new Blob([e],{type:"text/html"}),o=URL.createObjectURL(i),a=document.createElement("a");a.href=o,a.download=n,a.click(),URL.revokeObjectURL(o)}}function eK(e){return Ae({queryKey:["customer_refs",e],queryFn:async()=>{var d;const[n,r,s]=await Promise.all([w.from("customers").select("lead_id, full_name, phone, email").eq("id",e).single(),w.from("addresses").select("address_line1, address_line2, city, state, zip").eq("entity_type","customer").eq("entity_id",e).eq("is_primary",!0).maybeSingle(),w.from("jobs").select("id").eq("customer_id",e).order("created_at",{ascending:!1}).limit(1).maybeSingle()]),i=n.data,o=r.data,a=((d=s.data)==null?void 0:d.id)||null,l=o!=null&&o.address_line1?o.address_line2?`${o.address_line1}, ${o.address_line2}`:o.address_line1:null;return{lead_id:(i==null?void 0:i.lead_id)||null,full_name:(i==null?void 0:i.full_name)||null,phone:(i==null?void 0:i.phone)||null,email:(i==null?void 0:i.email)||null,address:l,city:(o==null?void 0:o.city)||null,state:(o==null?void 0:o.state)||null,zip:(o==null?void 0:o.zip)||null,job_id:a}},enabled:!!e})}async function Z0(e){const n=new Set,r=[],s=await Promise.all(e);for(const i of s)for(const o of i.data||[])n.has(o.id)||(n.add(o.id),r.push(o));return r.sort((i,o)=>new Date(o.created_at).getTime()-new Date(i.created_at).getTime()),r}function tK(e,n){return Ae({queryKey:["customer_agreements",e,n],queryFn:()=>Z0([w.from("agreements").select("*").eq("customer_id",e).order("created_at",{ascending:!1}),...n?[w.from("agreements").select("*").eq("lead_id",n).order("created_at",{ascending:!1})]:[]]),enabled:!!e})}function nK(e,n){return Ae({queryKey:["customer_accepted_quotes",e,n],queryFn:()=>Z0([w.from("quotes").select("id, quote_number, lead_id, created_at, status, commercial_type, monthly_rental_price, total, install_fee, subtotal, tax_amount, signed_at, signed_name, signature_data, expires_at").eq("customer_id",e).in("status",["accepted","signed"]).order("created_at",{ascending:!1}),...n?[w.from("quotes").select("id, quote_number, lead_id, created_at, status, commercial_type, monthly_rental_price, total, install_fee, subtotal, tax_amount, signed_at, signed_name, signature_data, expires_at").eq("lead_id",n).in("status",["accepted","signed"]).order("created_at",{ascending:!1})]:[]]),enabled:!!e})}function rK(e,n){return Ae({queryKey:["customer_paid_invoices",e],queryFn:()=>
1104Z0([w.from("invoices").select("id, invoice_number, created_at, paid_at, status, total_amount, amount_paid, subtotal, tax_amount, signed_at, signed_name, signature_data, line_items_snapshot").eq("customer_id",e).eq("status","paid").order("paid_at",{ascending:!1})]),enabled:!!e})}function sK(e){return Ae({queryKey:["customer_job_forms",e],queryFn:async()=>{if(!e)return[];const{data:n}=await w.from("job_form_responses").select("*").eq("job_id",e).order("submitted_at",{ascending:!1});return n||[]},enabled:!!e})}function iK(e){return Ae({queryKey:["customer_job_signatures",e],queryFn:async()=>{if(!e)return[];const{data:n}=await w.from("job_signatures").select("*").eq("job_id",e).order("signed_at",{ascending:!1});return n||[]},enabled:!!e})}function oK(e){return Ae({queryKey:["customer_approved_photos",e],queryFn:async()=>{if(!e)return[];const{data:n}=await w.from("job_photos").select("*").eq("job_id",e).eq("review_status","approved").order("created_at",{ascending:!0});return n||[]},enabled:!!e})}function aK({customerId:e}){const{role:n}=Ee(),{data:r,isLoading:s}=lZ(e),{data:i}=eK(e),o=(i==null?void 0:i.lead_id)||null,{data:a=[]}=tK(e,o),{data:l=[]}=nK(e,o),{data:d=[]}=rK(e),{data:c=[]}=sK((i==null?void 0:i.job_id)||null),{data:f=[]}=iK((i==null?void 0:i.job_id)||null),{data:p=[]}=oK((i==null?void 0:i.job_id)||null),[u,h]=g.useState(null),[y,m]=g.useState(null),[b,A]=g.useState(null);async function v(k){var q;A(k.id);try{let $=((q=k.terms_snapshot)==null?void 0:q.blocks)||[];if(!$.length){const{data:I}=await w.from("term_blocks").select("slug, display_title, title, content, version").like("slug","ra-%").eq("is_active",!0).order("sort_order");$=I||[]}Yd(XZ(k,i,$),`${k.agreement_number}.html`)}catch($){console.error("Download failed:",$.message)}finally{A(null)}}async function x(k){A(k.id);try{let{data:q}=await w.from("document_line_items").select("*").eq("quote_id",k.id).order("sort_order");if(!q||q.length===0){const{data:$}=await w.from("quote_line_items").select("*").eq("quote_id",k.id).order("sort_order");q=$||[]}Yd(YZ(k,i,q||[]),`${k.quote_number}.html`)}catch(q){console.error("Download failed:",q.message)}finally{A(null)}}async function _(k){var q;A(k.id);try{let $=[];if((q=k.line_items_snapshot)!=null&&q.length)$=k.line_items_snapshot;else{const{data:I}=await w.from("quotes").select("id").eq("customer_id",e).in("status",["accepted","signed"]).order("created_at",{ascending:!1}).limit(5);if(I!=null&&I.length)for(const B of I){const{data:J}=await w.from("document_line_items").select("*").eq("quote_id",B.id).order("sort_order");if(J!=null&&J.length){$=J;break}}}Yd(GZ(k,i,$),`${k.invoice_number}.html`)}catch($){console.error("Download failed:",$.message)}finally{A(null)}}function j(k){A(k.id);try{const q=k.customer_signature_url||null;k.form_type==="ro_drilling_consent"?Yd(JZ(k,q),`RO-Drilling-Consent-${k.id}.html`):k.form_type==="ro_handover"&&Yd(QZ(k,q,i),`RO-Handover-${k.id}.html`)}catch(q){console.error("Download failed:",q)}finally{A(null)}}if(s)return t.jsx("p",{className:"text-sm text-muted text-center py-8",children:"Loading documents..."});const C=r||[],S=C.filter(k=>k.review_status==="pending"),T=C.filter(k=>k.review_status!=="pending"),L=a.length>0,E=l.length>0,R=d.length>0,N=c.length>0,O=f.length>0,z=p.length>0,P=C.length>0||L||E||R||N||O||z||!!o,D={ro_handover:"RO System Handover",ro_drilling_consent:"RO Drilling Consent"},M=({id:k,label:q,onClick:$})=>t.jsx("button",{onClick:$,disabled:b===k,className:"text-xs px-2 py-0.5 rounded-lg font-semibold disabled:opacity-50",style:{backgroundColor:"rgba(56,189,248,0.12)",color:"#38bdf8",border:"1px solid rgba(56,189,248,0.25)"},children:b===k?"â¦":q});return t.jsxs("div",{className:"space-y-5",children:[L&&t.jsx(bi,{title:"Agreements",icon:"ð",count:a.length,children:a.map(k=>t.jsxs(Qa,{children:[t.jsxs("div",{className:"flex items-center justify-between mb-1",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{className:"text-sm",children:"ð"}),t.jsx("span",{className:"text-sm font-medium text-white",children:KZ[k.agreement_type||k.commercial_type||k.quote_type]||"Rental Agreement"})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{className:`text-xs px-2 py-0.5 rounded-full font-semibold ${k.signed_at?"bg-green-500/20 text-green-400":"bg-gray-700 text-gray-400"}`,children:k.signed_at?"Signed":"Pending"}),k.signed_at&&t.jsx(M,{id:k.id,label:"⬠Full PDF",onClick:()=>v(k)})]})]}),t.jsxs("div",{className:"text-xs text-muted space-y-0.5",children:[k.agreement_number&&t.jsx("div",{className:"text-slate-400 font-medium",children:k.agreement_number}),k.signed_at&&t.jsxs("div",{children:["Signed: ",Ro(k.signed_at)]}),k.monthly_amount&&t.jsxs("div",{children:["Monthly: $",k.monthly_amount,"/mo"]})]}),(k.signature_data||k.customer_signature)&&t.jsxs("div",{className:"mt-2",children:[t.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"Customer signature:"}),t.jsx("img",{src:k.signature_data||k.customer_signature,alt:"Signature",className:"h-12 bg-white rounded px-2 py-1 cursor-pointer",onClick:()=>m(k.signature_data||k.customer_signature)})]})]},k.id))}),E&&t.jsx(bi,{title:"Accepted Quotes",icon:"ð",count:l.length,children:l.map(k=>t.jsxs(Qa,{children:[t.jsxs("div",{className:"flex items-center justify-between mb-1",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{className:"text-sm",children:"ð"}),t.jsx("span",{className:"text-sm font-medium text-white",children:k.commercial_type==="rental"?"Rental Quote":k.commercial_type==="financed"?"Financed Quote":"Purchase Quote"})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full font-semibold",style:{backgroundColor:"rgba(56,189,248,0.15)",color:"#38bdf8"},children:k.status==="signed"?"Signed":"Accepted"}),t.jsx(M,{id:k.id,label:"⬠Full PDF",onClick:()=>x(k)})]})]}),t.jsxs("div",{className:"text-xs text-muted space-y-0.5",children:[k.quote_number&&t.jsx("div",{className:"text-slate-400 font-medium",children:k.quote_number}),k.created_at&&t.jsxs("div",{children:["Date: ",Ro(k.created_at)]}),k.signed_at&&t.jsxs("div",{children:["Signed: ",Ro(k.signed_at)]}),k.monthly_rental_price&&t.jsxs("div",{children:["Monthly: $",k.monthly_rental_price,"/mo"]}),k.total&&t.jsxs("div",{children:["Total: $",k.total]})]})]},k.id))}),R&&t.jsx(bi,{title:"Paid Invoices",icon:"ð§¾",count:d.length,children:d.map(k=>t.jsxs(Qa,{children:[t.jsxs("div",{className:"flex items-center justify-between mb-1",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{className:"text-sm",children:"ð§¾"}),t.jsx("span",{className:"text-sm font-medium text-white",children:"Invoice"})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full font-semibold",style:{backgroundColor:"rgba(74,222,128,0.15)",color:"#4ade80"},children:k.status==="partially_paid"?"Partial":"Paid"}),t.jsx(M,{id:k.id,label:"⬠Full PDF",onClick:()=>_(k)})]})]}),t.jsxs("div",{className:"text-xs text-muted space-y-0.5",children:[k.invoice_number&&t.jsx("div",{className:"text-slate-400 font-medium",children:k.invoice_number}),k.paid_at&&t.jsxs("div",{children:["Paid: ",Ro(k.paid_at)]}),k.signed_at&&t.jsxs("div",{children:["Signed: ",Ro(k.signed_at)]}),k.total_amount&&t.jsxs("div",{children:["Total: $",k.total_amount]}),k.amount_paid&&t.jsxs("div",{children:["Amount paid: $",k.amount_paid]})]})]},k.id))}),N&&t.jsx(bi,{title:"Customer Handover",icon:"ð¤",count:c.length,children:c.map(k=>{var I;const q=k.response_data||{},$=k.form_type==="ro_drilling_consent"||k.form_type==="ro_handover";return t.jsxs(Qa,{children:[t.jsxs("div",{className:"flex items-center justify-between mb-1",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{className:"text-sm",children:"ð¤"}),t.jsx("span",{className:"text-sm font-medium text-white",children:D[k.form_type]||((I=k.form_type)==null?void 0:I.replace(/_/g," "))||"Handover Form"})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full font-semibold bg-green-500/20 text-green-400",children:"Completed"}),$&&t.jsx(M,{id:k.id,label:"⬠Full PDF",onClick:()=>j(k)})]})]}),t.jsxs("div",{className:"text-xs text-muted space-y-0.5",children:[t.jsxs("div",{children:["Submitted: ",Ro(k.submitted_at)]}),q.customer_name&&t.jsxs("div",{children:["Signed by: ",q.customer_name]}),q.tds_reading&&t.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[t.jsxs("span",{className:"text-blue-400 font-semibold",children:["TDS: ",q.tds_reading," ppm"]}),t.jsx("span",{className:"text-gray-500",children:"post-filter reading"})]})]}),k.customer_signature_url&&t.jsxs("div",{className:"mt-2",children:[t.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"Customer signature:"}),t.jsx("img",{src:k.customer_signature_url,alt:"Signature",className:"h-12 bg-white rounded px-2 py-1 cursor-pointer",onClick:()=>m(k.customer_signature_url)})]})]},k.id)})}),O&&t.jsx(bi,{title:"Consent Signatures",icon:"âï¸",count:f.length,children:f.map(k=>t.jsxs(Qa,{children:[t.jsxs("div",{className:"flex items-center justify-between mb-1",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{className:"text-sm",children:"âï¸"}),t.jsx("span",{className:"text-sm font-medium text-white",children:"Customer Consent"})]}),t.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full font-semibold bg-green-500/20 text-green-400",children:"Signed"})]}),t.jsxs("div",{className:"text-xs text-muted space-y-0.5",children:[t.jsxs("div",{children:["Signed: ",Ro(k.signed_at)]}),k.signed_by_name&&t.jsxs("div",{children:["Signed by: ",k.signed_by_name]})]}),k.signature_url&&t.jsx("div",{className:"mt-2",children:t.jsx("img",{src:k.signature_url,alt:"Signature",className:"h-12 bg-white rounded px-2 py-1 cursor-pointer",onClick:()=>m(k.signature_url)})})]},k.id))}),S.length>0&&t.jsx(bi,{title:"Pending Review",icon:"ð",count:S.length,urgentColor:!0,children:S.map(k=>t.jsx(Ej,{proof:k,canReview:yt.reviewDocuments(n),onReview:()=>h(k)},k.id))}),T.length>0&&t.jsx(bi,{title:"Compliance Documents",icon:"ð",count:T.length,children:T.map(k=>t.jsx(Ej,{proof:k,canReview:!1},k.id))}
1104),z&&t.jsx(bi,{title:"Approved Install Photos",icon:"ð·",count:p.length,children:t.jsx("div",{className:"grid grid-cols-3 gap-2 px-3 pb-3",children:p.map(k=>{var q;return t.jsxs("div",{className:"cursor-pointer",onClick:()=>m(k.photo_url),children:[t.jsx("img",{src:k.photo_url,alt:k.caption||"Install photo",className:"w-full aspect-square object-cover rounded-lg"}),t.jsx("div",{className:"text-[10px] text-gray-500 mt-1 capitalize",children:(q=k.category)==null?void 0:q.replace(/_/g," ")})]},k.id)})})}),o&&t.jsx($0,{leadId:o,title:"Site Visit Photos"}),!P&&t.jsxs("div",{className:"bg-card border border-border rounded-xl p-6 text-center",children:[t.jsx("div",{className:"text-3xl mb-2",children:"ð"}),t.jsx("div",{className:"text-sm text-muted",children:"No documents on file yet."}),t.jsx("div",{className:"text-xs text-muted mt-1",children:"Agreements, quotes, invoices, handover records, and compliance proofs will appear here."})]}),u&&t.jsx(ZZ,{proof:u,customerId:e,onClose:()=>h(null),onCompleted:()=>h(null)}),y&&t.jsxs("div",{className:"fixed inset-0 bg-black/90 z-50 flex items-center justify-center p-8 cursor-pointer",onClick:()=>m(null),children:[t.jsx("img",{src:y,alt:"Document",className:"max-w-full max-h-full object-contain rounded-lg"}),t.jsx("button",{className:"absolute top-6 right-6 text-white text-2xl hover:text-gray-300",onClick:()=>m(null),children:"Ã"})]})]})}function bi({title:e,icon:n,count:r,urgentColor:s,children:i}){return t.jsxs("div",{className:`bg-card border rounded-xl overflow-hidden ${s?"border-amber-700/40":"border-border"}`,children:[t.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-border/50",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{className:"text-sm",children:n}),t.jsx("h4",{className:"text-xs font-bold text-slate-300 uppercase tracking-wide",children:e})]}),t.jsx("span",{className:`text-xs px-2 py-0.5 rounded-full font-medium ${s?"bg-amber-500/20 text-amber-400":"bg-gray-700 text-gray-300"}`,children:r})]}),t.jsx("div",{className:"divide-y divide-border/30",children:i})]})}function Qa({children:e}){return t.jsx("div",{className:"px-4 py-3",children:e})}function Ej({proof:e,canReview:n,onReview:r}){var i;const s=Rj[e.review_status]||Rj.pending;return t.jsxs(Qa,{children:[t.jsxs("div",{className:"flex items-center justify-between mb-1",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{className:"text-sm",children:"ð"}),t.jsx("span",{className:"text-sm font-medium text-white",children:((i=e.proof_type)==null?void 0:i.replace(/_/g," "))||"Compliance Proof"})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{className:"text-xs font-semibold px-2 py-0.5 rounded-full",style:{backgroundColor:`${s.color}20`,color:s.color},children:s.label}),n&&e.review_status==="pending"&&r&&t.jsx("button",{onClick:r,className:"text-xs px-2 py-0.5 rounded-lg font-semibold",style:{backgroundColor:"rgba(56,189,248,0.12)",color:"#38bdf8",border:"1px solid rgba(56,189,248,0.25)"},children:"Review"})]})]}),t.jsxs("div",{className:"text-xs text-muted space-y-0.5",children:[t.jsxs("div",{children:["Submitted: ",Nj(e.submitted_at)]}),e.reviewed_at&&t.jsxs("div",{children:["Reviewed: ",Nj(e.reviewed_at),e.reviewed_by?` by ${e.reviewed_by}`:""]}),e.review_notes&&t.jsxs("div",{className:"text-slate-400 mt-1",children:["Notes: ",e.review_notes]})]}),e.proof_url&&t.jsx("a",{href:e.proof_url,target:"_blank",rel:"noopener noreferrer",className:"text-xs mt-2 inline-block",style:{color:"#38bdf8"},children:"View document â"})]})}var m3={exports:{}},lK="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED",dK=lK,cK=dK;function x3(){}function y3(){}y3.resetWarningCache=x3;var uK=function(){function e(s,i,o,a,l,d){if(d!==cK){var c=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");throw c.name="Invariant Violation",c}}e.isRequired=e;function n(){return e}var r={array:e,bigint:e,bool:e,func:e,number:e,object:e,string:e,symbol
vendor: 7,252 bytes, lines 1104-1105
1104:e,any:e,arrayOf:n,element:e,elementType:e,instanceOf:n,node:e,objectOf:n,oneOf:n,oneOfType:n,shape:n,exact:n,checkPropTypes:y3,resetWarningCache:x3};return r.PropTypes=r,r};m3.exports=uK();var pK=m3.exports;const Jt=C2(pK);function Pj(e,n){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);n&&(s=s.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,s)}return r}function qj(e){for(var n=1;n<arguments.length;n++){var r=arguments[n]!=null?arguments[n]:{};n%2?Pj(Object(r),!0).forEach(function(s){b3(e,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Pj(Object(r)).forEach(function(s){Object.defineProperty(e,s,Object.getOwnPropertyDescriptor(r,s))})}return e}function mh(e){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?mh=function(n){return typeof n}:mh=function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},mh(e)}function b3(e,n,r){return n in e?Object.defineProperty(e,n,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[n]=r,e}function hK(e,n){if(e==null)return{};var r={},s=Object.keys(e),i,o;for(o=0;o<s.length;o++)i=s[o],!(n.indexOf(i)>=0)&&(r[i]=e[i]);return r}function fK(e,n){if(e==null)return{};var r=hK(e,n),s,i;if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(i=0;i<o.length;i++)s=o[i],!(n.indexOf(s)>=0)&&Object.prototype.propertyIsEnumerable.call(e,s)&&(r[s]=e[s])}return r}function A3(e,n){return gK(e)||mK(e,n)||xK(e,n)||yK()}function gK(e){if(Array.isArray(e))return e}function mK(e,n){var r=e&&(typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"]);if(r!=null){var s=[],i=!0,o=!1,a,l;try{for(r=r.call(e);!(i=(a=r.next()).done)&&(s.push(a.value),!(n&&s.length===n));i=!0);}catch(d){o=!0,l=d}finally{try{!i&&r.return!=null&&r.return()}finally{if(o)throw l}}return s}}function xK(e,n){if(e){if(typeof e=="string")return Dj(e,n);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return Dj(e,n)}}function Dj(e,n){(n==null||n>e.length)&&(n=e.length);for(var r=0,s=new Array(n);r<n;r++)s[r]=e[r];return s}function yK(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. 1105In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var qn=function(n,r,s){var i=!!s,o=ut.useRef(s);ut.useEffect(function(){o.current=s},[s]),ut.useEffect(function(){if(!i||!n)return function(){};var a=function(){o.current&&o.current.apply(o,arguments)};return n.on(r,a),function(){n.off(r,a)}},[i,r,n,o])},Iy=function(n){var r=ut.useRef(n);return ut.useEffect(function(){r.current=n},[n]),r.current},rd=function(n){return n!==null&&mh(n)==="object"},bK=function(n){return rd(n)&&typeof n.then=="function"},AK=function(n){return rd(n)&&typeof n.elements=="function"&&typeof n.createToken=="function"&&typeof n.createPaymentMethod=="function"&&typeof n.confirmCardPayment=="function"},Oj="[object Object]",vK=function e(n,r){if(!rd(n)||!rd(r))return n===r;var s=Array.isArray(n),i=Array.isArray(r);if(s!==i)return!1;var o=Object.prototype.toString.call(n)===Oj,a=Object.prototype.toString.call(r)===Oj;if(o!==a)return!1;if(!o&&!s)return n===r;var l=Object.keys(n),d=Object.keys(r);if(l.length!==d.length)return!1;for(var c={},f=0;f<l.length;f+=1)c[l[f]]=!0;for(var p=0;p<d.length;p+=1)c[d[p]]=!0;var u=Object.keys(c);if(u.length!==l.length)return!1;var h=n,y=r,m=function(A){return e(h[A],y[A])};return u.every(m)},v3=function(n,r,s){return rd(n)?Object.keys(n).reduce(function(i,o){var a=!rd(r)||!vK(n[o],r[o]);return s.includes(o)?(a&&console.warn("Unsupported prop change: options.".concat(o," is not a mutable property.")),i):a?qj(qj({},i||{}),{},b3({},o,n[o])):i},null):null},_3="Invalid prop `stripe` supplied to `Elements`. We recommend using the `loadStripe` utility from `@stripe/stripe-js`. See https://stripe.com/docs/stripe-js/react#elements-props-stripe for details.",Ij=function(n){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:_3;if(n===null||AK(n))return n;throw new Error(r)},_K=function(n){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:_3;if(bK(n))return{tag:"async",stripePromise:Promise.resolve(n).then(function(i){return Ij(i,r)})};var s=Ij(n,r);return s===null?{tag:"empty"}:{tag:"sync",stripe:s}},jK=function(n){!n||!n._registerWrapper||!n.registerAppInfo||(n._registerWrapper({name:"react-stripe-js",version:"6.0.0"}),n.registerAppInfo({name:"react-stripe-js",version:"6.0.0",url:"https://stripe.com/docs/stripe-js/react"}))},og=ut.createContext(null);og.displayName="ElementsContext";var j3=function(n,r){if(!n)throw new Error("Could not find Elements context; You need to wrap the part of your app that ".concat(r," in an <Elements> provider."));return n},ag=function(n){var r=n.stripe,s=n.options,i=n.children,o=ut.useMemo(function(){return _K(r)},[r]),a=ut.useState(function(){return{stripe:o.tag==="sync"?o.stripe:null,elements:o.tag==="sync"?o.stripe.elements(s):null}}),l=A3(a,2),d=l[0],c=l[1];ut.useEffect(function(){var u=!0,h=function(m){c(function(b){return b.stripe?b:{stripe:m,elements:m.elements(s)}})};return o.tag==="async"&&!d.stripe?o.stripePromise.then(function(y){y&&u&&h(y)}):o.tag==="sync"&&!d.stripe&&h(o.stripe),function(){u=!1}},[o,d,s]);var f=Iy(r);ut.useEffect(function(){f!==null&&f!==r&&console.warn("Unsupported prop change on Elements: You cannot change the `stripe` prop after setting it.")},[f,r]);var p=Iy(s);return ut.useEffect(function(){if(d.elements){var u=v3(s,p,["clientSecret","fonts"]);u&&d.elements.update(u)}},[s,p,d.elements]),ut.useEffect(function(){jK(d.stripe)},[d.stripe]),ut.createElement(og.Provider,{value:d},i)};ag.propTypes={stripe:Jt.any,options:Jt.object};var wK=function(n){var r=ut.useContext(og);return j3(r,n)},K0=function(){var n=wK("calls useElements()"),r=n.elements;return r};Jt.func.isRequired;var w3=ut.createContext(null);w3.displayName="CheckoutContext";var Ly=function(n){var r=ut.useContext(w3),s=ut.useContext(og);if(r){if(s)throw new Error("You cannot wrap the part of your app that ".concat(n," in both a checkout provider and <Elements> provider."));return r}else return j3(s,n)},SK=["mode"],kK=function(n){return n.charAt(0).toUpperCase()+n.slice(1)},pr=function(n,r,s){var i="".concat(kK(n),"Element"),o=function(c){var f=c.id,p=c.className,u=c.options,h=u===void 0?{}:u,y=c.onBlur,m=c.onFocus,b=c.onReady,A=c.onChange,v=c.onEscape,x=c.onClick,_=c.onLoadError,j=c.onLoaderStart,C=c.onNetworksChange,S=c.onConfirm,T=c.onCancel,L=c.onShippingAddressChange,E=c.onShippingRateChange,R=c.onSavedPaymentMethodRemove,N=c.onSavedPaymentMethodUpdate,O=Ly("mounts <".concat(i,">")),z="elements"in O?O.elements:null,P="checkoutState"in O?O.checkoutState:null,D=(P==null?void 0:P.type)==="success"||(P==null?void 0:P.type)==="loading"?P.sdk:null,M=ut.useState(null),k=A3(M,2),q=k[0],$=k[1],I=ut.useRef(null),B=ut.useRef(null);qn(q,"blur",y),qn(q,"focus",m),qn(q,"escape",v),qn(q,"click",x),qn(q,"loaderror",_),qn(q,"loaderstart",j),qn(q,"networksch
1105ange",C),qn(q,"confirm",S),qn(q,"cancel",T),qn(q,"shippingaddresschange",L),qn(q,"shippingratechange",E),qn(q,"savedpaymentmethodremove",R),qn(q,"savedpaymentmethodupdate",N),qn(q,"change",A);var J;b&&(n==="expressCheckout"?J=b:J=function(){b(q)}),qn(q,"ready",J),ut.useLayoutEffect(function(){if(I.current===null&&B.current!==null&&(z||D)){var te=null;if(D){var U=D,W=D;switch(n){case"paymentForm":te=W.createForm(h);break;case"payment":te=U.createPaymentElement(h);break;case"address":if("mode"in h){var G=h.mode,V=fK(h,SK);if(G==="shipping")te=U.createShippingAddressElement(V);else if(G==="billing")te=U.createBillingAddressElement(V);else throw new Error("Invalid options.mode. mode must be 'billing' or 'shipping'.")}else throw new Error("You must supply options.mode. mode must be 'billing' or 'shipping'.");break;case"expressCheckout":te=U.createExpressCheckoutElement(h);break;case"currencySelector":te=D.createCurrencySelectorElement();break;case"taxId":te=U.createTaxIdElement(h);break;default:throw new Error("<".concat(i,"> is not supported inside a checkout provider. Use an <Elements> provider instead."))}}else z&&(te=z.create(n,h));I.current=te,$(te),te&&te.mount(B.current)}},[z,D,h]);var ae=Iy(h);return ut.useEffect(function(){if(I.current){var te=v3(h,ae,["paymentRequest"]);te&&"update"in I.current&&I.current.update(te)}},[h,ae]),ut.useLayoutEffect(function(){return function(){if(I.current&&typeof I.current.destroy=="function")try{I.current.destroy(),I.current=null}catch{}}},[]),ut.createElement("div",{id:f,className:p,ref:B})},a=function(c){Ly("mounts <".concat(i,">"));var f=c.id,p=c.className;return ut.createElement("div",{id:f,className:p})},l=r?a:o;return l.propTypes={id:Jt.string,className:Jt.string,onChange:Jt.func,onBlur:Jt.func,onFocus:Jt.func,onReady:Jt.func,onEscape:Jt.func,onClick:Jt.func,onLoadError:Jt.func,onLoaderStart:Jt.func,onNetworksChange:Jt.func,onConfirm:Jt.func,onCancel:Jt.func,onShippingAddressChange:Jt.func,onShippingRateChange:Jt.func,onSavedPaymentMethodRemove:Jt.func,onSavedPaymentMethodUpdate:Jt.func,options:Jt.object},l.displayName=i,l.__elementType=n,l},hr=typeof window>"u",CK=ut.createContext(null);CK.displayName="EmbeddedCheckoutProviderContext";var lg=function(){var n=Ly("calls useStripe()"),r=n.stripe;return r};pr("auBankAccount",hr);var sd=pr("card",hr);pr("cardNumber",hr);pr("cardExpiry",hr);pr("cardCvc",hr);pr("iban",hr);pr("payment",hr);pr("expressCheckout",hr);pr("paymentRequestButton",hr);pr("linkAuthentication",hr);pr("address",hr);pr("shippingAddress",hr);pr("paymentMethodMessaging",hr);pr("taxId",hr);const Lj=e=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}).format(e||0),TK={style:{base:{color:"#e2e8f0",fontSize:"15px","::placeholder":{color:"#64748b"}},invalid:{color:"#f87171"}}};function zK({customer:e,amount:n,invoiceId:r,description:s,onSuccess:i,onClose:o}){const a=lg(),l=K0(),d=typeof n=="number"&&n>0,[c,f]=g.useState(d?String(n):""),[p,u]=g.useState("once"),[h,y]=g.useState(!1),[m,b]=g.useState("");async function A(){var j;if(!a||!l)return;const x=l.getElement(sd);if(!x)return;const _=d?n:parseFloat(c);if(!_||_<=0){b("Enter a valid amount");return}y(!0),b("");try{const{client_secret:C,stripe_customer_id:S}=await _0({stripe_customer_id:e.stripe_customer_id||void 0,customer_name:e.full_name,customer_email:e.email||void 0});e.stripe_customer_id||await eu(e.id,S);const T=await a.confirmCardSetup(C,{payment_method:{card:x}});if(T.error)throw new Error(T.error.message);const L=typeof T.setupIntent.payment_method=="string"?T.setupIntent.payment_method:(j=T.setupIntent.payment_method)==null?void 0:j.id;if(!L)throw new Error("Could not read the new card");let E;if(p!=="once"){const N=await(await fetch("/api/stripe/get-payment-method",{method:"POST",headers:await At(),body:JSON.stringify({payment_method_id:L})})).json(),O=await Qc({customer_id:e.id,stripe_payment_method_id:L,last_four:N.last4||"????",exp_month:N.exp_month||0,exp_year:N.exp_year||0,make_default:p==="save_default",type:N.type||"card"});E=O==null?void 0:O.id}await Gf({stripe_customer_id:S,payment_method_id:L,amount_cents:Math.round(_*100),description:s||(r?"Invoice payment":"Payment"),customer_id:e.id,invoice_id:r||void 0,supabase_pm_id:E}),i()}catch(C){b(C.message||"Charge failed")}finally{y(!1)}}
1105const v={display:"flex",alignItems:"flex-start",gap:8,fontSize:13,color:"#cbd5e1",cursor:"pointer",padding:"2px 0"};return t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:11,color:"#64748b",fontWeight:600,textTransform:"uppercase",letterSpacing:"0.08em",marginBottom:4},children:"Charging"}),t.jsx("div",{style:{fontSize:13,color:"#94a3b8",marginBottom:6},children:e.full_name}),d?t.jsx("div",{style:{fontSize:20,fontWeight:800,color:"#e2e8f0"},children:Lj(n)}):t.jsx("input",{type:"number",step:"0.01",value:c,onChange:x=>f(x.target.value),placeholder:"Amount ($)",style:{width:"100%",fontSize:15,borderRadius:8,padding:"9px 12px",background:"#0f172a",border:"1px solid rgba(148,163,184,0.2)",color:"#e2e8f0",outline:"none"}})]}),t.jsx("div",{style:{background:"#0f172a",borderRadius:10,padding:"13px 14px",border:"1px solid rgba(148,163,184,0.2)"},children:t.jsx(sd,{options:TK})}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[t.jsxs("label",{style:v,children:[t.jsx("input",{type:"radio",name:"savemode",checked:p==="once",onChange:()=>u("once"),style:{marginTop:2}}),t.jsxs("span",{children:["Charge this card once ",t.jsx("span",{style:{color:"#64748b"},children:"â don't save"})]})]}),t.jsxs("label",{style:v,children:[t.jsx("input",{type:"radio",name:"savemode",checked:p==="save",onChange:()=>u("save"),style:{marginTop:2}}),t.jsxs("span",{children:["Save card on file ",t.jsx("span",{style:{color:"#64748b"},children:"â keep current default"})]})]}),t.jsxs("label",{style:v,children:[t.jsx("input",{type:"radio",name:"savemode",checked:p==="save_default",onChange:()=>u("save_default"),style:{marginTop:2}}),t.jsxs("span",{children:["Save and make default ",t.jsx("span",{style:{color:"#64748b"},children:"â future auto-payments use this card"})]})]})]}),m&&t.jsx("div",{style:{fontSize:13,borderRadius:8,padding:"10px 12px",color:"#f87171",background:"rgba(248,113,113,0.1)",border:"1px solid rgba(248,113,113,0.25)"},children:m}),t.jsxs("div",{style:{display:"flex",gap:10,justifyContent:"flex-end"},children:[t.jsx("button",{onClick:o,disabled:h,style:{padding:"9px 16px",borderRadius:8,fontSize:14,fontWeight:600,cursor:"pointer",color:"#94a3b8",background:"transparent",border:"1px solid #1e3a4f"},children:"Cancel"}),t.jsx("button",{onClick:A,disabled:h||!a,style:{padding:"9px 18px",borderRadius:8,fontSize:14,fontWeight:700,cursor:h?"default":"pointer",color:"#052e16",background:"#4ade80",border:"none",opacity:h||!a?.6:1},children:h?"Chargingâ¦":d?`Charge ${Lj(n)}`:"Charge"})]})]})}function S3({stripePromise:e,onClose:n,...r}){return t.jsxs("div",{style:{position:"fixed",inset:0,zIndex:60,display:"flex",alignItems:"center",justifyContent:"center"},children:[t.jsx("div",{style:{position:"absolute",inset:0,background:"rgba(0,0,0,0.55)",backdropFilter:"blur(3px)"},onClick:n}),t.jsxs("div",{style:{position:"relative",width:"100%",maxWidth:440,margin:16,background:"#162232",borderRadius:14,border:"1px solid #1e3a4f",padding:22},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:16},children:[t.jsx("div",{style:{fontWeight:800,fontSize:16,color:"#e2e8f0"},children:"Charge a new card"}),t.jsx("button",{onClick:n,style:{background:"none",border:"none",color:"#64748b",cursor:"pointer",fontSize:20,lineHeight:1},children:"Ã"})]}),e?t.jsx(ag,{stripe:e,children:t.jsx(zK,{onClose:n,...r})}):t.jsx("div",{style:{fontSize:13,color:"#94a3b8"},children:"Loading payment formâ¦"})]})]})}function Ci(e){return`$${Number(e).toLocaleString("en-US",{minimumFractionDigits:2})}`}const NK={style:{base:{color:"#e2e8f0",fontFamily:"system-ui, sans-serif",fontSize:"14px","::placeholder":{color:"#475569"}},invalid:{color:"#f87171"}}};function RK({customerId:e,customer:n,onSuccess:r,onCancel:s}){const i=lg(),o=K0(),[a,l]=g.useState(!0),[d,c]=g.useState(!1),[f,p]=g.useState("");async function u(){var y;if(!i||!o)return;const h=o.getElement(sd);if(h){c(!0),p("");try{const{client_secret:m,stripe_customer_id:b}=await _0({stripe_customer_id:n.stripe_customer_id||void 0,customer_name:n.full_name,customer_email:n.email||void 0});n.stripe_customer_id||await eu(e,b);const A=await i.confirmCardSetup(m,{payment_method:{card:h}});if(A.error)throw new Error(A.error.message);const v=typeof A.setupIntent.payment_method=="string"?A.setupIntent.payment_method:(y=A.setupIntent.payment_method)==null?void 0:y.id,_=await(await fetch("/api/stripe/get-payment-method",{method:"POST",headers:await At(),body:JSON.stringify({payment_method_id:v})})).json();await Qc({customer_id:e,stripe_payment_method_id:v,last_four:_.last4||"????",exp_month:_.exp_month||0,exp_year:_.exp_year||0,make_default:a,type:_.type||"card"}),r()}catch(m){p(m.message||"Failed to save card")}finally{c(!1)}}}return t.jsxs("div",{className:"rounded-xl p-4 space-y-4",style:{backgroundColor:"rgba(96,165,250,0.06)",border:"1px solid rgba(96,165,250,0.2)"},children:[t.jsx("div",{className:"text-sm font-semibold text-slate-200",children:"ð³ Add Credit / Debit Card"}),t.jsx("div",{className:"rounded-lg px-3 py-3",style:{backgroundColor:"#0f172a",border:"1px solid rgba(148,163,184,0.2)"},children:t.jsx(sd,{options:NK})}),t.jsxs("label",{className:"flex items-center gap-2 text-sm text-slate-400 cursor-pointer",children:[t.jsx("input",{type:"checkbox",checked:a,onChange:h=>l(h.target.checked),className:"rounded"}),"Set as default payment method"]}),f&&t.jsx("div",{className:"text-xs rounded-lg px-3 py-2",style:{color:"#f87171",backgroundColor:"rgba(239,68,68,0.1)",border:"1px solid rgba(239,68,68,0.2)"},children:f}),t.jsxs("div",{className:"flex gap-2 justify-end",children:[t.jsx("button",{onClick:s,className:"text-xs px-3 py-1.5 rounded-lg text-slate-400 hover:text-slate-200 transition-colors",children:"Cancel"}),t.jsx("button",{onClick:u,disabled:d||!i,className:"text-xs px-4 py-1.5 rounded-lg font-semibold transition-colors disabled:opacity-50",style:{backgroundColor:"rgba(96,165,250,0.15)",color:"#60a5fa",border:"1px solid rgba(96,165,250,0.3)"},children:d?"Saving...":"Save Card"})]})]})}function EK({customerId:e,customer:n,onSuccess:r,onCancel:s}){const i=lg(),[o,a]=g.useState(!0),[l,d]=g.useState(!1),[c,f]=g.useState(""),[p,u]=g.useState("choose"),[h,y]=g.useState(""),[m,b]=g.useState(""),[A,v]=g.useState("checking"),[x,_]=g.useState(n.full_name||""),[j,C]=g.useState(""),[S,T]=g.useState(""),[L,E]=g.useState(""),[R,N]=g.useState("");async function O(){const k=await(await fetch("/api/stripe/setup-bank-account",{method:"POST",headers:await At(),body:JSON.stringify({stripe_customer_id:n.stripe_customer_id||void 0,customer_name:n.full_name,customer_email:n.email||void 0})})).json();if(k.error)throw new Error(k.error);return k}async function z(){var M,k,q,$;if(i){d(!0),f("");try{const{client_secret:I,stripe_customer_id:B}=await O();n.stripe_customer_id||await eu(e,B);const J=await i.collectBankAccountForSetup({clientSecret:I,params:{payment_method_type:"us_bank_account",payment_method_data:{billing_details:{name:n.full_name,email:n.email||void 0}}}});if(J.error)throw new Error(J.error.message);if(((M=J.setupIntent)==null?void 0:M.status)==="requires_confirmation"){const W=await i.confirmUsBankAccountSetup(I);if(W.error)throw new Error(W.error.message)}const ae=typeof((k=J.setupIntent)==null?void 0:k.payment_method)=="string"?J.setupIntent.payment_method:($=(q=J.setupIntent)==null?void 0:q.payment_method)==null?void 0:$.id,U=await(await fetch("/api/stripe/get-payment-method",{method:"POST",headers:await At(),body:JSON.stringify({payment_method_id:ae})})).json();await Qc({customer_id:e,stripe_payment_method_id:ae,last_four:U.last4||"????",exp_month:0,exp_year:0,make_default:o,type:"us_bank_account"}),r()}catch(I){f(I.message||"Bank connection failed")}finally{d(!1)}}}async function P(){var M,k,q;if(i){if(!h||!m||!x){f("Please fill in all fields");return}d(!0),f("");try{const{client_secret:$,stripe_customer_id:I}=await O();n.stripe_customer_id||await eu(e,I);const B=await i.confirmUsBankAccountSetup($,{payment_method:{us_bank_account:{routing_number:h,account_number:m,account_holder_type:"individual",account_type:A},billing_details:{name:x,email:n.email||void 0}}});if(B.error)throw new Error(B.error.message);const J=typeof((M=B.setupIntent)==null?void 0:M.payment_method)=="string"?B.setupIntent.payment_method:(q=(k=B.setupIntent)==null?void 0:k.payment_method)==null?void 0:q.id;await Qc({customer_id:e,stripe_payment_method_id:J,last_four:m.slice(-4),exp_month:0,exp_year:0,make_default:!1,type:"us_bank_account",status:"pending_verification"}),C($),T(J),u("pending_verification")}catch($){f($.message||"Failed to add bank account")}finally{d(!1)}}}
1105async function D(){if(!L||!R){f("Enter both deposit amounts");return}d(!0),f("");try{const k=await(await fetch("/api/stripe/verify-microdeposits",{method:"POST",headers:await At(),body:JSON.stringify({client_secret:j,amounts:[parseInt(L),parseInt(R)]})})).json();if(k.error)throw new Error(k.error);r()}catch(M){f(M.message||"Verification failed â check your amounts")}finally{d(!1)}}return p==="pending_verification"?t.jsxs("div",{className:"rounded-xl p-4 space-y-4",style:{backgroundColor:"rgba(251,191,36,0.06)",border:"1px solid rgba(251,191,36,0.25)"},children:[t.jsx("div",{className:"text-sm font-semibold text-slate-200",children:"ð¦ Verify Bank Account"}),t.jsxs("div",{className:"text-xs text-slate-400",children:["Stripe sent 2 small deposits to your bank account (usually appear within 1â2 business days). Enter the exact amounts in ",t.jsx("span",{className:"text-yellow-400 font-semibold",children:"cents"})," to verify."]}),t.jsx("div",{className:"text-xs rounded-lg px-3 py-2",style:{color:"#fbbf24",backgroundColor:"rgba(245,158,11,0.08)",border:"1px solid rgba(245,158,11,0.2)"},children:"Example: if you see $0.32 and $0.45, enter 32 and 45"}),t.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[t.jsxs("div",{children:[t.jsx("label",{className:"text-xs text-muted uppercase tracking-wide block mb-1",children:"First deposit (cents)"}),t.jsx("input",{type:"number",value:L,onChange:M=>E(M.target.value),placeholder:"32",className:"w-full text-sm rounded-lg px-3 py-2 outline-none",style:{backgroundColor:"#0f172a",border:"1px solid rgba(148,163,184,0.2)",color:"#e2e8f0"}})]}),t.jsxs("div",{children:[t.jsx("label",{className:"text-xs text-muted uppercase tracking-wide block mb-1",children:"Second deposit (cents)"}),t.jsx("input",{type:"number",value:R,onChange:M=>N(M.target.value),placeholder:"45",className:"w-full text-sm rounded-lg px-3 py-2 outline-none",style:{backgroundColor:"#0f172a",border:"1px solid rgba(148,163,184,0.2)",color:"#e2e8f0"}})]})]}),c&&t.jsx("div",{className:"text-xs rounded-lg px-3 py-2",style:{color:"#f87171",backgroundColor:"rgba(239,68,68,0.1)",border:"1px solid rgba(239,68,68,0.2)"},children:c}),t.jsxs("div",{className:"flex gap-2 justify-end",children:[t.jsx("button",{onClick:s,className:"text-xs px-3 py-1.5 rounded-lg text-slate-400 hover:text-slate-200",children:"Cancel"}),t.jsx("button",{onClick:D,disabled:l,className:"text-xs px-4 py-1.5 rounded-lg font-semibold disabled:opacity-50",style:{backgroundColor:"rgba(251,191,36,0.15)",color:"#fbbf24",border:"1px solid rgba(251,191,36,0.3)"},children:l?"Verifying...":"Verify Account"})]})]}):p==="choose"?t.jsxs("div",{className:"rounded-xl p-4 space-y-3",style:{backgroundColor:"rgba(74,222,128,0.05)",border:"1px solid rgba(74,222,128,0.2)"},children:[t.jsx("div",{className:"text-sm font-semibold text-slate-200",children:"ð¦ Add Bank Account (ACH)"}),t.jsx("div",{className:"text-xs text-slate-400 mb-2",children:"Lower fees than cards â 0.8% capped at $5/transaction"}),t.jsx("button",{onClick:z,disabled:l,className:"w-full rounded-xl p-4 text-left transition-all disabled:opacity-50",style:{backgroundColor:"rgba(96,165,250,0.08)",border:"1px solid rgba(96,165,250,0.25)"},children:t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-semibold text-white",children:"ð Connect via Bank Login"}),t.jsx("div",{className:"text-xs text-slate-400 mt-0.5",children:"Instant â log into Chase, Wells Fargo, BofA and 5,000+ banks. No waiting."})]}),t.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full font-semibold ml-3 flex-shrink-0",style:{backgroundColor:"rgba(74,222,128,0.15)",color:"#4ade80"},children:"Recommended"})]})}),t.jsxs("button",{onClick:()=>u("manual"),className:"w-full rounded-xl p-4 text-left transition-all",style:{backgroundColor:"rgba(148,163,184,0.05)",border:"1px solid rgba(148,163,184,0.15)"},children:[t.jsx("div",{className:"text-sm font-semibold text-white",children:"âï¸ Enter Routing & Account Number"}),t.jsx("div",{className:"text-xs text-slate-400 mt-0.5",children:"Manual entry â requires 1â2 day micro-deposit verification"})]}),c&&t.jsx("div",{className:"text-xs rounded-lg px-3 py-2",style:{color:"#f87171",backgroundColor:"rgba(239,68,68,0.1)",border:"1px solid rgba(239,68,68,0.2)"},children:c}),t.jsx("div",{className:"flex justify-end",children:t.jsx("button",{onClick:s,className:"text-xs px-3 py-1.5 rounded-lg text-slate-400 hover:text-slate-200",children:"Cancel"})})]}):t.jsxs("div",{className:"rounded-xl p-4 space-y-4",style:{backgroundColor:"rgba(148,163,184,0.05)",border:"1px solid rgba(148,163,184,0.15)"},children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("button",{onClick:()=>u("choose"),className:"text-xs text-slate-400 hover:text-slate-200",children:"â Back"}),t.jsx("div",{className:"text-sm font-semibold text-slate-200",children:"âï¸ Manual Bank Entry"})]}),t.jsxs("div",{children:[t.jsx("label",{className:"text-xs text-muted uppercase tracking-wide block mb-1",children:"Account Holder Name"}),t.jsx("input",{type:"text",value:x,onChange:M=>_(M.target.value),className:"w-full text-sm rounded-lg px-3 py-2 outline-none",style:{backgroundColor:"#0f172a",border:"1px solid rgba(148,163,184,0.2)",color:"#e2e8f0"}})]}),t.jsxs("div",{children:[t.jsx("label",{className:"text-xs text-muted uppercase tracking-wide block mb-1",children:"Routing Number"}),t.jsx("input",{type:"text",value:h,onChange:M=>y(M.target.value),placeholder:"9 digits",maxLength:9,className:"w-full text-sm rounded-lg px-3 py-2 outline-none",style:{backgroundColor:"#0f172a",border:"1px solid rgba(148,163,184,0.2)",color:"#e2e8f0"}})]}),t.jsxs("div",{children:[t.jsx("label",{className:"text-xs text-muted uppercase tracking-wide block mb-1",children:"Account Number"}),t.jsx("input",{type:"text",value:m,onChange:M=>b(M.target.value),className:"w-full text-sm rounded-lg px-3 py-2 outline-none",style:{backgroundColor:"#0f172a",border:"1px solid rgba(148,163,184,0.2)",color:"#e2e8f0"}})]}),t.jsxs("div",{children:[t.jsx("label",{className:"text-xs text-muted uppercase tracking-wide block mb-1",children:"Account Type"}),t.jsx("div",{className:"flex gap-2",children:["checking","savings"].map(M=>t.jsx("button",{onClick:()=>v(M),className:"text-xs px-4 py-1.5 rounded-lg font-medium capitalize transition-all",style:{backgroundColor:A===M?"rgba(96,165,250,0.15)":"rgba(148,163,184,0.05)",color:A===M?"#60a5fa":"#94a3b8",border:`1px solid ${A===M?"rgba(96,165,250,0.3)":"rgba(148,163,184,0.15)"}`},children:M},M))})]}),t.jsxs("label",{className:"flex items-center gap-2 text-sm text-slate-400 cursor-pointer",children:[t.jsx("input",{type:"checkbox",checked:o,onChange:M=>a(M.target.checked),className:"rounded"}),"Set as default after verification"]}),t.jsx("div",{className:"text-xs rounded-lg px-3 py-2",style:{color:"#fbbf24",backgroundColor:"rgba(245,158,11,0.08)",border:"1px solid rgba(245,158,11,0.2)"},children:"â± Stripe will send 2 small deposits to verify this account (1â2 business days)"}),c&&t.jsx("div",{className:"text-xs rounded-lg px-3 py-2",style:{color:"#f87171",backgroundColor:"rgba(239,68,68,0.1)",border:"1px solid rgba(239,68,68,0.2)"},children:c}),t.jsxs("div",{className:"flex gap-2 justify-end",children:[t.jsx("button",{onClick:s,className:"text-xs px-3 py-1.5 rounded-lg text-slate-400 hover:text-slate-200",children:"Cancel"}),t.jsx("button",{onClick:P,disabled:l||!i,className:"text-xs px-4 py-1.5 rounded-lg font-semibold disabled:opacity-50",style:{backgroundColor:"rgba(96,165,250,0.15)",color:"#60a5fa",border:"1px solid rgba(96,165,250,0.3)"},children:l?"Saving...":"Save & Send Micro-Deposits"})]})]})}function PK({customer:e,paymentMethods:n,contracts:r,onClose:s,onSuccess:i}){const o=n.find(j=>j.is_default)||n[0],a=r.find(j=>j.status==="active"),[l,d]=g.useState((o==null?void 0:o.id)||""),[c,f]=g.useState((a==null?void 0:a.id)||""),[p,u]=g.useState(a?String(a.monthly_amount):""),[h,y]=g.useState(a?`Monthly rental â Contract ${a.contract_number}`:""),[m,b]=g.useState(!1),[A,v]=g.useState(""),x=n.find(j=>j.id===l);async function _(){if(!(!x||!p||!e.stripe_customer_id)){b(!0),v("");try{await Gf({stripe_customer_id:e.stripe_customer_id,payment_method_id:x.external_id,amount_cents:Math.round(parseFloat(p)*100),description:h,customer_id:e.id,contract_id:c||void 0,supabase_pm_id:x.id}),i()}catch(j){v(j.message)}finally{b(!1)}}}return t.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4",style:{backgroundColor:"rgba(0,0,0,0.7)"},children:t.jsxs("div",{className:"w-full max-w-md rounded-2xl p-6 space-y-4",style:{backgroundColor:"#1e293b",border:"1px solid rgba(148,163,184,0.15)"},children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx("div",{className:"text-base font-bold text-white",children:"Charge Payment"}),t.jsx("button",{onClick:s,className:"text-slate-400 hover:text-slate-200 text-xl",children:"Ã"})]}),t.jsxs("div",{children:[t.jsx("label",{className:"text-xs text-muted uppercase tracking-wide block mb-1.5",children:"Payment Method"}
1105),t.jsx("select",{value:l,onChange:j=>d(j.target.value),className:"w-full text-sm rounded-lg px-3 py-2 outline-none",style:{backgroundColor:"#0f172a",border:"1px solid rgba(148,163,184,0.2)",color:"#e2e8f0"},children:n.map(j=>t.jsxs("option",{value:j.id,children:[j.type==="us_bank_account"?"ð¦":"ð³"," â¢â¢â¢â¢ ",j.last_four,j.type==="us_bank_account"?" (ACH)":` â ${j.exp_month}/${j.exp_year}`,j.is_default?" (default)":""]},j.id))})]}),r.length>0&&t.jsxs("div",{children:[t.jsx("label",{className:"text-xs text-muted uppercase tracking-wide block mb-1.5",children:"Contract (optional)"}),t.jsxs("select",{value:c,onChange:j=>{f(j.target.value);const C=r.find(S=>S.id===j.target.value);C&&(u(String(C.monthly_amount)),y(`Monthly rental â Contract ${C.contract_number}`))},className:"w-full text-sm rounded-lg px-3 py-2 outline-none",style:{backgroundColor:"#0f172a",border:"1px solid rgba(148,163,184,0.2)",color:"#e2e8f0"},children:[t.jsx("option",{value:"",children:"No contract"}),r.map(j=>t.jsxs("option",{value:j.id,children:[j.contract_number," â $",j.monthly_amount,"/mo (",j.status,")"]},j.id))]})]}),t.jsxs("div",{children:[t.jsx("label",{className:"text-xs text-muted uppercase tracking-wide block mb-1.5",children:"Amount ($)"}),t.jsx("input",{type:"number",step:"0.01",value:p,onChange:j=>u(j.target.value),className:"w-full text-sm rounded-lg px-3 py-2 outline-none",style:{backgroundColor:"#0f172a",border:"1px solid rgba(148,163,184,0.2)",color:"#e2e8f0"}})]}),t.jsxs("div",{children:[t.jsx("label",{className:"text-xs text-muted uppercase tracking-wide block mb-1.5",children:"Description"}),t.jsx("input",{type:"text",value:h,onChange:j=>y(j.target.value),className:"w-full text-sm rounded-lg px-3 py-2 outline-none",style:{backgroundColor:"#0f172a",border:"1px solid rgba(148,163,184,0.2)",color:"#e2e8f0"}})]}),!e.stripe_customer_id&&t.jsx("div",{className:"text-xs rounded-lg px-3 py-2",style:{color:"#fbbf24",backgroundColor:"rgba(245,158,11,0.1)",border:"1px solid rgba(245,158,11,0.2)"},children:"â ï¸ No Stripe customer ID â save a payment method first"}),A&&t.jsx("div",{className:"text-xs rounded-lg px-3 py-2",style:{color:"#f87171",backgroundColor:"rgba(239,68,68,0.1)",border:"1px solid rgba(239,68,68,0.2)"},children:A}),t.jsxs("div",{className:"flex gap-2 justify-end pt-2",children:[t.jsx("button",{onClick:s,className:"text-xs px-3 py-1.5 rounded-lg text-slate-400 hover:text-slate-200",children:"Cancel"}),t.jsx("button",{onClick:_,disabled:m||!l||!p||!e.stripe_customer_id,className:"text-xs px-4 py-1.5 rounded-lg font-semibold disabled:opacity-50",style:{backgroundColor:"rgba(74,222,128,0.15)",color:"#4ade80",border:"1px solid rgba(74,222,128,0.3)"},children:m?"Charging...":`Charge ${p?Ci(parseFloat(p)):""}`})]})]})})}function qK(e){const n=new Date,r=new Date(n.getFullYear(),n.getMonth(),e);return r>n?r.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):new Date(n.getFullYear(),n.getMonth()+1,e).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}function DK({customerId:e,customer:n}){const r=rt(),{profile:s}=Ee(),{role:i}=rs(s==null?void 0:s.role),[o,a]=g.useState(null);g.useEffect(()=>{let H=!1;return(async()=>{try{const pe=await(await fetch("/api/stripe/publishable-key",{method:"POST",headers:await At()})).json();!H&&(pe!=null&&pe.publishable_key)&&a(Xf(pe.publishable_key))}catch{}})(),()=>{H=!0}},[s==null?void 0:s.tenant_id]);const l=yt.editMonthlyBilling(i),[d,c]=g.useState(null),[f,p]=g.useState(!1),[u,h]=g.useState(!1),[y,m]=g.useState(!1),[b,A]=g.useState(""),[v,x]=g.useState(""),[_,j]=g.useState(!1),[C,S]=g.useState(""),[T,L]=g.useState(!1),[E,R]=g.useState(""),[N,O]=g.useState(!1),[z,P]=g.useState(""),[D,M]=g.useState(!1),[k,q]=g.useState(""),[$,I]=g.useState(null),[B,J]=g.useState(""),[ae,te]=g.useState(!1),[U,W]=g.useState(""),{data:G=[],isLoading:V}=Ae({queryKey:["payment-methods",e],queryFn:()=>Zk(e)}),{data:ee=[],isLoading:re}=Ae({queryKey:["payment-transactions",e],queryFn:()=>dM(e)}),{data:Q=[]}=ig(e),oe=Q.find(H=>H.status==="active"),{data:ne=[]}=Ae({queryKey:["active-service-plans",e],queryFn:async()=>{try{const{data:H,error:de}=await w.from("customer_service_plans").select("id, price_monthly, billing_interval, next_billing_date, status, plan_id, tax_rate").eq("customer_id",e).eq("status","active").order("next_billing_date",{ascending:!0});if(de)throw de;const pe=(H||[]).map(Ie=>
1105Ie.plan_id).filter(Boolean);let Ne={};if(pe.length>0){const{data:Ie}=await w.from("service_plans").select("id, name").in("id",pe);for(const Ze of Ie||[])Ne[Ze.id]=Ze.name}return(H||[]).map(Ie=>({id:Ie.id,name:Ne[Ie.plan_id]||"Service Plan",price:Number(Ie.price_monthly)||0,billing_interval:Ie.billing_interval||"monthly",next_billing_date:Ie.next_billing_date,tax_rate:typeof Ie.tax_rate=="number"?Ie.tax_rate:.07}))}catch(H){return console.error("Failed to fetch active plans:",H),[]}}});function ge(){r.invalidateQueries({queryKey:["payment-methods",e]}),r.invalidateQueries({queryKey:["payment-transactions",e]}),r.invalidateQueries({queryKey:["rental-contracts",e]}),r.invalidateQueries({queryKey:["active-service-plans",e]})}async function be(){if(!oe)return;const H=parseFloat(C);if(isNaN(H)||H<=0){R("Enter a valid amount");return}L(!0),R("");try{const{error:de}=await w.from("contracts").update({monthly_amount:H}).eq("id",oe.id);if(de)throw de;j(!1),ge()}catch(de){R(de.message||"Failed to save")}finally{L(!1)}}async function we(){if(!oe)return;const H=parseInt(z,10);if(isNaN(H)||H<1||H>31){q("Enter a day between 1 and 31");return}M(!0),q("");try{const{error:de}=await w.from("contracts").update({billing_day:H}).eq("id",oe.id);if(de)throw de;O(!1),ge()}catch(de){q(de.message||"Failed to save")}finally{M(!1)}}async function F(H){const de=parseFloat(B);if(isNaN(de)||de<0){W("Enter a valid amount");return}te(!0),W("");try{const{error:pe}=await w.from("customer_service_plans").update({price_monthly:de}).eq("id",H);if(pe)throw pe;I(null),ge()}catch(pe){W(pe.message||"Failed to save")}finally{te(!1)}}async function K(){if(oe){m(!0),x(""),A("");try{const{url:H}=await Vk({amount_cents:Math.round(oe.monthly_amount*100),description:`Monthly rental â Contract ${oe.contract_number}`,customer_name:n.full_name,contract_number:oe.contract_number,customer_id:e,contract_id:oe.id});A(H)}catch(H){x(H.message)}finally{m(!1)}}}const Z=ee.filter(H=>H.status==="succeeded").reduce((H,de)=>H+Number(de.amount),0),ie=ee.filter(H=>H.status==="failed").slice(0,3),Y=[];if(oe!=null&&oe.monthly_amount&&(oe!=null&&oe.billing_day)){const H=typeof oe.tax_rate=="number"?oe.tax_rate:.07,de=parseFloat((oe.monthly_amount*(1+H)).toFixed(2));Y.push({label:`Rental â ${oe.contract_number}`,amount:de,date:qK(oe.billing_day),type:"rental"})}for(const H of ne)if(H.price>0){const de=typeof H.tax_rate=="number"?H.tax_rate:.07,pe=parseFloat((H.price*(1+de)).toFixed(2));Y.push({label:H.name,amount:pe,date:H.next_billing_date?new Date(H.next_billing_date+"T12:00:00").toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):"TBD",type:"plan",planId:H.id})}Y.sort((H,de)=>new Date(H.date).getTime()-new Date(de.date).getTime());const X=Y.reduce((H,de)=>H+de.amount,0);return o?t.jsxs(ag,{stripe:o,children:[t.jsxs("div",{className:"space-y-5",children:[t.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[t.jsx(Om,{label:"Total Collected",value:Ci(Z),color:"#4ade80"}),t.jsx(Om,{label:"Payment Methods",value:String(G.length),color:"#60a5fa",sub:G.find(H=>H.is_default)?`â¢â¢â¢â¢ ${G.find(H=>H.is_default).last_four} default`:"None on file"}),t.jsx(Om,{label:"Failed (recent)",value:String(ie.length),color:ie.length>0?"#f87171":"#4ade80",sub:ie.length>0?"Action required":"All clear"})]}),ie.length>0&&t.jsxs("div",{className:"rounded-xl p-4 space-y-2",style:{backgroundColor:"rgba(239,68,68,0.08)",border:"1px solid rgba(239,68,68,0.25)"},children:[t.jsx("div",{className:"text-xs font-bold uppercase tracking-wide",style:{color:"#f87171"},children:"â ï¸ Recent Failed Payments"}),ie.map(H=>t.jsxs("div",{className:"flex items-center justify-between text-xs",children:[t.jsx("span",{className:"text-slate-300",children:H.description||"Payment"}),t.jsxs("span",{style:{color:"#f87171"},children:[Ci(H.amount)," â ",H.failure_reason||"failed"]})]},H.id))]}),oe&&t.jsxs("div",{className:"bg-card border border-border rounded-xl p-4",children:[t.jsxs("div",{className:"flex items-center justify-between mb-3",children:[t.jsx("div",{className:"text-xs font-bold text-slate-300 uppercase tracking-wide",children:"Billing Plan"}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full font-semibold",style:{backgroundColor:oe.status==="active"?"rgba(74,222,128,0.12)":"rgba(239,68,68,0.12)",color:oe.status==="active"?"#4ade80":"#f87171",border:`1px solid ${oe.status==="active"?"rgba(74,222,128,0.25)":"rgba(239,68,68,0.25)"}`},children:oe.status==="active"?"Active":oe.status}),l&&(oe.status==="active"?t.jsx("button",{onClick:async()=>{confirm("Deactivate this contract? Autopay will stop.")&&(await w.from("contracts").update({status:"cancelled",cancelled_at:new Date().toISOString()}).eq("id",oe.id),w.from("customers").update({lifecycle_stage:"at_risk"}).eq("id",e).then(()=>{}).catch(()=>{}),w.auth.getSession().then(({data:{session:H}})=>{H!=null&&H.access_token&&fetch("/api/automations/trigger",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${(H==null?void 0:H.access_token)||""}`},body:JSON.stringify({key:"cancellation_at_risk_flag",to:"",entity_type:"customer",entity_id:e,tenant_id:(s==null?void 0:s.tenant_id)||null,variables:{}})})}).catch(()=>{}),ge())},className:"text-xs px-2 py-0.5 rounded-lg font-semibold transition-colors",style:{backgroundColor:"rgba(239,68,68,0.10)",color:"#f87171",border:"1px solid rgba(239,68,68,0.25)"},children:"Deactivate"}):t.jsx("button",{onClick:async()=>{await w.from("contracts").update({status:"active",signed_at:new Date().toISOString()}).eq("id",oe.id),ge()},className:"text-xs px-2 py-0.5 rounded-lg font-semibold transition-colors",style:{backgroundColor:"rgba(74,222,128,0.10)",color:"#4ade80",border:"1px solid rgba(74,222,128,0.25)"},children:"Activate"}))]})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsxs("div",{className:"flex items-center justify-between text-xs",children:[t.jsx("span",{className:"text-slate-400",children:"Contract"}),t.jsx("span",{className:"text-slate-200 font-medium",children:oe.contract_number})]}),t.jsxs("div",{className:"flex items-center justify-between text-xs",children:[t.jsx("span",{className:"text-slate-400",children:"Start date"}),t.jsx("span",{className:"text-slate-200 font-medium",children:oe.start_date?new Date(oe.start_date.length===10?oe.start_date+"T12:00:00":oe.start_date).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):"â"})]}),t.jsxs("div",{className:"flex items-center justify-between text-xs",children:[t.jsx("span",{className:"text-slate-400",children:"End date"}),t.jsx("span",{className:"text-slate-200 font-medium",children:oe.end_date?new Date(oe.end_date.length===10?oe.end_date+"T12:00:00":oe.end_date).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):"â"})]}),t.jsxs("div",{className:"flex items-center justify-between text-xs",children:[t.jsx("span",{className:"text-slate-400",children:"Charges on"}),N?t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("input",{type:"number",min:1,max:31,value:z,onChange:H=>P(H.target.value),autoFocus:!0,className:"w-14 text-sm rounded-lg px-2 py-1 outline-none text-right",style:{backgroundColor:"#0f172a",border:"1px solid rgba(96,165,250,0.4)",color:"#e2e8f0"}}),t.jsx("span",{className:"text-slate-400",children:"of month"}),t.jsx("button",{onClick:we,disabled:D,className:"text-xs px-2 py-1 rounded-lg font-semibold disabled:opacity-50",style:{backgroundColor:"rgba(74,222,128,0.15)",color:"#4ade80",border:"1px solid rgba(74,222,128,0.3)"},children:D?"â¦":"Save"}),t.jsx("button",{onClick:()=>{O(!1),q("")},className:"text-xs text-slate-400 hover:text-slate-200",children:"Cancel"})]}):t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{className:"text-slate-200 font-medium",children:oe.billing_day?`${oe.billing_day===1?"1st":oe.billing_day===2?"2nd":oe.billing_day===3?"3rd":`${oe.b
1105illing_day}th`} of each month`:"Not set"}),l&&t.jsx("button",{onClick:()=>{P(String(oe.billing_day??"")),O(!0),q("")},className:"text-muted hover:text-slate-300 transition-colors",title:"Edit billing day",style:{lineHeight:1},children:"âï¸"})]})]}),k&&t.jsx("div",{className:"text-xs rounded-lg px-2 py-1",style:{color:"#f87171",backgroundColor:"rgba(239,68,68,0.08)",border:"1px solid rgba(239,68,68,0.2)"},children:k}),t.jsxs("div",{className:"flex items-center justify-between text-xs",children:[t.jsx("span",{className:"text-slate-400",children:"Monthly amount"}),_?t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{className:"text-slate-400",children:"$"}),t.jsx("input",{type:"number",step:"0.01",value:C,onChange:H=>S(H.target.value),autoFocus:!0,className:"w-20 text-sm rounded-lg px-2 py-1 outline-none text-right",style:{backgroundColor:"#0f172a",border:"1px solid rgba(96,165,250,0.4)",color:"#e2e8f0"}}),t.jsx("button",{onClick:be,disabled:T,className:"text-xs px-2 py-1 rounded-lg font-semibold disabled:opacity-50",style:{backgroundColor:"rgba(74,222,128,0.15)",color:"#4ade80",border:"1px solid rgba(74,222,128,0.3)"},children:T?"â¦":"Save"}),t.jsx("button",{onClick:()=>{j(!1),R("")},className:"text-xs text-slate-400 hover:text-slate-200",children:"Cancel"})]}):t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsxs("span",{className:"text-white font-semibold",children:[Ci(oe.monthly_amount),"/mo"]}),l&&t.jsx("button",{onClick:()=>{S(String(oe.monthly_amount)),j(!0),R("")},className:"text-muted hover:text-slate-300 transition-colors",title:"Edit monthly amount",style:{lineHeight:1},children:"âï¸"})]})]}),E&&t.jsx("div",{className:"text-xs rounded-lg px-2 py-1",style:{color:"#f87171",backgroundColor:"rgba(239,68,68,0.08)",border:"1px solid rgba(239,68,68,0.2)"},children:E})]})]}),Y.length>0&&t.jsxs("div",{className:"bg-card border border-border rounded-xl p-4",children:[t.jsxs("div",{className:"flex items-center justify-between mb-3",children:[t.jsx("div",{className:"text-xs font-bold text-slate-300 uppercase tracking-wide",children:"Upcoming Charges"}),t.jsx("div",{className:"text-xs font-semibold",style:{color:"#fbbf24"},children:(()=>{const H=!!oe,de=ne.some(Ne=>Ne.billing_interval==="monthly"),pe=!H&&!de?"/yr":"/mo";return`${Ci(X)}${pe} total`})()})]}),t.jsxs("div",{className:"space-y-2",children:[Y.map((H,de)=>t.jsxs("div",{className:"flex items-center justify-between py-1.5 border-b last:border-0",style:{borderColor:"rgba(148,163,184,0.08)"},children:[t.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[t.jsx("span",{className:"text-xs flex-shrink-0",style:{color:H.type==="rental"?"#0ea5e9":"#a855f7"},children:H.type==="rental"?"ð":"ð§"}),t.jsx("span",{className:"text-xs truncate",style:{color:"#e2e8f0"},children:H.label})]}),t.jsxs("div",{className:"flex items-center gap-3 flex-shrink-0 ml-3",children:[t.jsx("span",{className:"text-xs",style:{color:"#64748b"},children:H.date}),H.type==="plan"&&H.planId&&$===H.planId?t.jsxs("div",{className:"flex items-center gap-1",children:[t.jsx("span",{className:"text-xs text-slate-400",children:"$"}),t.jsx("input",{type:"number",step:"0.01",value:B,onChange:pe=>J(pe.target.value),autoFocus:!0,className:"w-16 text-xs rounded px-1.5 py-0.5 outline-none text-right",style:{backgroundColor:"#0f172a",border:"1px solid rgba(168,85,247,0.4)",color:"#e2e8f0"}}),t.jsx("button",{onClick:()=>F(H.planId),disabled:ae,className:"text-xs px-1.5 py-0.5 rounded font-semibold disabled:opacity-50",style:{backgroundColor:"rgba(74,222,128,0.15)",color:"#4ade80",border:"1px solid rgba(74,222,128,0.3)"},children:ae?"â¦":"Save"}),t.jsx("button",{onClick:()=>{I(null),W("")},className:"text-xs text-slate-400 hover:text-slate-200",children:"â"})]}):t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx("span",{className:"text-xs font-semibold",style:{color:H.type==="rental"?"#0ea5e9":"#a855f7"},children:Ci(H.amount)}),H.type==="plan"&&H.planId&&l&&t.jsx("button",{onClick:()=>{J(String(H.amount)),I(H.planId),W("")},className:"text-muted hover:text-slate-300 transition-colors",title:"Edit plan price",style:{lineHeight:1,fontSize:11},children:"âï¸"})]})]})]},de)),U&&t.jsx("div",{className:"text-xs rounded px-2 py-1 mt-1",style:{color:"#f87171",backgroundColor:"rgba(239,68,68,0.08)",border:"1px solid rgba(239,68,68,0.2)"},children:U})]})]}),t.jsxs("div",{className:"bg-card border border-border rounded-xl p-4",children:[t.jsxs("div",{className:"flex items-center justify-between mb-3",children:[t.jsx("div",{className:"text-xs font-bold text-slate-300 uppercase tracking-wide",children:"Payment Methods"}),t.jsxs("div",{className:"flex gap-2",children:[G.length>0&&t.jsx("button",{onClick:()=>p(!0),className:"text-xs px-3 py-1 rounded-lg font-semibold",style:{backgroundColor:"rgba(74,222,128,0.12)",color:"#4ade80",border:"1px solid rgba(74,222,128,0.25)"},children:"ð³ Charge"}),t.jsx("button",{onClick:()=>h(!0),className:"text-xs px-3 py-1 rounded-lg font-semibold",style:{backgroundColor:"rgba(96,165,250,0.12)",color:"#60a5fa",border:"1px solid rgba(96,165,250,0.25)"},children:"ð³ New card & charge"}),!d&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:()=>c("bank"),className:"text-xs px-3 py-1 rounded-lg font-semibold",style:{backgroundColor:"rgba(74,222,128,0.10)",color:"#4ade80",border:"1px solid rgba(74,222,128,0.22)"},children:"+ Bank (ACH)"}),t.jsx("button",{onClick:()=>c("card"),className:"text-xs px-3 py-1 rounded-lg font-semibold",style:{backgroundColor:"rgba(96,165,250,0.12)",color:"#60a5fa",border:"1px solid rgba(96,165,250,0.25)"},children:"+ Card"})]})]})]}
1105),d==="card"&&t.jsx("div",{className:"mb-3",children:t.jsx(RK,{customerId:e,customer:n,onSuccess:()=>{c(null),ge()},onCancel:()=>c(null)})}),d==="bank"&&t.jsx("div",{className:"mb-3",children:t.jsx(EK,{customerId:e,customer:n,onSuccess:()=>{c(null),ge()},onCancel:()=>c(null)})}),V?t.jsx("div",{className:"text-xs text-muted py-3",children:"Loading..."}):G.length===0?t.jsx("div",{className:"text-xs text-muted italic py-2",children:"No payment methods on file"}):t.jsx("div",{className:"space-y-2",children:G.map(H=>t.jsx(OK,{pm:H,onSetDefault:async()=>{await cM(e,H.id),ge()},onRemove:async()=>{await uM(H.id),ge()}},H.id))})]}),oe&&t.jsxs("div",{className:"bg-card border border-border rounded-xl p-4",children:[t.jsx("div",{className:"text-xs font-bold text-slate-300 uppercase tracking-wide mb-3",children:"Invoice Payment Link"}),t.jsxs("p",{className:"text-xs text-slate-400 mb-3",children:["Generate a Stripe-hosted payment link for ",Ci(oe.monthly_amount)," â Contract ",oe.contract_number]}),b?t.jsxs("div",{className:"space-y-2",children:[t.jsxs("div",{className:"flex items-center gap-2 rounded-lg px-3 py-2",style:{backgroundColor:"rgba(74,222,128,0.08)",border:"1px solid rgba(74,222,128,0.2)"},children:[t.jsx("span",{className:"text-xs text-slate-300 truncate flex-1",children:b}),t.jsx("button",{onClick:()=>navigator.clipboard.writeText(b),className:"text-xs font-semibold flex-shrink-0",style:{color:"#4ade80"},children:"Copy"}),t.jsx("a",{href:b,target:"_blank",rel:"noopener noreferrer",className:"text-xs font-semibold flex-shrink-0",style:{color:"#60a5fa"},children:"Open â"})]}),t.jsx("button",{onClick:()=>A(""),className:"text-xs text-muted hover:text-slate-300",children:"Generate new link"})]}):t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:K,disabled:y,className:"text-xs px-4 py-1.5 rounded-lg font-semibold disabled:opacity-50",style:{backgroundColor:"rgba(56,189,248,0.12)",color:"#38bdf8",border:"1px solid rgba(56,189,248,0.25)"},children:y?"Generating...":"ð Generate Payment Link"}),v&&t.jsx("p",{className:"text-xs mt-2",style:{color:"#f87171"},children:v})]})]}),t.jsxs("div",{className:"bg-card border border-border rounded-xl p-4",children:[t.jsxs("div",{className:"text-xs font-bold text-slate-300 uppercase tracking-wide mb-3",children:["Transaction History ",ee.length>0&&t.jsxs("span",{className:"text-muted font-normal",children:["(",ee.length,")"]})]}),re?t.jsx("div",{className:"text-xs text-muted py-3",children:"Loading..."}):ee.length===0?t.jsx("div",{className:"text-xs text-muted italic",children:"No transactions yet"}):t.jsx("div",{className:"space-y-1 max-h-72 overflow-y-auto",children:ee.map(H=>t.jsx(IK,{tx:H},H.id))})]})]}),u&&t.jsx(S3,{customer:n,stripePromise:o,onClose:()=>h(!1),onSuccess:()=>{h(!1),ge()}}),f&&t.jsx(PK,{customer:n,paymentMethods:G,contracts:Q,onClose:()=>p(!1),onSuccess:()=>{p(!1),ge()}})]}):t.jsx("div",{className:"text-sm text-slate-400 p-4",children:"Loading payment formâ¦"})}function Om({label:e,value:n,color:r,sub:s}){return t.jsxs("div",{className:"bg-card border border-border rounded-xl p-3",children:[t.jsx("div",{className:"text-xs text-muted uppercase tracking-wide mb-1",children:e}),t.jsx("div",{className:"text-lg font-bold",style:{color:r},children:n}),s&&t.jsx("div",{className:"text-xs text-muted mt-0.5",children:s})]})}function OK({pm:e,onSetDefault:n,onRemove:r}){const s=e.type==="us_bank_account",i=e.status==="pending_verification";return t.jsxs("div",{className:"flex items-center justify-between px-3 py-2.5 rounded-lg",style:{backgroundColor:e.is_default?"rgba(96,165,250,0.08)":"rgba(148,163,184,0.05)",border:`1px solid ${i?"rgba(251,191,36,0.3)":e.is_default?"rgba(96,165,250,0.2)":"rgba(148,163,184,0.12)"}`},children:[t.jsxs("div",{className:"flex items-center gap-3",children:[t.jsx("span",{className:"text-base",children:s?"ð¦":"ð³"}),t.jsxs("div",{children:[t.jsxs("div",{className:"text-sm text-slate-200 font-medium",children:["â¢â¢â¢â¢ ",e.last_four]}),t.jsx("div",{className:"text-xs text-muted",children:s?"ACH Bank Account":`Expires ${e.exp_month}/${e.exp_year}`})]}),e.is_default&&!i&&t.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded-full font-semibold",style:{backgroundColor:"rgba(96,165,250,0.15)",color:"#60a5fa"},children:"Default"}),i&&t.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded-full font-semibold",style:{backgroundColor:"rgba(251,191,36,0.15)",color:"#fbbf24"},children:"Pending Verification"})]}),t.jsxs("div",{className:"flex gap-2",children:[!e.is_default&&!i&&t.jsx("button",{onClick:n,className:"text-xs text-muted hover:text-slate-200 transition-colors",children:"Set default"}),t.jsx("button",{onClick:r,className:"text-xs hover:text-red-400 transition-colors",style:{color:"#64748b"},children:"Remove"})]})]})}function IK({tx:e}){const r={succeeded:"#4ade80",failed:"#f87171",pending:"#fbbf24",refunded:"#94a3b8"}[e.status]||"#94a3b8";return t.jsxs("div",{className:"flex items-center justify-between py-2 border-b last:border-0",style:{borderColor:"rgba(148,163,184,0.1)"},children:[t.jsxs("div",{className:"flex-1 min-w-0",children:[t.jsx("div",{className:"text-xs text-slate-300 truncate",children:e.description||"Payment"}),t.jsx("div",{className:"text-xs text-muted",children:new Date(e.created_at||e.processed_at).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})})]}),t.jsxs("div",{className:"text-right flex-shrink-0 ml-4",children:[t.jsxs("div",{className:"text-sm font-semibold",style:{color:r},children:[e.status==="refunded"?"-":"",Ci(e.amount)]}),t.jsx("div",{className:"text-xs capitalize",style:{color:r},children:e.status})]})]})}const LK={sent:{icon:"â",label:"Sent",color:"#60a5fa"},viewed:{icon:"ð",label:"Opened",color:"#34d399"},signed:{icon:"â",label:"Signed",color:"#38bdf8"},accepted:{icon:"â",label:"Accepted",color:"#4ade80"},declined:{icon:"â",label:"Declined",color:"#f87171"}};function WK(e){return new Date(e).toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function Wy({quoteId:e}){const[n,r]=g.useState(null);return g.useEffect(()=>{let s=!0;return W8(e).then(i=>{s&&r(i)}),()=>{s=!1}},[e]),n===null?t.jsx("div",{style:{fontSize:12,color:"#64748b",padding:"8px 0"},children:"Loading activity\\u2026"}):n.length===0?t.jsx("div",{style:{fontSize:12,color:"#64748b",padding:"8px 0"},children:"No activity recorded yet."}):t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6,paddingTop:4},children:n.map((s,i)=>{const o=LK[s.event]||{icon:"â¢",label:s.event,color:"#94a3b8"};return t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:12},children:[t.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:18,height:18,borderRadius:9,fontSize:10,background:o.color+"22",color:o.color,flexShrink:0},children:o.icon}),t.jsx("span",{style:{color:"#e2e8f0",fontWeight:600},children:o.label}),s.actor_type&&t.jsxs("span",{style:{color:"#64748b",fontSize:11},children:["by ",s.actor_type]}),t.jsx("span",{style:{color:"#64748b",marginLeft:"auto"},children:WK(s.created_at)})]},i)})})}function $K(e){return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}).format(e)}function Dp(e){return e?new Date(e).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):"â"}function MK({customerId:e,customerName:n,customerAddress:r,customerPhone:s}){const[i,o]=g.useState([]),[a,l]=g.useState(!0),[d,c]=g.useState("list"),[f,p]=g.useState(null),[u,h]=g.useState(null);g.useEffect(()=>{y()},[e]);async function y(){l(!0);try{const b=await rg(e);o(b)}catch(b){console.error(b)}finally{l(!1)}}if(d==="create"||d==="edit")return t.jsx("div",{style:{margin:"-16px"},children:t.jsx(W0,{customerId:e,customerName:n,customerAddress:r,customerPhone:s,existingQuote:d==="edit"?f:null,onSaved:()=>{y(),c("list"),p(null)},onCancel:()=>{c("list"),p(null)}})});i.some(b=>b.status==="draft");const m=i.some(b=>b.status==="accepted"||b.status==="signed");return t.jsxs("div",{children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:16},children:[t.jsxs("div",{children:[t.jsxs("span",{style:{color:"#94a3b8",fontSize:13},children:[i.length," quote",i.length!==1?"s":""]}),m&&t.jsx("span",{style:{marginLeft:10,fontSize:12,color:"#4ade80",background:"#14532d",padding:"2px 8px",borderRadius:6,fontWeight:600},children:"â Accepted"})]}),t.jsx("button",{onClick:()=>c("create"),style:{padding:"8px 18px",borderRadius:8,border:"none",cursor:"pointer",background:"#0d7ea3",color:"#fff",fontWeight:700,fontSize:13},children:"+ New Quote"})]}),a?t.jsx("div",{style:{padding:32,textAlign:"center",color:"#64748b"},children:"Loadingâ¦"}):i.length===0?t.jsxs("div",{style:{textAlign:"center",padding:"40px 20px",background:"#0f1923",borderRadius:10,border:"1px dashed #1e3a4f"},children:[t.jsx("div",{style:{fontSize:32,marginBottom:10},children:"ð"}),t.jsx("div",{style:{color:"#64748b",fontSize:13,marginBottom:16},children:"No quotes for this customer yet"}),t.jsx("button",{onClick:()=>c("create"),style:{padding:"9px 22px",borderRadius:8,border:"none",cursor:"pointer",background:"#0d7ea3",color:"#fff",fontWeight:700,fontSize:13},children:"Create Quote"})]}):t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:i.map(b=>{const A=uf[b.status]||{bg:"#1e293b",text:"#94a3b8"},v=hf[b.commercial_type]||"#94a3b8",x=b.status==="draft",_=b.status==="accepted"||b.status==="signed";return t.jsxs("div",{style:{background:"#0f1923",border:"1px solid",borderColor:_?"#166534":"#1e3a4f",borderRadius:10,padding:"14px 16px",cursor:"pointer",transition:"border-color 0.15s"},onClick:()=>{p(b),c("edit")},onMouseEnter:j=>j.currentTarget.style.borderColor="#0d7ea3",onMouseLeave:j=>j.currentTarget.style.borderColor=_?"#166534":"#1e3a4f",children:[t.jsxs("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:12},children:[t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:4},children:[t.jsx("span",{style:{color:"#60a5fa",fontWeight:700,fontSize:13,fontFamily:"monospace"},children:b.quote_number}),t.jsx("span",{style:{fontSize:11,fontWeight:700,color:v,background:v+"22",padding:"2px 7px",borderRadius:5},children:pf[b.commercial_type]}),t.jsx("span",{style:{fontSize:11,fontWeight:700,color:A.text,background:A.bg,padding:"2px 7px",borderRadius:5},children:cf[b.status]})]}),t.jsxs("div",{style:{display:"flex",gap:16,color:"#64748b",fontSize:12},children:[t.jsxs("span",{children:["Expires ",Dp(b.valid_until||null)]}),t.jsxs("span",{children:["Created ",Dp(b.created_at)]}),b.sent_at&&t.jsxs("span",{children:["Sent ",Dp(b.sent_at)]}),b.accepted_at&&t.jsxs("span",{style:{color:"#4ade80"},children:["â Accepted ",Dp(b.accepted_at)]})]})]}),t.jsxs("div",{style:{textAlign:"right",flexShrink:0},children:[t.jsx("div",{style:{color:"#e2e8f0",fontWeight:800,fontSize:16},children:$K(b.total)}),t.jsx("div",{style:{color:"#64748b",fontSize:11},children:"incl. tax"})]})]}),t.jsxs("div",{style:{display:"flex",gap:6,marginTop:10},onClick:j=>j.stopPropagation(),children:[x&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:()=>{p(b),c("edit")},style:{padding:"5px 12px",borderRadius:6,border:"1px solid #1e3a4f",background:"transparent",color:"#94a3b8",curs
1105or:"pointer",fontSize:12},children:"Edit"}),t.jsx("button",{onClick:async()=>{confirm("Mark as sent? Snapshot will be frozen.")&&(await _u(b.id),y())},style:{padding:"5px 12px",borderRadius:6,border:"1px solid #0d7ea3",background:"transparent",color:"#22d3ee",cursor:"pointer",fontSize:12,fontWeight:600},children:"Send"})]}),t.jsxs("button",{onClick:()=>h(u===b.id?null:b.id),style:{padding:"5px 12px",borderRadius:6,border:"1px solid #1e3a4f",background:u===b.id?"#13233a":"transparent",color:"#94a3b8",cursor:"pointer",fontSize:12},children:["ð Activity",(b.view_count||0)>0?` (${b.view_count})`:""]}),t.jsx("button",{onClick:()=>{p(b),c("edit")},style:{padding:"5px 12px",borderRadius:6,border:"1px solid #1e3a4f",background:"transparent",color:"#60a5fa",cursor:"pointer",fontSize:12},children:"ð Preview"})]}),u===b.id&&t.jsx("div",{onClick:j=>j.stopPropagation(),style:{marginTop:10,paddingTop:10,borderTop:"1px solid #1e3a4f"},children:t.jsx(Wy,{quoteId:b.id})})]},b.id)})})]})}function FK({customerId:e}){const{profile:n}=Ee(),r=(n==null?void 0:n.role)||"",s=yt.addServicePlans(r),i=yt.pauseServicePlans(r),o=yt.cancelServicePlans(r),a=yt.overridePlanPrice(r),l=yt.editReminders(r),[d,c]=g.useState([]),[f,p]=g.useState({}),[u,h]=g.useState(!0),[y,m]=g.useState(!1),[b,A]=g.useState(null),[v,x]=g.useState(null);g.useEffect(()=>{_()},[e]);async function _(){h(!0);try{const R=await WW(e);c(R);const N=R.filter(z=>["active","pending_payment_method","paused","payment_failed"].includes(z.status)).map(z=>z.id),O={};await Promise.all(N.map(async z=>{try{O[z]=await KW(z)}catch{O[z]=[]}})),p(O)}catch(R){console.error("Failed to load service plans:",R)}h(!1)}async function j(R,N){const O=N.trim(),z=O===""?null:parseInt(O,10);if(z!==null&&(isNaN(z)||z<0)){alert("Reminder days must be a positive number, or blank for no reminder."),_();return}if(z!==(R.reminder_days_before??null)){x(R.id);try{await YW(R.id,z),p(P=>{const D={};for(const[M,k]of Object.entries(P))D[M]=k.map(q=>q.id===R.id?{...q,reminder_days_before:z}:q);return D})}catch(P){alert("Failed to save reminder timing: "+P.message),_()}x(null)}}async function C(R){const N=prompt("Reason for pausing (optional):");if(N!==null){A(R.id);try{await FW(R.id,N||void 0),_()}catch(O){alert("Failed to pause: "+O.message)}A(null)}}async function S(R){A(R.id);try{await BW(R.id),_()}catch(N){alert("Failed to resume: "+N.message)}A(null)}async function T(R){const N=prompt("Reason for cancellation:");if(N&&confirm(`Cancel "${R.plan_name}"? This cannot be undone.`)){A(R.id);try{await UW(R.id,N),_()}catch(O){alert("Failed to cancel: "+O.message)}A(null)}}const L=d.filter(R=>["active","pending_payment_method","pending_install","paused","payment_failed"].includes(R.status)),E=d.filter(R=>["cancelled","completed","expired"].includes(R.status));return u?t.jsx("div",{style:{textAlign:"center",color:"#64748b",padding:"48px 0"},children:"Loading service plans..."}):t.jsxs("div",{children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:16},children:[t.jsxs("div",{children:[t.jsx("h2",{style:{color:"#e2e8f0",fontWeight:700,fontSize:16,margin:0},children:"Service Plans"}),t.jsxs("p",{style:{color:"#64748b",fontSize:12,marginTop:4},children:[L.length," active plan",L.length!==1?"s":"",E.length>0&&` · ${E.length} past`]})]}),s&&t.jsx("button",{onClick:()=>m(!0),style:{padding:"8px 18px",borderRadius:10,fontSize:13,fontWeight:700,background:"linear-gradient(135deg, #f59e0b, #d97706)",color:"#fff",border:"none",cursor:"pointer"},children:"+ Add Service Plan"})]}),y&&t.jsx(BK,{customerId:e,canOverridePrice:a,onClose:()=>m(!1),onAdded:()=>{m(!1),_()}}),L.length===0&&E.length===0?t.jsxs("div",{style:{textAlign:"center",padding:"48px 0"},children:[t.jsx("div",{style:{fontSize:40,marginBottom:12},children:"ð"}),t.jsx("p",{style:{color:"#64748b",fontSize:14},children:"No service plans yet."}),s&&t.jsx("p",{style:{color:"#64748b",fontSize:12,marginTop:4},children:'Click "+ Add Service Plan" to enroll this customer.'})]}):t.jsxs(t.Fragment,{children:[L.length>0&&t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:10,marginBottom:E.length>0?24:0},children:L.map(R=>{const N=fp[R.status]||fp.active,O=b===R.id,z=f[R.id]||[];return t.jsxs("div",{style:{background:"#162232",border:"1px solid #1e3a4f",borderRadius:14,padding:16},children:[t.jsxs("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:12},children:[t.jsxs("div",{style:{flex:1},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[t.jsx("span",{style:{color:"#e2e8f0",fontWeight:700,fontSize:14},children:R.plan_name}),t.jsx("span",{style:{fontSize:11,padding:"2px 10px",borderRadius:20,fontWeight:700,background:N.bgColor,color:N.color,border:`1px solid ${N.c
1105olor}30`},children:N.label}),R.source==="auto_install"&&t.jsx("span",{style:{fontSize:10,padding:"2px 8px",borderRadius:20,background:"rgba(245,158,11,0.1)",color:"#f59e0b",border:"1px solid rgba(245,158,11,0.25)"},children:"Auto-enrolled"})]}),R.notes&&t.jsx("div",{style:{fontSize:11,color:"#64748b",marginTop:4},children:R.notes})]}),t.jsxs("div",{style:{textAlign:"right",flexShrink:0},children:[t.jsxs("div",{style:{color:"#e2e8f0",fontWeight:700,fontSize:16,fontFamily:"monospace"},children:["$",Number(R.price_monthly).toFixed(2)]}),t.jsx("div",{style:{color:"#64748b",fontSize:10},children:ya[R.billing_interval]||""})]})]}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(4, 1fr)",gap:12,marginTop:12},children:[t.jsx(Op,{label:"Fulfillment",value:td[R.plan_fulfillment_type||""]||"â"}),t.jsx(Op,{label:"Started",value:sr(R.activated_at)}),t.jsx(Op,{label:"Next Billing",value:dn(R.next_billing_date)}),t.jsx(Op,{label:"Next Service",value:(()=>{const D=(f[R.id]||[]).filter(M=>M.next_due_date&&M.status==="active").map(M=>M.next_due_date).sort()[0];return dn(D)})()})]}),R.status==="pending_payment_method"&&t.jsxs("div",{style:{marginTop:10,padding:"8px 12px",borderRadius:8,fontSize:12,background:"rgba(251,191,36,0.06)",border:"1px solid rgba(251,191,36,0.2)",color:"#fbbf24",display:"flex",alignItems:"center",gap:6},children:[t.jsx("span",{children:"ð³"}),t.jsx("span",{children:"Card required to start billing. Save a payment method to activate."})]}),R.status==="payment_failed"&&t.jsxs("div",{style:{marginTop:10,padding:"8px 12px",borderRadius:8,fontSize:12,background:"rgba(248,113,113,0.06)",border:"1px solid rgba(248,113,113,0.2)",color:"#f87171",display:"flex",alignItems:"center",gap:6},children:[t.jsx("span",{children:"â ï¸"}),t.jsxs("span",{children:["Payment failed ",R.failed_billing_count," time",R.failed_billing_count!==1?"s":"",". Update card to resume billing."]})]}),z.length>0&&t.jsxs("div",{style:{marginTop:12,padding:"10px 12px",background:"rgba(56,189,248,0.04)",border:"1px solid rgba(56,189,248,0.12)",borderRadius:10},children:[t.jsx("div",{style:{fontSize:10,color:"#38bdf8",fontWeight:700,textTransform:"uppercase",letterSpacing:"0.05em",marginBottom:8},children:"Service Schedule"}),t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:z.map(P=>t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[t.jsx("span",{style:{fontSize:12},children:P.fulfillment_type==="tech_visit"?"ð§":P.fulfillment_type==="shipment"?"ð¦":P.fulfillment_type==="delivery"?"ð":"ð"}),t.jsx("span",{style:{fontSize:12,color:"#e2e8f0"},children:P.label}),t.jsx("span",{style:{fontSize:10,color:"#64748b"},children:P.interval_months?`· every ${P.interval_months} mo`:"· on-demand"})]}),t.jsxs("div",{style:{display:"flex",gap:12,alignItems:"center"},children:[P.last_completed_at&&t.jsxs("span",{style:{fontSize:10,color:"#64748b"},children:["Last: ",sr(P.last_completed_at)]}),l?t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},title:"Remind this customer this many days before the due date. Blank = no reminder.",children:[t.jsx("span",{style:{fontSize:10,color:P.reminder_days_before!=null?"#38bdf8":"#475569"},children:"ð"}),t.jsx("input",{type:"number",min:"0",defaultValue:P.reminder_days_before??"",placeholder:"â",disabled:v===P.id,onBlur:D=>j(P,D.target.value),onKeyDown:D=>{D.key==="Enter"&&D.target.blur()},style:{width:42,background:"rgba(255,255,255,0.05)",border:"1px solid #1e3a4f",borderRadius:4,padding:"2px 4px",color:"#e2e8f0",fontSize:10,outline:"none",textAlign:"center",opacity:v===P.id?.5:1}}),t.jsx("span",{style:{fontSize:9,color:"#475569"},children:"d before"})]}):P.reminder_days_before!=null&&t.jsxs("span",{style:{fontSize:10,color:"#64748b"},children:["ð ",P.reminder_days_before,"d before"]}),t.jsx("span",{style:{fontSize:11,fontWeight:600,color:P.next_due_date?new Date(P.next_due_date+"T12:00:00")<new Date?"#f87171":"#4ade80":"#64748b"},children:P.next_due_date?`Due ${dn(P.next_due_date)}`:"â"})]})]},P.id))})]}),t.jsxs("div",{style:{display:"flex",gap:8,marginTop:12},children:[R.status==="active"&&i&&t.jsx(Im,{label:O?"...":"Pause",color:"#fbbf24",onClick:()=>C(R),disabled:O}),R.status==="paused"&&i&&t.jsx(Im,{label:O?"...":"Resume",color:"#4ade80",onClick:()=>S(R),disabled:O}),o&&!["cancelled","completed","expired"].includes(R.status)&&t.jsx(Im,{label:O?"...":"Cancel",color:"#f87171",onClick:()=>T(R),disabled:O})]})]},R.id)})}),E.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{style:{color:"#64748b",fontSize:11,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:8},children:"Past Plans"}),t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:E.map(R=>{const N=fp[R.status]||fp.cancelled;return t.jsxs("div",{style:{background:"#162232",border:"1px solid #1e3a4f",borderRadius:10,padding:"10px 14px",opacity:.5},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[t.jsx("span",{style:{color:"#e2e8f0",fontWeight:600,fontSize:13},children:R.plan_name}),t.jsx("span",{style:{fontSize:10,padding:"2px 8px",borderRadius:20,fontWeight:700,background:N.bgColor,color:N.color},children:N.label})]}),t.jsx("span",{style:{color:"#64748b",fontSize:11}
1105,children:R.cancelled_at?`Cancelled ${sr(R.cancelled_at)}`:sr(R.activated_at)})]}),R.cancel_reason&&t.jsxs("div",{style:{fontSize:11,color:"#64748b",marginTop:4},children:["Reason: ",R.cancel_reason]})]},R.id)})})]})]})]})}function Op({label:e,value:n}){return t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:10,color:"#64748b",textTransform:"uppercase",letterSpacing:"0.05em",marginBottom:2},children:e}),t.jsx("div",{style:{fontSize:12,color:"#e2e8f0",fontWeight:500},children:n})]})}function Im({label:e,color:n,onClick:r,disabled:s}){return t.jsx("button",{onClick:r,disabled:s,style:{padding:"5px 14px",borderRadius:8,fontSize:12,fontWeight:600,cursor:s?"not-allowed":"pointer",background:`${n}12`,color:n,border:`1px solid ${n}30`,opacity:s?.5:1},children:e})}function BK({customerId:e,canOverridePrice:n,onClose:r,onAdded:s}){const[i,o]=g.useState([]),[a,l]=g.useState([]),[d,c]=g.useState(!1),[f,p]=g.useState(!0),[u,h]=g.useState(!1),[y,m]=g.useState(""),[b,A]=g.useState(""),[v,x]=g.useState(""),[_,j]=g.useState(""),[C,S]=g.useState("immediate"),[T,L]=g.useState("");g.useEffect(()=>{async function P(){p(!0);try{const[D,M,k]=await Promise.all([b0(!0),f8(e),Dk(e)]);o(D),l((M||[]).filter(q=>q.is_active!==!1)),c(k)}catch(D){console.error("Failed to load modal data:",D)}p(!1)}P()},[e]);const E=i.find(P=>P.id===b),R=(E==null?void 0:E.requires_installed_system)??!0,N=E&&Array.isArray(E.applies_to_categories)&&E.applies_to_categories.length>0?a.filter(P=>E.applies_to_categories.includes(P.commercial_type||P.system_name)):a;async function O(){if(!b){m("Select a plan");return}if(R&&!v){m("Select an installed system");return}h(!0),m("");try{await MW({customer_id:e,plan_id:b,installed_system_id:R?v:null,price_override:_?parseFloat(_):null,billing_start:C,notes:T.trim()||void 0}),s()}catch(P){m(P.message||"Failed to activate plan")}h(!1)}const z={width:"100%",boxSizing:"border-box",background:"rgba(255,255,255,0.05)",border:"1px solid #1e3a4f",borderRadius:10,padding:"9px 14px",color:"#e2e8f0",fontSize:13,outline:"none"};return t.jsx("div",{style:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"rgba(0,0,0,0.6)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},onClick:r,children:t.jsxs("div",{style:{background:"#162232",border:"1px solid #1e3a4f",borderRadius:16,width:480,maxHeight:"80vh",overflow:"auto",padding:24},onClick:P=>P.stopPropagation(),children:[t.jsx("h3",{style:{color:"#e2e8f0",fontWeight:700,fontSize:16,marginBottom:16},children:"Add Service Plan"}),f?t.jsx("div",{style:{textAlign:"center",color:"#64748b",padding:24},children:"Loading..."}):t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:14},children:[y&&t.jsx("div",{style:{background:"rgba(248,113,113,0.08)",border:"1px solid rgba(248,113,113,0.3)",borderRadius:10,padding:"8px 14px",fontSize:12,color:"#f87171"},children:y}),t.jsxs("div",{children:[t.jsx("label",{style:{display:"block",fontSize:11,color:"#64748b",marginBottom:6},children:"Select Plan"}),t.jsxs("select",{value:b,onChange:P=>{A(P.target.value),x("")},style:z,children:[t.jsx("option",{value:"",style:{background:"#0f1923"},children:"Choose a plan..."}),i.map(P=>t.jsxs("option",{value:P.id,style:{background:"#0f1923"},children:[P.name," â $",Number(P.price_monthly).toFixed(2),ya[P.billing_interval]||""]},P.id))]})]}),E&&t.jsxs("div",{style:{background:"rgba(245,158,11,0.04)",border:"1px solid rgba(245,158,11,0.15)",borderRadius:10,padding:"10px 14px"},children:[t.jsx("div",{style:{fontSize:12,color:"#e2e8f0",fontWeight:600,marginBottom:4},children:E.name}),E.description&&t.jsx("div",{style:{fontSize:11,color:"#64748b",marginBottom:6},children:E.description}),t.jsxs("div",{style:{display:"flex",gap:16,fontSize:11,color:"#94a3b8"},children:[t.jsxs("span",{children:["Billing: ",E.billing_interval]}),t.jsxs("span",{children:["Fulfillment: ",td[E.fulfillment_type]]}),E.fulfillment_interval_months&&t.jsxs("span",{children:["Every ",E.fulfillment_interval_months," mo"]})]})]}),E&&R&&t.jsxs("div",{children:[t.jsx("label",{style:{display:"block",fontSize:11,color:"#64748b",marginBottom:6},children:"Installed System"}),N.length===0?t.jsx("div",{style:{fontSize:12,color:"#f87171",padding:"8px 0"},children:"No matching installed systems found for this plan type."}
1105):t.jsxs("select",{value:v,onChange:P=>x(P.target.value),style:z,children:[t.jsx("option",{value:"",style:{background:"#0f1923"},children:"Choose a system..."}),N.map(P=>t.jsxs("option",{value:P.id,style:{background:"#0f1923"},children:[P.system_name||"â"," â ",P.commercial_type,P.install_date?` (installed ${dn(P.install_date)})`:""]},P.id))]})]}),E&&n&&t.jsxs("div",{children:[t.jsxs("label",{style:{display:"block",fontSize:11,color:"#64748b",marginBottom:6},children:["Price Override ",t.jsxs("span",{style:{color:"#334155"},children:["(leave empty for default: $",Number(E.price_monthly).toFixed(2),")"]})]}),t.jsx("input",{type:"number",step:"0.01",min:"0",value:_,onChange:P=>j(P.target.value),placeholder:String(E.price_monthly),style:z})]}),E&&E.billing_interval!=="one_time"&&t.jsxs("div",{children:[t.jsx("label",{style:{display:"block",fontSize:11,color:"#64748b",marginBottom:6},children:"Billing Start"}),t.jsx("div",{style:{display:"flex",gap:8},children:["immediate","next_cycle"].map(P=>t.jsx("button",{onClick:()=>S(P),style:{flex:1,padding:"8px 12px",borderRadius:10,fontSize:12,cursor:"pointer",background:C===P?"rgba(245,158,11,0.1)":"rgba(255,255,255,0.03)",color:C===P?"#f59e0b":"#64748b",border:`1px solid ${C===P?"rgba(245,158,11,0.4)":"#1e3a4f"}`,fontWeight:C===P?700:400},children:P==="immediate"?"Start Immediately":"Start Next Cycle"},P))})]}),E&&!d&&E.billing_interval!=="one_time"&&t.jsxs("div",{style:{background:"rgba(251,191,36,0.06)",border:"1px solid rgba(251,191,36,0.2)",borderRadius:10,padding:"8px 14px",fontSize:12,color:"#fbbf24",display:"flex",gap:8},children:[t.jsx("span",{children:"ð³"}),t.jsxs("span",{children:["No card on file. Plan will be created as ",t.jsx("strong",{children:'"Card Required"'})," â billing starts when a card is saved."]})]}),E&&t.jsxs("div",{children:[t.jsx("label",{style:{display:"block",fontSize:11,color:"#64748b",marginBottom:6},children:"Notes (optional)"}),t.jsx("textarea",{value:T,onChange:P=>L(P.target.value),rows:2,placeholder:"Internal notes about this plan",style:{...z,resize:"none",fontFamily:"inherit"}})]}),t.jsxs("div",{style:{display:"flex",gap:8,paddingTop:4,justifyContent:"flex-end"},children:[t.jsx("button",{onClick:r,style:{padding:"8px 16px",borderRadius:10,fontSize:13,color:"#64748b",cursor:"pointer",background:"rgba(255,255,255,0.04)",border:"1px solid #1e3a4f"},children:"Cancel"}),t.jsx("button",{onClick:O,disabled:u||!b,style:{padding:"8px 20px",borderRadius:10,fontSize:13,fontWeight:700,color:"#fff",background:"linear-gradient(135deg, #f59e0b, #d97706)",border:"none",cursor:u||!b?"not-allowed":"pointer",opacity:u||!b?.5:1},children:u?"Activating...":d?"Activate Plan":"Create Plan (Card Required)"})]})]})]})})}function UK({customerId:e}){const[n,r]=g.useState([]),[s,i]=g.useState(!0),[o,a]=g.useState(!1),[l,d]=g.useState(null),[c,f]=g.useState([]),[p,u]=g.useState([]);g.useEffect(()=>{h()},[e]);async function h(){i(!0);const{data:x}=await w.from("customers").select("lead_id").eq("id",e).maybeSingle(),_=x!=null&&x.lead_id?[x.lead_id]:[];f(_),u([]);const j=await Y8(_,[],e);j.sort((C,S)=>new Date(S.tested_at||"").getTime()-new Date(C.tested_at||"").getTime()),r(j),i(!1)}function y(x){a(!1),d(null),h()}function m(x){d(x),a(!0)}async function b(x){if(!confirm("Delete this water test? This cannot be undone."))return;const{deleteWaterTest:_}=await Fo(async()=>{const{deleteWaterTest:j}=await Promise.resolve().then(()=>e3);return{deleteWaterTest:j}},void 0);await _(x.id),h()}if(s)return t.jsx("div",{style:{textAlign:"center",color:"#64748b",padding:"48px 0"},children:"Loading water tests..."});const A=n.some(x=>x.test_type==="initial"),v=n.some(x=>x.test_type==="post_install");return t.jsxs("div",{children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:16},children:[t.jsxs("div",{children:[t.jsx("h2",{style:{color:"#e2e8f0",fontWeight:700,fontSize:16,margin:0},children:"Water Tests"}),t.jsxs("p",{style:{color:"#64748b",fontSize:12,marginTop:4},children:[n.length," test",n.length!==1?"s":""," recorded",A&&v&&" â before & after comparison available"]})]}),!o&&t.jsx("button",{onClick:()=>{d(null),a(!0)},style:{padding:"6px 16px",borderRadius:8,fontSize:12,fontWeight:700,background:"rgba(34,211,238,0.1)",color:"#22d3ee",border:"1px solid rgba(34,211,238,0.25)",cursor:"pointer"},children:"+ Record Test"})]}),o&&t.jsx("div",{style:{marginBottom:16},children:t.jsx(fh,{leadId:c[0]||void 0,testType:"routine",existingTest:l,onSaved:y,onCancel:()=>{a(!1),d(null)}})}),!o&&A&&v&&t.jsx("div",{style:{marginBottom:16},children:t.jsx(KH,{tests:n})}),!o&&n.length>0&&t.jsx(Oy,{tests:n,onEdit:m,onDelete:b}),!o&&n.length===0&&t.jsxs("div",{style:{background:"#162232",border:"1px solid #1e3a4f",borderRadius:14,padding:"48px 20px",textAlign:"center"},children:[t.jsx("div",{style:{fontSize:40,marginBottom:12,opacity:.4},children:"ð§"}),t.jsx("p",{style:{color:"#64748b",fontSize:13},children:"No water tests recorded for this customer. Tests from the lead and installation will appear here automatically."})]})]})}const k3={pending:{label:"Pending",color:"#f59e0b",bgColor:"#f59e0b20",icon:"ð¦"},label_created:{label:"Label Created",color:"#8b5cf6",bgColor:"#8b5cf620",icon:"ð·ï¸"},shipped:{label:"Shipped",color:"#3b82f6",bgColor:"#3b82f620",icon:"ð"},in_transit:{label:"In Transit",color:"#06b6d4",bgColor:"#06b6d420",icon:"âï¸"},delivered:{label:"Delivered",color:"#10b981",bgColor:"#10b98120",icon:"â "},cancelled:{label:"Cancelled",color:"#6b7280",bgColor:"#6b728020",icon:"â"},returned:{label:"Returned",color:"#ef4444",bgColor:"#ef444420",icon:"â©ï¸"}},dg={filter:"Filter Replacement",replacement:"Replacement Part",warranty:"Warranty Replacement",new_install:"New Install",other:"Other"},C3={addresses_primary:"Primary Address",customer_primary_inline:"Primary Address (legacy)",customer_primary:"Primary Address",service_address:"Service Address",manual_override:"Manual Override"};async function HK(e){try{const[n,r]=await Promise.all([w.from("customers").select("full_name").eq("id",e).single(),w.from("addresses").select("address_line1, address_line2, city, state, zip").eq("entity_type","customer").eq("entity_id",e).eq("is_primary",!0).maybeSingle()]),s=n.data;if(!s)return null;const i=s.full_name||"",o=r.data;if(o&&o.address_line1&&o.city&&o.state&&o.zip){const a=o.address_line2?`${o.address_line1}, ${o.address_line2}`:o.address_line1;return{name:i,address:a,city:o.city,state:o.state,zip:o.zip,source:"addresses_primary"}}return null}catch(n){return console.error("resolveShippingAddress error:",n),null}}async function VK(e={}){try{let n=w.from("shipments").select(` 1106 *, 1107 customers(full_name, email, phone), 1108 customer_service_plans!customer_plan_id(id, plan_id, service_plans(name)), 1109 customer_service_plan_components!plan_component_id(component_name, label, component_code) 1110 `).order("created_at",{ascending:!1});e.status&&e.status!=="all"&&(n=n.eq("status",e.status)),e.dateFrom&&(n=n.gte("due_date",e.dateFrom)),e.dateTo&&(n=n.lte("due_date",e.dateTo));const r=Kt();r&&(n=n.eq("branch_id",r));const{data:s,error:i}=await n;if(i)throw i;return(s||[]).map(R3)}catch(n){return console.error("fetchShipments error:",n),[]}}async function ZK(e){try{const{data:n,error:r}=await w.from("shipments").select(` 1111 *, 1112 customers(full_name, email, phone), 1113 customer_service_plans!customer_plan_id(id, plan_id, service_plans(name)), 1114 customer_service_plan_components!plan_component_id(component_name, label, component_code) 1115 `).eq("customer_id",e).order("created_at",{ascending:!1});if(r)throw r;return(n||[]).map(R3)}catch(n){return console.error("fetchShipmentsByCustomer error:",n),[]}}async function KK(){try{let e=w.from("shipments").select("status");const n=Kt();n&&(e=e.eq("branch_id",n));const{data:r,error:s}=await e;if(s)throw s;const i={all:0};
1115return(r||[]).forEach(o=>{i.all=(i.all||0)+1,i[o.status]=(i[o.status]||0)+1}),i}catch(e){return console.error("getShipmentCounts error:",e),{all:0}}}async function YK(e){try{const{data:n,error:r}=await w.from("shipments").insert({customer_id:e.customer_id,customer_plan_id:e.customer_service_plan_id||null,plan_component_id:e.plan_component_id||null,due_date:e.scheduled_date||e.fulfillment_due_date||null,source:e.source||"manual",shipment_type:e.type,carrier:e.carrier||"fedex",status:"pending",ship_to_name:e.ship_to_name,ship_to_address:e.ship_to_address,ship_to_city:e.ship_to_city,ship_to_state:e.ship_to_state,ship_to_zip:e.ship_to_zip,address_source:e.address_source,notes:e.notes||null,created_by:e.created_by||null}).select().single();if(r)throw r;return n}catch(n){return console.error("createShipment error:",n),null}}async function XK(e,n){try{const{error:r}=await w.from("shipments").update({...n,updated_at:new Date().toISOString()}).eq("id",e);if(r)throw r;return!0}catch(r){return console.error("updateShipment error:",r),!1}}async function GK(e,n){try{const{error:r}=await w.from("shipments").update({status:"label_created",tracking_number:n.tracking_number,label_url:n.label_url||null,updated_at:new Date().toISOString()}).eq("id",e).in("status",["pending"]);if(r)throw r;return!0}catch(r){return console.error("markLabelCreated error:",r),!1}}async function T3(e){try{const{data:n,error:r}=await w.rpc("rpc_mark_shipment_shipped",{p_shipment_id:e});if(r)throw r;return{success:(n==null?void 0:n.success)??!1,planDatesAdvanced:(n==null?void 0:n.plan_dates_advanced)??!1,error:(n==null?void 0:n.error)||void 0}}catch(n){return console.error("markShipped error:",n),{success:!1,planDatesAdvanced:!1,error:"Failed to mark shipped"}}}async function JK(e){try{const{error:n}=await w.from("shipments").update({status:"in_transit",updated_at:new Date().toISOString()}).eq("id",e).in("status",["shipped"]);if(n)throw n;return!0}catch(n){return console.error("markInTransit error:",n),!1}}async function z3(e){try{const{error:n}=await w.from("shipments").update({status:"delivered",delivered_at:new Date().toISOString(),updated_at:new Date().toISOString()}).eq("id",e).in("status",["shipped","in_transit"]);if(n)throw n;return!0}catch(n){return console.error("markDelivered error:",n),!1}}async function N3(e){try{const{error:n}=await w.from("shipments").update({status:"cancelled",updated_at:new Date().toISOString()}).eq("id",e).in("status",["pending","label_created"]);if(n)throw n;return!0}catch(n){return console.error("cancelShipment error:",n),!1}}async function QK(e,n){try{const r={status:"returned",updated_at:new Date().toISOString()};n&&(r.notes=n);const{error:s}=await w.from("shipments").update(r).eq("id",e).in("status",["delivered"]);if(s)throw s;return!0}catch(r){return console.error("markReturned error:",r),!1}}function R3(e){var l;const n=e.customers,r=e.customer_service_plan_components,s=e.customer_service_plans,i=(r==null?void 0:r.label)||(r==null?void 0:r.component_name)||void 0,o=((l=s==null?void 0:s.service_plans)==null?void 0:l.name)||void 0,a=e.shipment_type;return{...e,type:a??e.type,customer_name:(n==null?void 0:n.full_name)||void 0,customer_email:(n==null?void 0:n.email)||void 0,customer_phone:(n==null?void 0:n.phone)||void 0,product_name:i||o||void 0,plan_name:o||void 0}}function eY({customerId:e}){rs();const{data:n=[],isLoading:r}=Ae({queryKey:["customer_shipments",e],queryFn:()=>ZK(e),enabled:!!e}),s=["pending","label_created","shipped","in_transit"],i=n.filter(a=>s.includes(a.status)),o=n.filter(a=>!s.includes(a.status));return r?t.jsx("div",{style:{padding:24,color:"#64748b"},children:"Loading shipments..."}):t.jsxs("div",{style:{padding:"0 0 24px",display:"flex",flexDirection:"column",gap:20},children:[t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(140px, 1fr))",gap:12},children:[t.jsx(Ip,{label:"Active",value:i.length,color:"#3b82f6"}),t.jsx(Ip,{label:"Pending",value:n.filter(a=>a.status==="pending").length,color:"#f59e0b"}),t.jsx(Ip,{label:"Delivered",value:n.filter(a=>a.status==="delivered").length,color:"#10b981"}),t.jsx(Ip,{label:"Total",value:n.length,color:"#94a3b8"})]}),i.length>0&&t.jsx(Wj,{title:"Active Shipments",color:"#3b82f6",children:i.map(a=>t.jsx($j,{shipment:a},a.id))}),i.length===0&&t.jsx("div",{style:{padding:24,textAlign:"center",color:"#64748b",background:"#162232",borderRadius:12,border:"1px solid #1e3a4f"},children:"No active shipments"}),o.length>0&&t.jsx(Wj,{title:"Past Shipments",color:"#64748b",children:o.map(a=>t.jsx($j,{shipment:a,dimmed:!0},a.id))})]})}function Ip({label:e,value:n,color:r}){return t.jsxs("div",{style:{background:"#162232",border:"1px solid #1e3a4f",borderRadius:10,padding:"12px 16px",textAlign:"center"},children:[t.jsx("div",{style:{fontSize:22,fontWeight:700,color:r},children:n}),t.jsx("div",{style:{fontSize:11,fontWeight:600,color:"#64748b",textTransform:"uppercase"},children:e})]})}function Wj({title:e,color:n,children:r}){return t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:11,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.06em",color:n,marginBottom:10},children:e}),t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:r})]})}function $j({shipment:e,dimmed:n}
1115){const r=k3[e.status]||{label:e.status,color:"#64748b",bgColor:"#64748b20",icon:"ð¦"};return t.jsxs("div",{style:{background:"#162232",border:"1px solid #1e3a4f",borderRadius:12,padding:"14px 18px",opacity:n?.55:1,display:"flex",justifyContent:"space-between",alignItems:"center",gap:12,flexWrap:"wrap"},children:[t.jsxs("div",{style:{flex:1,minWidth:160},children:[t.jsx("div",{style:{fontSize:14,fontWeight:600,color:"#e2e8f0"},children:e.product_name||"No product"}),t.jsxs("div",{style:{fontSize:12,color:"#64748b",marginTop:2},children:[dg[e.type]||e.type,e.source==="cron_fulfillment"&&t.jsx("span",{style:{marginLeft:6,color:"#0d7ea3"},children:"⢠Auto"})]})]}),t.jsxs("div",{style:{textAlign:"center",minWidth:120},children:[e.scheduled_date&&t.jsxs("div",{style:{fontSize:12,color:"#94a3b8"},children:["Scheduled: ",new Date(e.scheduled_date+"T00:00:00").toLocaleDateString()]}),e.shipped_date&&t.jsxs("div",{style:{fontSize:12,color:"#3b82f6"},children:["Shipped: ",new Date(e.shipped_date+"T00:00:00").toLocaleDateString()]}),e.delivered_date&&t.jsxs("div",{style:{fontSize:12,color:"#10b981"},children:["Delivered: ",new Date(e.delivered_date+"T00:00:00").toLocaleDateString()]})]}),t.jsxs("div",{style:{textAlign:"right",minWidth:120},children:[t.jsxs("span",{style:{display:"inline-block",padding:"3px 10px",borderRadius:20,fontSize:11,fontWeight:700,color:r.color,background:r.bgColor,border:`1px solid ${r.color}30`},children:[r.icon," ",r.label]}),e.tracking_number&&t.jsx("div",{style:{fontSize:11,color:"#3b82f6",fontFamily:"monospace",marginTop:4},children:e.tracking_number})]})]})}const mn=e=>e==null||Number.isNaN(Number(e))?"â":new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}).format(Number(e)),Go=e=>e?new Date(e).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):"â";function tY(){const[e,n]=g.useState(window.innerWidth<768);return g.useEffect(()=>{const r=()=>n(window.innerWidth<768);return window.addEventListener("resize",r),()=>window.removeEventListener("resize",r)},[]),e}const nY=[{key:"all",label:"All",icon:"â",color:"#e2e8f0",bg:"rgba(226,232,240,0.1)",border:"rgba(226,232,240,0.2)"},{key:"draft",label:"Draft",icon:"â",color:"#94a3b8",bg:"rgba(148,163,184,0.1)",border:"rgba(148,163,184,0.25)"},{key:"sent",label:"Sent",icon:"â",color:"#60a5fa",bg:"rgba(96,165,250,0.1)",border:"rgba(96,165,250,0.25)"},{key:"paid",label:"Paid",icon:"â",color:"#4ade80",bg:"rgba(74,222,128,0.1)",border:"rgba(74,222,128,0.25)"},{key:"overdue",label:"Overdue",icon:"â ",color:"#f87171",bg:"rgba(248,113,113,0.1)",border:"rgba(248,113,113,0.25)"},{key:"signed",label:"Signed",icon:"â",color:"#fbbf24",bg:"rgba(251,191,36,0.1)",border:"rgba(251,191,36,0.25)"},{key:"void",label:"Void",icon:"â",color:"#71717a",bg:"rgba(113,113,122,0.1)",border:"rgba(113,113,122,0.25)"}];function $y({status:e}){const n=q8[e];return t.jsx("span",{style:{display:"inline-flex",alignItems:"center",padding:"3px 10px",borderRadius:20,fontSize:11,fontWeight:700,color:n,background:n+"22",border:`1px solid ${n}40`},children:ZU[e]})}function My({invoice:e}){var r,s;if(!(e!=null&&e.signed_at)||(s=(r=e==null?void 0:e.terms_snapshot)==null?void 0:r.blocks)!=null&&s.length)return null;const n="#f87171";return t.jsx("span",{title:"Signed with no terms attached. This document has no legal terms on record. Add terms in Terms Admin, then re-issue.",style:{display:"inline-flex",alignItems:"center",padding:"3px 10px",borderRadius:20,fontSize:11,fontWeight:700,color:n,background:n+"22",border:"1px solid "+n+"40",whiteSpace:"nowrap"},children:"â No terms"})}function rY({invoice:e,onClose:n,onRefresh:r}){const{profile:s}=Ee(),i=gt(),o=yt.manageInvoices(s==null?void 0:s.role),[a,l]=g.useState(!1),[d,c]=g.useState(!1),[f,p]=g.useState(""),[u,h]=g.useState(!1),[y,m]=g.useState(""),b=ac(e),A=e.total>0?e.amount_paid/e.total*100:0,v=e.discount_total||e.line_items_snapshot.reduce((z,P)=>z+(Number(P.discount_amount)||0),0),[x,_]=g.useState(!1),[j,C]=g.useState(null);g.useEffect(()=>{let z=!1;return(async()=>{try{const D=await(await fetch("/api/stripe/publishable-key",{method:"POST",headers:await At()})).json();!z&&(D!=null&&D.publishable_key)&&C(Xf(D.publishable_key))}catch{}})(),()=>{z=!0}},[]);async function S(){if(confirm("Void this invoice?")){l(!0);try{await JU(e.id),r(),n()}catch(z){alert(z.message)}finally{l(!1)}}}async function T(){l(!0);try{await nj(e.id,"sent"),r()}catch(z){alert(z.message)}finally{l(!1)}}async function L(){const z=parseFloat(f)||e.total;l(!0);try{await GU(e.id,z),c(!1),r()}catch(P){alert(P.message)}finally{l(!1)}}async function E(){l(!0);try{const z=await Zk(e.customer_id),P=z.find(M=>M.is_default)||z[0];if(!P){alert("No saved card on file. Open the customer's Billing tab and add a card first.");return}if(!window.confirm(`Charge ${mn(b)} to card ending ${P.last_four}?`))return;const{data:D}=await w.from("customers").select("stripe_customer_id").eq("id",e.customer_id).single();if(!(D!=null&&D.stripe_customer_id)){alert("This customer has no Stripe account on file yet. Add a card via their Billing tab first.");return}await Gf({stripe_customer_id:D.stripe_customer_id,payment_method_id:P.external_id,amount_cents:Math.round(b*100),description:`Payment for invoice ${e.invoice_number}`,customer_id:e.customer_id,invoice_id:e.id,supabase_pm_id:P.id}),r()}catch(z){alert(z.message)}finally{l(!1)}}async function R(){h(!0),m("");try{const z=await fetch("/api/email/send-invoice",{method:"POST",headers:await At(),body:JSON.stringify({invoiceId:e.id,senderEmail:s==null?void 0:s.email,senderName:s==null?void 0:s.full_name})}),P=await z.json();if(!z.ok)throw new Error(P.error||"Failed to send");e.status==="draft"&&await nj(e.id,"sent"),m("â Invoice emailed successfully"),r()}catch(z){m(`â ${z.message}`)}finally{h(!1)}}const N={background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:8,color:"#e2e8f0",padding:"10px 14px",width:"100%",fontSize:14,outline:"none",boxSizing:"border-box"},O={width:"100%",padding:"11px 0",borderRadius:8,border:"none",cursor:"pointer",fontSize:13,fontWeight:700,color:"#fff",transition:"opacity 0.15s"};return t.jsxs("div",{style:{position:"fixed",inset:0,zIndex:50,display:"flex"},children:[t.jsx("div",{style:{flex:1,background:"rgba(0,0,0,0.5)",backdropFilter:"blur(4px)"},onClick:n}),t.jsxs("div",{style:{width:"100%",maxWidth:480,background:"#162232",display:"flex",flexDirection:"column",overflowY:"auto"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"16px 20px",borderBottom:"1px solid #1e3a4f",background:"#0f1923"},children:[t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:11,color:"#64748b",fontWeight:600,textTransform:"uppercase",letterSpacing:"0.08em"},children:"Invoice"}),t.jsx("div",{style:{fontSize:18,fontWeight:800,color:"#e2e8f0"},children:e.invoice_number})]}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12},children:[t.jsx(My,{invoice:e}),t.jsx($y,{status:e.status}),t.jsx("button",{onClick:n,style:{background:"none",border:"none",color:"#64748b",cursor:"pointer",fontSize:22,lineHeight:1},children:"Ã"})]})]}),t.jsxs("div",{style:{flex:1,padding:20,display:"flex",flexDirection:"column",gap:16},children:[t.jsxs("div",{style:{background:"#0f1923",borderRadius:10,padding:16,border:"1px solid #1e3a4f"},children:[t.jsx("div",{style:{fontSize:11,color:"#64748b",fontWeight:600,textTransform:"uppercase",letterSpacing:"0.08em",marginBottom:8},children:"Bill To"}),t.jsx("div",{style:{fontWeight:700,color:"#e2e8f0",fontSize:15},children:e.customer_name||"â"}),e.customer_email&&t.jsx("div",{style:{fontSize:13,color:"#94a3b8"},children:e.customer_email}),e.customer_phone&&t.jsx("div",{style:{fontSize:13,color:"#94a3b8"},children:e.customer_phone}),t.jsx("button",{onClick:()=>{n(),i(`/customers/${e.customer_id}`)},style:{background:"none",border:"none",color:"#22d3ee",cursor:"pointer",fontSize:12,fontWeight:600,padding:0,marginTop:6},children:"View Customer â"})]}),t.jsx("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:10},children:[{label:"Total",value:mn(e.total),color:"#e2e8f0"},{label:"Paid",value:mn(e.amount_paid),color:"#4ade80"},{label:"Balance",value:mn(b),color:b>0?"#f87171":"#4ade80"}].map(({label:z,value:P,color:D})=>t.jsxs("div",{style:{background:"#0f1923",borderRadius:10,padding:12,textAlign:"center",border:"1px solid #1e3a4f"},children:[t.jsx("div",{style:{fontSize:11,color:"#64748b",marginBottom:4},children:z}),t.jsx("div",{style:{fontSize:18,fontWeight:800,color:D},children:P})]},z))}),e.total>0&&t.jsxs("div",{children:[t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",fontSize:11,color:"#64748b",marginBottom:4},children:[t.jsx("span",{children:"Payment progress"}),t.jsxs("span",{children:[Math.round(A),"%"]})]}),t.jsx("div",{style:{width:"100%",height:6,borderRadius:3,background:"#1e3a4f",overflow:"hidden"},children:t.jsx("div",{style:{height:"100%",borderRadius:3,width:`${Math.min(100,A)}%`,background:A>=100?"#4ade80":"#f59e0b",transition:"width 0.3s"}})})]}),t.jsx("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[["Created",Go(e.created_at)],["Due",Go(e.due_date)],["Sent",e.sent_at?Go(e.sent_at):"â"],["Paid",e.paid_at?Go(e.paid_at):"â"]].map(([z,P])=>t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:11,color:"#64748b"},children:z}),t.jsx("div",{style:{fontSize:13,fontWeight:600,color:"#e2e8f0"},children:P})]},z))}),e.line_items_snapshot.length>0&&t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:11,color:"#64748b",fontWeight:600,textTransform:"uppercase",letterSpacing:"0.08em",marginBottom:8},children:"Line Items"}),t.jsx("div",{style:{border:"1px solid #1e3a4f",borderRadius:10,overflow:"hidden"},children:t.jsxs("table",{style:{width:"100%",borderCollapse:"collapse"},children:[t.jsx("thead",{children:t.jsx("tr",{style:{background:"#0f1923",borderBottom:"1px solid #1e3a4f"},children:["Description","Qty","Unit","Disc","Total"].map((z,P)=>t.jsx("th",{style:{padding:"8px 12px",fontSize:11,fontWeight:700,color:"#64748b",textTransform:"uppercase",letterSpacing:"0.06em",textAlign:P===0?"left":"right"},children:z},z))})}),t.jsx("tbody",{children:e.line_items_snapshot.map((z,P)=>t.jsxs("tr",{style:{borderBottom:"1px solid #1a2a3a"},children:[t.jsx("td",{style:{padding:"10px 12px",fontSize:13,color:"#e2e8f0"},children:z.description}),t.jsx("td",{style:{padding:"10px 12px",fontSize:13,color:"#94a3b8",textAlign:"right"},children:z.quantity}),t.jsx("td",{style:{padding:"10px 12px",fontSize:13,color:"#94a3b8",textAlign:"right"},children:mn(z.unit_price)}),t.jsx("td",{style:{padding:"10px 12px",fontSize:12,color:"#4ade80",textAlign:"right",whiteSpace:"nowrap"},children:Number(z.discount_amount)>0?`â${mn(Number(z.discount_amount))} (${Number(z.discount_pct)||0}%)`:"â"}),t.jsx("td",{style:{padding:"10px 12px",fontSize:13,color:"#e2e8f0",fontWeight:600,textAlign:"right"},children:mn(z.total??z.total_price)})]},P))}),t.jsxs("tfoot",{children:[t.jsxs("tr",{style:{borderTop:"1px solid #1e3a4f"},children:[t.jsx("td",{colSpan:4,style:{padding:"6px 12px",fontSize:11,color:"#64748b",textAlign:"right"},children:"Subtotal"}),t.jsx("td",{style:{padding:"6px 12px",fontSize:13,fontWeight:600,color:"#e2e8f0",textAlign:"right"},children:mn(e.subtotal+v)})]}),v>0&&t.jsxs("tr",{children:[t.jsx("td",{colSpan:4,style:{padding:"6px 12px",fontSize:11,color:"#4ade80",textAlign:"right"},children:"Discount"}),t.jsxs("td",{style:{padding:"6px 12px",fontSize:13,fontWeight:600,color:"#4ade80",textAlign:"right"},children:["â",mn(v)]})]}),t.jsxs("tr",{children:[t.jsx("td",{colSpan:4,style:{padding:"6px 12px",fontSize:11,color:"#64748b",textAlign:"right"},children:"Tax (7%)"}),t.jsx("td",{style:{padding:"6px 12px",fontSize:13,fontWeight:600,color:"#e2e8f0",textAlign:"right"},children:mn(e.tax_amount)})]}),t.jsxs("tr",{style:{borderTop:"1px solid #1e3a4f"},children:[t.jsx("td",{colSpan:4,style:{padding:"10px 12px",fontSize:13,fontWeight:700,color:"#e2e8f0",textAlign:"right"},children:"Total"}),t.jsx("td",{style:{padding:"10px 12px",fontSize:15,fontWeight:800,color:"#22d3ee",textAlign:"right"},children:mn(e.total)})]})]})]})})]}),e.notes&&t.jsxs("div",{style:{background:"#1a2a3a",borderRadius:10,padding:14,border:"1px solid #1e3a4f"},children:[t.jsx("div",{style:{fontSize:11,color:"#f59e0b",fontWeight:600,marginBottom:4},children:"Notes"}),t.jsx("div",{style:{fontSize:13,color:"#e2e8f0"},children:e.notes})]}),y&&t.jsx("div",{style:{fontSize:13,fontWeight:600,color:y.startsWith("â")?"#4ade80":"#f87171"},children:y})]}),e.status!=="void"&&t.jsxs("div",{style:{padding:20,borderTop:"1px solid #1e3a4f",dis
1115play:"flex",flexDirection:"column",gap:8},children:[o&&e.status==="draft"&&t.jsx("button",{onClick:T,disabled:a,style:{...O,background:"#0d7ea3",opacity:a?.5:1},children:"Mark as Sent"}),o&&["draft","sent","overdue"].includes(e.status)&&t.jsx("button",{onClick:()=>{p(b.toFixed(2)),c(!0)},style:{...O,background:"#16a34a"},children:"Record Payment"}),o&&["draft","sent","overdue"].includes(e.status)&&t.jsx("button",{onClick:E,disabled:a,style:{...O,background:"#4ade80",color:"#06251a",opacity:a?.5:1},children:"ð³ Charge to card"}),o&&["draft","sent","overdue"].includes(e.status)&&t.jsx("button",{onClick:()=>_(!0),disabled:a,style:{...O,background:"transparent",border:"1px solid #60a5fa60",color:"#60a5fa",opacity:a?.5:1},children:"ð³ Charge new card"}),t.jsx("button",{onClick:R,disabled:u,style:{...O,background:"#6366f1",opacity:u?.5:1},children:u?"Sendingâ¦":"â Email Invoice"}),o&&e.status!=="paid"&&t.jsx("button",{onClick:S,disabled:a,style:{...O,background:"transparent",border:"1px solid #f8717140",color:"#f87171",opacity:a?.5:1},children:"Void Invoice"})]})]}),x&&t.jsx(S3,{customer:{id:e.customer_id,full_name:e.customer_name||"Customer",email:e.customer_email},stripePromise:j,amount:b,invoiceId:e.id,description:`Payment for invoice ${e.invoice_number}`,onClose:()=>_(!1),onSuccess:()=>{_(!1),r()}}),d&&t.jsxs("div",{style:{position:"fixed",inset:0,zIndex:60,display:"flex",alignItems:"center",justifyContent:"center"},children:[t.jsx("div",{style:{position:"absolute",inset:0,background:"rgba(0,0,0,0.6)"},onClick:()=>c(!1)}),t.jsxs("div",{style:{position:"relative",background:"#162232",borderRadius:12,padding:24,width:320,border:"1px solid #1e3a4f"},children:[t.jsx("div",{style:{fontWeight:800,fontSize:18,color:"#e2e8f0",marginBottom:16},children:"Record Payment"}),t.jsxs("div",{children:[t.jsx("label",{style:{display:"block",fontSize:11,color:"#64748b",marginBottom:4},children:"Amount ($)"}),t.jsx("input",{type:"number",step:"0.01",value:f,onChange:z=>p(z.target.value),style:N}),t.jsxs("div",{style:{fontSize:11,color:"#64748b",marginTop:4},children:["Balance due: ",mn(b)]})]}),t.jsxs("div",{style:{display:"flex",gap:8,marginTop:16},children:[t.jsx("button",{onClick:()=>c(!1),style:{flex:1,padding:"10px 0",borderRadius:8,border:"1px solid #1e3a4f",background:"transparent",color:"#94a3b8",cursor:"pointer",fontSize:13},children:"Cancel"}),t.jsx("button",{onClick:L,disabled:a,style:{flex:1,padding:"10px 0",borderRadius:8,border:"none",background:"#16a34a",color:"#fff",cursor:"pointer",fontWeight:700,fontSize:13,opacity:a?.5:1},children:"Confirm"})]})]})]})]})}function E3({onClose:e,onCreated:n,initialCustomerId:r}){const[s,i]=g.useState([]),[o,a]=g.useState(r||""),[l,d]=g.useState([]),[c,f]=g.useState(""),[p,u]=g.useState("from_quote"),[h,y]=g.useState(!1),[m,b]=g.useState(""),[A,v]=g.useState("1"),[x,_]=g.useState(""),[j,C]=g.useState(""),[S,T]=g.useState(new Date(Date.now()+14*864e5).toISOString().slice(0,10)),[L,E]=g.useState(!1);g.useEffect(()=>{w.from("customers").select("id,full_name").order("full_name").then(({data:z})=>i(z||[]))},[]),g.useEffect(()=>{if(!o)return d([]);rg(o).then(z=>d(z.filter(P=>P.status==="accepted"||P.status==="signed")))},[o]);async function R(){if(!o)return alert("Select a customer");y(!0);try{if(p==="from_quote"){if(!c)throw new Error("Select a quote");await XU(c)}else{const z=parseFloat(x);if(!m||!z)throw new Error("Description and price required");const P=parseInt(A)||1,D=P*z,M=D*.07;if(L){const{data:k}=await w.from("customers").select("full_name, email, phone").eq("id",o).maybeSingle();if(!(k!=null&&k.email)&&!(k!=null&&k.phone))throw new Error("Customer has no email or phone on file â cannot send pay link");const{data:{session:q}}=await w.auth.getSession(),$=await fetch("/api/stripe/create-payment-link",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${(q==null?void 0:q.access_token)||""}`},body:JSON.stringify({customer_id:o,recipient_name:(k==null?void 0:k.full_name)||"Customer",recipient_email:(k==null?void 0:k.email)||void 0,recipient_phone:(k==null?void 0:k.phone)||void 0,line_items:[{description:m,qty:P,unit_price:z}],notes:j||void 0})}),I=await $.json();if(!$.ok)throw new Error(I.error||"Failed to send pay link")}else await O8({customer_id:o,line_items:[{description:m,quantity:P,unit_price:z,total:D}],subtotal:D,tax_amount:M,total:D+M,due_date:S,notes:j||void 0})}n(),e()}catch(z){alert(z.message)}finally{y(!1)}}const N={background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:8,color:"#e2e8f0",padding:"10px 14px",width:"100%",fontSize:14,outline:"none",boxSizing:"border-box"},O={...N,appearance:"none",backgroundImage:`url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%2364748b' stroke-width='2'%3E%3Cpath d='M6 9l6 6 6-6'/%3E%3C/svg%3E")`,backgroundRepeat:"no-repeat",backgroundPosition:"right 12px center"};return t.jsxs("div",{style:{position:"fixed",inset:0,zIndex:50,display:"flex",alignItems:"center",justifyContent:"center"},children:[t.jsx("div",{style:{position:"absolute",inset:0,background:"rgba(0,0,0,0.5)"},onClick:e}),t.jsxs("div",{style:{position:"relative",background:"#162232",borderRadius:14,border:"1px solid #1e3a4f",width:"100%",maxWidth:440,padding:28,display:"flex",flexDirection:"column",gap:16,margin:16},children:[t.jsx("div",{style:{fontWeight:800,fontSize:20,color:"#e2e8f0"},children:"New Invoice"}),t.jsx("div",{style:{display:"flex",gap:4,background:"#0f1923",borderRadius:8,padding:3},children:["from_quote","manual"].map(z=>t.jsx("button",{onClick:()=>u(z),style:{flex:1,padding:"8px 0",borderRadius:6,border:"none",cursor:"pointer",fontSize:13,fontWeight:600,transition:"all 0.15s",background:p===z?"#162232":"transparent",color:p===z?"#e2e8f0":"#64748b",boxShadow:p===z?"0 1px 3px rgba(0,0,0,0.3)":"none"},children:z==="from_quote"?"From Quote":"Manual"},z))}),t.jsxs("div",{children:[t.jsx("label",{style:{display:"block",fontSize:11,color:"#64748b",fontWeight:600,marginBottom:4},children:"Customer *"}),t.jsxs("select",{value:o,onChange:z=>a(z.target.value),style:O,children:[t.jsx("option",{value:"",children:"Select customerâ¦"}),s.map(z=>t.jsx("option",{value:z.id,children:z.full_name},z.id))]})]}),p==="from_quote"?t.jsxs("div",{children:[t.jsx("label",{style:{display:"block",fontSize:11,color:"#64748b",fontWeight:600,marginBottom:4},children:"Accepted Quote *"}),t.jsxs("select",{value:c,onChange:z=>f(z.target.value),style:O,children:[t.jsx("option",{value:"",children:"Select quoteâ¦"}),l.length===0&&o&&t.jsx("option",{disabled:!0,value:"",children:"No accepted quotes"}),l.map(z=>t.jsxs("option",{value:z.id,children:[z.quote_number," â $",parseFloat(z.total).toFixed(2)]},z.id))]})]}):t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[t.jsxs("div",{children:[t.jsx("label",{style:{display:"block",fontSize:11,color:"#64748b",fontWeight:600,marginBottom:4},children:"Description *"}),t.jsx("input",{value:m,onChange:z=>b(z.target.value),placeholder:"e.g. Monthly rental â RO System",style:N})]}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[t.jsxs("div",{children:[t.jsx("label",{style:{display:"block",fontSize:11,color:"#64748b",fontWeight:600,marginBottom:4},children:"Qty"}),t.jsx("input",{type:"number",value:A,onChange:z=>v(z.target.value),style:N})]}),t.jsxs("div",{children:[t.jsx("label",{style:{display:"block",fontSize:11,color:"#64748b",fontWeight:600,marginBottom:4},children:"Unit Price ($) *"}),t.jsx("input",{type:"number",step:"0.01",value:x,onChange:z=>_(z.target.value),placeholder:"29.99",style:N})]})]}),t.jsxs("div",{children:[t.jsx("label",{style:{display:"block",fontSize:11,color:"#64748b",fontWeight:600,marginBottom:4},children:"Due Date"}),t.jsx("input",{type:"date",value:S,onChange:z=>T(z.target.value),style:N})]}),t.jsxs("div",{children:[t.jsx("label",{style:{display:"block",fontSize:11,color:"#64748b",fontWeight:600,marginBottom:4},children:"Notes"}),t.jsx("textarea",{value:j,onChange:z=>C(z.target.value),rows:2,style:{...N,resize:"none"}})]}),t.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,fontSize:13,color:"#94a3b8",curs
1115or:"pointer"},children:[t.jsx("input",{type:"checkbox",checked:L,onChange:z=>E(z.target.checked),style:{accentColor:"#0d7ea3"}}),"Send Stripe payment link to customer"]})]}),t.jsxs("div",{style:{display:"flex",gap:10,marginTop:4},children:[t.jsx("button",{onClick:e,style:{flex:1,padding:"11px 0",borderRadius:8,border:"1px solid #1e3a4f",background:"transparent",color:"#94a3b8",cursor:"pointer",fontSize:13,fontWeight:600},children:"Cancel"}),t.jsx("button",{onClick:R,disabled:h,style:{flex:1,padding:"11px 0",borderRadius:8,border:"none",background:"#0d7ea3",color:"#fff",cursor:"pointer",fontWeight:700,fontSize:13,opacity:h?.5:1},children:h?"Workingâ¦":p==="manual"&&L?"Send Pay Link":"Create Invoice"})]})]})]})}function sY(){const e=tY(),[n,r]=g.useState([]),[s,i]=g.useState(!0),[o,a]=g.useState(null),[l,d]=g.useState(!1),[c,f]=g.useState("all"),[p,u]=g.useState("");async function h(){i(!0);try{await QU(),r(await KU())}catch(_){console.error(_)}finally{i(!1)}}g.useEffect(()=>{h()},[]);const y=n.filter(_=>{const j=c==="all"||_.status===c,C=p.toLowerCase();return j&&(!C||(_.customer_name||"").toLowerCase().includes(C)||_.invoice_number.toLowerCase().includes(C))}),m=n.filter(_=>["sent","overdue","partially_paid","signed"].includes(_.status)).reduce((_,j)=>_+ac(j),0),b=n.filter(_=>_.status==="overdue").length,A=new Date().toISOString().slice(0,7),v=n.filter(_=>{var j;return _.status==="paid"&&((j=_.paid_at)==null?void 0:j.startsWith(A))}).reduce((_,j)=>_+j.amount_paid,0),x=_=>_==="all"?n.length:n.filter(j=>j.status===_).length;return t.jsxs("div",{style:{background:"#0f1923",minHeight:"100vh",color:"#e2e8f0",display:"flex",flexDirection:"column"},children:[t.jsxs("div",{style:{background:"#162232",borderBottom:"1px solid #1e3a4f",padding:"16px 20px",display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsx("div",{style:{fontWeight:800,fontSize:20,color:"#e2e8f0",lineHeight:1.2},children:"Invoices"}),t.jsx("div",{style:{color:"#64748b",fontSize:12,marginTop:2},children:"Track billing, payments, and balances"})]}),!e&&t.jsx("input",{placeholder:"Search customer or invoice #â¦",value:p,onChange:_=>u(_.target.value),style:{background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:8,color:"#e2e8f0",padding:"9px 14px",fontSize:13,outline:"none",width:220,flexShrink:0}}),t.jsx("button",{onClick:()=>d(!0),style:{padding:"10px 18px",borderRadius:8,border:"none",cursor:"pointer",background:"#0d7ea3",color:"#fff",fontWeight:700,fontSize:14,flexShrink:0,whiteSpace:"nowrap"},children:"+ New Invoice"})]}),e&&t.jsx("div",{style:{padding:"10px 16px",background:"#0f1923",borderBottom:"1px solid #1e3a4f"},children:t.jsx("input",{placeholder:"Search customer or invoice #â¦",value:p,onChange:_=>u(_.target.value),style:{background:"#162232",border:"1px solid #1e3a4f",borderRadius:8,color:"#e2e8f0",padding:"10px 14px",fontSize:14,outline:"none",width:"100%",boxSizing:"border-box"}})}),t.jsx("div",{style:{background:"#0c1a26",borderBottom:"1px solid #1e3a4f",padding:"10px 16px",display:"flex",gap:6,flexShrink:0,overflowX:"auto"},children:nY.map(_=>{const j=x(_.key),C=c===_.key;return t.jsxs("button",{onClick:()=>f(_.key),style:{flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:e?"8px 10px":"11px 8px",borderRadius:10,border:`1px solid ${C?_.color+"60":_.border}`,background:C?_.bg:"rgba(255,255,255,0.02)",color:C?_.color:"#475569",cursor:"pointer",fontSize:e?12:13,fontWeight:C?700:500,boxShadow:C?`0 0 14px ${_.color}20`:"none"},children:[t.jsx("span",{children:_.icon}),!e&&t.jsx("span",{children:_.label}),j>0&&t.jsx("span",{style:{background:C?_.color+"30":"rgba(255,255,255,0.06)",color:C?_.color:"#64748b",borderRadius:20,padding:"1px 6px",fontSize:11,fontWeight:700},children:j})]},_.key)})}),t.jsx("div",{style:{display:"flex",gap:10,padding:"12px 16px",borderBottom:"1px solid #1e3a4f",background:"#0f1923",flexShrink:0,overflowX:"auto"},children:[{label:"Outstanding",val:mn(m),color:"#60a5fa",sub:`${n.filter(_=>["sent","overdue"].includes(_.status)).length} invoices`},{label:"Overdue",val:String(b),color:b>0?"#f87171":"#94a3b8",sub:"need attention"},{label:"Paid MTD",val:mn(v),color:"#4ade80",sub:"this month"}].map(_=>t.jsxs("div",{style:{background:"#162232",border:"1px solid #1e3a4f",borderRadius:10,padding:e?"8px 12px":"10px 18px",flexShrink:0,minWidth:e?100:130},children:[t.jsx("div",{style:{color:"#64748b",fontSize:10,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.08em"},children:_.label}),t.jsx("div",{style:{color:_.color,fontWeight:800,fontSize:e?16:20,marginTop:3},children:_.val}),!e&&t.jsx("div",{style:{color:"#475569",fontSize:11,marginTop:2},children:_.sub})]},_.label))}),t.jsx("div",{style:{flex:1,overflowY:"auto",padding:e?"12px 12px":"16px 24px"},children:s?t.jsx("div",{style:{textAlign:"center",padding:60,color:"#64748b"},children:"Loading invoicesâ¦"}):y.length===0?t.jsxs("div",{style:{textAlign:"center",padding:60},children:[t.jsx("div",{style:{fontSize:40,marginBottom:12},children:"ð"}),t.jsx("div",{style:{color:"#64748b",fontSize:15},children:"No invoices found"}),t.jsx("button",{onClick:()=>d(!0),style:{marginTop:16,padding:"10px 24px",borderRadius:8,border:"none",cursor:"pointer",background:"#0d7ea3",color:"#fff",fontWeight:700},children:"Create one â"})]}):e?t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:10},children:y.map(_=>{const j=ac(_);return q8[_.status],t.jsxs("div",{onClick:()=>a(_),style:{background:"#162232",border:"1px solid #1e3a4f",borderRadius:12,padding:"14px 16px",cursor:"pointer"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:8},children:[t.jsx("span",{style:{fontSize:13,fontWeight:700,color:"#60a5fa",fontFamily:"monospace"},children:_.invoice_number}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[t.jsx(My,{invoice:_}),t.jsx($y,{status:_.status})]})]}),t.jsx("div",{style:{fontSize:15,fontWeight:700,color:"#e2e8f0",marginBottom:10},children:_.customer_name||"â"}),t.jsxs("div",{style:{display:"flex",gap:12,alignItems:"center",flexWrap:"wrap"},children:[t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:10,
1115color:"#64748b",textTransform:"uppercase",fontWeight:600},children:"Total"}),t.jsx("div",{style:{fontSize:15,fontWeight:800,color:"#e2e8f0"},children:mn(_.total)})]}),j>0&&t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:10,color:"#64748b",textTransform:"uppercase",fontWeight:600},children:"Balance"}),t.jsx("div",{style:{fontSize:15,fontWeight:800,color:"#f87171"},children:mn(j)})]}),t.jsxs("div",{style:{marginLeft:"auto"},children:[t.jsx("div",{style:{fontSize:10,color:"#64748b",textTransform:"uppercase",fontWeight:600},children:"Due"}),t.jsx("div",{style:{fontSize:13,color:"#94a3b8"},children:Go(_.due_date)})]})]})]},_.id)})}):t.jsx("div",{style:{background:"#162232",border:"1px solid #1e3a4f",borderRadius:12,overflow:"hidden"},children:t.jsxs("table",{style:{width:"100%",borderCollapse:"collapse"},children:[t.jsx("thead",{children:t.jsx("tr",{style:{background:"#0f1923",borderBottom:"1px solid #1e3a4f"},children:["Invoice #","Customer","Status","Total","Balance Due","Due Date","Created"].map((_,j)=>t.jsx("th",{style:{padding:"10px 14px",fontSize:11,fontWeight:700,color:"#64748b",textTransform:"uppercase",letterSpacing:"0.08em",textAlign:j>=3?"right":"left"},children:_},_))})}),t.jsx("tbody",{children:y.map(_=>t.jsxs("tr",{onClick:()=>a(_),style:{borderBottom:"1px solid #1a2a3a",cursor:"pointer",transition:"background 0.1s"},onMouseEnter:j=>j.currentTarget.style.background="#1a2e42",onMouseLeave:j=>j.currentTarget.style.background="transparent",children:[t.jsx("td",{style:{padding:"12px 14px",fontSize:13,fontWeight:700,color:"#60a5fa",fontFamily:"monospace"},children:_.invoice_number}),t.jsx("td",{style:{padding:"12px 14px",fontSize:13,fontWeight:600,color:"#e2e8f0"},children:_.customer_name||"â"}),t.jsx("td",{style:{padding:"12px 14px"},children:t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[t.jsx($y,{status:_.status}),t.jsx(My,{invoice:_})]})}),t.jsx("td",{style:{padding:"12px 14px",textAlign:"right",fontSize:13,fontWeight:700,color:"#e2e8f0"},children:mn(_.total)}),t.jsx("td",{style:{padding:"12px 14px",textAlign:"right",fontSize:13,fontWeight:700,color:ac(_)>0?"#f87171":"#4ade80"},children:mn(ac(_))}),t.jsx("td",{style:{padding:"12px 14px",textAlign:"right",fontSize:12,color:"#64748b"},children:Go(_.due_date)}),t.jsx("td",{style:{padding:"12px 14px",textAlign:"right",fontSize:12,color:"#64748b"},children:Go(_.created_at)})]},_.id))})]})})}),o&&t.jsx(rY,{invoice:o,onClose:()=>a(null),onRefresh:async()=>{if(await h(),o){const _=await D8(o.id);_&&a(_)}}}),l&&t.jsx(E3,{onClose:()=>d(!1),onCreated:h})]})}function iY(e,n,r,s){const i=Date.UTC(e,n-1,r,s,0,0),o=new Intl.DateTimeFormat("en-US",{timeZone:yu,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1}).formatToParts(new Date(i)),a=c=>{var f;return((f=o.find(p=>p.type===c))==null?void 0:f.value)||""};let l=+a("hour");return l===24&&(l=0),(Date.UTC(+a("year"),+a("month")-1,+a("day"),l,+a("minute"),0)-i)/6e4}function oY(e,n,r,s,i){const o=iY(e,n,r,s);return new Date(Date.UTC(e,n-1,r,s,i,0)-o*6e4).toISOString()}function P3(e,n){return oY(+e.slice(0,4),+e.slice(5,7),+e.slice(8,10),+n.slice(0,2),+n.slice(3,5))}const aY=["phone","text","email","walk_in","other"];function lY({customerId:e,customerName:n,onClose:r,onCreated:s}){const i=rt(),{user:o,profile:a}=Ee(),{data:l=[]}=vu(),{data:d=[]}=Ae({queryKey:["ticket_owners"],queryFn:E0}),[c,f]=g.useState("complaint"),[p,u]=g.useState("normal"),[h,y]=g.useState("phone"),[m,b]=g.useState(""),[A,v]=g.useState(""),[x,_]=g.useState(!0),[j,C]=g.useState(""),[S,T]=g.useState("09:00"),[L,E]=g.useState(""),[R,N]=g.useState(!1),[O,z]=g.useState(null),[P,D]=g.useState(null);g.useEffect(()=>{A||!(o!=null&&o.id)||d.some(te=>te.id===o.id)&&v(o.id)},[d,o==null?void 0:o.id,A]);const[M,k]=g.useState(null);g.useEffect(()=>{let te=!1;return w.from("addresses").select("id").eq("entity_type","customer").eq("entity_id",e).eq("is_primary",!0).limit(1).then(({data:U,error:W})=>{if(!te){if(W){k(null);return}k(((U==null?void 0:U.length)??0)>0)}}),()=>{te=!0}},[e]);async function q(){if(!m.trim()){z("Describe what the customer reported.");return}if(!(o!=null&&o.id)){z("Not signed in.");return}N(!0),z(null);const te={actor_id:o.id,actor_name:(a==null?void 0:a.full_name)??null};let U=P;if(!U)try{U=await rU({customer_id:e,category:c,priority:p,source:h,description:m.trim(),owner_id:A||null},te),D(U)}catch(W){z((W==null?void 0:W.message)||"Could not open the ticket."),N(!1);return}if(x)try{const W=j?P3(j,S):null;await T8({customer_id:e,notes:m.trim(),scheduled_at:W,assigned_technician_id:L||null,ticket_id:U.id},te),W&&await iU(U.id,"scheduled")}catch(W){z(`Ticket ${U.ticket_number} was opened, but the visit was not booked: ${(W==null?void 0:W.message)||"unknown error"}. Press the button again to retry the visit only, or untick "Book a tech visit now" and add the visit later.`),i.invalidateQueries(),N(!1);return}i.invalidateQueries(),s()}const $=!!P,I=R?"Savingâ¦":P?x?"Retry booking the visit":"Done":x?j?"Open ticket & book visit":"Open ticket & send to dispatch":"Open ticket",B={color:"#94a3b8",fontSize:12,fontWeight:600},J={width:"100%",backgroundColor:"rgba(15, 23, 42, 0.6)",border:"1px solid rgba(148, 163,
1115184, 0.25)",borderRadius:8,padding:"8px 10px",color:"#e2e8f0",fontSize:14},ae=$?{opacity:.55}:{};return t.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4",style:{backgroundColor:"rgba(0,0,0,0.6)"},onClick:R?void 0:r,children:t.jsxs("div",{className:"w-full max-w-lg rounded-xl",style:{backgroundColor:"#0f172a",border:"1px solid rgba(148,163,184,0.2)",maxHeight:"92vh",overflowY:"auto"},onClick:te=>te.stopPropagation(),children:[t.jsxs("div",{className:"px-5 py-4",style:{borderBottom:"1px solid rgba(148,163,184,0.15)"},children:[t.jsx("div",{style:{color:"#e2e8f0",fontSize:16,fontWeight:700},children:P?`Ticket ${P.ticket_number}`:"New service ticket"}),n&&t.jsx("div",{style:{color:"#64748b",fontSize:13,marginTop:2},children:n})]}),t.jsxs("div",{className:"px-5 py-4 space-y-4",children:[t.jsxs("div",{className:"flex gap-3",style:ae,children:[t.jsxs("div",{style:{flex:1},children:[t.jsx("label",{style:B,children:"Category"}),t.jsx("select",{value:c,disabled:$,onChange:te=>f(te.target.value),style:{...J,marginTop:6},children:Object.keys(da).map(te=>t.jsx("option",{value:te,children:da[te]},te))})]}),t.jsxs("div",{style:{flex:1},children:[t.jsx("label",{style:B,children:"Priority"}),t.jsx("select",{value:p,disabled:$,onChange:te=>u(te.target.value),style:{...J,marginTop:6},children:Object.keys(Cl).map(te=>t.jsx("option",{value:te,children:Cl[te]},te))})]}),t.jsxs("div",{style:{flex:1},children:[t.jsx("label",{style:B,children:"How did they reach us?"}),t.jsx("select",{value:h,disabled:$,onChange:te=>y(te.target.value),style:{...J,marginTop:6},children:aY.map(te=>t.jsx("option",{value:te,children:v8[te]},te))})]})]}),t.jsxs("div",{style:ae,children:[t.jsx("label",{style:B,children:"What did the customer report?"}),t.jsx("textarea",{value:m,onChange:te=>b(te.target.value),disabled:$,rows:3,autoFocus:!0,placeholder:"Softener making a loud noise during regeneration, started Friday.",style:{...J,marginTop:6,resize:"vertical"}})]}),t.jsxs("div",{style:ae,children:[t.jsx("label",{style:B,children:"Owner â responsible until it's closed"}),t.jsxs("select",{value:A,disabled:$,onChange:te=>v(te.target.value),style:{...J,marginTop:6},children:[t.jsx("option",{value:"",children:"No owner yet"}),d.map(te=>t.jsx("option",{value:te.id,children:te.full_name},te.id))]})]}),t.jsx("div",{style:{borderTop:"1px dashed rgba(148,163,184,0.25)",paddingTop:12},children:t.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer",color:"#e2e8f0",fontSize:13,fontWeight:600},children:[t.jsx("input",{type:"checkbox",checked:x,onChange:te=>_(te.target.checked)}),"Book a tech visit now"]})}),x&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex gap-3",children:[t.jsxs("div",{style:{flex:2},children:[t.jsx("label",{style:B,children:"Date"}),t.jsx("input",{type:"date",value:j,onChange:te=>C(te.target.value),style:{...J,marginTop:6}})]}),t.jsxs("div",{style:{flex:1},children:[t.jsx("label",{style:B,children:"Time"}),t.jsx("input",{type:"time",value:S,onChange:te=>T(te.target.value),disabled:!j,style:{...J,marginTop:6,opacity:j?1:.5}})]})]}),t.jsxs("div",{children:[t.jsx("label",{style:B,children:"Technician"}),t.jsxs("select",{value:L,onChange:te=>E(te.target.value),style:{...J,marginTop:6},children:[t.jsx("option",{value:"",children:"Not assigned yet"}),l.map(te=>t.jsx("option",{value:te.id,children:te.full_name},te.id))]})]}),M===!1&&t.jsx("div",{className:"rounded-lg px-3 py-2 text-sm",style:{backgroundColor:"rgba(239, 68, 68, 0.12)",border:"1px solid rgba(239, 68, 68, 0.3)",color:"#f87171"},children:"This customer has no address on file. The visit will be created, but it will reach the technician without one."}),!j&&t.jsx("div",{className:"rounded-lg px-3 py-2 text-sm",style:{backgroundColor:"rgba(251, 191, 36, 0.12)",border:"1px solid rgba(251, 191, 36, 0.3)",color:"#fbbf24"},children:"No date set. The visit will sit on the dispatch board as ready to schedule, and the ticket stays Open."})]}),!x&&t.jsx("div",{style:{color:"#94a3b8",fontSize:12},children:"The ticket opens with no visit â for a phone fix, or while waiting on the customer."}),t.jsx("div",{style:{color:"#64748b",fontSize:12},children:"No text message is sent to the customer."}),O&&t.jsx("div",{className:"rounded-lg px-3 py-2 text-sm",style:{backgroundColor:"rgba(239, 68, 68, 0.12)",border:"1px solid rgba(239, 68, 68, 0.3)",color:"#f87171"},children:O})]}),t.jsxs("div",{className:"px-5 py-4 flex justify-end gap-2",style:{borderTop:"1px solid rgba(148,163,184,0.15)"},children:[t.jsx("button",{onClick:P?()=>{i.invalidateQueries(),s()}:r,disabled:R,className:"rounded-lg px-4 py-2 text-sm font-semibold",style:{color:"#94a3b8",border:"1px solid rgba(148,163,184,0.25)"}
1115,children:P?"Close":"Cancel"}),t.jsx("button",{onClick:P&&!x?()=>{i.invalidateQueries(),s()}:q,disabled:R||!m.trim(),className:"rounded-lg px-4 py-2 text-sm font-semibold",style:{backgroundColor:R||!m.trim()?"rgba(52,211,153,0.35)":"#34d399",color:"#052e21"},children:I})]})]})})}function q3(e){return Ae({queryKey:["service_tickets",e],queryFn:()=>tU(e),enabled:!!e})}const id="America/Indiana/Indianapolis",Fy=864e5;function Mj(e){return e?new Date(e).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",timeZone:id}):""}function ff(e){return e?new Date(e).toLocaleString("en-US",{weekday:"short",month:"short",day:"numeric",hour:"numeric",minute:"2-digit",timeZone:id}):"not scheduled yet"}function dY(e){const n=e.filter(r=>r.job_status!=="complete"&&r.job_status!=="cancelled");return n.length===0?null:[...n].sort((r,s)=>r.scheduled_at?s.scheduled_at?r.scheduled_at.localeCompare(s.scheduled_at):-1:1)[0]}function cY({customerId:e}){const{data:n=[],isLoading:r,isError:s,error:i}=q3(e);if(r)return t.jsx("div",{className:"text-sm text-muted",children:"Loading ticketsâ¦"});if(s)return t.jsxs("div",{className:"text-sm",style:{color:"#f87171"},children:["Could not load service tickets: ",(i==null?void 0:i.message)??"unknown error"]});const o=n.filter(u=>u.status!=="closed"),a=n.filter(u=>u.status==="closed"),l=Date.now()-365*Fy,d=n.flatMap(u=>u.jobs).filter(u=>u.job_status!=="cancelled"&&new Date(u.scheduled_at??u.completed_at??0).getTime()>=l).length,c=Date.now()-90*Fy,f={};for(const u of n)new Date(u.created_at).getTime()>=c&&(f[u.category]=(f[u.category]??0)+1);const p=Object.entries(f).sort((u,h)=>h[1]-u[1]).find(([,u])=>u>=2);return t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{className:"grid grid-cols-4 gap-3",children:[t.jsx(Lp,{label:"Open",value:String(o.length),color:"#93c5fd"}),t.jsx(Lp,{label:"Total tickets",value:String(n.length),color:"#e2e8f0"}),t.jsx(Lp,{label:"Visits (12 mo)",value:String(d),color:"#e2e8f0"}),t.jsx(Lp,{label:"Repeat issue?",value:p?`${da[p[0]]} Ã${p[1]} in 90 days`:"None",color:p?"#fbbf24":"#94a3b8",small:!0})]}),n.length===0&&t.jsxs("div",{className:"bg-card border border-border rounded-xl p-6 text-center text-sm text-muted",children:["No service tickets yet. Use ",t.jsx("b",{children:"New service ticket"})," at the top of the page when this customer calls with a problem."]}),o.length>0&&t.jsx(Fj,{title:"Open",children:o.map(u=>t.jsx(Bj,{ticket:u},u.id))}),a.length>0&&t.jsx(Fj,{title:"History",children:a.map(u=>t.jsx(Bj,{ticket:u},u.id))})]})}function Fj({title:e,children:n}){return t.jsxs("div",{children:[t.jsx("div",{className:"text-xs font-bold text-muted uppercase tracking-wide mb-2",children:e}),t.jsx("div",{className:"space-y-2",children:n})]})}function Lp({label:e,value:n,color:r,small:s}){return t.jsxs("div",{className:"bg-card border border-border rounded-xl p-3",children:[t.jsx("div",{className:"text-xs text-muted uppercase tracking-wide mb-1",children:e}),t.jsx("div",{className:s?"text-sm font-bold":"text-lg font-bold",style:{color:r},children:n})]})}function Bj({ticket:e}){var a,l;const[n,r]=g.useState(!1),s=j8[e.status],i=dY(e.jobs),o=e.status==="closed";return t.jsxs("div",{className:"bg-card border border-border rounded-xl",style:{borderLeft:o?void 0:`3px solid ${s.fg}`},children:[t.jsxs("button",{onClick:()=>r(d=>!d),className:"w-full text-left px-4 py-3",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[t.jsx("span",{className:"text-sm font-bold text-white",children:e.ticket_number}),t.jsxs("span",{className:"text-sm text-slate-300",children:["· ",e.subject]}),t.jsx("span",{className:"text-xs font-bold px-2 py-0.5 rounded-full",style:{backgroundColor:s.bg,color:s.fg},children:_8[e.status]})]}),t.jsxs("div",{className:"flex items-center gap-3 flex-shrink-0",children:[e.priority!=="normal"&&t.jsxs("span",{className:"text-xs font-bold",style:{color:w8[e.priority]},children:[e.priority==="high"||e.priority==="urgent"?"â² ":"",Cl[e.priority]]}),t.jsx("span",{className:"text-xs text-muted",children:n?"â¾":"â¸"})]})]}),t.jsxs("div",{className:"text-xs text-muted mt-1",children:[da[e.category]," · Opened ",Mj(e.created_at)," via ",v8[e.source].toLowerCase()," · ","Owner ",t.jsx("span",{className:"text-slate-300 font-semibold",children:((a=e.owner)==null?void 0:a.full_name)??"none"}),o&&e.closed_at&&t.jsxs(t.Fragment,{children:[" · Closed ",Mj(e.closed_at)]})]}),!o&&t.jsxs("div",{className:"text-xs text-slate-300 mt-1.5",children:["ð§ ",i?t.jsxs(t.Fragment,{children:["Visit ",ff(i.scheduled_at)," · ",((l=i.assigned_technician)==null?void 0:l.full_name)??"no tech yet"]}):e.jobs.length>0?"All visits done":"No visit booked"]}),o&&e.resolution&&t.jsxs("div",{className:"text-xs text-muted mt-1.5",children:["Resolution: ",e.resolution]})]}),n&&t.jsxs("div",{className:"px-4 pb-4 space-y-3",style:{borderTop:"1px solid rgba(148,163,184,0.12)"},children:[t.jsxs("div",{className:"pt-3",children:[t.jsx("div",{className:"text-xs font-bold text-muted uppercase tracking-wide mb-1",children:"What the customer reported"}),t.jsx("div",{className:"text-sm text-slate-300 whitespace-pre-wrap",children:e.description||e.subject})]}),t.jsx(fY,{ticket:e}),t.jsx(uY,{ticket:e}),t.jsx(ru,{entityType:"service_ticket",entityId:e.id,section:"general",visibilityDefault:"all",visibilitySelectorMode:"collapsed",title:"Ticket notes"}),t.jsx(pY,{ticketId:e.id})]})]})}const Eo=(e,n=!1)=>({fontSize:12,fontWeight:600,padding:"5px 11px",borderRadius:8,cursor:"pointer",background:n?e:`${e}1f`,color:n?"#052e21":e,border:`1px solid ${e}55`}),Xd={width:"100%",background:"rgba(15,23,42,0.6)",border:"1px solid rgba(148,163,184,0.25)",borderRadius:8,padding:"7px 9px",color:"#e2e8f0",fontSize:13};function By(e=0){return new Intl.DateTimeFormat("en-CA",{timeZone:id,year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date(Date.now()+e*Fy))}function uY({ticket:e}){const n=rt(),{user:r,profile:s}=Ee(),i={actor_id:(r==null?void 0:r.id)??"",actor_name:(s==null?void 0:s.full_name)??null},{data:o=[]}=Ae({queryKey:["ticket_owners"],queryFn:E0}),{data:a=[]}=Ae({queryKey:["ticket_tasks",e.id],queryFn:()=>S8(e.id)}),[l,d]=g.useState(null),[c,f]=g.useState(""),[p,u]=g.useState(By(1)),[h,y]=g.useState(e.owner_id??""),[m,b]=g.useState(!1),[A,v]=g.useState(!1),[x,_]=g.useState(null);function j(){n.invalidateQueries({queryKey:["service_tickets"]}),n.invalidateQueries({queryKey:["ticket_tasks",e.id]}),n.invalidateQueries({queryKey:["ticket_timeline",e.id]}),n.invalidateQueries({queryKey:["notes"]}),n.invalidateQueries({queryKey:["jobs"]})}async function C(N){if(!(r!=null&&r.id)){_("Not signed in.");return}v(!0),_(null);try{await N(),d(null),f(""),j()}catch(O){_((O==null?void 0:O.message)||"Something went wrong.")}finally{v(!1)}}function S(N){_(null),d(N),f(N==="close"?e.resolution??"":""),b(N==="close"),N==="task"&&(u(By(1)),y(e.owner_id??""))}const T=a.filter(N=>!N.completed_at),L=e.jobs.filter(N=>
1115N.job_status!=="complete"&&N.job_status!=="cancelled"),E=e.status,R=N=>{var O;return((O=o.find(z=>z.id===N))==null?void 0:O.full_name)??(N?"someone":"nobody")};return t.jsxs("div",{className:"bg-card border border-border rounded-xl p-3 space-y-3",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{className:"text-xs font-bold text-muted uppercase tracking-wide",children:"Owner"}),t.jsxs("select",{value:e.owner_id??"",disabled:A||E==="closed",onChange:N=>{const O=N.target.value||null;C(()=>dU(e,O,O?R(O):null,i))},style:{...Xd,width:"auto",padding:"4px 8px",fontSize:12},children:[t.jsx("option",{value:"",children:"No owner"}),o.map(N=>t.jsx("option",{value:N.id,children:N.full_name},N.id))]})]}),t.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[(E==="open"||E==="scheduled"||E==="in_progress")&&t.jsx("button",{disabled:A,style:Eo("#f9a8d4"),onClick:()=>C(()=>cU(e,i)),children:"Waiting on customer"}),E==="waiting_on_customer"&&t.jsx("button",{disabled:A,style:Eo("#93c5fd"),onClick:()=>C(()=>q0(e,i)),children:"Back to open"}),E!=="resolved"&&E!=="closed"&&t.jsx("button",{disabled:A,style:Eo("#4ade80"),onClick:()=>S("resolve"),children:"Resolveâ¦"}),E==="resolved"&&t.jsx("button",{disabled:A,style:Eo("#34d399",!0),onClick:()=>S("close"),children:"Close ticketâ¦"}),(E==="resolved"||E==="closed")&&t.jsx("button",{disabled:A,style:Eo("#fbbf24"),onClick:()=>S("reopen"),children:"Reopenâ¦"})]})]}),E==="resolved"&&l===null&&t.jsxs("div",{className:"text-xs",style:{color:"#4ade80"},children:["Resolved",e.resolution?`: ${e.resolution}`:""," â confirm with the customer, then close it."]}),l&&l!=="task"&&t.jsxs("div",{className:"space-y-2",children:[t.jsxs("div",{className:"text-xs font-semibold text-slate-300",children:[l==="resolve"&&"What fixed it?",l==="close"&&"Confirmed with the customer? What fixed it (required to close)",l==="reopen"&&"Why is it being reopened? (optional)"]}),t.jsx("textarea",{rows:2,value:c,onChange:N=>f(N.target.value),autoFocus:!0,style:{...Xd,resize:"vertical"},placeholder:l==="reopen"?"Same noise came back on Monday":"Replaced injector and flow control, ran a manual regen â quiet"}),l==="resolve"&&t.jsxs("div",{className:"text-xs text-muted",children:["Resolving gives ",R(e.owner_id)," a task to confirm with the customer in 2 days."]}),l==="close"&&T.length>0&&t.jsxs("div",{className:"text-xs text-muted",children:["Closing also completes ",T.length," open task",T.length===1?"":"s"," on this ticket."]}),(l==="resolve"||l==="close")&&L.length>0&&t.jsxs("div",{className:"rounded-lg px-3 py-2 text-xs",style:{background:"rgba(251,191,36,0.10)",border:"1px solid rgba(251,191,36,0.3)",color:"#fbbf24"},children:[t.jsx("div",{className:"font-semibold mb-1",children:L.length===1?"A visit is still booked on this ticket:":`${L.length} visits are still booked on this ticket:`}),L.map(N=>{var O;return t.jsxs("div",{style:{color:"#fde68a"},children:["⢠",ff(N.scheduled_at)," · ",((O=N.assigned_technician)==null?void 0:O.full_name)??"no tech"]},N.id)}),t.jsxs("label",{className:"flex items-center gap-2 mt-2",style:{color:"#e2e8f0",cursor:"pointer"},children:[t.jsx("input",{type:"checkbox",checked:m,onChange:N=>b(N.target.checked)}
1115),"Cancel ",L.length===1?"this visit":"these visits"," â it comes off Dispatch and the Calendar"]})]}),t.jsxs("div",{className:"flex gap-2 justify-end",children:[t.jsx("button",{disabled:A,onClick:()=>{d(null),_(null)},className:"text-xs text-muted px-3",children:"Cancel"}),t.jsx("button",{disabled:A||l!=="reopen"&&!c.trim(),style:{...Eo("#34d399",!0),opacity:A||l!=="reopen"&&!c.trim()?.5:1},onClick:()=>C(()=>l==="resolve"?k8(e,c,i,{cancelVisitIds:m?L.map(N=>N.id):[]}):l==="close"?uU(e,c,i,{cancelVisitIds:m?L.map(N=>N.id):[]}):pU(e,c,i)),children:A?"Savingâ¦":l==="resolve"?"Resolve":l==="close"?"Close ticket":"Reopen"})]})]}),t.jsxs("div",{children:[t.jsxs("div",{className:"flex items-center justify-between mb-1",children:[t.jsxs("span",{className:"text-xs font-bold text-muted uppercase tracking-wide",children:["Owner tasks (",T.length," open)"]}),E!=="closed"&&l!=="task"&&t.jsx("button",{className:"text-xs font-semibold",style:{color:"#60a5fa"},onClick:()=>S("task"),children:"+ Add task"})]}),a.length===0&&l!=="task"&&t.jsx("div",{className:"text-xs text-muted italic",children:"No tasks on this ticket"}),a.map(N=>t.jsxs("label",{className:"flex items-center gap-2 text-xs py-0.5",style:{color:N.completed_at?"#64748b":"#cbd5e1",cursor:N.completed_at?"default":"pointer"},children:[t.jsx("input",{type:"checkbox",checked:!!N.completed_at,disabled:A||!!N.completed_at,onChange:()=>C(()=>aU(e,N,i))}),t.jsx("span",{style:{textDecoration:N.completed_at?"line-through":"none"},children:N.title}),t.jsxs("span",{className:"text-muted",children:["· ",R(N.assigned_to)," · due ",N.due_date]})]},N.id)),l==="task"&&t.jsxs("div",{className:"space-y-2 mt-2",children:[t.jsx("input",{value:c,onChange:N=>f(N.target.value),autoFocus:!0,style:Xd,placeholder:"Call customer to confirm Wednesday window"}),t.jsxs("div",{className:"flex gap-2",children:[t.jsx("input",{type:"date",value:p,onChange:N=>u(N.target.value),style:{...Xd,width:170}}),t.jsxs("select",{value:h,onChange:N=>y(N.target.value),style:{...Xd,width:"auto"},children:[t.jsx("option",{value:"",children:"Unassigned"}),o.map(N=>t.jsx("option",{value:N.id,children:N.full_name},N.id))]}),t.jsxs("div",{className:"flex gap-2 ml-auto",children:[t.jsx("button",{disabled:A,onClick:()=>{d(null),_(null)},className:"text-xs text-muted px-3",children:"Cancel"}),t.jsx("button",{disabled:A||!c.trim()||!p,style:{...Eo("#60a5fa",!0),opacity:A||!c.trim()||!p?.5:1},onClick:()=>C(()=>lf(e,c,p,h||null,i)),children:A?"Savingâ¦":"Add task"})]})]})]})]}),x&&t.jsx("div",{className:"text-xs rounded-lg px-3 py-2",style:{background:"rgba(239,68,68,0.12)",color:"#f87171"},children:x})]})}function pY({ticketId:e}){const{data:n=[],isLoading:r}=Ae({queryKey:["ticket_timeline",e],queryFn:()=>lU(e)});return t.jsxs("div",{className:"bg-card border border-border rounded-xl p-3",children:[t.jsx("div",{className:"text-xs font-bold text-muted uppercase tracking-wide mb-2",children:"Timeline"}),r&&t.jsx("div",{className:"text-xs text-muted italic",children:"Loadingâ¦"}),!r&&n.length===0&&t.jsx("div",{className:"text-xs text-muted italic",children:"No events yet. Tickets opened before this update have no timeline entries."}),n.map(s=>t.jsxs("div",{className:"text-xs py-0.5 text-slate-300",children:[t.jsx("span",{className:"text-muted",children:new Date(s.created_at).toLocaleString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",timeZone:id})})," · ",s.description,s.actor_name&&t.jsxs("span",{className:"text-muted",children:[" â ",s.actor_name]})]},s.id))]})}function hY(e){if(!e)return{date:By(1),time:"09:00"};const n=new Date(e),r=new Intl.DateTimeFormat("en-CA",{timeZone:id,year:"numeric",month:"2-digit",day:"2-digit"}).format(n);let s=new Intl.DateTimeFormat("en-GB",{timeZone:id,hour:"2-digit",minute:"2-digit",hour12:!1}).format(n);return s.startsWith("24")&&(s="00"+s.slice(2)),{date:r,time:s}}function fY({ticket:e}){const n=rt(),{user:r,profile:s}=Ee(),{data:i=[]}=vu(),[o,a]=g.useState(null),[l,d]=g.useState(""),[c,f]=g.useState("09:00"),[p,u]=g.useState(""),[h,y]=g.useState(!1),[m,b]=g.useState(null);function A(j,C){var T;const S=hY((C==null?void 0:C.scheduled_at)??null);d(S.date),f(S.time),u(((T=C==null?void 0:C.assigned_technician)==null?void 0:T.id)??""),b(null),a(j)}async function v(){var C;if(!(r!=null&&r.id)){b("Not signed in.");return}if(!l){b("Pick a date.");return}y(!0),b(null);const j={actor_id:r.id,actor_name:(s==null?void 0:s.full_name)??null};try{const S=P3(l,c),T=(C=i.find(E=>E.id===p))==null?void 0:C.full_name,L=`${ff(S)}${T?` · ${T}`:""}`;o==="new"?(await T8({customer_id:e.customer_id,notes:e.description||e.subject,scheduled_at:S,assigned_technician_id:p||null,ticket_id:e.id},j),await mU(e,L,j)):o&&await gU(e,o,S,p||null,L,j),a(null),n.invalidateQueries({queryKey:["service_tickets"]}),n.invalidateQueries({queryKey:["ticket_timeline",e.id]}),n.invalidateQueries({queryKey:["jobs"]})}catch(S){b((S==null?void 0:S.message)||"Could not save the visit.")}finally{y(!1)}}const x=j=>
1115j.job_status!=="complete"&&j.job_status!=="cancelled",_={background:"rgba(15,23,42,0.6)",border:"1px solid rgba(148,163,184,0.25)",borderRadius:8,padding:"5px 8px",color:"#e2e8f0",fontSize:12};return t.jsxs("div",{children:[t.jsxs("div",{className:"flex items-center justify-between mb-1",children:[t.jsxs("span",{className:"text-xs font-bold text-muted uppercase tracking-wide",children:["Visits (",e.jobs.length,")"]}),e.status!=="closed"&&o===null&&t.jsx("button",{className:"text-xs font-semibold",style:{color:"#60a5fa"},onClick:()=>A("new"),children:"+ Book visit"})]}),e.jobs.length===0&&o!=="new"&&t.jsx("div",{className:"text-xs text-muted italic",children:"No visits on this ticket"}),e.jobs.map((j,C)=>{var S;return t.jsxs("div",{className:"text-xs py-0.5",style:{color:x(j)?"#cbd5e1":"#64748b"},children:["Visit ",C+1," · ",ff(j.scheduled_at)," · ",((S=j.assigned_technician)==null?void 0:S.full_name)??"no tech",t.jsxs("span",{className:"text-muted",children:[" · ",j.job_status.replace(/_/g," ")]}),x(j)&&o===null&&e.status!=="closed"&&t.jsx("button",{className:"ml-2 font-semibold",style:{color:"#60a5fa"},onClick:()=>A(j.id,j),children:"Change time"})]},j.id)}),o!==null&&t.jsxs("div",{className:"mt-2 rounded-lg p-3 space-y-2",style:{background:"rgba(96,165,250,0.06)",border:"1px solid rgba(96,165,250,0.25)"},children:[t.jsx("div",{className:"text-xs font-semibold text-slate-300",children:o==="new"?"Book another visit on this ticket":"Move this visit"}),t.jsxs("div",{className:"flex gap-2 flex-wrap items-center",children:[t.jsx("input",{type:"date",value:l,onChange:j=>d(j.target.value),style:_}),t.jsx("input",{type:"time",value:c,onChange:j=>f(j.target.value),style:_}),t.jsxs("select",{value:p,onChange:j=>u(j.target.value),style:_,children:[t.jsx("option",{value:"",children:"No tech yet"}),i.map(j=>t.jsx("option",{value:j.id,children:j.full_name},j.id))]}),t.jsxs("div",{className:"flex gap-2 ml-auto",children:[t.jsx("button",{disabled:h,className:"text-xs text-muted px-2",onClick:()=>{a(null),b(null)},children:"Cancel"}),t.jsx("button",{disabled:h||!l,onClick:v,style:{fontSize:12,fontWeight:600,padding:"5px 11px",borderRadius:8,background:"#60a5fa",color:"#0b1222",opacity:h||!l?.5:1},children:h?"Savingâ¦":o==="new"?"Book visit":"Save new time"})]})]}),t.jsx("div",{className:"text-xs text-muted",children:"No text message is sent to the customer. Indiana time."}),m&&t.jsx("div",{className:"text-xs",style:{color:"#f87171"},children:m})]})]})}function gY(){var oe;const{customerId:e}=di(),n=gt(),[r]=If(),[s,i]=g.useState(!1),[o,a]=g.useState(!1),{data:l,isLoading:d,error:c}=rZ(e||""),{data:f}=V0(e||""),{data:p}=ig(e||""),{data:u}=sZ(e||""),{data:h}=a3(e||""),{data:y}=l3(e||""),{data:m}=o3(e||""),{data:b=[]}=q3(e||""),[A,v]=g.useState(null),[x,_]=g.useState(0);g.useEffect(()=>{if(!e)return;async function ne(){try{const{data:ge,error:be}=await w.from("customer_service_plans").select("id, status, price_monthly, plan_id").eq("customer_id",e).in("status",["active","pending_payment_method"]).order("created_at",{ascending:!1});if(!be&&ge){_(ge.length);const we=ge.find(F=>F.status==="active")||ge[0]||null;v(we)}}catch{}}ne()},[e]);const[j,C]=g.useState(()=>r.get("tab")==="service"?"service":"overview"),[S,T]=g.useState(!1),[L,E]=g.useState(""),[R,N]=g.useState(!1),[O,z]=g.useState(null);if(d)return t.jsx("div",{className:"flex items-center justify-center h-full",children:t.jsx("div",{className:"text-muted text-sm",children:"Loading customer..."})});if(c||!l)return t.jsx("div",{className:"flex items-center justify-center h-full",children:t.jsxs("div",{className:"text-center",children:[t.jsx("div",{className:"text-sm mb-2",style:{color:"#f87171"},children:"Customer not found."}),t.jsx("button",{onClick:()=>n("/customers"),className:"text-accent text-sm hover:underline",children:"â Back"})]})});const P=(f||[]).filter(ne=>ne.is_active!==!1),D=P.filter(ne=>ne.ownership_type==="purchased").length,M=P.filter(ne=>ne.ownership_type==="rented").length,k=(u||[]).filter(ne=>ne.warranty_status==="warning"||ne.warranty_status==="void"),q=k.filter(ne=>ne.warranty_status==="void"),$=k.filter(ne=>ne.warranty_status==="warning"),I=!!A;
1115(p||[]).find(ne=>ne.status==="active");const B=(p||[]).length>0,J=(y||[]).filter(ne=>ne.status==="overdue"),ae=(y||[]).filter(ne=>ne.status==="due_soon"),te=l.lifecycle_stage==="at_risk",U=q.length>0||te||J.length>0,W=m?[m.address_line1,m.address_line2,m.city,m.state,m.zip].filter(Boolean).join(", "):"";let G="None",V="No active plan",ee="#94a3b8";if(I){const ne=((oe=A==null?void 0:A.service_plans)==null?void 0:oe.name)||"Service Plan",ge=A.price?`$${Number(A.price).toFixed(2)}`:"",be=A.billing_cycle==="yearly"?"/yr":A.billing_cycle==="monthly"?"/mo":"";A.status==="active"?(G=x>1?`${x} Active`:"Active",V=ge?`${ne} â ${ge}${be}`:ne,ee="#4ade80"):A.status==="pending_payment_method"&&(G="Pending",V=`${ne} â needs card`,ee="#fbbf24")}const re=b.filter(ne=>ne.status!=="closed").length,Q=[{key:"overview",label:"Overview",show:!0},{key:"systems",label:"Systems",show:!0},{key:"rental",label:"Rental & Buyout",show:B},{key:"billing",label:"Billing",show:!0},{key:"quotes",label:"Quotes",show:!0},{key:"service_plans",label:"Service Plans",show:!0},{key:"service",label:re>0?`Service (${re})`:"Service",show:!0},{key:"shipments",label:"Shipments",show:!0},{key:"water_tests",label:"Water Tests",show:!0},{key:"maintenance",label:"Maintenance",show:!1},{key:"activity",label:"Activity",show:!0},{key:"documents",label:"Documents",show:!0}];return t.jsxs("div",{className:"flex flex-col h-full",children:[t.jsxs("div",{className:"flex items-start justify-between mb-3 flex-shrink-0",children:[t.jsxs("div",{children:[t.jsx("button",{onClick:()=>n("/customers"),className:"text-xs text-muted hover:text-accent transition-colors mb-2 flex items-center gap-1",children:"â Back to Customers"}),t.jsx("h1",{className:"text-xl font-bold text-white",children:l.full_name}),l.customer_number&&t.jsx("div",{className:"text-xs font-mono mt-0.5",style:{color:"#0d7ea3"},children:l.customer_number}),W&&t.jsx("div",{className:"text-sm text-muted mt-0.5",children:W}),t.jsxs("div",{className:"text-xs text-muted mt-0.5",children:[l.phone,l.email&&` · ${l.email}`]})]}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[t.jsx("button",{onClick:()=>a(!0),style:{padding:"7px 16px",borderRadius:8,border:"1px solid rgba(251,191,36,0.3)",background:"rgba(251,191,36,0.1)",color:"#fbbf24",fontSize:13,fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",gap:6},children:"ð§ New service ticket"}),t.jsx("button",{onClick:()=>i(!0),style:{padding:"7px 16px",borderRadius:8,border:"1px solid rgba(74,222,128,0.3)",background:"rgba(74,222,128,0.1)",color:"#4ade80",fontSize:13,fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",gap:6},children:"ð° Quick Invoice"}),t.jsx("button",{onClick:()=>{T(!0),z(null),E("")},style:{padding:"7px 16px",borderRadius:8,border:"1px solid rgba(6,182,212,0.3)",background:"rgba(6,182,212,0.1)",color:"#06b6d4",fontSize:13,fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",gap:6},children:"ð¬ Send Text"}),t.jsx("div",{className:`stage-badge border ${uZ[l.lifecycle_stage]||""}`,children:d3[l.lifecycle_stage]||l.lifecycle_stage})]})]}),o&&t.jsx(lY,{customerId:l.id,customerName:l.full_name,onClose:()=>a(!1),onCreated:()=>{a(!1),C("service")}}),s&&t.jsx(E3,{initialCustomerId:l.id,onClose:()=>i(!1),onCreated:()=>i(!1)}),U&&t.jsxs("div",{className:"space-y-2 mb-3 flex-shrink-0",children:[q.length>0&&t.jsxs("div",{className:"rounded-lg px-4 py-2.5 text-sm font-semibold flex items-center gap-2",style:{backgroundColor:"rgba(239, 68, 68, 0.12)",border:"1px solid rgba(239, 68, 68, 0.3)",color:"#f87171"},children:[t.jsx("span",{children:"â ï¸"}),t.jsxs("span",{children:[q.length," warranty ",q.length===1?"record":"records"," VOID â compliance action required"]})]}),$.length>0&&!q.length&&t.jsxs("div",{className:"rounded-lg px-4 py-2.5 text-sm font-semibold flex items-center gap-2",style:{backgroundColor:"rgba(245, 158, 11, 0.12)",border:"1px solid rgba(245, 158, 11, 0.3)",color:"#fbbf24"},children:[t.jsx("span",{children:"â ï¸"}),t.jsxs("span",{children:[$.length," warranty ",$.length===1?"record is":"records are"," at warning status"]})]}),J.length>0&&t.jsxs("div",{className:"rounded-lg px-4 py-2.5 text-sm font-semibold flex items-center gap-2",style:{backgroundColor:"rgba(245, 158, 11, 0.12)",border:"1px solid rgba(245, 158, 11, 0.3)",color:"#fbbf24"},children:[t.jsx("span",{children:"ð§"}),t.jsxs("span",{children:[J.length," overdue service ",J.length===1?"item":"items"]})]}),te&&t.jsxs("div",{className:"rounded-lg px-4 py-2.5 text-sm font-semibold flex items-center gap-2",style:{backgroundColor:"rgba(239, 68, 68, 0.12)",border:"1px solid rgba(239, 68, 68, 0.3)",color:"#f87171"},children:[t.jsx("span",{children:"ð¨"}),t.jsx("span",{children:"Customer flagged as At Risk â review account immediately"})]})]}),t.jsxs("div",{className:"grid grid-cols-4 gap-3 mb-4 flex-shrink-0",children:[t.jsx(Wp,{label:"Installed Systems",value:String(P.length),sub:[D>0?`${D} purchased`:"",M>0?`${M}
1115 rented`:""].filter(Boolean).join(" · ")||"None",color:"#38bdf8"}),t.jsx(Wp,{label:"Warranty",value:k.length>0?`${k.length} issue${k.length!==1?"s":""}`:"â Valid",sub:q.length>0?`${q.length} void`:$.length>0?`${$.length} warning`:"All systems covered",color:q.length>0?"#f87171":$.length>0?"#fbbf24":"#4ade80"}),t.jsx(Wp,{label:"Service Plan",value:G,sub:V,color:ee}),t.jsx(Wp,{label:"Service Schedule",value:J.length>0?`${J.length} overdue`:ae.length>0?`${ae.length} due soon`:"â Current",sub:`${(y||[]).length} total items`,color:J.length>0?"#f87171":ae.length>0?"#fbbf24":"#4ade80"})]}),!1,t.jsx("div",{className:"flex border-b border-border flex-shrink-0 overflow-x-auto",children:Q.filter(ne=>ne.show).map(ne=>t.jsx("button",{onClick:()=>C(ne.key),className:`px-4 py-2.5 text-xs font-semibold uppercase tracking-wide whitespace-nowrap transition-colors ${j===ne.key?"text-accent border-b-2 border-accent":"text-muted hover:text-slate-300"}`,children:ne.label},ne.key))}),t.jsxs("div",{className:"flex-1 overflow-y-auto py-5",children:[j==="overview"&&t.jsx(AZ,{customer:l}),j==="systems"&&t.jsx(wZ,{customerId:l.id}),j==="rental"&&t.jsx(EZ,{customerId:l.id}),j==="billing"&&t.jsx(DK,{customerId:l.id,customer:l}),j==="quotes"&&t.jsx(MK,{customerId:l.id,customerName:l.full_name,customerAddress:"",customerPhone:l.phone}),j==="service_plans"&&t.jsx(FK,{customerId:l.id}),j==="service"&&t.jsx(cY,{customerId:l.id}),j==="shipments"&&t.jsx(eY,{customerId:l.id}),j==="water_tests"&&t.jsx(UK,{customerId:l.id}),j==="maintenance"&&t.jsx(MZ,{customerId:l.id}),j==="activity"&&t.jsx(HZ,{customerId:l.id,leadId:l.lead_id}),j==="documents"&&t.jsx(aK,{customerId:l.id})]}),S&&t.jsx("div",{style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.75)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:60,padding:16},children:t.jsxs("div",{style:{background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:16,width:"100%",maxWidth:460,overflow:"hidden"},children:[t.jsxs("div",{style:{padding:"18px 24px",borderBottom:"1px solid #1e3a4f",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[t.jsxs("div",{children:[t.jsxs("div",{style:{color:"#e2e8f0",fontWeight:800,fontSize:16},children:["Send Text to ",l.full_name]}),t.jsxs("div",{style:{color:"#475569",fontSize:12,marginTop:2},children:["To: ",l.phone," · From: (463) 300-5100"]})]}),t.jsx("button",{onClick:()=>T(!1),style:{background:"none",border:"none",color:"#64748b",fontSize:20,cursor:"pointer"},children:"Ã"})]}),t.jsxs("div",{style:{padding:"18px 24px"},children:[t.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6,marginBottom:12},children:[{label:"Appointment",msg:`Hi ${l.full_name}, just a reminder about your upcoming appointment. Reply to confirm or call us for any changes.`},{label:"Follow-Up",msg:`Hi ${l.full_name}, we wanted to check in â how is your water system working? Any questions? Reply or call us.`},{label:"Payment",msg:`Hi ${l.full_name}, we noticed a payment is due on your account. Please reply or call us for assistance.`}].map(ne=>t.jsx("button",{onClick:()=>E(ne.msg),style:{fontSize:11,padding:"4px 10px",borderRadius:6,border:"1px solid #1e3a4f",background:"#162232",color:"#94a3b8",cursor:"pointer"},children:ne.label},ne.label))}),t.jsx("textarea",{value:L,onChange:ne=>E(ne.target.value),placeholder:"Type your messageâ¦",rows:4,style:{width:"100%",background:"#162232",border:"1px solid #1e3a4f",borderRadius:8,color:"#e2e8f0",padding:"10px 14px",fontSize:14,outline:"none",boxSizing:"border-box",resize:"vertical",fontFamily:"inherit"}}),t.jsxs("div",{style:{fontSize:11,color:"#334155",marginTop:4},children:[L.length," chars · ",Math.ceil(L.length/160)||0," segment",Math.ceil(L.length/160)!==1?"s":""]}),O==="sent"&&t.jsx("div",{style:{marginTop:10,padding:"8px 14px",borderRadius:8,background:"rgba(74,222,128,0.1)",border:"1px solid rgba(74,222,128,0.25)",color:"#4ade80",fontSize:13},children:"Message sent!"}),O==="error"&&t.jsx("div",{style:{marginTop:10,padding:"8px 14px",borderRadius:8,background:"rgba(239,68,68,0.1)",border:"1px solid rgba(239,68,68,0.25)",color:"#f87171",fontSize:13},children:"Failed to send. Check console."})]}),t.jsxs("div",{style:{padding:"14px 24px",borderTop:"1px solid #1e3a4f",dis
1115play:"flex",gap:10,justifyContent:"flex-end"},children:[t.jsx("button",{onClick:()=>T(!1),style:{padding:"8px 16px",fontSize:13,color:"#64748b",background:"none",border:"none",cursor:"pointer"},children:"Cancel"}),t.jsx("button",{disabled:R||!L.trim()||O==="sent",onClick:async()=>{N(!0),z(null);try{const ne=await fetch("/api/openphone/send-sms",{method:"POST",headers:await At(),body:JSON.stringify({to:l.phone,body:L,entity_type:"customer",entity_id:l.id})});z(ne.ok?"sent":"error"),ne.ok&&setTimeout(()=>T(!1),1500)}catch{z("error")}N(!1)},style:{padding:"9px 22px",borderRadius:8,border:"none",background:!L.trim()||O==="sent"?"#334155":"#06b6d4",color:"#fff",fontWeight:700,fontSize:14,cursor:"pointer",opacity:R?.5:1},children:R?"Sendingâ¦":O==="sent"?"Sent!":"Send SMS"})]})]})})]})}function Wp({label:e,value:n,sub:r,color:s}){return t.jsxs("div",{className:"bg-card border border-border rounded-xl p-3",children:[t.jsx("div",{className:"text-xs text-muted uppercase tracking-wide mb-1",children:e}),t.jsx("div",{className:"text-lg font-bold",style:{color:s},children:n}),t.jsx("div",{className:"text-xs text-muted mt-0.5",children:r})]})}function Lm(e){return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}).format(e)}function mY(e){const n=new Date(e),r=Date.now()-n.getTime(),s=Math.floor(r/6e4);if(s<60)return`${s}m ago`;const i=Math.floor(s/60);if(i<24)return`${i}h ago`;const o=Math.floor(i/24);return o<7?`${o}d ago`:n.toLocaleDateString("en-US",{month:"short",day:"numeric"})}function Uj(e){return e?new Date(e).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):"â"}function xY(){const[e,n]=g.useState(window.innerWidth<768);return g.useEffect(()=>{const r=()=>n(window.innerWidth<768);return window.addEventListener("resize",r),()=>window.removeEventListener("resize",r)},[]),e}const yY=[{key:"all",label:"All",icon:"â",color:"#e2e8f0",bg:"rgba(226,232,240,0.1)",border:"rgba(226,232,240,0.2)"},{key:"draft",label:"Draft",icon:"â",color:"#94a3b8",bg:"rgba(148,163,184,0.1)",border:"rgba(148,163,184,0.25)"},{key:"sent",label:"Sent",icon:"â",color:"#60a5fa",bg:"rgba(96,165,250,0.1)",border:"rgba(96,165,250,0.25)"},{key:"viewed",label:"Viewed",icon:"ð",color:"#34d399",bg:"rgba(52,211,153,0.1)",border:"rgba(52,211,153,0.25)"},{key:"accepted",label:"Accepted",icon:"â",color:"#4ade80",bg:"rgba(74,222,128,0.1)",border:"rgba(74,222,128,0.25)"},{key:"signed",label:"Signed",icon:"â",color:"#38bdf8",bg:"rgba(56,189,248,0.1)",border:"rgba(56,189,248,0.25)"},{key:"declined",label:"Declined",icon:"â",color:"#f87171",bg:"rgba(248,113,113,0.1)",border:"rgba(248,113,113,0.25)"},{key:"expired",label:"Expired",icon:"â±",color:"#71717a",bg:"rgba(113,113,122,0.1)",border:"rgba(113,113,122,0.25)"}];function bY(){const{profile:e}=Ee();gt();const n=xY(),r=yt.manageQuotes(e==null?void 0:e.role),[s,i]=g.useState("list"),[o,a]=g.useState([]),[l,d]=g.useState(!0),[c,f]=g.useState("all"),[p,u]=g.useState(""),[h,y]=g.useState("all"),[m,b]=g.useState(""),[A,v]=g.useState(""),[x,_]=g.useState(null),[j,C]=g.useState(null),[S,T]=g.useState([]),[L,E]=g.useState(""),[R,N]=g.useState(null),[O,z]=g.useState(null);g.useEffect(()=>{P()},[]);async function P(){d(!0);try{a(await rg())}catch(V){console.error(V)}finally{d(!1)}}async function D(V){const{data:ee}=await w.from("customers").select("*").ilike("full_name",`%${V}%`).order("full_name").limit(20);T(ee||[])}g.useEffect(()=>{L.length>0?D(L):T([])},[L]);async function M(V,ee){if(ee.stopPropagation(),!!confirm(`Delete ${V.quote_number}? 1116 1117This cannot be undone.`)){C(V.id);try{const{error:re}=await w.from("quotes").delete().eq("id",V.id);if(re)throw re;a(Q=>Q.filter(oe=>oe.id!==V.id))}catch(re){alert("Delete failed: "+(re.message||re))}finally{C(null)}}}const[k,q]=g.useState(null);async function $(V,ee){ee.stopPropagation();const re=V.customer_email||"this customer";if(confirm(`Resend ${V.quote_number} to ${re}? 1118 1119They will receive the quote email and a text message again.`)){q(V.id);try{const{data:{session:Q}}=await w.auth.getSession();if(!(Q!=null&&Q.access_token))throw new Error("Session expired - sign in again");const oe=await fetch("/api/email/send-quote",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Q.access_token}`},body:JSON.stringify({quoteId:V.id})}),ne=await oe.json();if(!oe.ok)throw new Error(ne.error||`Failed (${oe.status})`);alert(ne.resent?`Quote resent to ${ne.to}`:`Quote sent to ${ne.to}`)}catch(Q){alert("Resend failed: "+(Q.message||Q))}finally{q(null)}}}const[I,B]=g.useState(null);async function J(V,ee){ee.stopPropagation();const re=V.customer_email||"this customer";if(confirm(`Send ${V.quote_number} to ${re}? 1120 1121They will receive the quote by email and a text message.`)){B(V.id);try{await _u(V.id);const{data:{session:Q}}=await w.auth.getSession();if(!(Q!=null&&Q.access_token))throw new Error("Session expired - sign in again");const oe=await fetch("/api/email/send-quote",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Q.access_token}`},body:JSON.stringify({quoteId:V.id})}),ne=await oe.json();if(!oe.ok)throw new Error(ne.error||`Failed (${oe.status})`);alert(`Quote sent to ${ne.to}`)}catch(Q){alert("Delivery failed: "+(Q.message||Q)+` 1122 1123The quote is marked sent. Use Resend to try delivery again.`)}finally{B(null),P()}}}const ae=g.useMemo(()=>
1123{if(h==="all")return o;const V=(ge,be)=>{const[we,F,K]=ge.split("-").map(Number);return be?new Date(we,F-1,K,23,59,59,999):new Date(we,F-1,K)},ee=new Date;let re,Q;if(h==="custom"){if(!m&&!A)return o;re=m?V(m,!1):new Date(1970,0,1),Q=A?V(A,!0):new Date(9999,11,31,23,59,59,999)}else if(h==="week"){const ge=new Date(ee.getFullYear(),ee.getMonth(),ee.getDate()-ee.getDay());re=ge,Q=new Date(ge.getFullYear(),ge.getMonth(),ge.getDate()+6,23,59,59,999)}else h==="month"?(re=new Date(ee.getFullYear(),ee.getMonth(),1),Q=new Date(ee.getFullYear(),ee.getMonth()+1,0,23,59,59,999)):(re=new Date(ee.getFullYear(),ee.getMonth()-1,1),Q=new Date(ee.getFullYear(),ee.getMonth(),0,23,59,59,999));const oe=re.getTime(),ne=Q.getTime();return o.filter(ge=>{if(!ge.created_at)return!1;const be=new Date(ge.created_at).getTime();return be>=oe&&be<=ne})},[o,h,m,A]),te=t.jsxs(t.Fragment,{children:[t.jsxs("select",{value:h,onChange:V=>y(V.target.value),style:{background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:8,color:"#e2e8f0",padding:"9px 12px",fontSize:13,outline:"none",flexShrink:0,cursor:"pointer"},children:[t.jsx("option",{value:"all",children:"All time"}),t.jsx("option",{value:"week",children:"This week"}),t.jsx("option",{value:"month",children:"This month"}),t.jsx("option",{value:"lastmonth",children:"Last month"}),t.jsx("option",{value:"custom",children:"Custom rangeâ¦"})]}),h==="custom"&&t.jsxs(t.Fragment,{children:[t.jsx("input",{type:"date",value:m,onChange:V=>b(V.target.value),style:{background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:8,color:"#e2e8f0",padding:"8px 10px",fontSize:12,outline:"none",flexShrink:0,colorScheme:"dark"}}),t.jsx("input",{type:"date",value:A,onChange:V=>v(V.target.value),style:{background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:8,color:"#e2e8f0",padding:"8px 10px",fontSize:12,outline:"none",flexShrink:0,colorScheme:"dark"}})]})]}),U=ae.filter(V=>{if(c!=="all"&&V.status!==c)return!1;if(p){const ee=p.toLowerCase();return V.quote_number.toLowerCase().includes(ee)||(V.customer_name||"").toLowerCase().includes(ee)}return!0}),W=V=>V==="all"?ae.length:ae.filter(ee=>ee.status===V).length,G={total:ae.length,sent:ae.filter(V=>V.status==="sent"||V.status==="viewed").length,accepted:ae.filter(V=>V.status==="accepted"||V.status==="signed").length,value:ae.filter(V=>V.status==="accepted"||V.status==="signed").reduce((V,ee)=>V+ee.total,0)};if(s==="create"&&!R)return t.jsx("div",{style:{background:"#0f1923",minHeight:"100vh",padding:24},children:t.jsxs("div",{style:{maxWidth:520,margin:"60px auto"},children:[t.jsx("button",{onClick:()=>i("list"),style:{color:"#64748b",background:"none",border:"none",cursor:"pointer",fontSize:14,marginBottom:24},children:"â Back"}),t.jsxs("div",{style:{background:"#162232",borderRadius:12,border:"1px solid #1e3a4f",padding:32},children:[t.jsx("div",{style:{color:"#e2e8f0",fontWeight:700,fontSize:18,marginBottom:6},children:"New Quote"}),t.jsx("div",{style:{color:"#64748b",fontSize:13,marginBottom:24},children:"Select a customer to begin"}),t.jsx("input",{placeholder:"Search customersâ¦",value:L,onChange:V=>E(V.target.value),autoFocus:!0,style:{background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:8,color:"#e2e8f0",padding:"10px 14px",width:"100%",fontSize:14,outline:"none",marginBottom:8,boxSizing:"border-box"}}),S.length>0&&t.jsx("div",{style:{border:"1px solid #1e3a4f",borderRadius:8,overflow:"hidden"},children:S.map(V=>t.jsxs("button",{onClick:()=>{N(V)},style:{display:"flex",flexDirection:"column",width:"100%",padding:"12px 14px",background:"none",border:"none",cursor:"pointer",textAlign:"left",borderBottom:"1px solid #1a2a3a"},onMouseEnter:ee=>ee.currentTarget.style.background="#1e3a5f",onMouseLeave:ee=>ee.currentTarget.style.background="none",children:[t.jsx("span",{style:{color:"#e2e8f0",fontWeight:600,fontSize:14},children:V.full_name}),V.email&&t.jsx("span",{style:{color:"#64748b",fontSize:12},children:V.email})]},V.id))})]})]})});if(s==="create"||s==="edit"){const V=s==="edit"?{id:x==null?void 0:x.customer_id,full_name:x==null?void 0:x.customer_name,phone:x==null?void 0:x.customer_phone}:R;return t.jsx(W0,{customerId:V.id,customerName:V.full_name,customerAddress:"",customerPhone:V.phone||V.mobile||"",existingQuote:s==="edit"?x:null,initialView:s==="edit"?"preview":"form",onSaved:()=>{P(),i("list"),N(null),_(null)},onCancel:()=>{i("list"),N(null),_(null)}})}return t.jsxs("div",{style:{background:"#0f1923",minHeight:"100vh",color:"#e2e8f0",display:"flex",flexDirection:"column"},children:[t.jsxs("div",{style:{background:"#162232",borderBottom:"1px solid #1e3a4f",padding:"16px 20px",display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsx("div",{style:{fontWeight:800,fontSize:20,color:"#e2e8f0",lineHeight:1.2},children:"Quotes"}),t.jsxs("div",{style:{color:"#64748b",fontSize:12,marginTop:2},children:[G.total," total"]})]}),!n&&t.jsx("input",{placeholder:"Search quote # or customerâ¦",value:p,onChange:V=>u(V.target.value),style:{background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:8,color:"#e2e8f0",padding:"9px 14px",fontSize:13,outline:"none",width:220,flexShrink:0}}),!n&&te,t.jsx("button",{onClick:()=>{i("create"),E(""),N(null)},style:{padding:"10px 18px",borderRadius:8,border:"none",cursor:"pointer",background:"#0d7ea3",color:"#fff",fontWeight:700,fontSize:14,flexShrink:0,whiteSpace:"nowrap"},children:"+ New Quote"})]}),n&&t.jsxs("div",{style:{padding:"10px 16px",background:"#0f1923",borderBottom:"1px solid #1e3a4f",dis
1123play:"flex",gap:8,alignItems:"center",flexWrap:"wrap"},children:[t.jsx("input",{placeholder:"Search quote # or customerâ¦",value:p,onChange:V=>u(V.target.value),style:{background:"#162232",border:"1px solid #1e3a4f",borderRadius:8,color:"#e2e8f0",padding:"10px 14px",fontSize:14,outline:"none",width:"100%",boxSizing:"border-box"}}),te]}),t.jsx("div",{style:{background:"#0c1a26",borderBottom:"1px solid #1e3a4f",padding:"10px 16px",display:"flex",gap:6,flexShrink:0,overflowX:"auto"},children:yY.map(V=>{const ee=W(V.key),re=c===V.key;return t.jsxs("button",{onClick:()=>f(V.key),style:{flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:n?"8px 10px":"11px 8px",borderRadius:10,border:`1px solid ${re?V.color+"60":V.border}`,background:re?V.bg:"rgba(255,255,255,0.02)",color:re?V.color:"#475569",cursor:"pointer",fontSize:n?12:13,fontWeight:re?700:500,boxShadow:re?`0 0 14px ${V.color}20`:"none",minWidth:n?"auto":void 0},children:[t.jsx("span",{children:V.icon}),!n&&t.jsx("span",{children:V.label}),ee>0&&t.jsx("span",{style:{background:re?V.color+"30":"rgba(255,255,255,0.06)",color:re?V.color:"#64748b",borderRadius:20,padding:"1px 6px",fontSize:11,fontWeight:700},children:ee})]},V.key)})}),t.jsx("div",{style:{display:"flex",gap:10,padding:"12px 16px",borderBottom:"1px solid #1e3a4f",background:"#0f1923",flexShrink:0,overflowX:"auto"},children:[{label:"Total",val:G.total,color:"#94a3b8"},{label:"Open",val:G.sent,color:"#60a5fa"},{label:"Accepted",val:G.accepted,color:"#4ade80"},{label:"Value Won",val:Lm(G.value),color:"#22d3ee"}].map(V=>t.jsxs("div",{style:{background:"#162232",border:"1px solid #1e3a4f",borderRadius:10,padding:"8px 14px",flexShrink:0,minWidth:90},children:[t.jsx("div",{style:{color:"#64748b",fontSize:10,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.08em"},children:V.label}),t.jsx("div",{style:{color:V.color,fontWeight:800,fontSize:18,marginTop:2},children:V.val})]},V.label))}),t.jsx("div",{style:{flex:1,overflowY:"auto",padding:n?"12px 12px":"16px 24px"},children:l?t.jsx("div",{style:{textAlign:"center",padding:60,color:"#64748b"},children:"Loading quotesâ¦"}):U.length===0?t.jsxs("div",{style:{textAlign:"center",padding:60},children:[t.jsx("div",{style:{fontSize:40,marginBottom:12},children:"ð"}),t.jsx("div",{style:{color:"#64748b",fontSize:15},children:"No quotes found"}),t.jsx("button",{onClick:()=>i("create"),style:{marginTop:16,padding:"10px 24px",borderRadius:8,border:"none",cursor:"pointer",background:"#0d7ea3",color:"#fff",fontWeight:700},children:"Create First Quote"})]}):n?t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:10},children:U.map(V=>{const ee=uf[V.status]||{bg:"#1e293b",text:"#94a3b8"},re=hf[V.commercial_type]||"#94a3b8",Q=j===V.id;return t.jsxs("div",{onClick:()=>{_(V),i("edit")},style:{background:"#162232",border:"1px solid #1e3a4f",borderRadius:12,padding:"14px 16px",cursor:"pointer",opacity:Q?.4:1,transition:"border-color 0.15s"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:8},children:[t.jsx("span",{style:{fontSize:13,fontWeight:700,color:"#60a5fa",fontFamily:"monospace"},children:V.quote_number}),t.jsxs("div",{style:{display:"flex",gap:6,alignItems:"center"},children:[(V.view_count||0)>0&&t.jsxs("span",{onClick:oe=>{oe.stopPropagation(),z(O===V.id?null:V.id)},style:{fontSize:10,fontWeight:600,color:"#60a5fa",background:"rgba(96,165,250,0.15)",padding:"2px 6px",borderRadius:6,cursor:"pointer"},children:["ð ",V.view_count]}),t.jsx("span",{style:{fontSize:11,fontWeight:700,color:ee.text,background:ee.bg,padding:"3px 9px",borderRadius:20},children:cf[V.status]})]})]}),t.jsx("div",{style:{fontSize:15,fontWeight:700,color:"#e2e8f0",marginBottom:4},children:V.customer_name||"â"}),V.customer_email&&t.jsx("div",{style:{fontSize:12,color:"#64748b",marginBottom:10},children:V.customer_email}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[t.jsx("span",{style:{fontSize:11,fontWeight:700,color:re,background:re+"22",padding:"3px 8px",borderRadius:6},children:pf[V.commercial_type]}),t.jsx("span",{style:{fontSize:15,fontWeight:800,color:"#e2e8f0"},children:Lm(V.total)}),t.jsxs("span",{style:{fontSize:11,color:"#64748b",marginLeft:"auto"},children:["Exp: ",Uj(V.valid_until||null)]})]}),(V.status==="draft"||r||V.sent_at)&&t.jsxs("div",{style:{display:"flex",gap:8,marginTop:12,paddingTop:12,borderTop:"1px solid #1e3a4f"},onClick:oe=>oe.stopPropagation(),children:[V.status==="draft"&&t.jsx("button",{onClick:async oe
1123=>{oe.stopPropagation(),await J(V,oe)},style:{flex:1,padding:"8px 0",borderRadius:8,border:"1px solid #0d7ea3",background:"transparent",color:"#22d3ee",cursor:"pointer",fontSize:13,fontWeight:600},children:"Send"}),V.sent_at&&t.jsx("button",{onClick:oe=>$(V,oe),disabled:k===V.id,style:{flex:1,padding:"8px 0",borderRadius:8,border:"1px solid #0d7ea3",background:"transparent",color:"#22d3ee",cursor:"pointer",fontSize:13,fontWeight:600,opacity:k===V.id?.5:1},children:k===V.id?"Sending...":"â Resend"}),r&&t.jsx("button",{onClick:oe=>M(V,oe),disabled:Q,style:{padding:"8px 16px",borderRadius:8,border:"1px solid #3f1a1a",background:"transparent",color:"#ef4444",cursor:"pointer",fontSize:13},children:"ð Delete"})]}),O===V.id&&t.jsx("div",{style:{marginTop:10,borderTop:"1px solid #1e3a4f",paddingTop:10},onClick:oe=>oe.stopPropagation(),children:t.jsx(Wy,{quoteId:V.id})})]},V.id)})}):t.jsx("div",{style:{background:"#162232",border:"1px solid #1e3a4f",borderRadius:12,overflow:"hidden"},children:t.jsxs("table",{style:{width:"100%",borderCollapse:"collapse"},children:[t.jsx("thead",{children:t.jsx("tr",{style:{background:"#0f1923",borderBottom:"1px solid #1e3a4f"},children:["Quote #","Customer","Type","Total","Status","Valid Until","Created",""].map((V,ee)=>t.jsx("th",{style:{padding:"10px 14px",fontSize:11,fontWeight:700,color:"#64748b",textTransform:"uppercase",letterSpacing:"0.08em",textAlign:ee>=3?"right":"left"},children:V},V))})}),t.jsx("tbody",{children:U.map(V=>{const ee=uf[V.status]||{bg:"#1e293b",text:"#94a3b8"},re=hf[V.commercial_type]||"#94a3b8",Q=j===V.id;return t.jsxs(t.Fragment,{children:[t.jsxs("tr",{style:{borderBottom:"1px solid #1a2a3a",cursor:"pointer",opacity:Q?.4:1,transition:"background 0.1s"},onMouseEnter:oe=>oe.currentTarget.style.background="#1a2e42",onMouseLeave:oe=>oe.currentTarget.style.background="transparent",onClick:()=>{_(V),i("edit")},children:[t.jsx("td",{style:{padding:"12px 14px",fontSize:13,fontWeight:700,color:"#60a5fa",fontFamily:"monospace"},children:V.quote_number}),t.jsxs("td",{style:{padding:"12px 14px"},children:[t.jsx("div",{style:{fontSize:13,fontWeight:600,color:"#e2e8f0"},children:V.customer_name||"â"}),V.customer_email&&t.jsx("div",{style:{fontSize:11,color:"#64748b"},children:V.customer_email})]}),t.jsx("td",{style:{padding:"12px 14px"},children:t.jsx("span",{style:{fontSize:11,fontWeight:700,color:re,background:re+"22",padding:"3px 8px",borderRadius:6},children:pf[V.commercial_type]})}),t.jsx("td",{style:{padding:"12px 14px",textAlign:"right",fontSize:13,fontWeight:700,color:"#e2e8f0"},children:Lm(V.total)}),t.jsxs("td",{style:{padding:"12px 14px",textAlign:"right"},children:[t.jsx("span",{style:{fontSize:11,fontWeight:700,color:ee.text,background:ee.bg,padding:"3px 8px",borderRadius:6},children:cf[V.status]}),(V.view_count||0)>0&&t.jsxs("span",{onClick:oe=>{oe.stopPropagation(),z(O===V.id?null:V.id)},style:{fontSize:10,fontWeight:600,color:"#60a5fa",background:"rgba(96,165,250,0.15)",padding:"2px 6px",borderRadius:6,marginLeft:4,cursor:"pointer"},children:["ð ",V.view_count]})]}),t.jsx("td",{style:{padding:"12px 14px",textAlign:"right",fontSize:12,color:"#64748b"},children:Uj(V.valid_until||null)}),t.jsx("td",{style:{padding:"12px 14px",textAlign:"right",fontSize:12,color:"#64748b"},children:mY(V.created_at)}),t.jsx("td",{style:{padding:"12px 14px",textAlign:"right"},children:t.jsxs("div",{style:{display:"flex",gap:6,justifyContent:"flex-end",alignItems:"center"},children:[V.status==="draft"&&t.jsx("button",{onClick:async oe=>{oe.stopPropagation(),await J(V,oe)},style:{padding:"4px 12px",borderRadius:6,border:"1px solid #0d7ea3",background:"transparent",color:"#22d3ee",cursor:"pointer",fontSize:12,fontWeight:600},children:"Send"}),V.sent_at&&t.jsx("button",{onClick:oe=>$(V,oe),disabled:k===V.id,style:{padding:"4px 12px",borderRadius:6,border:"1px solid #0d7ea3",background:"transparent",color:"#22d3ee",cursor:"pointer",fontSize:12,fontWeight:600,opacity:k===V.id?.5:1},children:k===V.id?"...":"â Resend"}),r&&t.jsx("button",{onClick:oe=>M(V,oe),disabled:Q,style:{padding:"4px 8px",borderRadius:6,border:"1px solid #3f1a1a",background:"transparent",color:"#ef4444",cursor:"pointer",fontSize:14,lineHeight:1},onMouseEnter:oe=>{oe.currentTarget.style.background="#3f1a1a",oe.currentTarget.style.borderColor="#ef4444"},onMouseLeave:oe=>{oe.currentTarget.style.background="transparent",oe.currentTarget.style.borderColor="#3f1a1a"},children:"ð"})]})})]},V.id),O===V.id&&t.jsx("tr",{children:t.jsx("td",{colSpan:8,style:{padding:0,background:"#0f1923",borderBottom:"1px solid #1a2a3a"},children:t.jsx(Wy,{quoteId:V.id})})},`${V.id}-act`)]})})})]})})})]})}const Le={navyMid:"#162232",navyLight:"#1e3a4f",teal:"#0d7ea3",gold:"#d4a843",white:"#ffffff",border:"#1e3a4f",text:"#e2e8f0",muted:"#64748b",success:"#16a34a",danger:"#dc2626"},AY=.07,Gd=["January","February","March","April","May","June","July","August","September","October","November","December"];function qt(e){return"$"+e.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g,",")}async function vY(e,n,r){const{data:{session:s}}=await w.auth.getSession(),i=s==null?void 0:s.access_token;if(!i){alert("Not signed in - please refresh and try again");return}const o=new URLSearchParams({year:String(e),month:String(n),mode:r}),a=await fetch(`/api/export/sales-tax-report?${o}`,{headers:{Authorization:`Bearer ${i}`}});if(!a.ok){alert("Export failed â check console");return}const l=await a.blob(),d=URL.createObjectURL(l),c=document.createElement("a");c.href=d;const p=(a.headers.get("content-disposition")||"").match(/filename="(.+)"/);
1123c.download=p?p[1]:"Zenith_SalesTax.xlsx",c.click(),URL.revokeObjectURL(d)}async function _Y(){const{data:{session:e}}=await w.auth.getSession(),n=e==null?void 0:e.access_token;if(!n){alert("Not signed in - please refresh and try again");return}const r=await fetch("/api/export/book-of-business",{headers:{Authorization:`Bearer ${n}`}});if(!r.ok){alert("Export failed â check console");return}const s=await r.blob(),i=URL.createObjectURL(s),o=document.createElement("a");o.href=i;const l=(r.headers.get("content-disposition")||"").match(/filename="(.+)"/);o.download=l?l[1]:`Book_of_Business_${new Date().toISOString().slice(0,10)}.xlsx`,o.click(),URL.revokeObjectURL(i)}function jY(){const e=new Date().getFullYear(),n=new Date().getMonth()+1,[r,s]=g.useState("monthly"),[i,o]=g.useState(e),[a,l]=g.useState(n),[d,c]=g.useState([]),[f,p]=g.useState(!1),[u,h]=g.useState("transactions"),y=Array.from({length:4},(D,M)=>e-M);g.useEffect(()=>{m()},[r,i,a,u]);async function m(){p(!0);try{u==="quotes"?await A():await b()}catch(D){console.error(D)}finally{p(!1)}}async function b(){let D,M;r==="monthly"?(D=new Date(i,a-1,1).toISOString(),M=new Date(i,a,1).toISOString()):(D=new Date(i,0,1).toISOString(),M=new Date(i+1,0,1).toISOString());const{data:k,error:q}=await w.from("payment_transactions").select("amount, tax_amount, payment_type, status, processed_at").eq("status","succeeded").gte("processed_at",D).lt("processed_at",M).order("processed_at",{ascending:!0});if(q||!k){c([]);return}if(r==="monthly"){const $={};for(const I of k){const B=new Date(I.processed_at),J=B.toISOString().slice(0,10);$[J]||($[J]=v(B.getFullYear(),B.getMonth()+1,J)),x($[J],I)}c(Object.values($).sort((I,B)=>I.label.localeCompare(B.label)))}else{const $={};for(let I=1;I<=12;I++){const B=`${i}-${String(I).padStart(2,"0")}`;$[B]=v(i,I,`${Gd[I-1]} ${i}`)}for(const I of k){const B=new Date(I.processed_at),J=`${B.getFullYear()}-${String(B.getMonth()+1).padStart(2,"0")}`;$[J]&&x($[J],I)}c(Object.values($))}}async function A(){let D,M;r==="monthly"?(D=new Date(i,a-1,1).toISOString(),M=new Date(i,a,1).toISOString()):(D=new Date(i,0,1).toISOString(),M=new Date(i+1,0,1).toISOString());const{data:k,error:q}=await w.from("quotes").select("subtotal, tax_amount, total, commercial_type, accepted_at, created_at, status").in("status",["signed"]).gte("created_at",D).lt("created_at",M).order("created_at",{ascending:!0});if(q||!k){c([]);return}if(r==="monthly"){const $={};for(const I of k){const B=new Date(I.accepted_at||I.created_at),J=B.toISOString().slice(0,10);$[J]||($[J]=v(B.getFullYear(),B.getMonth()+1,J)),_($[J],I)}c(Object.values($).sort((I,B)=>I.label.localeCompare(B.label)))}else{const $={};for(let I=1;I<=12;I++){const B=`${i}-${String(I).padStart(2,"0")}`;$[B]=v(i,I,`${Gd[I-1]} ${i}`)}for(const I of k){const B=new Date(I.accepted_at||I.created_at),J=`${B.getFullYear()}-${String(B.getMonth()+1).padStart(2,"0")}`;$[J]&&_($[J],I)}c(Object.values($))}}function v(D,M,k){return{month:M,year:D,label:k,taxable_sales:0,non_taxable_revenue:0,tax_collected:0,total_collected:0,transaction_count:0,rental_revenue:0,purchase_revenue:0,install_revenue:0}}function x(D,M){const k=parseFloat(M.amount)||0,q=parseFloat(M.tax_amount)||0,$=k-q,I=M.payment_type||"",B=I==="install_fee";B?D.install_revenue+=$:I==="monthly_rental"||I==="first_month_rental"||I==="monthly_service_plan"||I==="first_month_service_plan"?D.rental_revenue+=$:D.purchase_revenue+=$,B?D.non_taxable_revenue+=$:D.taxable_sales+=$,D.tax_collected+=q,D.total_collected+=k,D.transaction_count+=1}function _(D,M){const k=parseFloat(M.subtotal)||0,q=parseFloat(M.tax_amount)||0,$=parseFloat(M.total)||k+q;M.commercial_type==="rental"?D.rental_revenue+=k:D.purchase_revenue+=k,D.taxable_sales+=k,D.tax_collected+=q,D.total_collected+=$,D.transaction_count+=1}const j=d.reduce((D,M)=>D+M.taxable_sales,0),C=d.reduce((D,M)=>D+M.non_taxable_revenue,0),S=d.reduce((D,M)=>D+M.tax_collected,0),T=d.reduce((D,M)=>D+M.total_collected,0),L=d.reduce((D,M)=>D+M.transaction_count,0),E=d.reduce((D,M)=>D+M.rental_revenue,0),R=d.reduce((D,M)=>D+M.purchase_revenue,0),N=d.reduce((D,M)=>D+M.install_revenue,0),O=j*AY,z=Math.max(0,O-S),P=r==="monthly"?`Sales Tax Report â ${Gd[a-1]} ${i}`:`Annual Sales Tax Report â ${i}`;return t.jsxs("div",{style:{background:"#0f1923",minHeight:"100vh",fontFamily:"'DM Sans', system-ui, sans-serif",color:Le.text},children:[t.jsx("div",{style:{background:Le.navyMid,borderBottom:`1px solid ${Le.border}`,padding:"20px 28px"},children:t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",flexWrap:"wrap",gap:12},children:[t.jsxs("div",{children:[t.jsx("div",{style:{fontWeight:800,fontSize:20,color:Le.white},children:"Accounting & Tax Reports"}),t.jsxs("div",{style:{color:Le.muted,fontSize:13,marginTop:2},children:["Indiana Sales Tax Rate: ",t.jsx("span",{style:{color:Le.gold,fontWeight:700},children:"7.00%"})," · Zenith Pure Solutions LLC"]})]}),t.jsx("button",{onClick:()=>vY(i,a,r),style:{padding:"10px 22px",borderRadius:8,border:"none",cursor:"pointer",background:Le.teal,color:"#fff",fontWeight:700,fontSize:14,display:"flex",alignItems:"center",gap:8},children:"⬠Export Tax Report"}),t.jsx("button",{onClick:_Y,style:{padding:"10px 22px",borderRadius:8,border:"1px solid #1e3a4f",cursor:"pointer",background:"#162232",color:"#94a3b8",fontWeight:700,fontSize:14,display:"flex",alignItems:"center",gap:8},children:"ð Book of Business"})]})}),t.jsxs("div",{style:{padding:"24px 28px",width:"100%"},children:[t.jsxs("div",{style:{display:"flex",gap:12,flexWrap:"wrap",marginBottom:24,alignItems:"center"},children:[t.jsx("div",{style:{display:"flex",background:Le.navyMid,borderRadius:8,padding:3,border:`1px solid ${Le.border}`},children:["monthly","yearly"].map(D=>t.jsx("button",{onClick:()=>s(D),style:{padding:"7px 20px",borderRadius:6,border:"none",cursor:"pointer",fontWeight:600,fontSize:13,transition:"all 0.15s",background:r===D?Le.teal:"transparent",color:r===D?"#fff":Le.muted},children:D==="monthly"?"ð
Monthly":"ð Yearly"},D))}),t.jsx("select",{value:i,onChange:D=>o(Number(D.target.value)),style:{padding:"8px 14px",borderRadius:8,border:`1px solid ${Le.border}`,background:Le.navyMid,color:Le.text,fontSize:13,cursor:"pointer"},children:y.map(D=>t.jsx("option",{value:D,children:D},D))}),r==="monthly"&&t.jsx("select",{value:a,onChange:D=>l(Number(D.target.value)),style:{padding:"8px 14px",borderRadius:8,border:`1px solid ${Le.border}`,background:Le.navyMid,color:Le.text,fontSize:13,cursor:"pointer"},children:Gd.map((D,M)=>t.jsx("option",{value:M+1,children:D},M))}),t.jsx("div",{style:{display:"flex",background:Le.navyMid,borderRadius:8,padding:3,border:`1px solid ${Le.border}`,marginLeft:"auto"},children:[["transactions","ð³ Payments"],["quotes","ð Quotes"]].map(([D,M])=>t.jsx("button",{onClick:()=>h(D),style:{padding:"7px 16px",borderRadius:6,border:"none",cursor:"pointer",fontWeight:600,fontSize:12,transition:"all 0.15s",background:u===D?Le.navyLight:"transparent",color:u===D?Le.text:Le.muted},children:M},D))})]}),t.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(180px, 1fr))",gap:14,marginBottom:28},children:[{label:"Total Collected",value:qt(T),color:Le.teal,sub:`${L} transactions`},{label:"Taxable Sales",value:qt(j),color:"#60a5fa",sub:"Pre-tax revenue"},{label:"Tax Owed @ 7%",value:qt(O),color:Le.gold,sub:"IN filing liability"},{label:"Tax Collected",value:qt(S),color:Le.success,sub:"Actually charged"},{label:"Under-Collected",value:qt(z),color:z>0?Le.danger:Le.muted,sub:z>0?"Owe state out-of-pocket":"No gap"}].map(D=>t.jsxs("div",{style:{background:Le.navyMid,border:`1px solid ${Le.border}`,borderRadius:10,padding:"16px 20px"},children:[t.jsx("div",{style:{color:Le.muted,fontSize:11,fontWeight:600,textTransform:"uppercase",letterSpacing:.5,marginBottom:6},children:D.label}),t.jsx("div",{style:{color:D.color,fontSize:22,fontWeight:800},children:D.value}),t.jsx("div",{style:{color:Le.muted,fontSize:11,marginTop:4},children:D.sub})]},D.label))}),t.jsxs("div",{style:{background:Le.navyMid,border:`2px solid ${Le.gold}`,borderRadius:10,padding:"20px 24px",marginBottom:28},children:[t.jsxs("div",{style:{fontWeight:700,fontSize:15,color:Le.gold,marginBottom:12},children:["ð¬ Indiana Sales Tax Filing Summary â ",P]}),t.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(3, 1fr)",gap:20},children:[{k:"Gross Sales",v:qt(T)},{k:"Taxable Sales (Pre-Tax)",v:qt(j)},{k:"Sales Tax Owed @ 7%",v:qt(O)},{k:"Sales Tax Collected",v:qt(S)},{k:"Under-Collected",v:qt(z),color:z>0?Le.danger:Le.text},{k:"Non-Taxable Revenue",v:qt(C)}].map(({k:D,v:M,color:k})=>t.jsxs("div",{children:[t.jsx("div",{style:{color:Le.muted,fontSize:11,fontWeight:600,marginBottom:3},children:D}),t.jsx("div",{style:{color:k||Le.text,fontSize:15,fontWeight:700},children:M})]},D))}),t.jsxs("div",{style:{marginTop:16,paddingTop:12,borderTop:`1px solid ${Le.border}`,fontSize:12,color:Le.muted},children:["File at: ",t.jsx("span",{style:{color:Le.teal},children:"intime.dor.in.gov"})," · Indiana DOR ST-103 Monthly Sales Tax Return  · Due: 20th of the following month"]})]}),t.jsxs("div",{style:{background:Le.navyMid,border:`1px solid ${Le.border}`,borderRadius:10,overflow:"hidden"},children:[t.jsxs("div",{style:{padding:"16px 20px",borderBottom:`1px solid ${Le.border}`,display:"flex",justifyContent:"space-between",alignItems:"center"},children:[t.jsxs("div",{style:{fontWeight:700,fontSize:14,color:Le.white},children:[r==="monthly"?"Daily Breakdown":"Monthly Breakdown"," â ",i,r==="monthly"?` ${Gd[a-1]}`:""]}),t.jsxs("div",{style:{color:Le.muted,fontSize:12},children:["Data source: ",u==="quotes"?"Signed Quotes":"Completed Payments"]})]}),f?t.jsx("div",{style:{padding:48,textAlign:"center",color:Le.muted},children:"Loadingâ¦"}):t.jsx("div",{style:{overflowX:"auto"},children:t.jsxs("table",{style:{width:"100%",borderCollapse:"collapse"},children:[t.jsx("thead",{children:t.jsx("tr",{style:{background:"#0f1923"},children:["Period","Rental","Purchase","Install","Taxable Sales","Tax Collected","Total","Txns"].map(D=>
1123t.jsx("th",{style:{padding:"10px 16px",textAlign:D==="Period"?"left":"right",color:Le.muted,fontSize:11,fontWeight:700,textTransform:"uppercase",letterSpacing:.5,borderBottom:`1px solid ${Le.border}`},children:D},D))})}),t.jsx("tbody",{children:d.length===0?t.jsx("tr",{children:t.jsx("td",{colSpan:8,style:{padding:40,textAlign:"center",color:Le.muted},children:`No data for this period. Switch data source to "Quotes" if payments aren't recorded yet.`})}):d.map((D,M)=>{const k=D.total_collected===0&&D.transaction_count===0;return t.jsxs("tr",{style:{background:M%2===0?"transparent":"rgba(255,255,255,0.02)",opacity:k?.35:1},children:[t.jsx("td",{style:{padding:"10px 16px",color:k?Le.muted:Le.text,fontSize:13,fontWeight:600},children:D.label}),t.jsx("td",{style:{padding:"10px 16px",textAlign:"right",color:"#a78bfa",fontSize:13},children:D.rental_revenue>0?qt(D.rental_revenue):"â"}),t.jsx("td",{style:{padding:"10px 16px",textAlign:"right",color:"#34d399",fontSize:13},children:D.purchase_revenue>0?qt(D.purchase_revenue):"â"}),t.jsx("td",{style:{padding:"10px 16px",textAlign:"right",color:"#94a3b8",fontSize:13},children:D.install_revenue>0?qt(D.install_revenue):"â"}),t.jsx("td",{style:{padding:"10px 16px",textAlign:"right",color:"#60a5fa",fontSize:13},children:D.taxable_sales>0?qt(D.taxable_sales):"â"}),t.jsx("td",{style:{padding:"10px 16px",textAlign:"right",color:Le.gold,fontSize:13,fontWeight:700},children:D.tax_collected>0?qt(D.tax_collected):"â"}),t.jsx("td",{style:{padding:"10px 16px",textAlign:"right",color:Le.teal,fontSize:13,fontWeight:700},children:D.total_collected>0?qt(D.total_collected):"â"}),t.jsx("td",{style:{padding:"10px 16px",textAlign:"right",color:Le.muted,fontSize:13},children:D.transaction_count||"â"})]},D.label)})}),d.length>0&&t.jsx("tfoot",{children:t.jsxs("tr",{style:{background:"#0a1520",borderTop:`2px solid ${Le.border}`},children:[t.jsx("td",{style:{padding:"12px 16px",fontWeight:800,color:Le.white,fontSize:13},children:"TOTAL"}),t.jsx("td",{style:{padding:"12px 16px",textAlign:"right",color:"#a78bfa",fontWeight:700,fontSize:13},children:qt(E)}),t.jsx("td",{style:{padding:"12px 16px",textAlign:"right",color:"#34d399",fontWeight:700,fontSize:13},children:qt(R)}),t.jsx("td",{style:{padding:"12px 16px",textAlign:"right",color:"#94a3b8",fontWeight:700,fontSize:13},children:qt(N)}),t.jsx("td",{style:{padding:"12px 16px",textAlign:"right",color:"#60a5fa",fontWeight:700,fontSize:13},children:qt(j)}),t.jsx("td",{style:{padding:"12px 16px",textAlign:"right",color:Le.gold,fontWeight:800,fontSize:14},children:qt(S)}),t.jsx("td",{style:{padding:"12px 16px",textAlign:"right",color:Le.teal,fontWeight:800,fontSize:14},children:qt(T)}),t.jsx("td",{style:{padding:"12px 16px",textAlign:"right",color:Le.muted,fontWeight:700,fontSize:13},children:L})]})})]})})]}),t.jsx("div",{style:{marginTop:16,color:Le.muted,fontSize:11,textAlign:"center"},children:"This report is generated from CRM data. Always reconcile against Stripe dashboard before filing.  · Indiana DOR: intime.dor.in.gov  · Due 20th of each month."})]})]})}const Hj={active:"Active",pending:"Pending Signature",cancelled:"Cancelled",completed:"Completed",expired:"Expired"},wY={active:"#22c55e",pending:"#f59e0b",cancelled:"#ef4444",completed:"#6366f1",expired:"#94a3b8"},Vj={rental:"Rental",purchase:"Purchase",financed:"Financed"},SY={rental:"#0ea5e9",purchase:"#a855f7",financed:"#f59e0b"};function kY(e){var n,r,s;return{...e,type:e.commercial_type??e.type??"rental",reference_number:e.contract_number??e.reference_number??"",payment_day:e.billing_day??e.payment_day??1,total_amount:e.total_contract_value??e.total_amount??null,amount_paid:e.amount_paid??0,customer_name:((n=e.customers)==null?void 0:n.full_name)??e.customer_name??"â",customer_phone:((r=e.customers)==null?void 0:r.phone)??e.customer_phone??"â",customer_email:((s=e.customers)==null?void 0:s.email)??e.customer_email??"â"}}async function CY(e){let n=w.from("contracts").select(` 1124 *, 1125 customers ( full_name, phone, email ) 1126 `).order("created_at",{ascending:!1});const r=Kt();r&&(n=n.eq("branch_id",r));const{data:s,error:i}=await n;if(i)throw i;return(s||[]).map(kY)}function Zj(e){if(!e.start_date)return 0;const n=new Date(e.start_date),r=new Date;return Math.max(0,(r.getFullYear()-n.getFullYear())*12+(r.getMonth()-n.getMonth()))}const Wm=e=>e!=null?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}).format(e):"â",TY=e=>e?new Date(e).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):"â";function Kj({label:e,color:n}){return t.jsx("span",{className:"inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-semibold",style:{backgroundColor:`${n}20`,color:n,border:`1px solid ${n}40`},children:e})}function zY(){const e=gt(),[n,r]=g.useState([]),[s,i]=g.useState(!0),[o,a]=g.useState(""),[l,d]=g.useState("all"),[c,f]=g.useState("all");g.useEffect(()=>{p()},[]);async function p(){i(!0);try{const v=await CY();r(v)}catch(v){console.error(v)}finally{i(!1)}}const u=n.filter(v=>{if(l!=="all"&&v.status!==l||c!=="all"&&v.type!==c)return!1;if(o){const x=o.toLowerCase();return(v.reference_number||"").toLowerCase().includes(x)||(v.customer_name||"").toLowerCase().includes(x)||(v.system_type||"").toLowerCase().includes(x)}return!0}),h=n.filter(v=>v.status==="active").length,y=n.filter(v=>v.status==="pending").length,m=n.filter(v=>v.status==="active"&&v.type==="rental").reduce((v,x)=>v+(x.monthly_amount||0),0),b=["all","active","pending","cancelled","completed","expired"],A=["all","rental","purchase","financed"];return t.jsxs("div",{className:"h-full flex flex-col",style:{background:"#080d13"},children:[t.jsxs("div",{className:"flex-shrink-0 px-6 pt-6 pb-4 border-b border-slate-800/60",children:[t.jsx("div",{className:"flex items-center justify-between mb-4",children:t.jsxs("div",{children:[t.jsx("h1",{className:"text-2xl font-bold text-white",children:"Contracts"}),t.jsx("p",{className:"text-sm text-slate-400 mt-0.5",children:"All rental agreements, purchase contracts, and financing"})]})}),t.jsx("div",{className:"grid grid-cols-3 gap-3 mb-4",children:[{label:"Active Contracts",value:h,color:"#22c55e"},{label:"Pending Signature",value:y,color:"#f59e0b"},{label:"Monthly Recurring",value:Wm(m),color:"#0ea5e9"}].map(({label:v,value:x,color:_})=>t.jsxs("div",{className:"rounded-xl p-3",style:{background:"rgba(148,163,184,0.05)",border:"1px solid rgba(148,163,184,0.1)"},children:[t.jsx("div",{className:"text-xs text-slate-500 mb-1",children:v}),t.jsx("div",{className:"text-xl font-bold",style:{color:_},children:x})]},v))}),t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx("input",{value:o,onChange:v=>a(v.target.value),placeholder:"Search by customer, contract #, or system typeâ¦",className:"w-full rounded-xl px-4 py-2.5 text-sm text-slate-200 placeholder-slate-500",style:{background:"rgba(148,163,184,0.07)",border:"1px solid rgba(148,163,184,0.15)"}}),t.jsxs("div",{className:"flex gap-2 flex-wrap",children:[b.map(v=>t.jsx("button",{onClick:()=>d(v),className:"px-3 py-1.5 rounded-lg text-xs font-medium transition-all",style:l===v?{background:"#0ea5e9",color:"#fff"}:{background:"rgba(148,163,184,0.07)",color:"#94a3b8",border:"1px solid rgba(148,163,184,0.12)"},children:v==="all"?"All Status":Hj[v]},v)),t.jsx("div",{className:"w-px bg-slate-700 mx-1"}),A.map(v=>t.jsx("button",{onClick:()=>f(v),className:"px-3 py-1.5 rounded-lg text-xs font-medium transition-all",style:c===v?{background:"#a855f7",color:"#fff"}:{background:"rgba(148,163,184,0.07)",color:"#94a3b8",border:"1px solid rgba(148,163,184,0.12)"},children:v==="all"?"All Types":Vj[v]},v))]})]})]}),t.jsx("div",{className:"flex-1 overflow-y-auto px-6 py-4 space-y-2",children:s?t.jsx("div",{className:"flex items-center justify-center h-40 text-slate-500",children:"Loading contractsâ¦"}):u.length===0?t.jsxs("div",{className:"flex flex-col items-center justify-center h-40 gap-2",children:[t.jsx("div",{className:"text-3xl",children:"ð"}),t.jsx("div",{className:"text-slate-400 text-sm",children:"No contracts found"})]}):u.map(v=>{const x=v.reference_number||v.id.slice(0,8).toUpperCase();return t.jsxs("div",{onClick:()=>e(`/contracts/${v.id}`),className:"rounded-xl p-4 cursor-pointer transition-all hover:translate-y-[-1px]",style:{background:"rgba(148,163,184,0.04)",border:"1px solid rgba(148,163,184,0.1)"},children:[t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"flex-1 min-w-0",children:[t.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[t.jsx("span",{className:"text-sm font-semibold text-white",children:v.customer_name}),t.jsx(Kj,{label:Hj[v.status],color:wY[v.status]}),t.jsx(Kj,{label:Vj[v.type],color:SY[v.type]})]}),t.jsxs("div",{className:"text-xs text-slate-500 mt-1 flex items-center gap-3",children:[t.jsx("span",{children:x}),v.system_type&&t.jsxs("span",{children:["· ",v.system_type]}),v.start_date&&t.jsxs("span",{children:["· Started ",TY(v.start_date)]})]})]}),t.jsxs("div",{className:"text-right flex-shrink-0",children:[v.monthly_amount?t.jsxs("div",{className:"text-sm font-bold",style:{color:"#0ea5e9"},children:[Wm(v.monthly_amount),"/mo"]}):v.total_amount?t.jsx("div",{className:"text-sm font-bold text-white",children:Wm(v.total_amount)}):null,v.term_months&&t.jsxs("div",{className:"text-xs text-slate-500 mt-0.5",children:[Zj(v),"/",v.term_months," mo"]})]})]}),v.type==="rental"&&v.term_months&&t.jsx("div",{className:"mt-3 h-1 rounded-full bg-slate-800 overflow-hidden",children:t.jsx("div",{className:"h-full rounded-full",style:{width:`${Math.min(100,Zj(v)/v.term_months*100)}%`,backgroundColor:"#0ea5e9"}})})]},v.id)})})]})}const Yj={active:"Active",pending:"Pending Signature",cancelled:"Cancelled",completed:"Completed",expired:"Expired"},Xj={active:"#22c55e",pending:"#f59e0b",cancelled:"#ef4444",completed:"#6366f1",expired:"#94a3b8"},Gj={rental:"Rental",purchase:"Purchase",financed:"Financed"},Jj={rental:"#0ea5e9",purchase:"#a855f7",financed:"#f59e0b"},NY={succeeded:"#22c55e",failed:"#ef4444",pending:"#f59e0b",refunded:"#6366f1"};
1126function Pi(e){return e==null?"â":`$${Number(e).toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}`}function Po({label:e,color:n}){return t.jsx("span",{style:{display:"inline-block",padding:"3px 10px",borderRadius:20,fontSize:12,fontWeight:600,letterSpacing:"0.02em",background:n+"22",color:n,border:`1px solid ${n}44`},children:e})}function el({children:e,style:n}){return t.jsx("div",{style:{background:"#162232",border:"1px solid #1e3a4f",borderRadius:12,padding:"20px 24px",...n},children:e})}function tl({children:e}){return t.jsx("p",{style:{fontSize:11,fontWeight:700,letterSpacing:"0.1em",textTransform:"uppercase",color:"#64748b",margin:"0 0 14px"},children:e})}function Gn({label:e,value:n}){return t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"8px 0",borderBottom:"1px solid #1e3a4f"},children:[t.jsx("span",{style:{fontSize:13,color:"#64748b"},children:e}),t.jsx("span",{style:{fontSize:14,color:"#e2e8f0",fontWeight:500},children:n??"â"})]})}function RY({contract:e,payments:n}){if(e.commercial_type!=="rental")return null;const r=e.total_contract_value,s=n.filter(l=>l.status==="succeeded"),o=s.reduce((l,d)=>l+Number(d.amount),0)*.5,a=r?Math.max(0,r-o):null;return t.jsxs(el,{style:{border:"1px solid #0ea5e933"},children:[t.jsx(tl,{children:"Buyout Calculator"}),r?t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[t.jsx("span",{style:{fontSize:13,color:"#94a3b8"},children:"Total Contract Value"}),t.jsx("span",{style:{fontSize:14,fontWeight:600,color:"#e2e8f0"},children:Pi(r)})]}),t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[t.jsxs("span",{style:{fontSize:13,color:"#94a3b8"},children:["Payments Made (",s.length,") à 50% Credit"]}),t.jsxs("span",{style:{fontSize:14,fontWeight:500,color:"#22c55e"},children:["â ",Pi(o)]})]}),t.jsx("div",{style:{borderTop:"1px solid #0ea5e933",margin:"4px 0"}}),t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[t.jsx("span",{style:{fontSize:15,fontWeight:700,color:"#e2e8f0"},children:"Buyout Amount"}),t.jsx("span",{style:{fontSize:22,fontWeight:700,color:"#0ea5e9"},children:Pi(a)})]}),t.jsx("div",{style:{background:"#0ea5e90a",border:"1px solid #0ea5e922",borderRadius:8,padding:"10px 12px",marginTop:4},children:t.jsx("p",{style:{margin:0,fontSize:12,color:"#64748b"},children:"Formula: Total Contract Value â (50% à Payments Made) = Buyout Amount"})})]}):t.jsx("p",{style:{margin:0,fontSize:13,color:"#64748b",fontStyle:"italic"},children:"Total contract value not recorded. The buyout calculator requires a total contract value to compute."})]})}function EY(){const{id:e}=di(),n=gt(),{role:r}=rs();g.useEffect(()=>{r==="technician"&&n("/",{replace:!0})},[r,n]);const[s,i]=g.useState(null),[o,a]=g.useState([]),[l,d]=g.useState([]),[c,f]=g.useState([]),[p,u]=g.useState(null),[h,y]=g.useState(!0),[m,b]=g.useState(null),[A,v]=g.useState(!1),[x,_]=g.useState(!1),[j,C]=g.useState(!1);g.useEffect(()=>{!e||r==="technician"||S(e)},[e,r]);async function S(z){var P,D,M;y(!0),b(null);try{const{data:k,error:q}=await w.from("contracts").select(` 1127 id, contract_number, customer_id, quote_id, commercial_type, status, 1128 monthly_amount, total_contract_value, start_date, end_date, 1129 signed_at, billing_day, bought_out_at, buyout_amount, 1130 stripe_subscription_id, tenant_id, branch_id, 1131 created_at, updated_at, 1132 customers ( full_name, phone, email ) 1133 `).eq("id",z).single();if(q||!k)throw new Error((q==null?void 0:q.message)||"Contract not found");const $={...k,type:k.commercial_type,customer_name:((P=k.customers)==null?void 0:P.full_name)??"â",customer_phone:((D=k.customers)==null?void 0:D.phone)??"â",customer_email:((M=k.customers)==null?void 0:M.email)??"â"};i($);const I=$.customer_id;if($.quote_id){const{data:te}=await w.from("document_line_items").select("id, description, quantity, unit_price, total, item_type, sort_order").eq("quote_id",$.quote_id).order("sort_order",{ascending:!0});d(te||[])}const{data:B}=await w.from("payment_transactions").select("id, amount, status, type, description, created_at, failure_reason").eq("customer_id",I).order("created_at",{ascending:!1}).limit(50);a(B||[]);const{data:J}=await w.from("installed_systems").select("id, system_type, name_snapshot, ownership_type, install_date, is_active").eq("customer_id",I).order("install_date",{ascending:!1});f(J||[]);let ae=null;if($.quote_id){const{data:te}=await w.from("agreements").select("id, status, created_at, quote_id").eq("quote_id",$.quote_id).eq("status","signed").limit(1).maybeSingle();ae=te||null}if(!ae){const{data:te}=await w.from("agreements").select("id, status, created_at, quote_id").eq("customer_id",I).eq("status","signed").order("created_at",{ascending:!1}).limit(1).maybeSingle();ae=te||null}u(ae)}catch(k){b(k.message||"Failed to load contract")}finally{y(!1)}}async function T(){if(s){_(!0);try{const{error:z}=await w.from("contracts").update({status:"cancelled",updated_at:new Date().toISOString()}).eq("id",s.id);if(z)throw z;v(!1),await S(s.id)}catch(z){alert("Cancel failed: "+z.message)}finally{_(!1)}}}async function L(){if(s){C(!0);try{const{error:z}=await w.from("contracts").update({status:"active",updated_at:new Date().toISOString()}).eq("id",s.id);if(z)throw z;await S(s.id)}catch(z){alert("Activate failed: "+z.message)}finally{C(!1)}}}if(r==="technician")return null;if(h)return t.jsx("div",{style:{minHeight:"100vh",background:"#0f1923",display:"flex",alignItems:"center",justifyContent:"center"},children:t.jsx("p",{style:{color:"#64748b",fontSize:14},children:"Loading contractâ¦"})});if(m||!s)return t.jsxs("div",{style:{minHeight:"100vh",background:"#0f1923",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:12},children:[t.jsx("p",{style:{color:"#ef4444",fontSize:14},children:m||"Contract not found"}),t.jsx("button",{onClick:()=>n(-1),style:{color:"#0d7ea3",background:"none",border:"none",cursor:"pointer",fontSize:14},children:"â Go back"})]});const E=s.commercial_type||s.type||"rental",R=s.contract_number||s.id.slice(0,8).toUpperCase(),N=yt.manageContracts(r)&&s.status==="active",O=yt.manageContracts(r)&&s.status==="pending";return t.jsxs("div",{style:{minHeight:"100vh",background:"#0f1923",color:"#e2e8f0",fontFamily:"system-ui, sans-serif"},children:[t.jsxs("div",{style:{background:"#162232",borderBottom:"1px solid #1e3a4f",padding:"14px 24px",display:"flex",alignItems:"center",gap:16,position:"sticky",top:0,zIndex:10},children:[t.jsx("button",{onClick:()=>n(-1),style:{background:"none",border:"none",color:"#64748b",cursor:"pointer",fontSize:20,padding:0,lineHeight:1},children:"â"}),t.jsxs("div",{style:{flex:1},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[t.jsx("span",{style:{fontSize:17,fontWeight:700,color:"#e2e8f0"},children:R}),t.jsx(Po,{label:Gj[E]??E,color:Jj[E]??"#64748b"}),t.jsx(Po,{label:Yj[s.status]??s.status,color:Xj[s.status]??"#64748b"})]}),t.jsx("p",{style:{margin:"2px 0 0",fontSize:13,color:"#64748b"},children:s.customer_name})]}),O&&t.jsx("button",{onClick:L,disabled:j,style:{background:"#22c55e22",border:"1px solid #22c55e44",color:"#22c55e",borderRadius:8,padding:"7px 14px",fontSize:13,fontWeight:600,cursor:j?"not-allowed":"pointer",opacity:j?.6:1},children:j?"Activatingâ¦":"Activate Contract"}),N&&t.jsx("button",{onClick:()=>v(!0),style:{background:"#ef444422",border:"1px solid #ef444444",color:"#ef4444",borderRadius:8,padding:"7px 14px",fontSize:13,fontWeight:600,cursor:"pointer"},children:"Cancel Contract"})]}),t.jsxs("div",{style:{maxWidth:860,margin:"0 auto",padding:"24px 20px",display:"flex",flexDirection:"column",gap:20},children:[t.jsxs(el,{children:[t.jsx(tl,{children:"Contract Summary"}),t.jsx(Gn,{label:"Contract #",value:R}),t.jsx(Gn,{label:"Customer",value:s.customer_name}),t.jsx(Gn,{label:"Phone",value:s.customer_phone}),t.jsx(Gn,{label:"Email",value:s.customer_email}),t.jsx(Gn,{label:"Type",value:t.jsx(Po,{label:Gj[E]??E,color:Jj[E]??"#64748b"})}),t.jsx(Gn,{label:"Status",value:t.jsx(Po,{label:Yj[s.status]??s.status,color:Xj[s.status]??"#64748b"})}),t.jsx(Gn,{label:"Monthly Amount",value:Pi(s.monthly_amount)}),t.jsx(Gn,{label:"Total Value",value:Pi(s.total_contract_value)}),t.jsx(Gn,{label:"Start Date",value:dn(s.start_date)}),t.jsx(Gn,{label:"End Date",value:dn(s.end_date)}),t.jsx(Gn,{label:"Billing Day",value:s.billing_day?`Day ${s.billing_day} of month`:"â"}),t.jsx(Gn,{label:"Signed",value:sr(s.signed_at)}),t.jsx(Gn,{label:"Created",value:sr(s.created_at)}),s.bought_out_at&&t.jsx(Gn,{label:"Bought Out",value:sr(s.bought_out_at)})]}),t.jsx(RY,{contract:s,payments:o}),l.length>0&&t.jsxs(el,{children:[t.jsx(tl,{children:"Line Items (from quote)"}),t.jsx("div",{style:{overflowX:"auto"},children:t.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:13},children:[t.jsx("thead",{children:t.jsx("tr",{children:["Description","Qty","Unit Price","Total"].map(z=>t.jsx("th",{style:{textAlign:"left",padding:"6px 10px",color:"#64748b",fontSize:11,fontWeight:700,letterSpacing:"0.06em",textTransform:"uppercase",borderBottom:"1px solid #1e3a4f",whiteSpace:"nowrap"},children:z},z))})}),t.jsx("tbody",{children:l.map((z,P)=>t.jsxs("tr",{style:{background:P%2===0?"transparent":"#0f192344"},children:[t.jsx("td",{style:{padding:"9px 10px",color:"#e2e8f0"},children:z.description||"â"}),t.jsx("td",{style:{padding:"9px 10px",color:"#94a3b8"},children:z.quantity??1}),t.jsx("td",{style:{padding:"9px 10px",color:"#94a3b8"},children:Pi(z.unit_price)}),t.jsx("td",{style:{padding:"9px 10px",color:"#e2e8f0",fontWeight:600},children:Pi(z.total)})]},z.id||P))})]})})]}),t.jsxs(el,{children:[t.jsx(tl,{children:"Systems on This Account"}),c.length===0?t.jsx("p",{style:{fontSize:13,color:"#64748b",margin:0},children:"No installed systems found."}):t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:10},children:c.map(z=>{var P;return t.jsxs("div",{style:{background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:8,padding:"12px 14px",display:"flex",alignItems:"center",justifyContent:"space-between",flexWrap:"wrap",gap:8},children:[t.jsxs("div",{children:[t.jsx("p",{style:{margin:0,fontSize:14,fontWeight:600,color:"#e2e8f0"},children:z.name_snapshot}),t.jsxs("p",{style:{margin:"2px 0 0",fontSize:12,color:"#64748b"},children:["Installed ",dn(z.install_date)," · ",(P=z.system_type)==null?void 0:P.replace(/_/g," ")
1133]})]}),t.jsxs("div",{style:{display:"flex",gap:8,flexWrap:"wrap"},children:[t.jsx(Po,{label:z.ownership_type==="rented"?"Rental":"Purchased",color:z.ownership_type==="rented"?"#0ea5e9":"#a855f7"}),t.jsx(Po,{label:z.is_active?"Active":"Inactive",color:z.is_active?"#22c55e":"#94a3b8"})]})]},z.id)})})]}),t.jsxs(el,{children:[t.jsx(tl,{children:"Signed Agreement"}),p?t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",flexWrap:"wrap",gap:10},children:[t.jsxs("div",{children:[t.jsxs("p",{style:{margin:0,fontSize:14,color:"#e2e8f0",fontWeight:500},children:["Signed ",sr(p.created_at)]}),t.jsx("p",{style:{margin:"3px 0 0",fontSize:12,color:"#64748b"},children:p.quote_id&&p.quote_id===s.quote_id?"Linked directly to this contract's quote":"Matched by account â may be from a related quote"})]}),t.jsx("button",{onClick:()=>n(`/agreements/${p.id}`),style:{background:"#0d7ea322",border:"1px solid #0d7ea344",color:"#0d7ea3",borderRadius:8,padding:"7px 14px",fontSize:13,fontWeight:600,cursor:"pointer"},children:"View Agreement â"})]}):t.jsx("p",{style:{margin:0,fontSize:13,color:"#64748b"},children:"No signed agreement on file."})]}),t.jsxs(el,{children:[t.jsx(tl,{children:"Account Payment History"}),t.jsx("p",{style:{margin:"-10px 0 14px",fontSize:11,color:"#475569",fontStyle:"italic"},children:"All payments on this account â records are not yet filtered to this contract individually."}),o.length===0?t.jsx("p",{style:{fontSize:13,color:"#64748b",margin:0},children:"No payment records found."}):t.jsx("div",{style:{overflowX:"auto"},children:t.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:13},children:[t.jsx("thead",{children:t.jsx("tr",{children:["Date","Type","Amount","Status"].map(z=>t.jsx("th",{style:{textAlign:"left",padding:"6px 10px",color:"#64748b",fontSize:11,fontWeight:700,letterSpacing:"0.06em",textTransform:"uppercase",borderBottom:"1px solid #1e3a4f",whiteSpace:"nowrap"},children:z},z))})}),t.jsx("tbody",{children:o.map((z,P)=>{var D;return t.jsxs("tr",{style:{background:P%2===0?"transparent":"#0f192344"},children:[t.jsx("td",{style:{padding:"9px 10px",color:"#94a3b8",whiteSpace:"nowrap"},children:sr(z.created_at)}),t.jsx("td",{style:{padding:"9px 10px",color:"#e2e8f0",whiteSpace:"nowrap"},children:(D=z.type)==null?void 0:D.replace(/_/g," ")}),t.jsx("td",{style:{padding:"9px 10px",color:"#e2e8f0",fontWeight:600,whiteSpace:"nowrap"},children:Pi(z.amount)}),t.jsxs("td",{style:{padding:"9px 10px",whiteSpace:"nowrap"},children:[t.jsx(Po,{label:z.status,color:NY[z.status]??"#64748b"}),z.failure_reason&&t.jsx("span",{style:{display:"block",fontSize:11,color:"#ef4444",marginTop:2},children:z.failure_reason})]})]},z.id)})})]})})]})]}),A&&t.jsx("div",{style:{position:"fixed",inset:0,background:"#00000099",zIndex:50,display:"flex",alignItems:"center",justifyContent:"center",padding:20},children:t.jsxs("div",{style:{background:"#162232",border:"1px solid #1e3a4f",borderRadius:14,padding:28,maxWidth:420,width:"100%"},children:[t.jsx("h3",{style:{margin:"0 0 8px",fontSize:17,color:"#e2e8f0"},children:"Cancel Contract"}),t.jsxs("p",{style:{margin:"0 0 20px",fontSize:13,color:"#64748b"},children:["This will mark ",t.jsx("strong",{style:{color:"#e2e8f0"},children:R})," as cancelled. Autopay stops on the next billing cycle. This cannot be undone."]}),t.jsxs("div",{style:{display:"flex",gap:10},children:[t.jsx("button",{onClick:()=>v(!1),style:{flex:1,background:"#1e3a4f",border:"1px solid #1e3a4f",color:"#94a3b8",borderRadius:8,padding:"10px 0",fontSize:14,fontWeight:600,cursor:"pointer"},children:"Keep Active"}),t.jsx("button",{onClick:T,disabled:x,style:{flex:1,background:"#ef444422",border:"1px solid #ef444466",color:"#ef4444",borderRadius:8,padding:"10px 0",fontSize:14,fontWeight:600,cursor:x?"not-allowed":"pointer",opacity:x?.6:1},children:x?"Cancellingâ¦":"Confirm Cancel"})]})]})})]})}const gf=e=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}).format(e||0);function PY(e){const n=Date.now()-new Date(e).getTime();return Math.max(0,Math.floor(n/864e5))}function qY(e){return e<=1?{label:e===0?"Today":"1 day",color:"#4ade80",bg:"rgba(74,222,128,0.1)",border:"rgba(74,222,128,0.25)"}:e<=7?{label:`${e} days`,color:"#fbbf24",bg:"rgba(251,191,36,0.1)",border:"rgba(251,191,36,0.25)"}:{label:`${e} days`,color:"#f87171",bg:"rgba(248,113,113,0.1)",border:"rgba(248,113,113,0.25)"}}
1133const DY={style:{base:{color:"#e2e8f0",fontSize:"15px","::placeholder":{color:"#64748b"}},invalid:{color:"#f87171"}}};function OY(e,n){return Ae({queryKey:["failed_payments_page",e,n],queryFn:async()=>{let r=w.from("payment_transactions").select("id, amount, failure_reason, created_at, customer_id, invoice_id, customers(id, full_name, phone, email, stripe_customer_id), invoices(invoice_number, status)").eq("tenant_id",e).eq("status","failed").order("created_at",{ascending:!1}).limit(200);n&&(r=r.eq("branch_id",n));const{data:s,error:i}=await r;if(i)throw i;return(s||[]).filter(o=>{var a;return((a=o.invoices)==null?void 0:a.status)!=="paid"})},enabled:!!e,refetchInterval:3e4})}function IY(e){const n=new Map;for(const r of e){const s=r.invoice_id?`inv:${r.invoice_id}`:`cust:${r.customer_id??r.id}`,i=n.get(s);(!i||new Date(r.created_at)>new Date(i.created_at))&&n.set(s,r)}return[...n.values()]}function LY({row:e,onSuccess:n,onClose:r}){var h;const s=lg(),i=K0(),[o,a]=g.useState(!0),[l,d]=g.useState(!1),[c,f]=g.useState(""),p=e.customers;async function u(){var m,b;if(!s||!i||!p)return;const y=i.getElement(sd);if(y){d(!0),f("");try{const{client_secret:A,stripe_customer_id:v}=await _0({stripe_customer_id:p.stripe_customer_id||void 0,customer_name:p.full_name,customer_email:p.email||void 0});p.stripe_customer_id||await eu(p.id,v);const x=await s.confirmCardSetup(A,{payment_method:{card:y}});if(x.error)throw new Error(x.error.message);const _=typeof x.setupIntent.payment_method=="string"?x.setupIntent.payment_method:(m=x.setupIntent.payment_method)==null?void 0:m.id;if(!_)throw new Error("Could not read the new card");let j;if(o){const S=await(await fetch("/api/stripe/get-payment-method",{method:"POST",headers:await At(),body:JSON.stringify({payment_method_id:_})})).json(),T=await Qc({customer_id:p.id,stripe_payment_method_id:_,last_four:S.last4||"????",exp_month:S.exp_month||0,exp_year:S.exp_year||0,make_default:!0,type:S.type||"card"});j=T==null?void 0:T.id}await Gf({stripe_customer_id:v,payment_method_id:_,amount_cents:Math.round((e.amount||0)*100),description:(b=e.invoices)!=null&&b.invoice_number?`Balance for invoice ${e.invoices.invoice_number}`:"Account balance",customer_id:p.id,invoice_id:e.invoice_id||void 0,supabase_pm_id:j}),n()}catch(A){f(A.message||"Charge failed")}finally{d(!1)}}}return t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:11,color:"#64748b",fontWeight:600,textTransform:"uppercase",letterSpacing:"0.08em",marginBottom:4},children:"Charging"}),t.jsx("div",{style:{fontSize:20,fontWeight:800,color:"#e2e8f0"},children:gf(e.amount)}),t.jsxs("div",{style:{fontSize:13,color:"#94a3b8",marginTop:2},children:[p==null?void 0:p.full_name,(h=e.invoices)!=null&&h.invoice_number?` · ${e.invoices.invoice_number}`:""]})]}),t.jsx("div",{style:{background:"#0f172a",borderRadius:10,padding:"13px 14px",border:"1px solid rgba(148,163,184,0.2)"},children:t.jsx(sd,{options:DY})}),t.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,fontSize:13,color:"#94a3b8",cursor:"pointer"},children:[t.jsx("input",{type:"checkbox",checked:o,onChange:y=>a(y.target.checked)}),"Save this card on file for future charges"]}),c&&t.jsx("div",{style:{fontSize:13,borderRadius:8,padding:"10px 12px",color:"#f87171",background:"rgba(248,113,113,0.1)",border:"1px solid rgba(248,113,113,0.25)"},children:c}),t.jsxs("div",{style:{display:"flex",gap:10,justifyContent:"flex-end"},children:[t.jsx("button",{onClick:r,disabled:l,style:{padding:"9px 16px",borderRadius:8,fontSize:14,fontWeight:600,cursor:"pointer",color:"#94a3b8",background:"transparent",border:"1px solid #1e3a4f"},children:"Cancel"}),t.jsx("button",{onClick:u,disabled:l||!s,style:{padding:"9px 18px",borderRadius:8,fontSize:14,fontWeight:700,cursor:l?"default":"pointer",color:"#052e16",background:"#4ade80",border:"none",opacity:l||!s?.6:1},children:l?"Chargingâ¦":`Charge ${gf(e.amount)}`})]})]})}function WY({row:e,stripePromise:n,onSuccess:r,onClose:s}){return t.jsxs("div",{style:{position:"fixed",inset:0,zIndex:60,display:"flex",alignItems:"center",justifyContent:"center"},children:[t.jsx("div",{style:{position:"absolute",inset:0,background:"rgba(0,0,0,0.55)",backdropFilter:"blur(3px)"},onClick:s}),t.jsxs("div",{style:{position:"relative",width:"100%",maxWidth:440,margin:16,background:"#162232",borderRadius:14,border:"1px solid #1e3a4f",padding:22},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:16},children:[t.jsx("div",{style:{fontWeight:800,fontSize:16,color:"#e2e8f0"},children:"Resolve with card"}),t.jsx("button",{onClick:s,style:{background:"none",border:"none",color:"#64748b",cursor:"pointer",fontSize:20,lineHeight:1},children:"Ã"})]}),n?t.jsx(ag,{stripe:n,children:t.jsx(LY,{row:e,onSuccess:r,onClose:s})}):t.jsx("div",{style:{padding:24,textAlign:"center",color:"#64748b"},children:"Loading payment formâ¦"})]})]})}function $Y(){const{profile:e}=Ee(),{selectedBranchId:n}=mu(),r=gt(),s=rt(),i=e==null?void 0:e.tenant_id,o=yt.recoverPayments(e==null?void 0:e.role),{data:a=[],isLoading:l,error:d,refetch:c}=OY(i,n),[f,p]=g.useState("amount"),[u,h]=g.useState(null),[y,m]=g.useState(null),[b,A]=g.useState(null),[v,x]=g.useState(null);g.useEffect(()=>{let T=!1;return(async()=>{try{const E=await(await fetch("/api/stripe/publishable-key",{method:"POST",headers:await At()})).json();!T&&(E!=null&&E.publishable_key)&&x(Xf(E.publishable_key))}catch{}})(),()=>{T=!0}},[e==null?void 0:e.tenant_id]);const _=g.useMemo(()=>[...IY(a)].sort((L,E)=>f==="amount"?(E.amount||0)-(L.amount||0):new Date(L.created_at).getTime()-new Date(E.created_at).getTime()),[a,f]),j=g.useMemo(()=>_.reduce((T,L)=>T+(L.amount||0),0),[_]);async function C(T){var L;if(T.customers){h(T.id),m(null);try{await Vk({amount_cents:Math.round((T.amount||0)*100),description:(L=T.invoices)!=null&&L.invoice_number?`Payment for invoice ${T.invoices.invoice_number}`:"Payment for your account",customer_name:T.customers.full_name,customer_id:T.customers.id,invoice_id:T.invoice_id||void 0}),m({msg:`Link sent to ${T.customers.full_name}`,ok:!0})}catch(E){m({msg:E.message||"Could not send link",ok:!1})}finally{h(null)}}}function S(){A(null),m({msg:"Payment charged â invoice updated",ok:!0}),s.invalidateQueries({queryKey:["failed_payments_page"]})}return o?t.jsxs("div",{style:{padding:"24px 28px",maxWidth:1100,margin:"0 auto"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"flex-end",justifyContent:"space-between",marginBottom:20,flexWrap:"wrap",gap:16},children:[t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:11,color:"#64748b",fontWeight:600,textTransform:"uppercase",letterSpacing:"0.1em",marginBottom:6},children:"Money at risk"}),t.jsxs("div",{style:{display:"flex",alignItems:"baseline",gap:14},children:[t.jsx("div",{style:{fontSize:34,fontWeight:800,color:_.length?"#f87171":"#4ade80",lineHeight:1},children:gf(j)}),t.jsxs("div",{style:{fontSize:14,color:"#94a3b8"},children:[_.length," ",_.length===1?"failed payment":"failed payments"]})]})]}),t.jsx("div",{style:{display:"flex",gap:8},children:["amount","age"].map(T=>t.jsx("button",{onClick:()=>p(T),style:{padding:"7px 14px",borderRadius:8,fontSize:13,fontWeight:600,cursor:"pointer",background:f===T?"rgba(96,165,250,0.15)":"transparent",color:f===T?"#60a5fa":"#94a3b8",border:`1px solid ${f===T?"rgba(96,165,250,0.35)":"#1e3a4f"}`},children:T==="amount"?"Highest amount":"Oldest first"},T))})]}),y&&t.jsx("div",{style:{marginBottom:16,padding:"10px 14px",borderRadius:8,fontSize:13,fontWeight:600,color:y.ok?"#4ade80":"#f87171",background:y.ok?"rgba(74,222,128,0.1)":"rgba(248,113,113,0.1)",border:`1px solid ${y.ok?"rgba(74,222,128,0.25)":"rgba(248,113,113,0.25)"}`},children:y.msg}),l&&t.jsx("div",{style:{padding:40,textAlign:"center",color:"#64748b"},children:"Loading failed paymentsâ¦"}),d&&t.jsxs("div",{style:{padding:20,borderRadius:10,background:"rgba(248,113,113,0.08)",border:"1px solid rgba(248,113,113,0.25)",color:"#f87171"},children:["Couldnât load failed payments. ",t.jsx("button",{onClick:()=>c(),style:{color:"#f87171",textDecoration:"underline",background:"none",border:"none",cursor:"pointer"},children:"Try again"})]}),!l&&!d&&_.length===0&&t.jsxs("div",{style:{padding:"56px 20px",textAlign:"center",color:"#94a3b8",background:"#0f1923",borderRadius:12,border:"1px solid #1e3a4f"},children:[t.jsx("div",{style:{fontSize:22,marginBottom:8},children:"â"}),t.jsx("div",{style:{fontWeight:700,color:"#e2e8f0",marginBottom:4},children:"No failed payments"}),t.jsx("div",{style:{fontSize:14},children:"Youâre all caught up. Recovered and cleared charges wonât show here."})]}),!l&&!d&&_.length>0&&t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:10},children:_.map(T=>{var N;const L=PY(T.created_at),E=qY(L),R=T.customers;return t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:16,padding:"14px 18px",background:"#0f1923",borderRadius:12,border:"1px solid #1e3a4f"},children:[t.jsx("div",{style:{flexShrink:0,minWidth:68,textAlign:"center",padding:"5px 10px",borderRadius:20,fontSize:12,fontWeight:700,color:E.color,background:E.bg,border:`1px solid ${E.border}`},children:E.label}),t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsx("button",{onClick:()=>R&&r(`/customers/${R.id}`),style:{background:"none",border:"none",padding:0,cursor:R?"pointer":"default",textAlign:"left"},children:t.jsx("div",{style:{fontWeight:700,color:"#e2e8f0",fontSize:15},children:(R==null?void 0:R.full_name)||"Unknown customer"})}),t.jsxs("div",{style:{fontSize:13,color:"#64748b",marginTop:2},children:[(N=T.invoices)!=null&&N.invoice_number?`${T.invoices.invoice_number} · `:"",(R==null?void 0:R.phone)||"No phone",T.failure_reason?` · ${T.failure_reason}`:""]})]}),t.jsx("div",{style:{flexShrink:0,fontWeight:800,fontSize:17,color:"#e2e8f0",minWidth:96,textAlign:"right"},children:gf(T.amount)}),t.jsxs("div",{style:{flexShrink:0,display:"flex",gap:8},children:[t.jsx("button",{onClick:()=>C(T),disabled:u===T.id||!R,style:{padding:"8px 14px",borderRadius:8,fontSize:13,fontWeight:600,cursor:u===T.id||!R?"default":"pointer",color:"#22d3ee",background:"rgba(34,211,238,0.1)",border:"1px solid rgba(34,211,238,0.3)",opacity:u===T.id||!R?.5:1},children:u===T.id?"Sendingâ¦":"Re-send link"}),t.jsx("button",{onClick:()=>R&&A(T),disabled:!R,style:{padding:"8px 14px",borderRadius:8,fontSize:13,fontWeight:600,cursor:R?"pointer":"default",color:"#e2e8f0",background:"rgba(96,165,250,0.15)",border:"1px solid rgba(96,165,250,0.35)",opacity:R?1:.5},children:"Resolve with card â"})]})]},T.id)})}),b&&t.jsx(WY,{row:b,stripePromise:v,onSuccess:S,onClose:()=>A(null)})]}):t.jsx("div",{style:{padding:40,color:"#94a3b8"},children:"You donât have access to payment recovery."})}const MY=[{key:"all",label:"All",color:"#94a3b8",icon:"ð¦"},{key:"pending",label:"Pending",color:"#f59e0b",icon:"â³"},{key:"label_created",label:"Label Created",color:"#8b5cf6",icon:"ð·ï¸"},{key:"shipped",label:"Shipped",color:"#3b82f6",icon:"ð"},{key:"in_transit",label:"In Transit",color:"#06b6d4",icon:"âï¸"},{key:"delivered",label:"Delivered",color:"#10b981",icon:"â
"},{key:"cancelled",label:"Cancelled",color:"#6b7280",icon:"â"},{key:"returned",label:"Returned",color:"#ef4444",icon:"â©ï¸"}];function FY(){const{user:e}=Ee();rs();const n=rt(),[r,s]=g.useState("all"),[i,o]=g.useState(""),[a,l]=g.useState(!1),[d,c]=g.useState(null),{data:f=[],isLoading:p}=Ae({queryKey:["shipments",r],queryFn:()=>VK({status:r==="all"?void 0:r})}),{data:u={}}=Ae({queryKey:["shipment_counts"],queryFn:KK}),h=f.filter(m=>{var A,v,x,_;if(!i)return!0;const b=i.toLowerCase();return((A=m.customer_name)==null?void 0:A.toLowerCase().includes(b))||((v=m.product_name)==null?void 0:v.toLowerCase().includes(b))||((x=m.tracking_number)==null?void 0:x.toLowerCase().includes(b))||((_=m.ship_to_city)==null?void 0:_.toLowerCase().includes(b))}),y=()=>{n.invalidateQueries({queryKey:["shipments"]}),n.invalidateQueries({queryKey:["shipment_counts"]})};return t.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",minHeight:0},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"16px 24px",gap:12,flexWrap:"wrap"},children:[t.jsx("h1",{style:{fontSize:22,fontWeight:700,color:"#e2e8f0",margin:0},children:"Shipping & Fulfillment"}),t.jsxs("div",{style:{display:"flex",gap:10,alignItems:"center"},children:[t.jsx("input",{type:"text",placeholder:"Search shipments...",value:i,onChange:m=>o(m.target.value),style:{background:"#162232",border:"1px solid #1e3a4f",borderRadius:8,padding:"8px 14px",color:"#e2e8f0",fontSize:13,width:220,outline:"none"}}),t.jsx("button",{onClick:()=>l(!0),style:{background:"#0d7ea3",color:"#fff",border:"none",borderRadius:8,padding:"8px 18px",fontSize:13,fontWeight:600,cursor:"pointer"},children:"+ New Shipment"})]})]}),t.jsx("div",{style:{display:"flex",gap:6,padding:"0 24px 16px",overflowX:"auto",flexShrink:0},children:MY.map(m=>{const b=r===m.key,A=m.key==="all"?u.all:u[m.key];return t.jsxs("button",{onClick:()=>s(m.key),style:{display:"flex",alignItems:"center",gap:6,padding:"8px 16px",borderRadius:10,border:"none",fontSize:12,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.04em",cursor:"pointer",transition:"all 0.15s",whiteSpace:"nowrap",flexShrink:0,background:b?`linear-gradient(135deg, ${m.color}22, ${m.color}0a)`:"rgba(255,255,255,0.03)",color:b?m.color:"#64748b",boxShadow:b?`0 0 12px ${m.color}15`:"none",outline:b?`1px solid ${m.color}40`:"1px solid rgba(255,255,255,0.06)"},children:[t.jsx("span",{children:m.icon}),t.jsx("span",{children:m.label}),A!==void 0&&A>0&&t.jsx("span",{style:{background:b?m.color+"25":"rgba(255,255,255,0.06)",color:b?m.color:"#64748b",padding:"1px 7px",borderRadius:10,fontSize:11,fontWeight:700},children:A})]},m.key)})}),t.jsx("div",{style:{flex:1,overflow:"auto",padding:"0 24px 24px"},children:t.jsx("div",{style:{background:"#162232",border:"1px solid #1e3a4f",borderRadius:14,overflow:"hidden"},children:t.jsxs("table",{style:{width:"100%",borderCollapse:"collapse"},children:[t.jsx("thead",{children:t.jsx("tr",{children:["Customer","Product","Type","Ship To","Scheduled","Tracking","Status","Actions"].map(m=>t.jsx("th",{style:{textAlign:"left",padding:"10px 14px",fontSize:10,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.06em",color:"#64748b",background:"rgba(255,255,255,0.03)",borderBottom:"1px solid #1e3a4f"},children:m},m))})}),t.jsx("tbody",{children:p?t.jsx("tr",{children:t.jsx("td",{colSpan:8,style:{padding:40,textAlign:"center",color:"#64748b"},children:"Loading shipments..."})}):h.length===0?t.jsx("tr",{children:t.jsx("td",{colSpan:8,style:{padding:40,textAlign:"center",color:"#64748b"},children:"No shipments found"})}):h.map(m=>t.jsxs("tr",{onClick:()=>c(m),style:{cursor:"pointer"},onMouseEnter:b=>b.currentTarget.style.background="rgba(255,255,255,0.02)",onMouseLeave:b=>b.currentTarget.style.background="transparent",children:[t.jsx("td",{style:_i,children:t.jsx("div",{style:{fontWeight:600,color:"#e2e8f0"},children:m.customer_name||"â"})}),t.jsx("td",{style:_i,children:t.jsx("span",{style:{color:"#e2e8f0"},children:m.product_name||"â"})}),t.jsx("td",{style:_i,children:t.jsx("span",{style:{color:"#94a3b8",fontSize:12},children:dg[m.type]||m.type})}),t.jsx("td",{style:_i,children:t.jsx("span",{style:{color:"#94a3b8",fontSize:12},children:m.ship_to_city&&m.ship_to_state?`${m.ship_to_city}, ${m.ship_to_state}`:m.ship_to_address?"Address set":t.jsx("span",{style:{color:"#f59e0b"},children:"Missing"})})}),t.jsx("td",{style:_i,children:t.jsx("span",{style:{color:"#94a3b8",fontSize:12},children:m.scheduled_date?new Date(m.scheduled_date+"T00:00:00").toLocaleDateString():"â"})}),t.jsx("td",{style:_i,children:m.tracking_number?t.jsx("span",{style:{color:"#3b82f6",fontSize:12,fontFamily:"monospace"},children:m.tracking_number}):t.jsx("span",{style:{color:"#64748b",fontSize:12},children:"â"})}),t.jsx("td",{style:_i,children:t.jsx(D3,{status:m.status})}),t.jsx("td",{style:_i,children:t.jsx(BY,{shipment:m,onUpdated:y})})]},m.id))})]})})}),a&&t.jsx(UY,{onClose:()=>l(!1),onCreated:()=>{l(!1),y()},userId:e==null?void 0:e.id}),d&&t.jsx(HY,{shipment:d,onClose:()=>c(null),onUpdated:()=>{c(null),y()}})]})}function D3({status:e})
1133{const n=k3[e]||{label:e,color:"#64748b",bgColor:"#64748b20"};return t.jsxs("span",{style:{display:"inline-block",padding:"3px 10px",borderRadius:20,fontSize:11,fontWeight:700,color:n.color,background:n.bgColor,border:`1px solid ${n.color}30`},children:[n.icon," ",n.label]})}function BY({shipment:e,onUpdated:n}){const{can:r}=rs(),s=async l=>{if(l.stopPropagation(),e.tracking_number){if(!confirm("Mark this shipment as shipped? This will advance the service plan fulfillment dates."))return}else if(!confirm(`No tracking number on this shipment. Mark as shipped anyway? 1134 1135Tip: Open the shipment to add a tracking number first.`))return;const d=await T3(e.id);if(d.success){const c=await At();fetch("/api/email/send-shipment",{method:"POST",headers:c,body:JSON.stringify({shipment_id:e.id})}).catch(()=>{}),n()}else alert(d.error||"Failed to mark shipped")},i=async l=>{l.stopPropagation(),await z3(e.id),n()},o=async l=>{l.stopPropagation(),confirm("Cancel this shipment?")&&(await N3(e.id),n())},a=l=>({padding:"4px 10px",borderRadius:6,fontSize:11,fontWeight:600,cursor:"pointer",border:`1px solid ${l}40`,background:`${l}15`,color:l});return t.jsxs("div",{style:{display:"flex",gap:4},onClick:l=>l.stopPropagation(),children:[e.status==="pending"&&r("shipping","mark_shipped")&&t.jsx("button",{onClick:s,style:a("#3b82f6"),children:"Ship"}),e.status==="label_created"&&r("shipping","mark_shipped")&&t.jsx("button",{onClick:s,style:a("#3b82f6"),children:"Ship"}),(e.status==="shipped"||e.status==="in_transit")&&r("shipping","mark_delivered")&&t.jsx("button",{onClick:i,style:a("#10b981"),children:"Delivered"}),(e.status==="pending"||e.status==="label_created")&&r("shipping","cancel")&&t.jsx("button",{onClick:o,style:a("#ef4444"),children:"Cancel"})]})}function UY({onClose:e,onCreated:n,userId:r}){const[s,i]=g.useState(""),[o,a]=g.useState(""),[l,d]=g.useState(""),[c,f]=g.useState("filter"),[p,u]=g.useState("fedex"),[h,y]=g.useState(""),[m,b]=g.useState(""),[A,v]=g.useState({name:"",address:"",city:"",state:"",zip:""}),[x,_]=g.useState("customer_primary"),[j,C]=g.useState(!1),[S,T]=g.useState([]),[L,E]=g.useState([]),[R,N]=g.useState([]);g.useEffect(()=>{w.from("customers").select("id, full_name").order("full_name").then(({data:z})=>{T((z||[]).map(P=>({id:P.id,name:P.full_name||""})))})},[]),g.useEffect(()=>{a(""),d(""),E([]),N([]),s&&(HK(s).then(z=>{z&&(v({name:z.name,address:z.address,city:z.city,state:z.state,zip:z.zip}),_(z.source))}),w.from("customer_service_plans").select("id, service_plans(name)").eq("customer_id",s).eq("status","active").then(({data:z,error:P})=>{if(P){console.error("Failed to load customer plans:",P);return}E((z||[]).map(D=>{const M=Array.isArray(D.service_plans)?D.service_plans[0]:D.service_plans,k=(M==null?void 0:M.name)||"Unnamed Plan";return{id:D.id,name:k}}))}))},[s]),g.useEffect(()=>{d(""),N([]),o&&w.from("customer_service_plan_components").select("id, component_name, label, component_code").eq("customer_plan_id",o).order("sort_order",{ascending:!0}).then(({data:z,error:P})=>{if(P){console.error("Failed to load plan components:",P);return}N((z||[]).map(D=>({id:D.id,label:D.label||D.component_name||"Unnamed Component",code:D.component_code||null})))})},[o]);const O=async()=>{if(!s)return alert("Select a customer");if(!A.address)return alert("Shipping address is required");if(o&&!l)return alert("Select a plan component, or clear the service plan to create an ad-hoc shipment");C(!0);try{const z={customer_id:s,customer_service_plan_id:o||null,plan_component_id:l||null,type:c,carrier:p,scheduled_date:h||null,ship_to_name:A.name,ship_to_address:A.address,ship_to_city:A.city,ship_to_state:A.state,ship_to_zip:A.zip,address_source:x,notes:m||null,created_by:r||null,source:"manual"};await YK(z)?n():alert("Failed to create shipment")}catch{alert("Error creating shipment")}finally{C(!1)}};return t.jsx("div",{style:O3,onClick:e,children:t.jsxs("div",{style:I3,onClick:z=>z.stopPropagation(),children:[t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:20},children:[t.jsx("h2",{style:{fontSize:18,fontWeight:700,color:"#e2e8f0",margin:0},children:"New Shipment"}),t.jsx("button",{onClick:e,style:{background:"none",border:"none",color:"#64748b",fontSize:20,cursor:"pointer"},children:"â"})]}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:14,overflowY:"auto",flex:1},children:[t.jsx(qo,{label:"Customer",children:t.jsxs("select",{value:s,onChange:z=>i(z.target.value),style:Qn,children:[t.jsx("option",{value:"",children:"Select customer..."}),S.map(z=>t.jsx("option",{value:z.id,children:z.name},z.id))]})}),t.jsxs(qo,{label:"Service Plan (optional)",children:[t.jsxs("select",{value:o,onChange:z=>a(z.target.value),disabled:!s,style:{...Qn,opacity:s?1:.5,cursor:s?"pointer":"not-allowed"},children:[t.jsx("option",{value:"",children:"None â ad-hoc shipment"}),L.map(z=>t.jsx("option",{value:z.id,children:z.name},z.id))]}),s&&L.length===0&&t.jsx("div",{style:{fontSize:11,color:"#64748b",fontStyle:"italic",marginTop:4},children:"No active service plans for this customer"})]}),o&&t.jsxs(qo,{label:"Plan Component *",children:[t.jsxs("select",{value:l,onCh
1135ange:z=>d(z.target.value),style:Qn,children:[t.jsx("option",{value:"",children:"Select component..."}),R.map(z=>t.jsxs("option",{value:z.id,children:[z.label,z.code?` (${z.code})`:""]},z.id))]}),R.length===0&&t.jsx("div",{style:{fontSize:11,color:"#f59e0b",fontStyle:"italic",marginTop:4},children:"No components defined on this plan"})]}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:14},children:[t.jsx(qo,{label:"Type",children:t.jsx("select",{value:c,onChange:z=>f(z.target.value),style:Qn,children:Object.entries(dg).map(([z,P])=>t.jsx("option",{value:z,children:P},z))})}),t.jsx(qo,{label:"Carrier",children:t.jsxs("select",{value:p,onChange:z=>u(z.target.value),style:Qn,children:[t.jsx("option",{value:"fedex",children:"FedEx"}),t.jsx("option",{value:"ups",children:"UPS"}),t.jsx("option",{value:"usps",children:"USPS"}),t.jsx("option",{value:"other",children:"Other"})]})})]}),t.jsx(qo,{label:"Scheduled Date",children:t.jsx("input",{type:"date",value:h,onChange:z=>y(z.target.value),style:Qn})}),t.jsxs("div",{style:{padding:12,background:"rgba(255,255,255,0.03)",borderRadius:10,border:"1px solid #1e3a4f"},children:[t.jsxs("div",{style:{fontSize:11,fontWeight:700,color:"#64748b",textTransform:"uppercase",marginBottom:10},children:["Ship To ",x&&t.jsxs("span",{style:{color:"#0d7ea3",fontWeight:600,textTransform:"none",marginLeft:6},children:["(",C3[x]||x,")"]})]}),!s&&t.jsx("div",{style:{fontSize:12,color:"#64748b",fontStyle:"italic",marginBottom:8},children:"Select a customer above to auto-fill address"}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[t.jsx("input",{placeholder:"Name",value:A.name,onChange:z=>{v(P=>({...P,name:z.target.value})),_("manual_override")},style:Qn}),t.jsx("input",{placeholder:"Address",value:A.address,onChange:z=>{v(P=>({...P,address:z.target.value})),_("manual_override")},style:Qn}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"2fr 1fr 1fr",gap:8},children:[t.jsx("input",{placeholder:"City",value:A.city,onChange:z=>{v(P=>({...P,city:z.target.value})),_("manual_override")},style:Qn}),t.jsx("input",{placeholder:"State",value:A.state,onChange:z=>{v(P=>({...P,state:z.target.value})),_("manual_override")},style:Qn}),t.jsx("input",{placeholder:"ZIP",value:A.zip,onChange:z=>{v(P=>({...P,zip:z.target.value})),_("manual_override")},style:Qn})]})]})]}),t.jsx(qo,{label:"Notes",children:t.jsx("textarea",{value:m,onChange:z=>b(z.target.value),rows:3,style:{...Qn,resize:"vertical"}})})]}),t.jsxs("div",{style:{display:"flex",gap:10,marginTop:16,paddingTop:16,borderTop:"1px solid #1e3a4f"},children:[t.jsx("button",{onClick:e,style:{flex:1,padding:"10px 0",borderRadius:8,background:"rgba(255,255,255,0.05)",border:"1px solid #1e3a4f",color:"#94a3b8",fontSize:13,fontWeight:600,cursor:"pointer"},children:"Cancel"}),t.jsx("button",{onClick:O,disabled:j,style:{flex:1,padding:"10px 0",borderRadius:8,background:"#0d7ea3",border:"none",color:"#fff",fontSize:13,fontWeight:600,cursor:j?"not-allowed":"pointer",opacity:j?.6:1},children:j?"Creating...":"Create Shipment"})]})]})})}function HY({shipment:e,onClose:n,onUpdated:r}){const{can:s}=rs(),[i,o]=g.useState(e.tracking_number||""),[a,l]=g.useState(e.label_url||""),[d,c]=g.useState(!1),[f,p]=g.useState(""),[u,h]=g.useState([]);g.useEffect(()=>{w.from("shipment_items").select("id, product_catalog_id, quantity, product_catalog(name)").eq("shipment_id",e.id).then(({data:v})=>{h((v||[]).map(x=>{var _;return{...x,product_name:((_=x.product_catalog)==null?void 0:_.name)||"Unknown",product_catalog:void 0}}))})},[e.id]);const y=async()=>{c(!0);try{e.status==="pending"&&i?await GK(e.id,{tracking_number:i,label_url:a||void 0}):await XK(e.id,{tracking_number:i,label_url:a}),r()}finally{c(!1)}},m=async()=>{if(confirm("Generate a FedEx shipping label for this shipment?")){p(""),c(!0);try{const v=await fetch("/api/shipping/create-label",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({shipment_id:e.id})}),x=await v.json();if(!v.ok||!x.success){const _=x.error||"";_.toLowerCase().includes("api_key")||_.toLowerCase().includes("unauthorized")||_.toLowerCase().includes("credential")||_.toLowerCase().includes("401")?p("FedEx API credentials not configured. Check FEDEX_API_KEY, FEDEX_SECRET_KEY, and FEDEX_ACCOUNT_NUMBER in Vercel environment variables."):e.ship_to_address?p(_||"Failed to create FedEx label. Check Vercel logs for details."):p("Cannot generate label â shipping address is missing on this shipment.")}else{if(x.label_url)if(x.label_url.startsWith("data:")){const _=await fetch(x.label_url).then(C=>C.blob()),j=URL.createObjectURL(_);window.open(j,"_blank")}else window.open(x.label_url,"_blank");r()}}catch{p("Network error generating FedEx label. Check your internet connection.")}finally{c(!1)}}},b=async()=>
1135{if(e.tracking_number){c(!0);try{const x=await(await fetch("/api/shipping/track",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tracking_number:e.tracking_number})})).json();x.success?alert(`Status: ${x.fedex_status||x.status} 1136${x.description||""} 1137${x.location?"Location: "+x.location:""}${x.estimated_delivery?` 1138ETA: `+new Date(x.estimated_delivery).toLocaleDateString():""}`):alert(x.error||"Tracking lookup failed")}catch{alert("Error fetching tracking info")}finally{c(!1)}}},A=async v=>{c(!0);try{switch(v){case"ship":{if(!e.tracking_number&&!i&&!confirm(`No tracking number set. Mark as shipped anyway? 1139 1140Tip: Add a tracking number above first so the customer email includes it.`)){c(!1);return}const x=await T3(e.id);if(!x.success){alert(x.error||"Failed");break}const _=await At();fetch("/api/email/send-shipment",{method:"POST",headers:_,body:JSON.stringify({shipment_id:e.id})}).catch(()=>{});break}case"in_transit":await JK(e.id);break;case"deliver":await z3(e.id);break;case"cancel":confirm("Cancel this shipment?")&&await N3(e.id);break;case"return":if(confirm("Mark as returned? This does not reopen the fulfillment cycle.")){const x=prompt("Return notes (optional):");await QK(e.id,x||void 0)}break}r()}finally{c(!1)}};return t.jsx("div",{style:O3,onClick:n,children:t.jsxs("div",{style:I3,onClick:v=>v.stopPropagation(),children:[t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:16},children:[t.jsxs("div",{children:[t.jsx("h2",{style:{fontSize:18,fontWeight:700,color:"#e2e8f0",margin:0},children:"Shipment Details"}),t.jsx(D3,{status:e.status})]}),t.jsx("button",{onClick:n,style:{background:"none",border:"none",color:"#64748b",fontSize:20,cursor:"pointer"},children:"â"})]}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:14,overflowY:"auto",flex:1},children:[t.jsx(Ai,{label:"Customer",value:e.customer_name||"â"}),t.jsx(Ai,{label:"Product",value:e.product_name||"â"}),t.jsx(Ai,{label:"Type",value:dg[e.type]||e.type}),t.jsx(Ai,{label:"Source",value:e.source==="cron_fulfillment"?"Auto (Fulfillment Cron)":"Manual"}),t.jsx(Ai,{label:"Carrier",value:(e.carrier||"fedex").toUpperCase()}),e.scheduled_date&&t.jsx(Ai,{label:"Scheduled Date",value:new Date(e.scheduled_date+"T00:00:00").toLocaleDateString()}),e.shipped_date&&t.jsx(Ai,{label:"Shipped Date",value:new Date(e.shipped_date+"T00:00:00").toLocaleDateString()}),e.delivered_date&&t.jsx(Ai,{label:"Delivered Date",value:new Date(e.delivered_date+"T00:00:00").toLocaleDateString()}),t.jsxs("div",{style:{padding:12,background:"rgba(255,255,255,0.03)",borderRadius:10,border:"1px solid #1e3a4f"},children:[t.jsxs("div",{style:{fontSize:10,fontWeight:700,color:"#64748b",textTransform:"uppercase",marginBottom:6},children:["Ship To ",e.address_source&&t.jsxs("span",{style:{color:"#0d7ea3",textTransform:"none"},children:["(",C3[e.address_source]||e.address_source,")"]})]}),t.jsxs("div",{style:{color:"#e2e8f0",fontSize:13,lineHeight:1.6},children:[e.ship_to_name&&t.jsx("div",{children:e.ship_to_name}),e.ship_to_address&&t.jsx("div",{children:e.ship_to_address}),(e.ship_to_city||e.ship_to_state||e.ship_to_zip)&&t.jsxs("div",{children:[[e.ship_to_city,e.ship_to_state].filter(Boolean).join(", ")," ",e.ship_to_zip]}),!e.ship_to_address&&t.jsx("div",{style:{color:"#f59e0b",fontStyle:"italic"},children:"Address missing â update before shipping"})]})]}),u.length>0&&t.jsxs("div",{style:{padding:12,background:"rgba(56,189,248,0.06)",borderRadius:10,border:"1px solid rgba(56,189,248,0.2)"},children:[t.jsx("div",{style:{fontSize:10,fontWeight:700,color:"#38bdf8",textTransform:"uppercase",marginBottom:8},children:"ð¦ Items in this shipment"}),t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:u.map((v,x)=>t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",fontSize:13},children:[t.jsx("span",{style:{color:"#e2e8f0"},children:v.product_name}),t.jsxs("span",{style:{color:"#64748b"},children:["Ã",v.quantity]})]},x))})]}),e.notes&&t.jsxs("div",{style:{padding:12,background:"rgba(255,255,255,0.03)",borderRadius:10,border:"1px solid #1e3a4f"},children:[t.jsx("div",{style:{fontSize:10,fontWeight:700,color:"#64748b",textTransform:"uppercase",marginBottom:6},children:"Notes"}),t.jsx("div",{style:{color:"#94a3b8",fontSize:13},children:e.notes})]}),f&&t.jsxs("div",{style:{padding:"10px 14px",borderRadius:10,fontSize:12,background:"rgba(239,68,68,0.1)",border:"1px solid rgba(239,68,68,0.3)",color:"#f87171"},children:["â ï¸ ",f]}),["pending","label_created"].includes(e.status)&&t.jsxs("div",{style:{padding:12,background:"rgba(255,255,255,0.03)",borderRadius:10,border:"1px solid #1e3a4f"},children:[t.jsx("div",{style:{fontSize:10,fontWeight:700,color:"#64748b",textTransform:"uppercase",marginBottom:8},children:"Tracking Information"}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[t.jsx("input",{placeholder:"Tracking Number (e.g. 794644774783)",value:i,onChange:v=>o(v.target.value),style:Qn}),t.jsx("input",{placeholder:"Label URL (optional)",value:a,onChange:v=>l(v.target.value),style:Qn}),t.jsx("button",{onClick:y,disabled:d||!i,style:{padding:"8px 0",borderRadius:8,background:"#8b5cf6",border:"none",color:"#fff",fontSize:13,fontWeight:600,cursor:!i||d?"not-allowed":"pointer",opacity:!i||d?.5:1},children:d?"Saving...":"Save Tracking"})]})]})]}),t.jsxs("div",{style:{display:"flex",gap:8,marginTop:16,paddingTop:16,borderTop:"1px solid #1e3a4f",flexWrap:"wrap"},children:[e.status==="pending"&&s("shipping","create")&&t.jsx(vi,{label:"ð¦ FedEx Label",color:"#8b5cf6",onClick:m,disabled:d}),["pending","label_created"].includes(e.status)&&s("shipping","mark_shipped")&&t.jsx(vi,{label:"Mark Shipped",color:"#3b82f6",onClick:()=>A("ship"),disabled:d}),e.status==="shipped"&&s("shipping","mark_delivered")&&t.jsxs(t.Fragment,{children:[t.jsx(vi,{label:"In Transit",color:"#06b6d4",onClick:()=>A("in_transit"),disabled:d}),t.jsx(vi,{label:"Delivered",color:"#10b981",onClick:()=>A("deliver"),disabled:d})]}),e.status==="in_transit"&&s("shipping","mark_delivered")&&t.jsx(vi,{label:"Delivered",color:"#10b981",onClick:()=>A("deliver"),disabled:d}),e.tracking_number&&["shipped","in_transit"].includes(e.status)&&t.jsx(vi,{label:"ð Track",color:"#06b6d4",onClick:b,disabled:d}),["pending","label_created"].includes(e.status)&&s("shipping","cancel")&&t.jsx(vi,{label:"Cancel",color:"#ef4444",onClick:()=>A("cancel"),disabled:d}),e.status==="delivered"&&s("shipping","mark_returned")&&t.jsx(vi,{label:"Mark Returned",color:"#ef4444",onClick:()=>A("return"),disabled:d})]})]})})}function qo({label:e,children:n}){return t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:11,fontWeight:700,color:"#64748b",textTransform:"uppercase",marginBottom:4},children:e}),n]})}function Ai({label:e,value:n}){return t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",padding:"6px 0",borderBottom:"1px solid rgba(255,255,255,0.04)"},children:[t.jsx("span",{style:{fontSize:12,color:"#64748b"},children:e}),t.jsx("span",{style:{fontSize:13,color:"#e2e8f0",fontWeight:500},children:n})]})}function vi({label:e,color:n,onClick:r,disabled:s}){return t.jsx("button",{onClick:r,disabled:s,style:{flex:1,minWidth:100,padding:"10px 0",borderRadius:8,background:`${n}18`,border:`1px solid ${n}40`,color:n,fontSize:13,fontWeight:600,cursor:s?"not-allowed":"pointer",opacity:s?.5:1},children:e})}const _i={padding:"11px 14px",borderBottom:"1px solid rgba(255,255,255,0.04)",fontSize:13,color:"#e2e8f0"},Qn={width:"100%",background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:8,padding:"8px 12px",color:"#e2e8f0",fontSize:13,outline:"none",boxSizing:"border-box"},O3={position:"fixed",inset:0,background:"rgba(0,0,0,0.6)",zIndex:1e3,display:"flex",justifyContent:"flex-end"},I3={width:460,maxWidth:"90vw",height:"100vh",background:"#162232",borderLeft:"1px solid #1e3a4f",padding:24,display:"flex",flexDirection:"column",overflowY:"auto"},VY=` 1141 *, 1142 customers(id, full_name, phone, email), 1143 customer_service_plans( 1144 id, plan_id, status, next_fulfillment_date, 1145 service_plans(id, name, fulfillment_type) 1146 ) 1147`;async function $m(e){let n=w.from("fulfillment_requests").select(VY).order("due_date",{ascending:!0}).order("created_at",{ascending:!0});e!=null&&e.status&&(Array.isArray(e.status)?n=n.in("status",e.status):n=n.eq("status",e.status)),e!=null&&e.type&&(n=n.eq("type",e.type)),e!=null&&e.customerId&&(n=n.eq("customer_id",e.customerId));const r=Kt();r&&(n=n.eq("branch_id",r));const{data:s,error:i}=await n;if(i)throw i;return s}async function ZY(e,n,r){const{data:s,error:i}=await w.from("fulfillment_requests").update({status:"scheduled",job_id:n,scheduled_at:r}).eq("id",e).eq("status","paid_awaiting_schedule").select().single();if(i)throw i;return s}async function KY(e){const{data:n,error:r}=await w.from("fulfillment_requests").update({status:"in_progress"}).eq("id",e).eq("status","scheduled").select().single();if(r)throw r;return n}
1147async function YY(e){var i;const{data:n,error:r}=await w.from("fulfillment_requests").update({status:"completed",completed_at:new Date().toISOString()}).eq("id",e).in("status",["scheduled","in_progress"]).select("*, customer_service_plans(id, next_fulfillment_date, service_plans(fulfillment_interval_months))").single();if(r)throw r;const s=n.customer_service_plans;if(s){const o=(i=s.service_plans)==null?void 0:i.fulfillment_interval_months;if(o){const a=s.next_fulfillment_date?new Date(s.next_fulfillment_date):new Date;a.setMonth(a.getMonth()+o);const{error:l}=await w.from("customer_service_plans").update({last_fulfilled_at:new Date().toISOString(),next_fulfillment_date:a.toISOString().split("T")[0]}).eq("id",s.id);l&&console.error("Failed to advance plan dates:",l)}}return n}async function XY(e,n){const{data:r,error:s}=await w.from("fulfillment_requests").update({status:"cancelled",notes:n||null}).eq("id",e).in("status",["paid_awaiting_schedule","scheduled"]).select().single();if(s)throw s;return r}function GY(e){const n=new Date(e),s=new Date().getTime()-n.getTime(),i=Math.floor(s/864e5);return i===0?"Today":i===1?"1 day ago":`${i} days ago`}function L3(e){const n=new Date(e);return Math.floor((new Date().getTime()-n.getTime())/864e5)}function yl(e){return e?new Date(e+"T00:00:00").toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):"â"}const Qj={paid_awaiting_schedule:{bg:"rgba(251,191,36,0.12)",text:"#fbbf24",border:"rgba(251,191,36,0.25)",label:"Awaiting Schedule"},scheduled:{bg:"rgba(96,165,250,0.12)",text:"#60a5fa",border:"rgba(96,165,250,0.25)",label:"Scheduled"},in_progress:{bg:"rgba(168,85,247,0.12)",text:"#a855f7",border:"rgba(168,85,247,0.25)",label:"In Progress"},completed:{bg:"rgba(74,222,128,0.12)",text:"#4ade80",border:"rgba(74,222,128,0.25)",label:"Completed"},cancelled:{bg:"rgba(248,113,113,0.12)",text:"#f87171",border:"rgba(248,113,113,0.25)",label:"Cancelled"}},W3={tech_visit:"ð§ Tech Visit",maintenance_visit:"âï¸ Maintenance",shipment:"ð¦ Shipment"},Mm=[{key:"awaiting",label:"Awaiting Schedule",icon:"ð",filter:["paid_awaiting_schedule"],color:"#fbbf24"},{key:"scheduled",label:"Scheduled",icon:"ð
",filter:["scheduled"],color:"#60a5fa"},{key:"in_progress",label:"In Progress",icon:"â¡",filter:["in_progress"],color:"#a855f7"},{key:"completed",label:"Completed",icon:"â
",filter:["completed"],color:"#4ade80"},{key:"all",label:"All",icon:"ð",filter:null,color:"#94a3b8"}];function $3({status:e}){const n=Qj[e]||Qj.cancelled;return t.jsx("span",{style:{fontSize:10,padding:"3px 8px",borderRadius:12,fontWeight:600,background:n.bg,color:n.text,border:`1px solid ${n.border}`,whiteSpace:"nowrap"},children:n.label})}function JY({fr:e,onClose:n,onAction:r}){var x,_,j;const s=gt(),i=rt(),[o,a]=g.useState(""),[l,d]=g.useState(""),[c,f]=g.useState(!1),p=e.customers,u=e.customer_service_plans,h=_n({mutationFn:()=>ZY(e.id,"",o),onSuccess:()=>{if(i.invalidateQueries({queryKey:["fulfillment"]}),p!=null&&p.phone){const C=o?new Date(o+"T12:00:00").toLocaleDateString("en-US",{weekday:"long",month:"long",day:"numeric"}):"";w.auth.getSession().then(({data:{session:S}})=>{S!=null&&S.access_token&&fetch("/api/automations/trigger",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${(S==null?void 0:S.access_token)||""}`},body:JSON.stringify({key:"fulfillment_scheduled_sms",to:p.phone,entity_type:"customer",entity_id:e.customer_id,variables:{first_name:(p.full_name||"there").split(" ")[0],name:(p.full_name||"there").split(" ")[0],date:C,time:""}})})}).catch(()=>{})}r()}}),y=_n({mutationFn:()=>KY(e.id),onSuccess:()=>{i.invalidateQueries({queryKey:["fulfillment"]}),r()}}),m=_n({mutationFn:()=>YY(e.id),onSuccess:()=>{i.invalidateQueries({queryKey:["fulfillment"]}),r()}}),b=_n({mutationFn:()=>XY(e.id,l),onSuccess:()=>{i.invalidateQueries({queryKey:["fulfillment"]}),r()}}),A=L3(e.due_date),v=e.status==="paid_awaiting_schedule"&&A>7;return t.jsxs("div",{style:{position:"fixed",inset:0,zIndex:50,display:"flex",justifyContent:"flex-end"},children:[t.jsx("div",{style:{position:"absolute",inset:0,background:"rgba(0,0,0,0.5)"},onClick:n}),t.jsxs("div",{style:{position:"relative",width:"100%",maxWidth:480,background:"#162232",borderLeft:"1px solid #1e3a4f",overflowY:"auto",padding:24},children:[t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:20},children:[t.jsx("h2",{style:{fontSize:18,fontWeight:700,color:"#e2e8f0",margin:0},children:"Fulfillment Request"}),t.jsx("button",{onClick:n,style:{background:"none",border:"none",color:"#64748b",fontSize:20,cursor:"pointer"},children:"â"})]}),v&&t.jsxs("div",{style:{background:"rgba(248,113,113,0.1)",border:"1px solid rgba(248,113,113,0.3)",borderRadius:10,padding:12,marginBottom:16},children:[t.jsxs("div",{style:{fontSize:13,fontWeight:600,color:"#f87171"},children:["â ï¸ Overdue â ",A," days since payment"]}),t.jsx("div",{style:{fontSize:11,color:"#fca5a5",marginTop:4},children:"Customer paid but has not been contacted to schedule service."})]}),t.jsxs("div",{style:{display:"flex",gap:8,marginBottom:16},children:[t.jsx($3,{status:e.status}),t.jsx("span",{style:{fontSize:11,color:"#94a3b8",padding:"3px 8px",borderRadius:12,background:"rgba(148,163,184,0.1)",border:"1px solid rgba(148,163,184,0.2)"},children:W3[e.type]||e.type})]}),t.jsxs("div",{style:{background:"#0f1923",borderRadius:10,border:"1px solid #1e3a4f",padding:16,marginBottom:16},children:[t.jsx("div",{style:{fontSize:11,color:"#64748b",fontWeight:600,textTransform:"uppercase",letterSpacing:1,marginBottom:8},children:"Customer"}),t.jsx("div",{style:{fontSize:15,fontWeight:600,color:"#e2e8f0"},children:(p==null?void 0:p.full_name)||"Unknown"}),(p==null?void 0:p.phone)&&t.jsxs("div",{style:{fontSize:12,color:"#94a3b8",marginTop:4},children:["ð ",p.phone]}),(p==null?void 0:p.email)&&t.jsxs("div",{style:{fontSize:12,color:"#94a3b8",marginTop:2},children:["âï¸ ",p.email]}),t.jsx("button",{onClick:()=>s(`/customers/${e.customer_id}`),style:{marginTop:10,fontSize:11,color:"#0d7ea3",background:"none",border:"none",cursor:"pointer",padding:0,textDecoration:"underline"},children:"View Customer Profile â"})]}),t.jsxs("div",{style:{background:"#0f1923",borderRadius:10,border:"1px solid #1e3a4f",padding:16,marginBottom:16},children:[t.jsx("div",{style:{fontSize:11,color:"#64748b",fontWeight:600,textTransform:"uppercase",letterSpacing:1,marginBottom:8},children:"Service Plan"}),t.jsx("div",{style:{fontSize:14,fontWeight:600,color:"#e2e8f0"},children:((x=u==null?void 0:u.service_plans)==null?void 0:x.name)||"Unknown plan"}),((_=u==null?void 0:u.service_plans)==null?void 0:_.name)&&t.jsxs("div",{style:{fontSize:12,color:"#94a3b8",marginTop:4},children:["Template: ",u.service_plans.name]})]}),t.jsxs("div",{style:{background:"#0f1923",borderRadius:10,border:"1px solid #1e3a4f",padding:16,marginBottom:16},children:[t.jsx("div",{style:{fontSize:11,color:"#64748b",fontWeight:600,textTransform:"uppercase",letterSpacing:1,marginBottom:8},children:"Timeline"}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:10,
1147color:"#64748b"},children:"Due Date"}),t.jsx("div",{style:{fontSize:13,fontWeight:600,color:"#e2e8f0"},children:yl(e.due_date)})]}),t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:10,color:"#64748b"},children:"Payment Date"}),t.jsx("div",{style:{fontSize:13,fontWeight:600,color:"#e2e8f0"},children:yl((j=e.created_at)==null?void 0:j.split("T")[0])})]}),e.scheduled_date&&t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:10,color:"#64748b"},children:"Scheduled For"}),t.jsx("div",{style:{fontSize:13,fontWeight:600,color:"#60a5fa"},children:yl(e.scheduled_date)})]}),e.completed_at&&t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:10,color:"#64748b"},children:"Completed"}),t.jsx("div",{style:{fontSize:13,fontWeight:600,color:"#4ade80"},children:yl(e.completed_at.split("T")[0])})]})]})]}),e.notes&&t.jsxs("div",{style:{background:"#0f1923",borderRadius:10,border:"1px solid #1e3a4f",padding:16,marginBottom:16},children:[t.jsx("div",{style:{fontSize:11,color:"#64748b",fontWeight:600,textTransform:"uppercase",letterSpacing:1,marginBottom:6},children:"Notes"}),t.jsx("div",{style:{fontSize:13,color:"#cbd5e1"},children:e.notes})]}),e.status==="paid_awaiting_schedule"&&t.jsxs("div",{style:{background:"#0f1923",borderRadius:10,border:"1px solid #1e3a4f",padding:16,marginBottom:16},children:[t.jsx("div",{style:{fontSize:13,fontWeight:600,color:"#e2e8f0",marginBottom:10},children:"Schedule Visit"}),t.jsx("input",{type:"date",value:o,onChange:C=>a(C.target.value),style:{width:"100%",padding:"8px 12px",borderRadius:8,fontSize:13,background:"#162232",color:"#e2e8f0",border:"1px solid #1e3a4f",marginBottom:10}}),t.jsx("button",{onClick:()=>h.mutate(),disabled:!o||h.isPending,style:{width:"100%",padding:"10px 0",borderRadius:8,fontSize:13,fontWeight:600,background:"#0d7ea3",color:"#fff",border:"none",cursor:"pointer",opacity:!o||h.isPending?.5:1},children:h.isPending?"Scheduling...":"ð
Mark Scheduled"}),t.jsx("div",{style:{fontSize:11,color:"#64748b",marginTop:6},children:"Customer will receive a confirmation SMS when scheduled."})]}),e.status==="scheduled"&&t.jsx("button",{onClick:()=>y.mutate(),disabled:y.isPending,style:{width:"100%",padding:"12px 0",borderRadius:8,fontSize:13,fontWeight:600,background:"#7c3aed",color:"#fff",border:"none",cursor:"pointer",marginBottom:12,opacity:y.isPending?.5:1},children:y.isPending?"Updating...":"â¡ Mark In Progress"}),e.status==="in_progress"&&t.jsx("button",{onClick:()=>m.mutate(),disabled:m.isPending,style:{width:"100%",padding:"12px 0",borderRadius:8,fontSize:13,fontWeight:600,background:"#16a34a",color:"#fff",border:"none",cursor:"pointer",marginBottom:12,opacity:m.isPending?.5:1},children:m.isPending?"Completing...":"â
Mark Completed"}),["paid_awaiting_schedule","scheduled"].includes(e.status)&&t.jsx(t.Fragment,{children:c?t.jsxs("div",{style:{background:"#0f1923",borderRadius:10,border:"1px solid rgba(248,113,113,0.25)",padding:16},children:[t.jsx("input",{type:"text",placeholder:"Reason for cancellation (optional)",value:l,onChange:C=>d(C.target.value),style:{width:"100%",padding:"8px 12px",borderRadius:8,fontSize:12,background:"#162232",color:"#e2e8f0",border:"1px solid #1e3a4f",marginBottom:10}}),t.jsxs("div",{style:{display:"flex",gap:8},children:[t.jsx("button",{onClick:()=>b.mutate(),disabled:b.isPending,style:{flex:1,padding:"8px 0",borderRadius:8,fontSize:12,fontWeight:600,background:"#dc2626",color:"#fff",border:"none",cursor:"pointer"},children:b.isPending?"Cancelling...":"Confirm Cancel"}),t.jsx("button",{onClick:()=>f(!1),style:{flex:1,padding:"8px 0",borderRadius:8,fontSize:12,fontWeight:600,background:"#1e3a4f",color:"#94a3b8",border:"none",cursor:"pointer"},children:"Never mind"})]})]}):t.jsx("button",{onClick:()=>f(!0),style:{width:"100%",padding:"10px 0",borderRadius:8,fontSize:12,fontWeight:600,background:"rgba(248,113,113,0.1)",color:"#f87171",border:"1px solid rgba(248,113,113,0.25)",cursor:"pointer"},children:"Cancel Request"})})]})]})}function QY(){Ee(),gt();const[e,n]=g.useState("awaiting"),[r,s]=g.useState(null),[i,o]=g.useState(""),a=Mm.find(h=>h.key===e)||Mm[0],{data:l=[],isLoading:d}=Ae({queryKey:["fulfillment","list",a.filter],queryFn:()=>a.filter?$m({status:a.filter}):$m(),refetchInterval:3e4}),c=i.trim()?l.filter(h=>{var m,b,A,v,x;const y=i.toLowerCase();return((b=(m=h.customers)==null?void 0:m.full_name)==null?void 0:b.toLowerCase().includes(y))||((x=(v=(A=h.customer_service_plans)==null?void 0:A.service_plans)==null?void 0:v.name)==null?void 0:x.toLowerCase().includes(y))}):l,{data:f=[]}=Ae({queryKey:["fulfillment","counts"],queryFn:()=>$m(),refetchInterval:3e4}),p={awaiting:f.filter(h=>h.status==="paid_awaiting_schedule").length,scheduled:f.filter(h=>h.status==="scheduled").length,in_progress:f.filter(h=>h.status==="in_progress").length,completed:f.filter(h=>h.status==="completed").length,all:f.length},u=r?l.find(h=>h.id===r):null;return t.jsxs("div",{style:{padding:"24px 20px",width:"100%"},children:[t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:20,flexWrap:"wrap",gap:12},children:[t.jsxs("div",{children:[t.jsx("h1",{style:{fontSize:22,fontWeight:700,color:"#e2e8f0",margin:0},children:"Service Fulfillment Queue"}),t.jsx("p",{style:{fontSize:13,color:"#64748b",margin:"4px 0 0"},children:"Customers who paid â schedule their service"})]}),t.jsx("input",{type:"text",placeholder:"Search by customer or plan...",value:i,onChange:h=>o(h.target.value),style:{padding:"8px 14px",borderRadius:8,fontSize:13,width:260,background:"#162232",color:"#e2e8f0",border:"1px solid #1e3a4f"}})]}),t.jsx("div",{style:{display:"flex",gap:6,marginBottom:20,overflowX:"auto",paddingBottom:4},children:Mm.map(h=>{const y=e===h.key,m=p[h.key]??0;return t.jsxs("button",{onClick:()=>n(h.key),style:{display:"flex",alignItems:"center",gap:6,padding:"8px 14px",borderRadius:8,fontSize:12,fontWeight:600,cursor:"pointer",whiteSpace:"nowrap",background:y?"rgba(13,126,163,0.15)":"#162232",color:y?"#0d7ea3":"#94a3b8",border:y?"1px solid rgba(13,126,163,0.3)":"1px solid #1e3a4f"},children:[t.jsx("span",{children:h.icon}),t.jsx("span",{children:h.label}),m>0&&t.jsx("span",{style:{fontSize:10,fontWeight:700,padding:"1px 6px",borderRadius:10,background:y?"rgba(13,126,163,0.25)":"rgba(148,163,184,0.1)",color:y?"#0d7ea3":"#64748b"},children:m})]},h.key)})}),d?t.jsx("div",{style:{textAlign:"center",padding:60,color:"#64748b"},children:"Loading..."}):c.length===0?t.jsxs("div",{style:{textAlign:"center",padding:60,color:"#64748b",background:"#162232",borderRadius:12,border:"1px solid #1e3a4f"},children:[t.jsx("div",{style:{fontSize:32,marginBottom:8},children:e==="awaiting"?"ð":"ð"}),t.jsx("div",{style:{fontSize:14,fontWeight:600},children:e==="awaiting"?"All caught up!":"No requests found"}),t.jsx("div",{style:{fontSize:12,marginTop:4},children:e==="awaiting"?"No customers waiting to be scheduled right now.":"No fulfillment requests match this filter."})]}):t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:c.map(h=>{var b,A,v,x,_;const y=L3(h.due_date),m=h.status==="paid_awaiting_schedule"&&y>7;return t.jsxs("div",{onClick:()=>s(h.id),style:{background:"#162232",borderRadius:10,padding:"14px 18px",border:m?"1px solid rgba(248,113,113,0.35)":"1px solid #1e3a4f",cursor:"pointer",display:"flex",alignItems:"center",gap:14,transition:"border-color 0.15s"},onMouseEnter:j=>j.currentTarget.style.borderColor="#0d7ea3",onMouseLeave:j=>j.currentTarget.style.borderColor=m?"rgba(248,113,113,0.35)":"#1e3a4f",children:[t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:4},children:[t.jsx("span",{style:{fontSize:14,fontWeight:600,color:"#e2e8f0"},children:((b=h.customers)==null?void 0:b.full_name)||"Unknown"}),t.jsx($3,{status:h.status}
1147),m&&t.jsxs("span",{style:{fontSize:10,color:"#f87171",fontWeight:700},children:["â ï¸ ",y,"d overdue"]})]}),t.jsxs("div",{style:{fontSize:12,color:"#94a3b8"},children:[((v=(A=h.customer_service_plans)==null?void 0:A.service_plans)==null?void 0:v.name)||"Unknown plan",t.jsx("span",{style:{margin:"0 6px",color:"#334155"},children:"·"}),W3[h.type]||h.type]})]}),t.jsxs("div",{style:{textAlign:"right",flexShrink:0},children:[t.jsxs("div",{style:{fontSize:12,fontWeight:600,color:"#e2e8f0"},children:[h.status==="paid_awaiting_schedule"&&`Paid ${GY(h.created_at)}`,h.status==="scheduled"&&`Visit: ${yl(h.scheduled_date)}`,h.status==="in_progress"&&"In progress",h.status==="completed"&&`Done ${yl(((x=h.completed_at)==null?void 0:x.split("T")[0])||null)}`,h.status==="cancelled"&&"Cancelled"]}),((_=h.customers)==null?void 0:_.phone)&&t.jsxs("a",{href:`tel:${h.customers.phone}`,onClick:j=>j.stopPropagation(),style:{fontSize:11,color:"#0d7ea3",textDecoration:"none"},children:["ð ",h.customers.phone]})]})]},h.id)})}),u&&t.jsx(JY,{fr:u,onClose:()=>s(null),onAction:()=>s(null)})]})}const M3={overdue:{label:"Overdue",text:"#f87171",bg:"rgba(239,68,68,0.12)",border:"rgba(239,68,68,0.35)",bar:"#ef4444"},urgent:{label:"This Week",text:"#fb923c",bg:"rgba(251,146,60,0.12)",border:"rgba(251,146,60,0.35)",bar:"#fb923c"},soon:{label:"Due Soon",text:"#fbbf24",bg:"rgba(245,158,11,0.12)",border:"rgba(245,158,11,0.35)",bar:"#fbbf24"},upcoming:{label:"Upcoming",text:"#4ade80",bg:"rgba(74,222,128,0.10)",border:"rgba(74,222,128,0.30)",bar:"#4ade80"},future:{label:"Upcoming",text:"#60a5fa",bg:"rgba(96,165,250,0.10)",border:"rgba(96,165,250,0.28)",bar:"#60a5fa"}};function eX(e){if(!e)return null;const[n,r,s]=e.split("-").map(Number);if(!n||!r||!s)return null;const i=Date.UTC(n,r-1,s),o=new Date,a=Date.UTC(o.getFullYear(),o.getMonth(),o.getDate());return Math.round((i-a)/864e5)}function tX(e){return e==null?"future":e<0?"overdue":e<=7?"urgent":e<=30?"soon":e<=90?"upcoming":"future"}function nX(e){return e==null?"":e<0?`${Math.abs(e)} day${Math.abs(e)===1?"":"s"} overdue`:e===0?"Today":e===1?"Tomorrow":e<31?`in ${e} days`:e<365?`in ${Math.round(e/30)} months`:`in ${Math.round(e/365)} year${e>=730?"s":""}`}const Jd=[{key:"7",label:"Next 7 Days",days:7},{key:"30",label:"Next 30 Days",days:30},{key:"90",label:"Next 90 Days",days:90},{key:"all",label:"All",days:null}];function e2(e,n){return e==null?n===null:e<0||n===null?!0:e<=n}function rX({tier:e}){const n=M3[e];return t.jsx("span",{style:{fontSize:10,padding:"3px 9px",borderRadius:12,fontWeight:700,background:n.bg,color:n.text,border:`1px solid ${n.border}`,whiteSpace:"nowrap",letterSpacing:"0.02em"},children:n.label})}function $p({label:e,value:n,accent:r,dim:s}){return t.jsxs("div",{style:{flex:"1 1 140px",minWidth:140,padding:"14px 16px",borderRadius:12,background:s?"#0f1923":`${r}14`,border:`1px solid ${s?"#1e3a4f":`${r}44`}`},children:[t.jsx("div",{style:{fontSize:26,fontWeight:700,color:s?"#e2e8f0":r,lineHeight:1.1},children:n}),t.jsx("div",{style:{fontSize:11,color:"#64748b",textTransform:"uppercase",letterSpacing:"0.07em",marginTop:4,fontWeight:600},children:e})]})}function sX(){const e=gt(),[n,r]=g.useState(""),[s,i]=g.useState("all"),o=g.useRef(!1),{data:a=[],isLoading:l,error:d}=Ae({queryKey:["service-due","list"],queryFn:dB}),c=a.map(m=>{const b=eX(m.next_due_date);return{...m,days:b,tier:tX(b)}}),f={};for(const m of Jd)f[m.key]=c.filter(b=>e2(b.days,m.days)).length;g.useEffect(()=>{if(o.current||l||c.length===0)return;o.current=!0;const m=Jd.find(b=>f[b.key]>0);m&&i(m.key)},[l,c.length]);const p=Jd.find(m=>m.key===s)||Jd[3],u=n.trim().toLowerCase(),h=c.filter(m=>e2(m.days,p.days)).filter(m=>!u||(m.customer_name||"").toLowerCase().includes(u)||(m.component_name||"").toLowerCase().includes(u)),y={overdue:c.filter(m=>m.tier==="overdue").length,week:c.filter(m=>m.tier==="urgent").length,month:c.filter(m=>m.tier==="urgent"||m.tier==="soon").length,total:c.length};return t.jsxs("div",{style:{padding:"24px 28px"},children:[t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",flexWrap:"wrap",gap:16,marginBottom:18},children:[t.jsxs("div",{children:[t.jsx("h1",{style:{margin:0,fontSize:24,fontWeight:700,color:"#e2e8f0"},children:"Service Due"}),t.jsx("p",{style:{margin:"4px 0 0",fontSize:13,color:"#64748b"},children:"Service visits owed to customers on active plans, soonest first"})]}),t.jsx("input",{value:n,onChange:m=>r(m.target.value),placeholder:"Search by customer or service...",style:{background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:8,padding:"9px 14px",fontSize:13,color:"#e2e8f0",minWidth:260}})]}),!l&&!d&&y.total>0&&t.jsxs("div",{style:{display:"flex",gap:12,flexWrap:"wrap",marginBottom:18},children:[t.jsx($p,{label:"Overdue",value:y.overdue,accent:"#ef4444",dim:y.overdue===0}),t.jsx($p,{label:"This Week",value:y.week,accent:"#fb923c",dim:y.week===0}),t.jsx($p,{label:"Next 30 Days",value:y.month,accent:"#fbbf24",dim:y.month===0}),t.jsx($p,{label:"Total On Book",value:y.total,accent:"#4ade80"})]}),!l&&!d&&t.jsx("div",{style:{display:"flex",gap:8,flexWrap:"wrap",marginBottom:16},children:Jd.map(m=>{const b=m.key===s,A=f[m.key]??0;return t.jsxs("button",{onClick:()=>{o.current=!0,i(m.key)},style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer",padding:"8px 14px",borderRadius:999,fontSize:13,fontWeight:600,background:b?"rgba(74,222,128,0.14)":"#0f1923",color:b?"#4ade80":"#94a3b8",border:`1px solid ${b?"rgba(74,222,128,0.4)":"#1e3a4f"}`},children:[t.jsx("span",{children:m.label}),t.jsx("span",{style:{fontSize:11,fontWeight:700,padding:"1px 7px",borderRadius:10,background:b?"rgba(74,222,128,0.2)":"#1e3a4f",color:b?"#4ade80":"#64748b"},children:A})]},m.key)})}),l?t.jsx("div",{style:{padding:48,textAlign:"center",color:"#64748b",fontSize:14},children:"Loadingâ¦"}):d?t.jsx("div",{style:{padding:24,borderRadius:10,background:"rgba(239,68,68,0.08)",border:"1px solid rgba(239,68,68,0.25)",color:"#f87171",fontSize:13},children:"Could not load service obligations. Try reloading the page."}):h.length===0?t.jsxs("div",{style:{padding:48,textAlign:"center",color:"#64748b",border:"1px solid #1e3a4f",borderRadius:10},children:[t.jsx("div",{style:{fontSize:32,marginBottom:8},children:c.length===0?"ð":u?"ð":"â
"}),t.jsx("div",{style:{fontSize:14,fontWeight:600,color:"#94a3b8"}
1147,children:c.length===0?"No service visits on the books":u?"No matches":`Nothing due in the ${p.label.toLowerCase()}`}),t.jsx("div",{style:{fontSize:12,marginTop:4},children:c.length===0?"Customers on active service plans will appear here as visits come due.":u?"Nothing matches that search.":`${c.length} visit${c.length===1?"":"s"} further out â widen the window to see them.`})]}):t.jsx("div",{style:{border:"1px solid #1e3a4f",borderRadius:10,overflow:"hidden"},children:t.jsxs("table",{style:{width:"100%",borderCollapse:"collapse"},children:[t.jsx("thead",{children:t.jsx("tr",{style:{background:"#0f1923",borderBottom:"1px solid #1e3a4f"},children:["Customer","Service","Due","Status"].map((m,b)=>t.jsx("th",{style:{padding:"10px 14px",fontSize:11,fontWeight:700,color:"#64748b",textTransform:"uppercase",letterSpacing:"0.06em",textAlign:b===3?"right":"left"},children:m},m))})}),t.jsx("tbody",{children:h.map((m,b)=>{const A=M3[m.tier];return t.jsxs("tr",{onClick:()=>m.customer_id&&e(`/customers/${m.customer_id}`),style:{borderBottom:"1px solid #1a2a3a",cursor:m.customer_id?"pointer":"default",background:b%2===0?"transparent":"#0f192344"},children:[t.jsx("td",{style:{padding:"12px 14px",fontSize:13,color:"#e2e8f0",fontWeight:500,borderLeft:`3px solid ${A.bar}`},children:m.customer_name||"â"}),t.jsx("td",{style:{padding:"12px 14px",fontSize:13,color:"#94a3b8"},children:m.component_name||"â"}),t.jsxs("td",{style:{padding:"12px 14px",whiteSpace:"nowrap"},children:[t.jsx("div",{style:{fontSize:13,color:"#e2e8f0",fontWeight:500},children:dn(m.next_due_date)}),t.jsx("div",{style:{fontSize:11,color:A.text,marginTop:2},children:nX(m.days)})]}),t.jsx("td",{style:{padding:"12px 14px",textAlign:"right"},children:t.jsx(rX,{tier:m.tier})})]},m.id)})})]})}),t.jsx("p",{style:{marginTop:14,fontSize:11,color:"#475569"},children:"Overdue visits always show, whichever window is selected. Booking from this list is not built yet â open the customer to record a visit."})]})}const iX="America/Indiana/Indianapolis",oX=864e5,F3=2,t2={urgent:0,high:1,normal:2,low:3},aX=[{key:"open",label:"Open",accent:"#93c5fd"},{key:"scheduled",label:"Scheduled",accent:"#fbbf24"},{key:"in_progress",label:"In progress",accent:"#c4b5fd"},{key:"waiting_on_customer",label:"Waiting on customer",accent:"#f9a8d4"},{key:"resolved",label:"Resolved · to confirm",accent:"#4ade80"},{key:"stale",label:`No activity ${F3}+ days`,accent:"#f87171"}];function n2(e){const n=e.customer;return n&&[n.first_name,n.last_name].filter(Boolean).join(" ")||"â"}function lX(e){const n=e.filter(r=>r.job_status!=="complete"&&r.job_status!=="cancelled");return n.length===0?null:[...n].sort((r,s)=>r.scheduled_at?s.scheduled_at?r.scheduled_at.localeCompare(s.scheduled_at):-1:1)[0]}function dX(e){return e?new Date(e).toLocaleString("en-US",{weekday:"short",month:"short",day:"numeric",hour:"numeric",minute:"2-digit",timeZone:iX}):"date not set"}function cX(e){return Math.floor((Date.now()-new Date(e).getTime())/oX)}function uX(e){return e<=0?"today":e===1?"1 day":`${e} days`}function r2({label:e,value:n,accent:r,active:s,onClick:i}){const o=n===0&&!s;return t.jsxs("button",{onClick:i,style:{flex:"1 1 130px",minWidth:130,padding:"12px 14px",borderRadius:12,textAlign:"left",cursor:"pointer",background:s?`${r}22`:o?"#0f1923":`${r}10`,border:`1px solid ${s?r:o?"#1e3a4f":`${r}44`}`},children:[t.jsx("div",{style:{fontSize:24,fontWeight:700,color:o?"#e2e8f0":r,lineHeight:1.1},children:n}),t.jsx("div",{style:{fontSize:10.5,color:"#64748b",textTransform:"uppercase",letterSpacing:"0.06em",marginTop:4,fontWeight:600},children:e})]})}const Ha={background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:8,padding:"8px 10px",fontSize:13,color:"#e2e8f0"};function pX(){const e=gt(),{user:n}=Ee(),{data:r=[]}=vu(),{data:s=[]}=Ae({queryKey:["ticket_owners"],queryFn:E0}),{data:i=[],isLoading:o,error:a}=Ae({queryKey:["service_tickets","board"],queryFn:sU,refetchInterval:6e4}),[l,d]=g.useState("all"),[c,f]=g.useState(!1),[p,u]=g.useState(""),[h,y]=g.useState(""),[m,b]=g.useState(""),[A,v]=g.useState(""),[x,_]=g.useState(""),j=g.useMemo(()=>i.map(R=>{const N=cX(R.last_activity_at);return{t:R,nv:lX(R.jobs),idle:N,stale:N>=F3}}),[i]),C=x.trim().toLowerCase(),S=j.filter(({t:R})=>
1147!(c&&R.owner_id!==(n==null?void 0:n.id)||p&&R.owner_id!==p||h&&!R.jobs.some(N=>{var O;return((O=N.assigned_technician)==null?void 0:O.id)===h})||m&&R.category!==m||A&&R.priority!==A||C&&!(n2(R).toLowerCase().includes(C)||R.ticket_number.toLowerCase().includes(C)||R.subject.toLowerCase().includes(C)))),T={all:S.length,stale:0};for(const R of S)T[R.t.status]=(T[R.t.status]??0)+1,R.stale&&T.stale++;const L=S.filter(R=>l==="all"?!0:l==="stale"?R.stale:R.t.status===l).sort((R,N)=>t2[R.t.priority]-t2[N.t.priority]||R.t.created_at.localeCompare(N.t.created_at)),E=c||p||h||m||A||C||l!=="all";return t.jsxs("div",{style:{padding:"24px 28px"},children:[t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",flexWrap:"wrap",gap:16,marginBottom:18},children:[t.jsxs("div",{children:[t.jsx("h1",{style:{margin:0,fontSize:24,fontWeight:700,color:"#e2e8f0"},children:"Service Board"}),t.jsx("p",{style:{margin:"4px 0 0",fontSize:13,color:"#64748b"},children:"Every open service ticket, urgent first then oldest"})]}),t.jsx("input",{value:x,onChange:R=>_(R.target.value),placeholder:"Search customer, ticket #, problemâ¦",style:{...Ha,padding:"9px 14px",minWidth:280}})]}),!o&&!a&&t.jsxs("div",{style:{display:"flex",gap:10,flexWrap:"wrap",marginBottom:14},children:[t.jsx(r2,{label:"All open",value:T.all,accent:"#e2e8f0",active:l==="all",onClick:()=>d("all")}),aX.map(R=>t.jsx(r2,{label:R.label,value:T[R.key]??0,accent:R.accent,active:l===R.key,onClick:()=>d(l===R.key?"all":R.key)},R.key))]}),t.jsxs("div",{style:{display:"flex",gap:8,flexWrap:"wrap",alignItems:"center",marginBottom:16},children:[t.jsx("button",{onClick:()=>f(R=>!R),style:{...Ha,cursor:"pointer",fontWeight:600,background:c?"rgba(251,191,36,0.14)":"#0f1923",color:c?"#fbbf24":"#94a3b8",border:`1px solid ${c?"rgba(251,191,36,0.4)":"#1e3a4f"}`},children:"â
My tickets"}),t.jsxs("select",{value:p,onChange:R=>u(R.target.value),style:Ha,children:[t.jsx("option",{value:"",children:"Owner: all"}),s.map(R=>t.jsx("option",{value:R.id,children:R.full_name},R.id))]}),t.jsxs("select",{value:h,onChange:R=>y(R.target.value),style:Ha,children:[t.jsx("option",{value:"",children:"Tech: all"}),r.map(R=>t.jsx("option",{value:R.id,children:R.full_name},R.id))]}),t.jsxs("select",{value:m,onChange:R=>b(R.target.value),style:Ha,children:[t.jsx("option",{value:"",children:"Category: all"}),Object.keys(da).map(R=>t.jsx("option",{value:R,children:da[R]},R))]}),t.jsxs("select",{value:A,onChange:R=>v(R.target.value),style:Ha,children:[t.jsx("option",{value:"",children:"Priority: all"}),Object.keys(Cl).map(R=>t.jsx("option",{value:R,children:Cl[R]},R))]}),E&&t.jsx("button",{onClick:()=>{d("all"),f(!1),u(""),y(""),b(""),v(""),_("")},style:{background:"none",border:"none",color:"#64748b",fontSize:12,cursor:"pointer"},children:"Clear filters"})]}),o?t.jsx("div",{style:{padding:48,textAlign:"center",color:"#64748b",fontSize:14},children:"Loadingâ¦"}):a?t.jsxs("div",{style:{padding:24,borderRadius:10,background:"rgba(239,68,68,0.08)",border:"1px solid rgba(239,68,68,0.25)",color:"#f87171",fontSize:13},children:["Could not load service tickets: ",(a==null?void 0:a.message)??"unknown error"]}):L.length===0?t.jsxs("div",{style:{padding:48,textAlign:"center",color:"#64748b",border:"1px solid #1e3a4f",borderRadius:10},children:[t.jsx("div",{style:{fontSize:32,marginBottom:8},children:i.length===0?"â
":"ð"}),t.jsx("div",{style:{fontSize:14,fontWeight:600,color:"#94a3b8"},children:i.length===0?"No open service tickets":"Nothing matches these filters"}),t.jsx("div",{style:{fontSize:12,marginTop:4},children:i.length===0?'Tickets are opened from a customer page with "New service ticket".':`${i.length} open ticket${i.length===1?"":"s"} in total â clear the filters to see them.`})]}):t.jsx("div",{style:{border:"1px solid #1e3a4f",borderRadius:10,overflowX:"auto"},children:t.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",minWidth:980},children:[t.jsx("thead",{children:t.jsx("tr",{style:{background:"#0f1923",borderBottom:"1px solid #1e3a4f"},children:["Ticket","Customer","Problem","Category","Priority","Status","Owner","Next visit · Tech","Last touch"].map(R=>t.jsx("th",{style:{padding:"10px 12px",fontSize:11,fontWeight:700,color:"#64748b",textTransform:"uppercase",letterSpacing:"0.06em",textAlign:"left",whiteSpace:"nowrap"},children:R},R))})}),t.jsx("tbody",{children:L.map(({t:R,nv:N,idle:O,stale:z},P)=>{var M,k;const D=j8[R.status];return t.jsxs("tr",{onClick:()=>e(`/customers/${R.customer_id}?tab=service`),style:{borderBottom:"1px solid #1a2a3a",cursor:"pointer",background:z?"rgba(127,29,29,0.22)":P%2===0?"transparent":"#0f192344"},children:[t.jsx("td",{style:{padding:"11px 12px",fontSize:13,color:"#e2e8f0",fontWeight:700,whiteSpace:"nowrap",borderLeft:`3px solid ${D.fg}`},children:R.ticket_number}),t.jsx("td",{style:{padding:"11px 12px",fontSize:13,color:"#e2e8f0",whiteSpace:"nowrap"},children:n2(R)}),t.jsx("td",{style:{padding:"11px 12px",fontSize:13,color:"#94a3b8",maxWidth:260,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:R.subject}),t.jsx("td",{style:{padding:"11px 12px",fontSize:12,color:"#94a3b8",whiteSpace:"nowrap"},children:da[R.category]}),t.jsx("td",{style:{padding:"11px 12px",fontSize:12,fontWeight:700,whiteSpace:"nowrap",color:w8[R.priority]},children:R.priority==="urgent"?t.jsx("span",{style:{background:"#b91c1c",color:"#fff",padding:"1px 6px",borderRadius:4},children:"URGENT"}):Cl[R.priority]}),t.jsx("td",{style:{padding:"11px 12px",whiteSpace:"nowrap"},children:t.jsx("span",{style:{fontSize:11,fontWeight:700,padding:"2px 8px",borderRadius:10,background:D.bg,color:D.fg},children:_8[R.status]})}),t.jsx("td",{style:{padding:"11px 12px",fontSize:13,color:R.owner?"#e2e8f0":"#f87171",whiteSpace:"nowrap"},children:((M=R.owner)==null?void 0:M.full_name)??"No owner"}),t.jsx("td",{style:{padding:"11px 12px",fontSize:12,whiteSpace:"nowrap",color:N?"#cbd5e1":"#64748b"},children:N?t.jsxs(t.Fragment,{children:[dX(N.scheduled_at)," · ",((k=N.assigned_technician)==null?void 0:k.full_name)??"no tech"]}):R.jobs.length>0?"visits done":"not booked"}),t.jsx("td",{style:{padding:"11px 12px",fontSize:12,whiteSpace:"nowrap",color:z?"#f87171":"#94a3b8",fontWeight:z?700:400},children:uX(O)})]},R.id)})})]})}),t.jsx("p",{style:{marginTop:14,fontSize:11,color:"#475569"},children:"Click a row to open the customer's Service tab. New tickets are opened from the customer page. Resolve, close and reopen from the ticket on that tab. "})]})}const Fm=36,Bm=5,Um=3,s2=6;function vt(){return Kt()}function Aa(e=new Date){const n=r=>String(r).padStart(2,"0");return`${e.getFullYear()}-${n(e.getMonth()+1)}-${n(e.getDate())}`}function B3(){const e=new Date;return{start:Aa(new Date(e.getFullYear(),e.getMonth(),1)),end:Aa(e),label:"MTD"}}function hX(){return{start:Aa(new Date(Date.now()-30*864e5)),end:Aa(new Date),label:"Last 30d"}}function fX(){return{start:Aa(new Date(Date.now()-90*864e5)),end:Aa(new Date),label:"Last 90
1147d"}}function gX(){return{start:`${new Date().getFullYear()}-01-01`,end:Aa(new Date),label:"YTD"}}async function U3(){const e=vt();let n=w.from("contracts").select("monthly_amount").eq("status","active");e&&(n=n.eq("branch_id",e));let r=w.from("customer_service_plans").select("price_monthly, billing_interval").eq("status","active");e&&(r=r.eq("branch_id",e));const[s,i]=await Promise.all([n,r]),o=(s.data||[]).reduce((l,d)=>l+(Number(d.monthly_amount)||0),0),a=(i.data||[]).reduce((l,d)=>{const c=Number(d.price_monthly)||0,f=d.billing_interval||"monthly";return f==="monthly"?l+c:f==="quarterly"?l+c/3:f==="yearly"?l+c/12:l+c},0);return o+a}async function H3(e){try{const n=vt();let r=w.from("leads").select("*",{count:"exact",head:!0}).neq("stage","won").neq("stage","lost").neq("stage","dnd").neq("stage","future_follow_up");n&&(r=r.eq("branch_id",n));let s=w.from("payment_transactions").select("amount").eq("status","succeeded").gte("processed_at",e.start+"T00:00:00").lte("processed_at",e.end+"T23:59:59");n&&(s=s.eq("branch_id",n));let i=w.from("jobs").select("*",{count:"exact",head:!0}).eq("job_status","complete").gte("completed_at",e.start+"T00:00:00").lte("completed_at",e.end+"T23:59:59");n&&(i=i.eq("branch_id",n));let o=w.from("payment_transactions").select("*",{count:"exact",head:!0}).eq("status","failed").gte("created_at",new Date(Date.now()-48*36e5).toISOString());n&&(o=o.eq("branch_id",n));let a=w.from("agreements").select("*",{count:"exact",head:!0}).eq("status","pending_signature");n&&(a=a.eq("branch_id",n));let l=w.from("jobs").select("*",{count:"exact",head:!0}).eq("job_status","scheduled").is("assigned_technician_id",null);n&&(l=l.eq("branch_id",n));const[d,c,f,p,u,h]=await Promise.all([r,s,i,o,a,l]),y=await U3(),m=(c.data||[]).reduce((b,A)=>b+(Number(A.amount)||0),0);return{activeLeads:d.count??0,mrr:y,cashCollected:m,installsCompleted:f.count??0,failedPayments48h:p.count??0,unsignedAgreements:u.count??0,unassignedJobs:h.count??0}}catch(n){throw console.error("getExecutiveKPIs:",n),n}}async function mX(e){try{const n=vt();let r=w.from("invoices").select("total_amount").eq("status","overdue");n&&(r=r.eq("branch_id",n));let s=w.from("payment_transactions").select("*",{count:"exact",head:!0}).eq("status","failed").gte("created_at",e.start+"T00:00:00").lte("created_at",e.end+"T23:59:59");n&&(s=s.eq("branch_id",n));let i=w.from("payment_transactions").select("amount").eq("status","succeeded").gte("processed_at",e.start+"T00:00:00").lte("processed_at",e.end+"T23:59:59");n&&(i=i.eq("branch_id",n));const[o,a,l]=await Promise.all([r,s,i]);return{mrr:await U3(),overdueTotal:(o.data||[]).reduce((c,f)=>c+(Number(f.total_amount)||0),0),cashCollected:(l.data||[]).reduce((c,f)=>c+(Number(f.amount)||0),0),failedPaymentsCount:a.count??0}}catch(n){throw console.error("getRevenueSummary:",n),n}}async function xX(e=6){try{const n=new Date;n.setMonth(n.getMonth()-(e-1)),n.setDate(1),n.setHours(0,0,0,0);let r=w.from("payment_transactions").select("amount, processed_at").eq("status","succeeded").gte("processed_at",n.toISOString()).not("processed_at","is",null);const s=vt();s&&(r=r.eq("branch_id",s));const{data:i,error:o}=await r;if(o)throw o;const a=new Date,l=[];for(let d=e-1;d>=0;d--){const c=new Date(a.getFullYear(),a.getMonth()-d,1);l.push({month:c.toLocaleDateString("en-US",{month:"short",year:"2-digit"}),date:c,total_collected:0,payment_count:0})}for(const d of i||[]){if(!d.processed_at)continue;const c=new Date(d.processed_at),f=l.find(p=>p.date.getFullYear()===c.getFullYear()&&p.date.getMonth()===c.getMonth());f&&(f.total_collected+=Number(d.amount)||0,f.payment_count++)}return l.map(d=>({month:d.month,total_collected:d.total_collected,payment_count:d.payment_count}))}catch(n){return console.error("getCashByMonth:",n),[]}}async function yX(e=6){try{const n=new Date;n.setMonth(n.getMonth()-(e-1)),n.setDate(1),n.setHours(0,0,0,0);let r=w.from("contracts").select("monthly_amount, signed_at").gte("signed_at",n.toISOString()).not("signed_at","is",null);const s=vt();s&&(r=r.eq("branch_id",s));const{data:i,error:o}=await r;if(o)throw o;const a=new Date,l=[];for(let d=e-1;d>=0;d--){const c=new Date(a.getFullYear(),a.getMonth()-d,1);l.push({month:c.toLocaleDateString("en-US",{month:"short",year:"2-digit"}),date:c,new_monthly_value:0,contract_count:0})}for(const d of i||[]){if(!d.signed_at)continue;const c=new Date(d.signed_at),f=l.find(p=>p.date.getFullYear()===c.getFullYear()&&p.date.getMonth()===c.getMonth());f&&(f.new_monthly_value+=Number(d.monthly_amount)||0,f.contract_count++)}return l.map(d=>({month:d.month,new_monthly_value:d.new_monthly_value,contract_count:d.contract_count}))}catch(n){return console.error("getNewContractValueByMonth:",n),[]}}async function bX(){try{let e=w.from("invoices").select("total_amount, due_date, status").in("status",["sent","overdue"]);const n=vt();n&&(e=e.eq("branch_id",n));const{data:r,error:s}=await e;if(s)throw s;const i=Date.now(),o={b0_30:0,b31_60:0,b61_90:0,b90plus:0},a={b0_30:0,b31_60:0,b61_90:0,b90plus:0};for(const l of r||[]){if(!l.due_date)continue;const d=Math.floor((i-new Date(l.due_date).getTime())/864e5),c=Number(l.total_amount)||0;d<=0||d<=30?(o.b0_30+=c,a.b0_30++):d<=60?(o.b31_60+=c,a.b31_60++):d<=90?(o.b61_90+=c,a.b61_90++):(o.b90plus+=c,a.b90plus++)}return{amounts:o,counts:a}}catch(e){return console.error("getInvoiceAging:",e),{amounts:{b0_30:0,b31_60:0,b61_90:0,b90plus:0},counts:{b0_30:0,b31_60:0,b61_90:0,b90plus:0}}}}async function AX(e,n=100){try{let r=w.from("payment_transactions").select("id, amount, status, payment_type, failure_reason, created_at, processed_at, customer_id").gte("created_at",e.start+"T00:00:00").lte("created_at",e.end+"T23:59:59").order("created_at",{ascending:!1}).limit(n);const s=vt();s&&(r=r.eq("branch_id",s));const{data:i,error:o}=await r;if(o)throw o;if(!(i!=null&&i.length))return[];const a=[...new Set(i.map(d=>
1147d.customer_id).filter(Boolean))];let l={};if(a.length){const{data:d}=await w.from("customers").select("id, full_name").in("id",a);for(const c of d||[])l[c.id]=c.full_name}return i.map(d=>({...d,customer_name:l[d.customer_id]||null}))}catch(r){return console.error("getPaymentsDrilldown:",r),[]}}async function vX(e){try{const n=vt();let r=w.from("jobs").select("*",{count:"exact",head:!0}).eq("job_status","complete").gte("completed_at",e.start+"T00:00:00").lte("completed_at",e.end+"T23:59:59");n&&(r=r.eq("branch_id",n));let s=w.from("jobs").select("*",{count:"exact",head:!0}).eq("job_status","scheduled");n&&(s=s.eq("branch_id",n));let i=w.from("jobs").select("*",{count:"exact",head:!0}).eq("job_status","in_progress");n&&(i=i.eq("branch_id",n));let o=w.from("jobs").select("*",{count:"exact",head:!0}).eq("job_status","waiting_for_stock");n&&(o=o.eq("branch_id",n));const[a,l,d,c]=await Promise.all([r,s,i,o]);return{completedInRange:a.count??0,scheduled:l.count??0,inProgress:d.count??0,proofBacklog:0,waitingStock:c.count??0}}catch(n){throw console.error("getInstallKPIs:",n),n}}async function _X(e=8){try{const n=new Date(Date.now()-e*7*864e5).toISOString();let r=w.from("jobs").select("completed_at").eq("job_status","complete").gte("completed_at",n).not("completed_at","is",null);const s=vt();s&&(r=r.eq("branch_id",s));const{data:i,error:o}=await r;if(o)throw o;const a=new Date,l=[];for(let d=e-1;d>=0;d--){const c=new Date(a);c.setDate(a.getDate()-a.getDay()-d*7),c.setHours(0,0,0,0),l.push({start:c,label:c.toLocaleDateString("en-US",{month:"short",day:"numeric"}),count:0})}for(const d of i||[]){if(!d.completed_at)continue;const c=new Date(d.completed_at),f=new Date(c);f.setDate(c.getDate()-c.getDay()),f.setHours(0,0,0,0);const p=l.find(u=>u.start.getTime()===f.getTime());p&&p.count++}return l.map(d=>({label:d.label,count:d.count}))}catch(n){return console.error("getWeeklyInstalls:",n),[]}}async function jX(e,n=100){try{let r=w.from("jobs").select("id, customer_name_snapshot, job_type, job_status, scheduled_at, completed_at, assigned_technician_id, service_address_snapshot").gte("scheduled_at",e.start).lte("scheduled_at",e.end+"T23:59:59").order("scheduled_at",{ascending:!1}).limit(n);const s=vt();s&&(r=r.eq("branch_id",s));const{data:i,error:o}=await r;if(o)throw o;if(!(i!=null&&i.length))return[];const a=[...new Set(i.map(d=>d.assigned_technician_id).filter(Boolean))];let l={};if(a.length){const{data:d}=await w.from("user_profiles").select("id, full_name").in("id",a);for(const c of d||[])l[c.id]=c.full_name}return i.map(d=>({...d,technician_name:l[d.assigned_technician_id]||null}))}catch(r){return console.error("getJobsDrilldown:",r),[]}}async function wX(){try{let e=w.from("leads").select("stage").not("stage","in","(won,lost,dnd,future_follow_up)");const n=vt();n&&(e=e.eq("branch_id",n));const{data:r,error:s}=await e;if(s)throw s;const i={};for(const a of r||[]){const l=a.stage||"unknown";i[l]=(i[l]||0)+1}return["new_lead","qualifying","qualified","site_visit_scheduled","proposal_in_progress","quote_sent","agreement_signed","new","site_visit","negotiating","agreed","signed","install_scheduled","installed"].filter(a=>i[a]>0).map(a=>({stage:a,lead_count:i[a]}))}catch(e){return console.error("getPipelineSnapshot:",e),[]}}async function SX(e){try{const n=vt();let r=w.from("leads").select("*",{count:"exact",head:!0}).eq("stage","won").gte("updated_at",e.start+"T00:00:00").lte("updated_at",e.end+"T23:59:59");n&&(r=r.eq("branch_id",n));let s=w.from("leads").select("*",{count:"exact",head:!0}).eq("stage","lost").gte("updated_at",e.start+"T00:00:00").lte("updated_at",e.end+"T23:59:59");n&&(s=s.eq("branch_id",n));let i=w.from("leads").select("*",{count:"exact",head:!0}).eq("stage","dnd");n&&(i=i.eq("branch_id",n));let o=w.from("leads").select("*",{count:"exact",head:!0}).eq("stage","future_follow_up");
1147n&&(o=o.eq("branch_id",n));const[a,l,d,c]=await Promise.all([r,s,i,o]);return{won:a.count??0,lost:l.count??0,dnd:d.count??0,parked:c.count??0}}catch(n){throw console.error("getPipelineOutcomes:",n),n}}async function kX(e=100){try{let n=w.from("leads").select("id, full_name, phone, stage, source, assigned_rep_id, created_at").neq("stage","won").neq("stage","lost").neq("stage","dnd").neq("stage","future_follow_up").order("created_at",{ascending:!1}).limit(e);const r=vt();r&&(n=n.eq("branch_id",r));const{data:s,error:i}=await n;if(i)throw i;const o=Date.now();return(s||[]).map(a=>({...a,days_open:Math.floor((o-new Date(a.created_at).getTime())/864e5)}))}catch(n){return console.error("getLeadsDrilldown:",n),[]}}async function CX(){try{let e=w.from("leads").select("lost_reason").eq("stage","lost");const n=vt();n&&(e=e.eq("branch_id",n));const{data:r,error:s}=await e;if(s)throw s;const i={price_too_high:"Price Too High",went_with_competitor:"Went With Competitor",finance_declined:"Finance Declined",no_response:"No Response After Follow-ups",deferred:"Deferred / Timing Not Right",other:"Other",unknown:"No Reason Recorded"},o=d=>{if(!d)return"unknown";const c=d.toLowerCase();return/price|cost|expensive|afford|too much/.test(c)?"price_too_high":/competitor|another|other company|elsewhere/.test(c)?"went_with_competitor":/financ|credit|declined|denied/.test(c)?"finance_declined":/no response|ghost|unreachable|not answer/.test(c)?"no_response":/later|timing|not now|defer|wait/.test(c)?"deferred":"other"},a={};for(const d of r||[]){const c=o(d.lost_reason);a[c]=(a[c]||0)+1}const l=Object.values(a).reduce((d,c)=>d+c,0);return l===0?[]:Object.entries(a).map(([d,c])=>({code:d,label:i[d]||d,count:c,pct:Math.round(c/l*100)})).sort((d,c)=>c.count-d.count)}
1147catch(e){return console.error("getLostReasonBreakdown:",e),[]}}async function V3(){var e,n;try{const r=vt();let s=w.from("leads").select("id, full_name, created_at, stage").is("source",null).neq("stage","won").neq("stage","lost").neq("stage","dnd").order("created_at",{ascending:!1}).limit(50);r&&(s=s.eq("branch_id",r));let i=w.from("quotes").select("id, quote_number, created_at, status").is("commercial_type",null).not("status","eq","draft").order("created_at",{ascending:!1}).limit(50);r&&(i=i.eq("branch_id",r));let o=w.from("jobs").select("id, customer_name_snapshot, completed_at, scheduled_at").eq("job_status","complete").order("completed_at",{ascending:!1}).limit(50);r&&(o=o.eq("branch_id",r));let a=w.from("customers").select("id, full_name, created_at, lifecycle_stage").order("created_at",{ascending:!1}).limit(300);r&&(a=a.eq("branch_id",r));let l=w.from("contracts").select("id, contract_number, customer_id, monthly_amount, created_at, signed_at").eq("status","active").eq("commercial_type","rental").lte("created_at",new Date(Date.now()-35*864e5).toISOString()).limit(200);r&&(l=l.eq("branch_id",r));let d=w.from("invoices").select("id, total_amount, due_date, status, customer_id").eq("status","overdue").lte("due_date",new Date(Date.now()-60*864e5).toISOString().split("T")[0]).order("due_date",{ascending:!0}).limit(50);r&&(d=d.eq("branch_id",r));const[c,f,p,u,h,y]=await Promise.all([s,i,o,a,l,d]);let m=[];if((e=u.data)!=null&&e.length){let j=w.from("installed_systems").select("customer_id");r&&(j=j.eq("branch_id",r));const{data:C}=await j,S=new Set((C||[]).map(T=>T.customer_id));m=u.data.filter(T=>!S.has(T.id)).slice(0,50)}let b=[];if((n=h.data)!=null&&n.length){const j=[...new Set(h.data.map(T=>T.customer_id))],{data:C}=await w.from("payment_transactions").select("customer_id").eq("status","succeeded").gte("created_at",new Date(Date.now()-35*864e5).toISOString()).in("customer_id",j),S=new Set((C||[]).map(T=>T.customer_id));b=h.data.filter(T=>!S.has(T.customer_id)).slice(0,50)}const A=new Set;for(const j of b)j.customer_id&&A.add(j.customer_id);for(const j of y.data||[])j.customer_id&&A.add(j.customer_id);let v={};if(A.size>0){const{data:j}=await w.from("customers").select("id, full_name").in("id",Array.from(A));for(const C of j||[])v[C.id]=C.full_name}const x=b.map(j=>({...j,customer_name:v[j.customer_id]||null})),_=(y.data||[]).map(j=>({...j,customer_name:v[j.customer_id]||null}));return{nullSourceLeads:c.data||[],nullCommercialTypeQuotes:f.data||[],noProofJobs:p.data||[],customersNoSystem:m,contractsNoPmt:x,overdue60Invoices:_}}catch(r){throw console.error("getDataQualityExceptions:",r),r}}async function TX(){try{const e=vt();let n=0,r=0,s=0,i=0,o=0;try{let a=w.from("customers").select("*",{count:"exact",head:!0});e&&(a=a.eq("branch_id",e));const{count:l}=await a;n=l??0}catch{}try{let a=w.from("customers").select("*",{count:"exact",head:!0}).eq("lifecycle_stage","active");e&&(a=a.eq("branch_id",e));const{count:l}=await a;r=l??0}catch{}try{let a=w.from("customers").select("*",{count:"exact",head:!0}).eq("lifecycle_stage","at_risk");e&&(a=a.eq("branch_id",e));const{count:l}=await a;s=l??0}catch{}try{const a=new Date,l=h=>String(h).padStart(2,"0"),d=`${a.getFullYear()}-${l(a.getMonth()+1)}-${l(a.getDate())}`,c=new Date(Date.now()+30*864e5),f=`${c.getFullYear()}-${l(c.getMonth()+1)}-${l(c.getDate())}`;let p=w.from("contracts").select("*",{count:"exact",head:!0}).eq("status","active").gte("end_date",d).lte("end_date",f);e&&(p=p.eq("branch_id",e));const{count:u}=await p;i=u??0}catch{}try{let a=w.from("service_schedule_items").select("*",{count:"exact",head:!0}).eq("status","overdue");e&&(a=a.eq("branch_id",e));const{count:l}=await a;o=l??0}catch{}return{totalCustomers:n,activeCustomers:r,atRisk:s,renewalsIn30:i,serviceDue:o}}catch(e){return console.error("getCustomerKPIs:",e),{totalCustomers:0,activeCustomers:0,atRisk:0,renewalsIn30:0,serviceDue:0}}}async function zX(){try{let e=w.from("customers").select("lifecycle_stage");const n=vt();n&&(e=e.eq("branch_id",n));const{data:r,error:s}=await e;if(s)throw s;const i={};for(const a of r||[]){const l=a.lifecycle_stage||"unknown";i[l]=(i[l]||0)+1}return["active","service_due","renewal_due","upsell","at_risk","inactive","churned","prospect","unknown"].filter(a=>i[a]>0).map(a=>({status:a,count:i[a]}))}catch(e){return console.error("getCustomerLifecycleDistribution:",e),[]}}async function NX(){try{let e=w.from("installed_systems").select("system_name");const n=vt();n&&(e=e.eq("branch_id",n));const{data:r,error:s}=await e;if(s)throw s;const i={};for(const o of r||[]){const a=o.system_name||"unknown";i[a]=(i[a]||0)+1}return Object.entries(i).sort((o,a)=>a[1]-o[1]).map(([o,a])=>({type:o,count:a}))}catch(e){return console.error("getSystemTypeDistribution:",e),[]}}async function RX(e=150){try{const n=vt();let r=w.from("customers").select("id, full_name, lifecycle_stage, created_at, phone, email").order("created_at",{ascending:!1}).limit(e);n&&(r=r.eq("branch_id",n));const{data:s,error:i}=await r;if(i)throw i;if(!(s!=null&&s.length))return[];const o=s.map(u=>u.id),{data:a}=await w.from("contracts").select("customer_id, commercial_type, monthly_amount, status, end_date").in("customer_id",o).eq("status","active"),{data:l}=await w.from("installed_systems").select("customer_id, system_name, commercial_type").in("customer_id",o),{data:d}=await w.from("payment_transactions").select("customer_id, processed_at, amount").eq("status","succeeded").in("customer_id",o).order("processed_at",{ascending:!1}),c={};for(const u of a||[])c[u.customer_id]||(c[u.customer_id]=u);const f={};for(const u of l||[])f[u.customer_id]||(f[u.customer_id]=[]),f[u.customer_id].push(u);const p={};for(const u of d||[])!p[u.customer_id]&&u.processed_at&&(p[u.customer_id]=u.processed_at);return s.map(u=>({...u,contract:c[u.id]||null,systems:f[u.id]||[],last_payment_at:p[u.
1147id]||null}))}catch(n){return console.error("getCustomersDrilldown:",n),[]}}async function EX(e=6){try{let n=w.from("customers").select("created_at").order("created_at",{ascending:!1});const r=vt();r&&(n=n.eq("branch_id",r));const{data:s,error:i}=await n;if(i)throw i;const o=new Date,a=[];for(let l=e-1;l>=0;l--){const d=new Date(o.getFullYear(),o.getMonth()-l,1);a.push({month:d.toLocaleDateString("en-US",{month:"short",year:"2-digit"}),date:d,count:0})}for(const l of s||[]){if(!l.created_at)continue;const d=new Date(l.created_at),c=a.find(f=>f.date.getFullYear()===d.getFullYear()&&f.date.getMonth()===d.getMonth());c&&c.count++}return a.map(l=>({month:l.month,count:l.count}))}catch(n){return console.error("getNewCustomersByMonth:",n),[]}}async function PX(){try{const e=vt();let n=w.from("installed_systems").select("commercial_type, customer_id");e&&(n=n.eq("branch_id",e));const{data:r,error:s}=await n;if(s)throw s;let i=w.from("contracts").select("customer_id, monthly_amount, commercial_type").eq("status","active");e&&(i=i.eq("branch_id",e));const{data:o}=await i,a={};for(const u of o||[])a[u.customer_id]=(a[u.customer_id]||0)+(Number(u.monthly_amount)||0);let l=w.from("payment_transactions").select("customer_id, amount, payment_type").eq("status","succeeded").in("payment_type",["deposit","installation_balance","payment"]);e&&(l=l.eq("branch_id",e));const{data:d}=await l,c={};for(const u of d||[])c[u.customer_id]=(c[u.customer_id]||0)+(Number(u.amount)||0);const f={};for(const u of r||[]){const h=u.commercial_type||"unknown";f[h]||(f[h]={count:0,totalValue:0}),f[h].count++,h==="rental"&&(f[h].totalValue+=a[u.customer_id]||0),h==="purchase"&&(f[h].totalValue+=c[u.customer_id]||0)}return["rental","purchase","financed","unknown"].filter(u=>f[u]).map(u=>({type:u,count:f[u].count,totalValue:f[u].totalValue}))}catch(e){return console.error("getCommercialTypeSplit:",e),[]}}async function qX(e=6){try{let n=w.from("contracts").select("commercial_type, status, signed_at").eq("commercial_type","rental").not("signed_at","is",null).order("signed_at",{ascending:!1});const r=vt();r&&(n=n.eq("branch_id",r));const{data:s,error:i}=await n;if(i)throw i;const o=new Date,a=[];for(let l=e-1;l>=0;l--){const d=new Date(o.getFullYear(),o.getMonth()-l,1);a.push({month:d.toLocaleDateString("en-US",{month:"short",year:"2-digit"}),date:d,active:0,expired:0,cancelled:0})}for(const l of s||[]){if(!l.signed_at)continue;const d=new Date(l.signed_at),c=a.find(p=>p.date.getFullYear()===d.getFullYear()&&p.date.getMonth()===d.getMonth());if(!c)continue;const f=l.status||"active";f==="active"?c.active++:f==="expired"?c.expired++:f==="cancelled"?c.cancelled++:c.active++}return a.map(l=>({month:l.month,active:l.active,expired:l.expired,cancelled:l.cancelled}))}catch(n){return console.error("getRentalLifecycleByMonth:",n),[]}}async function DX(){try{const e=vt(),{data:n}=await w.from("user_profiles").select("id, full_name, role").in("role",["salesrep","admin"]);if(!(n!=null&&n.length))return[];let r=w.from("leads").select("id, assigned_rep_id, stage, created_at");e&&(r=r.eq("branch_id",e));const{data:s}=await r;let i=w.from("quotes").select("lead_id, status, commercial_type, monthly_rental_price, total, created_at");e&&(i=i.eq("branch_id",e));const{data:o}=await i;let a=w.from("jobs").select("id, customer_id, assigned_technician_id, job_status").eq("job_status","complete");e&&(a=a.eq("branch_id",e));const{data:l}=await a;let d=w.from("customers").select("id, lead_id");e&&(d=d.eq("branch_id",e));const{data:c}=await d,f={},p={};for(const m of s||[])m.assigned_rep_id&&(f[m.id]=m.assigned_rep_id,p[m.assigned_rep_id]||(p[m.assigned_rep_id]={total:0,won:0,lost:0}),p[m.assigned_rep_id].total++,m.stage==="won"&&p[m.assigned_rep_id].won++,m.stage==="lost"&&p[m.assigned_rep_id].lost++);const u={};for(const m of o||[]){const b=m.lead_id?f[m.lead_id]:null;b&&(u[b]||(u[b]={sent:0,accepted:0,totalValue:0}),["sent","viewed","accepted","declined","expired","signed"].includes(m.status)&&u[b].sent++,["accepted","signed"].includes(m.status)&&(u[b].accepted++,u[b].totalValue+=Number(m.monthly_rental_price)||Number(m.total)||0))}const h={};
1147for(const m of c||[])m.lead_id&&(h[m.id]=m.lead_id);const y={};for(const m of l||[]){if(!m.customer_id)continue;const b=h[m.customer_id];if(!b)continue;const A=f[b];A&&(y[A]=(y[A]||0)+1)}return n.map(m=>{const b=p[m.id]||{total:0,won:0,lost:0},A=u[m.id]||{sent:0,accepted:0,totalValue:0},v=y[m.id]||0,x=A.sent>0?Math.round(A.accepted/A.sent*100):0;return{id:m.id,name:m.full_name||"Unknown",role:m.role,totalLeads:b.total,wonLeads:b.won,lostLeads:b.lost,quotesSent:A.sent,quotesWon:A.accepted,closeRate:x,totalValue:A.totalValue,installs:v}}).filter(m=>m.totalLeads>0||m.quotesSent>0||m.installs>0)}catch(e){return console.error("getRepPerformance:",e),[]}}async function OX(){try{let e=w.from("quotes").select("id, status, commercial_type, monthly_rental_price, total, created_at, updated_at").order("created_at",{ascending:!1});const n=vt();n&&(e=e.eq("branch_id",n));const{data:r,error:s}=await e;if(s)throw s;const i=r||[],o={total:0,draft:0,sent:0,viewed:0,accepted:0,declined:0,expired:0,rental:0,purchase:0,financed:0,avgDaysToAccept:0,acceptanceRate:0,avgQuoteValue:0,totalPipeline:0};let a=0,l=0,d=0;for(const c of i){o.total++;const f=c.status||"draft";if(f==="draft"&&o.draft++,f==="sent"&&o.sent++,f==="viewed"&&o.viewed++,["accepted","signed"].includes(f)&&(o.accepted++,c.updated_at&&c.created_at)){const h=Math.floor((new Date(c.updated_at).getTime()-new Date(c.created_at).getTime())/864e5);h>=0&&h<365&&(a+=h,l++)}f==="declined"&&o.declined++,f==="expired"&&o.expired++;const p=c.commercial_type||"";p==="rental"&&o.rental++,p==="purchase"&&o.purchase++,p==="financed"&&o.financed++,["sent","viewed","accepted","signed","declined","expired"].includes(f)&&d++;const u=Number(c.monthly_rental_price)||Number(c.total)||0;["sent","viewed"].includes(f)&&(o.totalPipeline+=u)}return o.acceptanceRate=d>0?Math.round(o.accepted/d*100):0,o.avgDaysToAccept=l>0?Math.round(a/l):0,o.avgQuoteValue=o.accepted>0?Math.round(i.filter(c=>["accepted","signed"].includes(c.status)).reduce((c,f)=>c+(Number(f.monthly_rental_price)||Number(f.total)||0),0)/o.accepted):0,{summary:o,quotes:i}}catch(e){return console.error("getQuotesSummary:",e),{summary:null,quotes:[]}}}async function IX(e){try{let n=w.from("leads").select("id, source, utm_source, utm_medium, utm_campaign, stage, created_at");const r=vt();if(r&&(n=n.eq("branch_id",r)),e){const m=new Date(e.end+"T00:00:00");m.setDate(m.getDate()+1),n=n.gte("created_at",e.start).lt("created_at",m.toISOString().slice(0,10))}const{data:s,error:i}=await n;if(i)throw i;const o={};for(const m of s||[]){const b=m.source||"unknown";o[b]||(o[b]={total:0,won:0,lost:0,active:0}),o[b].total++,m.stage==="won"&&o[b].won++,m.stage==="lost"&&o[b].lost++,["won","lost","dnd","future_follow_up"].includes(m.stage||"")||o[b].active++}const a=["won","lost","dnd","future_follow_up"],l=(m,b,A)=>{m[b]||(m[b]={total:0,won:0,lost:0,active:0}),m[b].total++,A==="won"&&m[b].won++,A==="lost"&&m[b].lost++,a.includes(A||"")||m[b].active++},d={},c={};for(const m of s||[])m.utm_source&&l(d,m.utm_source,m.stage),m.utm_campaign&&l(c,m.utm_campaign,m.stage);const f=Object.entries(o).map(([m,b])=>({source:m,...b,conversionRate:b.total>0?Math.round(b.won/b.total*100):0})).sort((m,b)=>b.total-m.total),p=Object.entries(d).map(([m,b])=>({source:m,count:b.total,...b,conversionRate:b.total>0?Math.round(b.won/b.total*100):0})).sort((m,b)=>b.total-m.total).slice(0,25),u=Object.entries(c).map(([m,b])=>({campaign:m,count:b.total,...b,conversionRate:b.total>0?Math.round(b.won/b.total*100):0})).sort((m,b)=>b.total-m.total).slice(0,25),h=["qualified","site_visit_scheduled","proposal_in_progress","quote_sent","agreement_signed","won"],y=(s||[]).map(m=>({lead_date:(m.created_at||"").split("T")[0],source:m.source||"",utm_source:m.utm_source||"",utm_medium:m.utm_medium||"",utm_campaign:m.utm_campaign||"",stage:m.stage||"",qualified:h.includes(m.stage||"")?"yes":"no",won:m.stage==="won"?"yes":"no"})).sort((m,b)=>m.lead_date<b.lead_date?1:-1);return{sources:f,utmSources:p,utmCampaigns:u,leadRows:y,totalLeads:(s||[]).length}}catch(n){return console.error("getLeadSourceBreakdown:",n),{sources:[],utmSources:[],utmCampaigns:[],leadRows:[],totalLeads:0}}}async function LX(){try{const e=vt();let n=w.from("contracts").select("id, monthly_amount, signed_at, start_date").eq("status","active").eq("commercial_type","rental");e&&(n=n.eq("branch_id",e));const{data:r}=await n;let s=w.from("payment_transactions").select("amount").eq("status","succeeded").in("payment_type",["deposit","installation_balance","payment"]);e&&(s=s.eq("branch_id",e));const{data:i}=await s;let o=w.from("installed_systems").select("id, commercial_type, product_catalog_id");e&&(o=o.eq("branch_id",e));const{data:a}=await o,{data:l}=await w.from("product_catalog").select("id, vendor_cost").not("vendor_cost","is",null).gt("vendor_cost",0),d={};for(const N of l||[])d[N.id]=Number(N.vendor_cost)||0;let c=0,f=0,p=0,u=0,h=0,y=0;for(const N of a||[]){const O=N.commercial_type==="purchase"||N.commercial_type==="financed",z=N.commercial_type==="rental",P=N.product_catalog_id&&d[N.product_catalog_id]||0,D=N.product_catalog_id&&d[N.product_catalog_id]>0;O?D?(c+=P,p++):u++:z&&(D?(f+=P,h++):y++)}const m=(i||[]).reduce((N,O)=>N+(Number(O.amount)||0),0),b=m-c,A=m>0?b/m*100:0,v=(r||[]).reduce((N,O)=>N+(Number(O.monthly_amount)||0),0),x=f/Fm,_=v-x,j=v>0?_/v*100:0,C=(i||[]).length,S=Date.now(),T=(r||[]).filter(N=>{const O=N.signed_at||N.start_date;return O?(S-new Date(O).getTime())/(1e3*60*60*24*30.44)>=s2:!1}).length,L=C<Bm||T<Um,E=[];C<Bm&&E.push(`${Bm}+ purchase payments (currently ${C})`),T<Um&&E.push(`${Um}+ rentals active >${s2} months (currently ${T})`);const R=E.length>0?`Need ${E.join(" and ")}`:"";return{hasInsufficientData:L,insufficientDataReason:R,amortizationMonths:Fm,purchase:{revenue:m,cost:c,margin:b,marginPct:Math.round(A),paymentCount:C,coveredUnits:p,uncoveredUnits:u,isEstimate:u>0},rental:{monthlyRevenue:v,monthlyAmortizedCost:x,monthlyMargin:_,marginPct:Math.round(j),activeContractCount:(r||[]).length,activeRentalUnitCount:h+y,coveredUnits:h,uncoveredUnits:y,isEstimate:y>0}}}catch(e){return console.error("getMarginSummary:",e),{hasInsufficientData:!0,insufficientDataReason:"Data load error",amortizationMonths:Fm,purchase:{revenue:0,cost:0,margin:0,marginPct:0,paymentCount:0,coveredUnits:0,uncoveredUnits:0,isEstimate:!0},rental:{monthlyRevenue:0,monthlyAmortizedCost:0,monthlyMargin:0,marginPct:0,activeContractCount:0,activeRentalUnitCount:0,coveredUnits:0,uncoveredUnits:0,isEstimate:!0}}}}async function WX(){try{let e=w.from("contracts").select("id, contract_number,
1147customer_id, monthly_amount, signed_at, start_date").eq("status","active").eq("commercial_type","rental");const n=vt();n&&(e=e.eq("branch_id",n));const{data:r}=await e;if(!(r!=null&&r.length))return[];const s=r.map(p=>p.id),i=[...new Set(r.map(p=>p.customer_id).filter(Boolean))],{data:o}=await w.from("installed_systems").select("contract_id, product_catalog_id").in("contract_id",s),a=[...new Set((o||[]).map(p=>p.product_catalog_id).filter(Boolean))];let l={};if(a.length){const{data:p}=await w.from("product_catalog").select("id, vendor_cost").in("id",a);for(const u of p||[])l[u.id]=Number(u.vendor_cost)||0}let d={};if(i.length){const{data:p}=await w.from("customers").select("id, full_name").in("id",i);for(const u of p||[])d[u.id]=u.full_name}const c={};for(const p of o||[])p.contract_id&&(c[p.contract_id]||(c[p.contract_id]={cost:0,unitCount:0}),c[p.contract_id].unitCount++,p.product_catalog_id&&(c[p.contract_id].cost+=l[p.product_catalog_id]||0));const f=Date.now();return r.map(p=>{var j,C;const u=((j=c[p.id])==null?void 0:j.cost)||0,h=((C=c[p.id])==null?void 0:C.unitCount)||0,y=Number(p.monthly_amount)||0,m=y>0?u/y:0,b=p.signed_at||p.start_date,v=(b?(f-new Date(b).getTime())/(1e3*60*60*24):0)/30.44,x=v<m?"paying_back":"paid_off",_=m>0?Math.min(100,Math.round(v/m*100)):100;return{contractId:p.id,contractNumber:p.contract_number,customerName:d[p.customer_id]||"Unknown",monthlyAmount:y,vendorCost:u,unitCount:h,paybackMonths:Math.round(m*10)/10,monthsActive:Math.round(v*10)/10,status:x,progressPct:_,isEstimate:u===0&&h>0}}).sort((p,u)=>u.monthlyAmount-p.monthlyAmount)}catch(e){return console.error("getRentalPaybackStatus:",e),[]}}function Rt(e){return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(e)}function nr(e){return new Date(e+"T00:00:00").toLocaleDateString("en-US",{month:"short",day:"numeric",year:"2-digit"})}function js(e,n){if(!e.length)return;const r=Object.keys(e[0]),s=e.map(d=>r.map(c=>{const f=d[c];return`"${(f==null?"":typeof f=="object"?JSON.stringify(f):String(f)).replace(/"/g,'""')}"`}).join(",")),i=[r.join(","),...s].join(` 1148`),o=new Blob([i],{type:"text/csv;charset=utf-8;"}),a=URL.createObjectURL(o),l=document.createElement("a");l.href=a,l.download=n,document.body.appendChild(l),l.click(),document.body.removeChild(l),URL.revokeObjectURL(a)}async function $X(e){const{data:{session:n}}=await w.auth.getSession(),r=n==null?void 0:n.access_token;if(!r){alert("Not signed in â please refresh and try again");return}const s=new URLSearchParams({start:e.start,end:e.end,label:e.label}),i=await fetch(`/api/export/lead-sources?${s}`,{headers:{Authorization:`Bearer ${r}`}});if(!i.ok){alert("Export failed â check console");return}const o=await i.blob(),a=URL.createObjectURL(o),l=document.createElement("a");l.href=a;const c=(i.headers.get("content-disposition")||"").match(/filename="(.+)"/);l.download=c?c[1]:`Lead_Sources_${e.start}_${e.end}.xlsx`,l.click(),URL.revokeObjectURL(a)}const i2={new_lead:"New Lead",qualifying:"Qualifying",qualified:"Qualified",site_visit_scheduled:"Site Visit",proposal_in_progress:"Proposal",quote_sent:"Quote Sent",agreement_signed:"Agreement Signed"},Hm={new_lead:"#64748b",qualifying:"#a78bfa",qualified:"#0d7ea3",site_visit_scheduled:"#22d3ee",proposal_in_progress:"#22d3ee",quote_sent:"#f59e0b",agreement_signed:"#4ade80"};function MX(e,n){var y,m,b;const r=[],s=(e==null?void 0:e.failedPayments48h)??0;r.push({label:"Failed Payments",score:s===0?100:s<=2?60:20,weight:25,status:s===0?"good":s<=2?"warn":"bad",detail:s===0?"All clear":`${s} failed in last 48h`});const i=(e==null?void 0:e.unsignedAgreements)??0;r.push({label:"Unsigned Agreements",score:i===0?100:i<=2?70:40,weight:15,status:i===0?"good":i<=2?"warn":"bad",detail:i===0?"All signed":`${i} awaiting signature`});const o=(e==null?void 0:e.unassignedJobs)??0;r.push({label:"Unassigned Jobs",score:o===0?100:o<=1?65:30,weight:15,status:o===0?"good":o<=1?"warn":"bad",detail:o===0?"All jobs assigned":`${o} job${o!==1?"s":""} need a tech`});const a=(e==null?void 0:e.activeLeads)??0;r.push({label:"Active Pipeline",score:a>=5?100:a>=2?75:a>=1?50:20,weight:10,status:a>=3?"good":a>
1148=1?"warn":"bad",detail:`${a} active lead${a!==1?"s":""} in pipeline`});const l=(e==null?void 0:e.mrr)??0;r.push({label:"Monthly Revenue",score:l>=500?100:l>=200?75:l>0?50:20,weight:15,status:l>=200?"good":l>0?"warn":"bad",detail:l>0?`${Rt(l)} MRR from active contracts`:"No active rental contracts"});const d=n?(((y=n.nullSourceLeads)==null?void 0:y.length)??0)+(((m=n.nullCommercialTypeQuotes)==null?void 0:m.length)??0)+(((b=n.overdue60Invoices)==null?void 0:b.length)??0):0;r.push({label:"Data Quality",score:d===0?100:d<=2?65:35,weight:20,status:d===0?"good":d<=2?"warn":"bad",detail:d===0?"No data issues found":`${d} data issue${d!==1?"s":""} need attention`});const c=r.reduce((A,v)=>A+v.weight,0),f=r.reduce((A,v)=>A+v.score*v.weight,0),p=Math.round(f/c),u=p>=90?"A":p>=75?"B":p>=60?"C":p>=40?"D":"F",h=p>=90?"#4ade80":p>=75?"#34d399":p>=60?"#fbbf24":p>=40?"#fb923c":"#f87171";return{score:p,grade:u,color:h,signals:r}}function FX({range:e}){const{data:n}=Ae({queryKey:["reports","executive",e.start,e.end],queryFn:()=>H3(e),refetchInterval:12e4}),{data:r}=Ae({queryKey:["reports","data_quality"],queryFn:()=>V3(),refetchInterval:3e5}),s=MX(n,r),{score:i,grade:o,color:a,signals:l}=s,d=o==="A"?"Excellent":o==="B"?"Good":o==="C"?"Fair":o==="D"?"Needs Attention":"Critical",c=l.filter(A=>A.status==="good").length,f=l.filter(A=>A.status==="warn").length,p=l.filter(A=>A.status==="bad").length,u=54,h=70,y=70,m=Math.PI*u,b=m-i/100*m;return t.jsxs("div",{style:{background:"#0f1923",border:`1px solid ${a}30`,borderRadius:16,padding:"20px 24px",display:"flex",gap:28,alignItems:"center",flexWrap:"wrap",marginBottom:20,position:"relative",overflow:"hidden"},children:[t.jsx("div",{style:{position:"absolute",top:-40,left:-40,width:200,height:200,borderRadius:"50%",background:`${a}08`,pointerEvents:"none"}}),t.jsxs("div",{style:{flexShrink:0,display:"flex",flexDirection:"column",alignItems:"center",gap:4},children:[t.jsxs("svg",{width:"140",height:"80",viewBox:"0 0 140 80",children:[t.jsx("path",{d:`M ${h-u} ${y} A ${u} ${u} 0 0 1 ${h+u} ${y}`,fill:"none",stroke:"#1e3a4f",strokeWidth:"10",strokeLinecap:"round"}),t.jsx("path",{d:`M ${h-u} ${y} A ${u} ${u} 0 0 1 ${h+u} ${y}`,fill:"none",stroke:a,strokeWidth:"10",strokeLinecap:"round",strokeDasharray:m,strokeDashoffset:b,style:{transition:"stroke-dashoffset 0.8s ease, stroke 0.4s ease"}}),t.jsx("text",{x:h,y:y-6,textAnchor:"middle",fill:a,fontSize:"22",fontWeight:"900",fontFamily:"system-ui",children:i}),t.jsx("text",{x:h,y:y+10,textAnchor:"middle",fill:"#475569",fontSize:"10",fontFamily:"system-ui",children:"/ 100"})]}),t.jsx("div",{style:{fontSize:13,fontWeight:800,color:a,letterSpacing:"-0.01em"},children:d}),t.jsx("div",{style:{fontSize:10,color:"#475569",fontWeight:600,textTransform:"uppercase",letterSpacing:"0.06em"},children:"Business Health"})]}),t.jsx("div",{style:{width:1,height:80,background:"#1e3a4f",flexShrink:0}}),t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsx("div",{style:{display:"flex",gap:8,marginBottom:10,flexWrap:"wrap"},children:[{count:c,label:"Healthy",color:"#4ade80",bg:"rgba(74,222,128,0.1)"},{count:f,label:"Warning",color:"#fbbf24",bg:"rgba(251,191,36,0.1)"},{count:p,label:"Critical",color:"#f87171",bg:"rgba(248,113,113,0.1)"}].map(A=>t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"4px 12px",borderRadius:20,background:A.bg,border:`1px solid ${A.color}25`},children:[t.jsx("span",{style:{fontSize:14,fontWeight:800,color:A.color},children:A.count}),t.jsx("span",{style:{fontSize:11,color:A.color,fontWeight:600},children:A.label})]},A.label))}),t.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(3, 1fr)",gap:6},children:l.map(A=>{const v=A.status==="good"?"#4ade80":A.status==="warn"?"#fbbf24":"#f87171",x=A.status==="good"?"â":A.status==="warn"?"â ":"â";return t.jsxs("div",{style:{padding:"8px 10px",borderRadius:10,background:`${v}08`,border:`1px solid ${v}20`,display:"flex",flexDirection:"column",gap:3},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:5},children:[t.jsx("span",{style:{fontSize:11,color:v,fontWeight:800},children:x}),t.jsx("span",{style:{fontSize:11,fontWeight:700,color:"#94a3b8"},children:A.label})]}
1148),t.jsx("div",{style:{fontSize:10,color:"#475569",lineHeight:1.4},children:A.detail})]},A.label)})})]})]})}function ot({label:e,value:n,sub:r,accent:s,icon:i,tooltip:o}){return t.jsxs("div",{style:{background:"#0f1923",border:`1px solid ${s}25`,borderTop:`3px solid ${s}`,borderRadius:12,padding:"16px 18px",position:"relative",overflow:"hidden"},children:[t.jsx("div",{style:{position:"absolute",top:-16,right:-16,width:60,height:60,borderRadius:"50%",background:`${s}10`,pointerEvents:"none"}}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,marginBottom:10},children:[t.jsx("span",{style:{fontSize:14},children:i}),t.jsx("span",{style:{fontSize:10,fontWeight:700,color:"#475569",textTransform:"uppercase",letterSpacing:"0.07em"},children:e}),o&&t.jsx("span",{title:o,style:{fontSize:11,color:"#334155",cursor:"help",marginLeft:2},children:"â"})]}),t.jsx("div",{style:{fontSize:30,fontWeight:900,color:s,lineHeight:1,letterSpacing:"-0.02em"},children:n}),r&&t.jsx("div",{style:{fontSize:11,color:"#475569",marginTop:8},children:r})]})}function ku({title:e,sub:n}){return t.jsxs("div",{style:{marginBottom:16},children:[t.jsx("h2",{style:{color:"#e2e8f0",fontWeight:800,fontSize:18,margin:0,letterSpacing:"-0.01em"},children:e}),n&&t.jsx("p",{style:{color:"#475569",fontSize:12,marginTop:4,marginBottom:0},children:n})]})}function su({title:e,children:n,tooltip:r}){return t.jsxs("div",{style:{background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:12,padding:"16px 18px"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,marginBottom:16},children:[t.jsx("span",{style:{fontSize:13,fontWeight:700,color:"#cbd5e1"},children:e}),r&&t.jsx("span",{title:r,style:{fontSize:11,color:"#334155",cursor:"help"},children:"â"})]}),n]})}function mf({data:e,height:n=120,color:r="#0d7ea3",formatValue:s}){const i=Math.max(...e.map(o=>o.value),1);return t.jsx("div",{style:{display:"flex",alignItems:"flex-end",gap:6,height:n+40,paddingTop:20},children:e.map((o,a)=>{const l=Math.max(o.value/i*n,o.value>0?4:0);return t.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",alignItems:"center",gap:4,justifyContent:"flex-end",height:"100%"},children:[t.jsx("div",{style:{fontSize:9,color:"#64748b",fontWeight:600,height:14},children:o.value>0?s?s(o.value):o.value:""}),t.jsx("div",{style:{width:"100%",height:l,background:`${r}cc`,borderRadius:"4px 4px 2px 2px",boxShadow:o.value>0?`0 0 8px ${r}30`:"none"}}),t.jsx("div",{style:{fontSize:9,color:"#475569",fontWeight:600,textTransform:"uppercase",letterSpacing:"0.03em",textAlign:"center"},children:o.label})]},a)})})}function BX({data:e}){const n=Math.max(...e.map(r=>r.value),1);return t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:10},children:e.map((r,s)=>t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[t.jsx("div",{style:{width:130,fontSize:11,color:"#94a3b8",textAlign:"right",flexShrink:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:r.label}),t.jsx("div",{style:{flex:1,height:18,background:"#0d1a26",borderRadius:4,overflow:"hidden"},children:t.jsx("div",{style:{height:"100%",width:`${r.value/n*100}%`,background:r.color,borderRadius:4,transition:"width 0.4s ease"}})}),t.jsx("div",{style:{width:28,fontSize:12,fontWeight:800,color:r.color,textAlign:"right",flexShrink:0},children:r.value})]},s))})}function Ys({columns:e,rows:n,emptyText:r="No data",onExport:s}){return t.jsxs("div",{style:{background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:12,overflow:"hidden"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 16px",borderBottom:"1px solid #1e3a4f",background:"#162232"},children:[t.jsxs("span",{style:{fontSize:12,fontWeight:700,color:"#64748b",textTransform:"uppercase",letterSpacing:"0.06em"},children:[n.length," record",n.length!==1?"s":""]}),s&&n.length>0&&t.jsx("button",{onClick:s,style:{fontSize:11,padding:"4px 12px",borderRadius:6,cursor:"pointer",background:"rgba(13,126,163,0.1)",border:"1px solid rgba(13,126,163,0.25)",color:"#0d7ea3",fontWeight:600},children:"â CSV"})]}),t.jsx("div",{style:{overflowX:"auto"},children:n.length===0?t.jsx("div",{style:{padding:"24px 16px",textAlign:"center",fontSize:13,color:"#334155"},children:r}):t.jsxs("table",{style:{width:"100%",borderCollapse:"collapse"},children:[t.jsx("thead",{children:t.jsx("tr",{children:e.map(i=>t.jsx("th",{style:{padding:"9px 14px",textAlign:"left",fontSize:10,fontWeight:700,color:"#475569",textTransform:"uppercase",letterSpacing:"0.06em",borderBottom:"1px solid #1e3a4f",whiteSpace:"nowrap",background:"#0d1a26"},children:i.label},i.key))})}),t.jsx("tbody",{children:n.map((i,o)=>t.jsx("tr",{style:{borderBottom:"1px solid #0d1a26"},onMouseEnter:a=>{a.currentTarget.style.background="rgba(255,255,255,0.02)"},onMouseLeave:a=>{a.currentTarget.style.background="transparent"},children:e.map(a=>t.jsx("td",{style:{padding:"10px 14px",fontSize:12,color:"#cbd5e1",whiteSpace:"nowrap"},children:a.render?a.render(i[a.key],i):i[a.key]??"â"},a.key))},o))})]})})]})}function Va({title:e,count:n,rows:r,columns:s,emptyText:i}){const[o,a]=g.useState(!1),l=n>0?"#f87171":"#4ade80";return t.jsxs("div",{style:{background:"#0f1923",border:`1px solid ${n>0?"rgba(248,113,113,0.2)":"#1e3a4f"}`,borderRadius:12,overflow:"hidden"},children:[t.jsxs("button",{onClick:()=>a(d=>!d),style:{width:"100%",display:"flex",alignItems:"center",justifyContent:"space-between",padding:"13px 16px",cursor:"pointer",background:"linear-gradient(135deg, #162232, #0d1a26)",border:"none",textAlign:"left"},children:[t.jsx("span",{style:{fontSize:13,fontWeight:700,color:"#cbd5e1"},children:e}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[t.jsx("span",{style:{minWidth:28,height:22,borderRadius:20,padding:"0 8px",display:"inline-flex",alignItems:"center",justifyContent:"center",fontSize:11,fontWeight:800,background:n===0?"rgba(74,222,128,0.12)":"rgba(248,113,113,0.12)",color:l,border:`1px solid ${n===0?"rgba(74,222,128,0.25)":"rgba(248,113,113,0.25)"}`},children:n}),n>0&&t.jsx("button",{onClick:d=>{d.stopPropagation(),js(r,`${e.toLowerCase().replace(/\s+/g,"_")}.csv`)},style:{fontSize:10,padding:"3px 8px",borderRadius:5,cursor:"pointer",background:"rgba(13,126,163,0.1)",border:"1px solid rgba(13,126,163,0.25)",color:"#0d7ea3"},children:"â CSV"}),t.jsx("span",{style:{color:"#334155",fontSize:13},children:o?"â¾":"â¸"})]})]}),o&&t.jsx("div",{style:{borderTop:"1px solid #1e3a4f"},children:t.jsx(Ys,{columns:s,rows:r,emptyText:i})})]})}function tn({small:e}){return t.jsx("div",{style:{padding:e?"20px 0":"48px 0",textAlign:"center",color:"#334155",fontSize:13},children:"Loadingâ¦"})}function UX({range:e}){const{data:n,isLoading:r}=Ae({queryKey:["reports","executive",e.start,e.end],queryFn:()=>H3(e),refetchInterval:12e4});if(r)return t.jsx(tn,{});const s=n||{activeLeads:0,mrr:0,cashCollected:0,installsCompleted:0,failedPayments48h:0,unsignedAgreements:0,unassignedJobs:0};return t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[t.jsx(ku,{title:"Executive Overview",sub:`${e.label} snapshot`}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(4, 1fr)",gap:12},children:[t.jsx(ot,{label:"Active Pipeline Leads",value:String(s.activeLeads),icon:"⬡",accent:"#38bdf8",sub:"Excludes won/lost/parked"}),t.jsx(ot,{label:"Current MRR",value:Rt(s.mrr),icon:"ð°",accent:"#4ade80",sub:"Active rental contracts",tooltip:"Sum of monthly_amount from contracts where status = active."}),t.jsx(ot,{label:"Cash Collected",value:Rt(s.cashCollected),icon:"ð³",accent:"#a78bfa",sub:`${e.label} â account level`,tooltip:"Payments recorded at account level. Individual contract attribution is not available."}),t.jsx(ot,{label:"Installs Completed",value:String(s.installsCompleted),icon:"â
",accent:"#34d399",sub:e.label})]}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(3, 1fr)",gap:12},children:[t.jsx(ot,{label:"Failed Payments",value:String(s.failedPayments48h),icon:"â ï¸",accent:s.failedPayments48h>0?"#f87171":"#4ade80",sub:"Last 48 hours"}),t.jsx(ot,{label:"Awaiting Signature",value:String(s.unsignedAgreements),icon:"âï¸",accent:s.unsignedAgreements>0?"#fbbf24":"#4ade80",sub:"Agreements pending"}),t.jsx(ot,{label:"Unassigned Jobs",value:String(s.unassignedJobs),icon:"ð·",accent:s.unassignedJobs>0?"#fb923c":"#4ade80",sub:"Scheduled, no tech"})]})]})}function HX({range:e}){const{data:n,isLoading:r}=Ae({queryKey:["reports","revenue_summary",e.start,e.end],queryFn:()=>mX(e)}),{data:s=[],isLoading:i}=Ae({queryKey:["reports","cash_by_month"],queryFn:()=>xX(6)}),{data:o=[],isLoading:a}=Ae({queryKey:["reports","contracts_by_month"],queryFn:()=>yX(6)}),{data:l,isLoading:d}=Ae({queryKey:["reports","invoice_aging"],queryFn:()=>bX()}),{data:c=[],isLoading:f}=Ae({queryKey:["reports","payments_drilldown",e.start,e.end],queryFn:()=>AX(e)}),p=n||{mrr:0,overdueTotal:0,cashCollected:0,failedPaymentsCount:0},u=l||{amounts:{b0_30:0,b31_60:0,b61_90:0,b90plus:0},counts:{b0_30:0,b31_60:0,b61_90:0,b90plus:0}};return t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[t.jsx(ku,{title:"Revenue & Billing",sub:"MRR is contract-level. Cash collected is account-level."}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(4, 1fr)",gap:12},children:[t.jsx(ot,{label:"Current MRR",value:r?"â¦":Rt(p.mrr),icon:"ð",accent:"#4ade80",tooltip:"Snapshot of current committed monthly revenue from active contracts."}),t.jsx(ot,{label:"Cash Collected",value:r?"â¦":Rt(p.cashCollected),icon:"ð³",accent:"#a78bfa",sub:`${e.label} â account level`,tooltip:"Payments recorded at account level. Individual contract attribution is not available."}),t.jsx(ot,{label:"Overdue Invoices",value:r?"â¦":Rt(p.overdueTotal),icon:"ð´",accent:p.overdueTotal>0?"#f87171":"#4ade80",sub:"Total outstanding"}),t.jsx(ot,{label:"Failed Payments",value:r?"â¦":String(p.failedPaymentsCount),icon:"â ï¸",accent:p.failedPaymentsCount>0?"#f87171":"#4ade80",sub:e.label})]}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:14},children:[t.jsx(su,{title:"Cash Collected by Month",tooltip:"Account-level cash actually received per month.",children:i?t.jsx(tn,{small:!0}):t.jsx(mf,{data:s.map(h=>({label:String(h.month),value:Number(h.total_collected)})),color:"#a78bfa",height:110,formatValue:h=>`$${Math.round(h/1e3)}k`})}),t.jsx(su,{title:"New Rental Contract Value by Month",tooltip:"Value of new rental contracts signed each month. Not a historical MRR trend â reflects new business only.",children:a?t.jsx(tn,{small:!0}):t.jsx(mf,{data:o.map(h=>({label:String(h.month),value:Number(h.new_monthly_value)})),color:"#4ade80",height:110,formatValue:h=>`$${Math.round(h/1e3)}k`})})]}),t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:13,fontWeight:700,color:"#94a3b8",marginBottom:10},children:"Invoice Aging"}),d?t.jsx(tn,{small:!0}):t.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(4, 1fr)",gap:10},children:[{label:"0â30 days",amt:u.amounts.b0_30,cnt:u.counts.b0_30,color:"#f59e0b"},{label:"31â60 days",amt:u.amounts.b31_60,cnt:u.counts.b31_60,color:"#fb923c"},{label:"61â90 days",amt:u.amounts.b61_90,cnt:u.counts.b61_90,color:"#f87171"},{label:"90+ days",amt:u.amounts.b90plus,cnt:u.counts.b90plus,color:"#dc2626"}].map(h=>t.jsxs("div",{style:{background:`${h.color}10`,border:`1px solid ${h.color}25`,borderRadius:10,padding:"12px 14px"}
1148,children:[t.jsx("div",{style:{fontSize:10,color:"#475569",fontWeight:700,textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:6},children:h.label}),t.jsx("div",{style:{fontSize:22,fontWeight:900,color:h.color},children:Rt(h.amt)}),t.jsxs("div",{style:{fontSize:11,color:"#64748b",marginTop:4},children:[h.cnt," invoice",h.cnt!==1?"s":""]})]},h.label))})]}),f?t.jsx(tn,{small:!0}):t.jsx(Ys,{columns:[{key:"customer_id",label:"Customer",render:(h,y)=>y.customer_name?t.jsx("span",{style:{color:"#cbd5e1"},children:y.customer_name}):h?t.jsxs("span",{style:{color:"#94a3b8",fontSize:10},children:[String(h).slice(0,8),"â¦"]}):"â"},{key:"amount",label:"Amount",render:h=>Rt(Number(h))},{key:"status",label:"Status",render:h=>t.jsx("span",{style:{fontSize:10,padding:"2px 8px",borderRadius:20,fontWeight:700,background:h==="succeeded"?"rgba(74,222,128,0.12)":h==="failed"?"rgba(248,113,113,0.12)":"rgba(100,116,139,0.12)",color:h==="succeeded"?"#4ade80":h==="failed"?"#f87171":"#94a3b8"},children:h})},{key:"payment_type",label:"Type"},{key:"failure_reason",label:"Failure Reason",render:h=>h||"â"},{key:"created_at",label:"Date",render:h=>h?nr(h.split("T")[0]):"â"}],rows:c,emptyText:"No payment transactions in this period",onExport:()=>js(c,`payments_${e.start}_${e.end}.csv`)})]})}function VX({range:e}){const{data:n,isLoading:r}=Ae({queryKey:["reports","install_kpis",e.start,e.end],queryFn:()=>vX(e)}),{data:s=[],isLoading:i}=Ae({queryKey:["reports","weekly_installs"],queryFn:()=>_X(8)}),{data:o=[],isLoading:a}=Ae({queryKey:["reports","jobs_drilldown",e.start,e.end],queryFn:()=>jX(e)}),l=n||{completedInRange:0,scheduled:0,inProgress:0,proofBacklog:0,waitingStock:0},d={scheduled:"Scheduled",in_progress:"In Progress",waiting_for_stock:"Waiting Stock",complete:"Complete",cancelled:"Cancelled"},c={scheduled:"#60a5fa",in_progress:"#22d3ee",waiting_for_stock:"#f59e0b",complete:"#4ade80",cancelled:"#64748b"};return t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[t.jsx(ku,{title:"Installations & Operations",sub:"Uses completed_at from jobs table"}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(5, 1fr)",gap:12},children:[t.jsx(ot,{label:"Completed",value:r?"â¦":String(l.completedInRange),icon:"â
",accent:"#4ade80",sub:e.label}),t.jsx(ot,{label:"Scheduled",value:r?"â¦":String(l.scheduled),icon:"ð
",accent:"#60a5fa",sub:"Future"}),t.jsx(ot,{label:"In Progress",value:r?"â¦":String(l.inProgress),icon:"â¡",accent:"#22d3ee",sub:"Active now"}),t.jsx(ot,{label:"Proof Backlog",value:r?"â¦":String(l.proofBacklog),icon:"ð¸",accent:l.proofBacklog>0?"#fbbf24":"#4ade80",sub:"Awaiting review"}),t.jsx(ot,{label:"Waiting Stock",value:r?"â¦":String(l.waitingStock),icon:"ð¦",accent:l.waitingStock>0?"#fb923c":"#4ade80",sub:"Blocked"})]}),t.jsx(su,{title:"Weekly Install Volume (last 8 weeks)",children:i?t.jsx(tn,{small:!0}):t.jsx(mf,{data:s.map(f=>({label:f.label,value:f.count})),color:"#4ade80",height:120})}),a?t.jsx(tn,{small:!0}):t.jsx(Ys,{columns:[{key:"customer_name_snapshot",label:"Customer"},{key:"job_type",label:"System"},{key:"job_status",label:"Status",render:f=>t.jsx("span",{style:{fontSize:10,padding:"2px 8px",borderRadius:20,fontWeight:700,background:`${c[f]||"#64748b"}18`,color:c[f]||"#64748b"},children:d[f]||f})},{key:"scheduled_at",label:"Scheduled",render:f=>f?nr(f.split("T")[0]):"â"},{key:"completed_at",label:"Completed",render:f=>f?nr(f.split("T")[0]):"â"},{key:"assigned_technician_id",label:"Technician",render:(f,p)=>p.technician_name?t.jsx("span",{style:{color:"#cbd5e1"},children:p.technician_name}):t.jsx("span",{style:{color:"#f59e0b"},children:"â Unassigned"})},{key:"proof_approved",label:"Proof",render:f=>f?t.jsx("span",{style:{color:"#4ade80",fontSize:11,fontWeight:700},children:"â Approved"}):t.jsx("span",{style:{color:"#f59e0b",fontSize:11,fontWeight:700},children:"Pending"})}],rows:o,emptyText:"No jobs in this period",onExport:()=>js(o,`installations_${e.start}_${e.end}.csv`)})]})}function ZX({range:e}){const{data:n=[],isLoading:r}=Ae({queryKey:["reports","pipeline_snapshot"],queryFn:()=>wX()}),{data:s,isLoading:i}=Ae({queryKey:["reports","pipeline_outcomes",e.start,e.end],queryFn:()=>SX(e)}),{data:o=[],isLoading:a}=Ae({queryKey:["reports","leads_drilldown"],queryFn:()=>kX(100)}),{data:l=[],isLoading:d}=Ae({queryKey:["reports","lost_reasons"],queryFn:()=>CX()}),c=s||{won:0,lost:0,dnd:0,parked:0},p=["new_lead","qualifying","qualified","site_visit_scheduled","proposal_in_progress","quote_sent","agreement_signed"].map(u=>n.find(h=>h.stage===u)||{stage:u,lead_count:0});return t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[t.jsx(ku,{title:"Pipeline Snapshot"}),t.jsxs("div",{style:{padding:"10px 14px",background:"rgba(99,102,241,0.08)",border:"1px solid rgba(99,102,241,0.2)",borderRadius:8,fontSize:12,color:"#94a3b8"},children:[t.jsx("strong",{style:{color:"#a5b4fc"},children:"Snapshot only."})," Shows where leads currently stand. Stage transition history is not tracked. Drop-off rates and time-in-stage are not available."]}),t.jsx(su,{title:"Open Pipeline â Current Stage Distribution",children:r?t.jsx(tn,{small:!0}):t.jsx(BX,{data:p.map(u=>({label:i2[u.stage]||u.stage,value:u.lead_count,color:Hm[u.stage]||"#64748b"}))})}),t.jsxs("div",{children:[t.jsxs("div",{style:{fontSize:12,fontWeight:700,color:"#64748b",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:10},children:["Pipeline Outcomes â ",e.label]}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(4, 1fr)",gap:10},children:[t.jsx(ot,{label:"Won (approx.)",value:i?"â¦":String(c.won),icon:"ð",accent:"#4ade80",tooltip:"Based on leads.updated_at. Approximate."}),t.jsx(ot,{label:"Lost (approx.)",value:i?"â¦":String(c.lost),icon:"â",accent:"#f87171",tooltip:"Based on leads.updated_at. Approximate."}),t.jsx(ot,{label:"DND (all time)",value:i?"â¦":String(c.dnd),icon:"ð«",accent:"#64748b",sub:"Do not disturb"}),t.jsx(ot,{label:"Parked",value:i?"â¦":String(c.parked),icon:"â¸ï¸",accent:"#94a3b8",sub:"Future follow-up"})]})]}),!d&&l.length>0&&t.jsx(su,{title:"Lost Reasons Breakdown",tooltip:"Buckets the free-text lost_reason field by keyword. Categories are heuristic.",children:t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:10},children:l.map((u,h)=>{const y=l[0].count,m=y>0?Math.round(u.count/y*100):0,b=h===0?"#f87171":h===1?"#fb923c":h===2?"#fbbf24":"#94a3b8";return t.jsxs("div",{children:[t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:5},children:[t.jsx("span",{style:{fontSize:12,color:"#94a3b8",fontWeight:600},children:u.label}),t.jsxs("div",{style:{display:"flex",gap:10,alignItems:"center"},children:[t.jsx("span",{style:{fontSize:12,fontWeight:800,color:b},children:u.count}
1148),t.jsxs("span",{style:{fontSize:10,color:"#475569",minWidth:32,textAlign:"right"},children:[u.pct,"%"]})]})]}),t.jsx("div",{style:{height:10,background:"#0d1a26",borderRadius:20,overflow:"hidden"},children:t.jsx("div",{style:{height:"100%",width:`${m}%`,background:`linear-gradient(90deg, ${b}80, ${b})`,borderRadius:20,transition:"width 0.4s ease"}})})]},u.code)})})}),a?t.jsx(tn,{small:!0}):t.jsx(Ys,{columns:[{key:"full_name",label:"Name"},{key:"phone",label:"Phone"},{key:"stage",label:"Stage",render:u=>t.jsx("span",{style:{fontSize:10,padding:"2px 8px",borderRadius:20,fontWeight:700,background:`${Hm[u]||"#64748b"}18`,color:Hm[u]||"#94a3b8"},children:i2[u]||u})},{key:"source",label:"Source",render:u=>u||t.jsx("span",{style:{color:"#f59e0b"},children:"â None"})},{key:"days_open",label:"Days Open",render:u=>t.jsx("span",{style:{color:u>30?"#f87171":u>14?"#fbbf24":"#94a3b8",fontWeight:600},children:u})},{key:"created_at",label:"Created",render:u=>u?nr(u.split("T")[0]):"â"}],rows:o,emptyText:"No active leads",onExport:()=>js(o,"pipeline_snapshot.csv")})]})}function KX(){const{data:e,isLoading:n}=Ae({queryKey:["reports","data_quality"],queryFn:()=>V3(),refetchInterval:3e5});if(n)return t.jsx(tn,{});const r=e||{nullSourceLeads:[],nullCommercialTypeQuotes:[],noProofJobs:[],customersNoSystem:[],contractsNoPmt:[],overdue60Invoices:[]};return t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[t.jsx(ku,{title:"Data Quality â Exceptions",sub:"Internal use. Expand each row to review and export."}),t.jsx("div",{style:{padding:"10px 14px",background:"rgba(251,146,60,0.08)",border:"1px solid rgba(251,146,60,0.2)",borderRadius:8,fontSize:12,color:"#94a3b8"},children:"These exceptions indicate data that may affect reporting accuracy. Address them before relying on other reports."}),t.jsx(Va,{title:"Leads with missing source",count:r.nullSourceLeads.length,rows:r.nullSourceLeads,columns:[{key:"full_name",label:"Name"},{key:"stage",label:"Stage"},{key:"created_at",label:"Created",render:s=>s?nr(s.split("T")[0]):"â"}],emptyText:"All active leads have a source â"}),t.jsx(Va,{title:"Non-draft quotes missing commercial_type",count:r.nullCommercialTypeQuotes.length,rows:r.nullCommercialTypeQuotes,columns:[{key:"quote_number",label:"Quote #"},{key:"status",label:"Status"},{key:"created_at",label:"Created",render:s=>s?nr(s.split("T")[0]):"â"}],emptyText:"All sent quotes have commercial_type â"}),t.jsx(Va,{title:"Completed installs awaiting proof review",count:r.noProofJobs.length,rows:r.noProofJobs,columns:[{key:"customer_name_snapshot",label:"Customer"},{key:"scheduled_at",label:"Scheduled",render:s=>s?nr(s.split("T")[0]):"â"},{key:"completed_at",label:"Completed",render:s=>s?nr(s.split("T")[0]):"â"}],emptyText:"All completed installs have approved proof â"}),t.jsx(Va,{title:"Customers with no installed system",count:r.customersNoSystem.length,rows:r.customersNoSystem,columns:[{key:"full_name",label:"Customer"},{key:"lifecycle_stage",label:"Status"},{key:"created_at",label:"Created",render:s=>s?nr(s.split("T")[0]):"â"}],emptyText:"All customers have at least one installed system â"}),t.jsx(Va,{title:"Active rental contracts â no payment in 35 days (account-level)",count:r.contractsNoPmt.length,rows:r.contractsNoPmt,columns:[{key:"customer_name",label:"Customer",render:(s,i)=>s||(i.customer_id?t.jsxs("span",{style:{color:"#94a3b8",fontSize:10},children:[String(i.customer_id).slice(0,8),"â¦"]}):"â")},{key:"contract_number",label:"Contract #"},{key:"monthly_amount",label:"Monthly",render:s=>Rt(Number(s))},{key:"signed_at",label:"Signed",render:s=>s?nr(s.split("T")[0]):"â"}],emptyText:"All active rental contracts have recent payments â"}),t.jsx(Va,{title:"Invoices overdue 60+ days",count:r.overdue60Invoices.length,rows:r.overdue60Invoices,columns:[{key:"customer_name",label:"Customer",render:(s,i)=>s||(i.customer_id?t.jsxs("span",{style:{color:"#94a3b8",fontSize:10},children:[String(i.customer_id).slice(0,8),"â¦"]}):"â")},{key:"total_amount",label:"Amount",render:s=>Rt(Number(s))},{key:"due_date",label:"Due Date",render:s=>s?nr(s):"â"},{key:"status",label:"Status"}],emptyText:"No invoices overdue 60+ days â"})]})}const o2={active:"#4ade80",service_due:"#fbbf24",renewal_due:"#fb923c",upsell:"#38bdf8",at_risk:"#f87171",inactive:"#64748b",unknown:"#334155"},a2={active:"Active",service_due:"Service Due",renewal_due:"Renewal Due",upsell:"Upsell",at_risk:"At Risk",inactive:"Inactive",unknown:"Unknown"},l2={ro:"RO System",ro_install:"RO System",softener:"Water Softener",softener_only:"Water Softener",whole_home_filter:"Whole Home Filter",iron_filter:"Iron Filter",dual_tank:"Dual Tank",advanced_softener:"Advanced Softener",unknown:"Unknown"},d2=["#38bdf8","#4ade80","#a78bfa","#fb923c","#22d3ee","#fbbf24","#f87171","#34d399"];function YX({range:e}){const{data:n,isLoading:r}=Ae({queryKey:["reports","customer_kpis"],queryFn:()=>TX(),refetchInterval:12e4}),{data:s=[],isLoading:i}=Ae({queryKey:["reports","customer_lifecycle"],queryFn:()=>zX()}),{data:o=[],isLoading:a}=Ae({queryKey:["reports","system_type_dist"],queryFn:()=>NX()}),{data:l=[],isLoading:d}=Ae({queryKey:["reports","new_customers_by_month"],queryFn:()=>EX(6)}),{data:c=[],isLoading:f}=Ae({queryKey:["reports","customers_drilldown"],queryFn:()=>RX(150)}),{data:p=[],isLoading:u}=Ae({queryKey:["reports","commercial_type_split"],queryFn:()=>PX()}),{data:h=[],isLoading:y}=Ae({queryKey:["reports","rental_lifecycle"],queryFn:()=>qX(6)}),{data:m,isLoading:b}=Ae({queryKey:["reports","margin_summary"],queryFn:()=>LX()}),{data:A=[],isLoading:v}=Ae({queryKey:["reports","rental_payback"],queryFn:()=>WX()}),x=n||{totalCustomers:0,activeCustomers:0,atRisk:0,renewalsIn30:0,serviceDue:0},_=o.reduce((S,T)=>S+T.count,0);let j=-90;const C=o.map((S,T)=>{const L=_>0?S.count/_:0,E=L*360,R=j;j+=E;const N=52,O=70,z=70,P=B=>B*Math.PI/180,D=O+N*Math.cos(P(R)),M=z+N*Math.sin(P(R)),k=O+N*Math.cos(P(R+E)),q=z+N*Math.sin(P(R+E)),$=E>180?1:0,I=`M ${O} ${z} L ${D} ${M} A ${N} ${N} 0 ${$} 1 ${k} ${q} Z`;return{...S,path:I,color:d2[T%d2.length],pct:L}});return t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[t.jsxs("div",{style:{marginBottom:4},children:[t.jsx("h2",{style:{color:"#e2e8f0",fontWeight:800,fontSize:18,margin:0,letterSpacing:"-0.01em"},children:"Customers & Rentals"}),t.jsx("p",{style:{color:"#475569",fontSize:12,marginTop:4,marginBottom:0},children:"Customer status counts depend on automation rules. Verify before acting on at-risk numbers."})]}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(5, 1fr)",gap:12},children:[t.jsx(ot,{label:"Total Customers",value:r?"â¦":String(x.totalCustomers),icon:"ð¥",accent:"#38bdf8"}),t.jsx(ot,{label:"Active",value:r?"â¦":String(x.activeCustomers),icon:"â
",accent:"#4ade80",sub:"lifecycle = active"}),t.jsx(ot,{label:"At Risk",value:r?"â¦":String(x.atRisk),icon:"ð´",accent:x.atRisk>0?"#f87171":"#4ade80",sub:"Needs attention"}),t.jsx(ot,{label:"Renewals in 30d",value:r?"â¦":String(x.renewalsIn30),icon:"â»",accent:x.renewalsIn30>0?"#fbbf24":"#4ade80",sub:"Active contracts"}),t.jsx(ot,{label:"Service Due",value:r?"â¦":String(x.serviceDue),icon:"ð§",accent:x.serviceDue>0?"#fb923c":"#4ade80",sub:"Due or overdue"})]}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:14},children:[t.jsxs("div",{style:{background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:12,padding:"16px 18px"},children:[t.jsx("div",{style:{fontSize:13,fontWeight:700,color:"#cbd5e1",marginBottom:16},children:"Customer Lifecycle"}),i?t.jsx(tn,{small:!0}):t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:s.length===0?t.jsx("div",{style:{color:"#334155",fontSize:13,textAlign:"center",padding:"20px 0"},children:"No customers yet"}):s.map(S=>{const T=Math.max(...s.map(E=>E.count),1),L=o2[S.status]||"#64748b";return t.jsxs("div",{children:[t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:4},children:[t.jsx("span",{style:{fontSize:11,color:"#94a3b8"},children:a2[S.status]||S.status}),t.jsx("span",{style:{fontSize:11,fontWeight:700,color:L},children:S.count})]}),t.jsx("div",{style:{height:8,background:"#0d1a26",borderRadius:4,overflow:"hidden"},children:t.jsx("div",{style:{height:"100%",width:`${S.count/T*100}%`,background:L,borderRadius:4,boxShadow:`0 0 6px ${L}40`}})})]},S.status)})})]}),t.jsxs("div",{style:{background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:12,padding:"16px 18px"},children:[t.jsx("div",{style:{fontSize:13,fontWeight:700,color:"#cbd5e1",marginBottom:16},children:"New Customers by Month"}),d?t.jsx(tn,{small:!0}):t.jsx(mf,{data:l.map(S=>({label:S.month,value:S.count}
1148)),color:"#38bdf8",height:110})]}),t.jsxs("div",{style:{background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:12,padding:"16px 18px"},children:[t.jsx("div",{style:{fontSize:13,fontWeight:700,color:"#cbd5e1",marginBottom:12},children:"Installed Systems"}),a?t.jsx(tn,{small:!0}):_===0?t.jsx("div",{style:{color:"#334155",fontSize:13,textAlign:"center",padding:"20px 0"},children:"No systems recorded"}):t.jsxs("div",{style:{display:"flex",gap:12,alignItems:"center"},children:[t.jsxs("svg",{width:"140",height:"140",viewBox:"0 0 140 140",style:{flexShrink:0},children:[C.map((S,T)=>t.jsx("path",{d:S.path,fill:S.color,opacity:.85},T)),t.jsx("circle",{cx:"70",cy:"70",r:"30",fill:"#0f1923"}),t.jsx("text",{x:"70",y:"73",textAnchor:"middle",fill:"#e2e8f0",fontSize:"14",fontWeight:"800",children:_}),t.jsx("text",{x:"70",y:"86",textAnchor:"middle",fill:"#475569",fontSize:"9",children:"systems"})]}),t.jsx("div",{style:{flex:1,display:"flex",flexDirection:"column",gap:5},children:C.map((S,T)=>t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[t.jsx("span",{style:{width:8,height:8,borderRadius:2,background:S.color,flexShrink:0}}),t.jsx("span",{style:{fontSize:10,color:"#94a3b8",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:l2[S.type]||S.type}),t.jsx("span",{style:{fontSize:10,fontWeight:700,color:S.color,flexShrink:0},children:S.count})]},T))})]})]})]}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:14},children:[t.jsxs("div",{style:{background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:12,padding:"16px 18px"},children:[t.jsx("div",{style:{fontSize:13,fontWeight:700,color:"#cbd5e1",marginBottom:16},children:"Rental vs Purchase vs Financed"}),u?t.jsx(tn,{small:!0}):p.length===0?t.jsx("div",{style:{color:"#334155",fontSize:13,textAlign:"center",padding:"20px 0"},children:"No contract data"}):t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[p.map((S,T)=>{const L=p.reduce((z,P)=>z+P.count,0),E=L>0?Math.round(S.count/L*100):0,N={rental:"#4ade80",purchase:"#38bdf8",financed:"#a78bfa",unknown:"#64748b"}[S.type]||"#64748b",O={rental:"Rental",purchase:"Purchase",financed:"Financed",unknown:"Unknown"};return t.jsxs("div",{children:[t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:5},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[t.jsx("span",{style:{width:10,height:10,borderRadius:3,background:N,flexShrink:0,display:"inline-block"}}),t.jsx("span",{style:{fontSize:12,color:"#94a3b8",fontWeight:600},children:O[S.type]||S.type})]}),t.jsxs("div",{style:{display:"flex",gap:10,alignItems:"center"},children:[t.jsx("span",{style:{fontSize:12,fontWeight:800,color:N},children:S.count}),t.jsxs("span",{style:{fontSize:10,color:"#475569"},children:[E,"%"]}),S.totalValue>0&&t.jsxs("span",{style:{fontSize:10,color:"#475569"},children:[Rt(S.totalValue),"/mo"]})]})]}),t.jsx("div",{style:{height:10,background:"#0d1a26",borderRadius:20,overflow:"hidden"},children:t.jsx("div",{style:{height:"100%",width:`${E}%`,background:`linear-gradient(90deg, ${N}99, ${N})`,borderRadius:20,boxShadow:`0 0 8px ${N}40`,transition:"width 0.5s ease"}})})]},T)}),t.jsxs("div",{style:{marginTop:4,padding:"10px 12px",background:"#162232",borderRadius:8,display:"flex",justifyContent:"space-between"},children:[t.jsx("span",{style:{fontSize:11,color:"#475569"},children:"Total contracts"}),t.jsx("span",{style:{fontSize:12,fontWeight:800,color:"#e2e8f0"},children:p.reduce((S,T)=>S+T.count,0)})]})]})]}),t.jsxs("div",{style:{background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:12,padding:"16px 18px"},children:[t.jsx("div",{style:{fontSize:13,fontWeight:700,color:"#cbd5e1",marginBottom:4},children:"Monthly Rental Lifecycle"}),t.jsx("div",{style:{fontSize:11,color:"#475569",marginBottom:14},children:"Rental contracts signed per month by status"}),y?t.jsx(tn,{small:!0}):t.jsx("div",{style:{display:"flex",alignItems:"flex-end",gap:8,height:140,paddingTop:16},children:h.map((S,T)=>{const L=S.active+S.expired+S.cancelled,E=Math.max(...h.map(N=>N.active+N.expired+N.cancelled),1),R=L>0?Math.max(L/E*100,4):0;return t.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",alignItems:"center",gap:4,justifyContent:"flex-end",height:"100%"},children:[t.jsx("div",{style:{fontSize:9,color:"#64748b",fontWeight:600,height:12},children:L>0?L:""}),t.jsxs("div",{style:{width:"100%",height:R,borderRadius:"4px 4px 2px 2px",overflow:"hidden",display:"flex",flexDirection:"column"},children:[S.active>0&&t.jsx("div",{style:{flex:S.active,background:"#4ade80",minHeight:2}}),S.expired>0&&t.jsx("div",{style:{flex:S.expired,background:"#f59e0b",minHeight:2}}),S.cancelled>0&&t.jsx("div",{style:{flex:S.cancelled,background:"#f87171",minHeight:2}})]}),t.jsx("div",{style:{fontSize:9,color:"#475569",fontWeight:600,textTransform:"uppercase",letterSpacing:"0.03em",textAlign:"center"},children:S.month})]},T)})}),!y&&t.jsx("div",{style:{display:"flex",gap:12,marginTop:10},children:[["#4ade80","Active"],["#f59e0b","Expired"],["#f87171","Cancelled"]].map(([S,T])=>t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[t.jsx("span",{style:{width:8,height:8,borderRadius:2,background:S,display:"inline-block"}}
1148),t.jsx("span",{style:{fontSize:10,color:"#475569"},children:T})]},T))})]})]}),t.jsxs("div",{children:[t.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:12},children:t.jsxs("div",{children:[t.jsx("h3",{style:{color:"#cbd5e1",fontWeight:700,fontSize:15,margin:0},children:"Margin Analysis"}),t.jsxs("p",{style:{color:"#475569",fontSize:11,marginTop:3,marginBottom:0},children:["Purchase: lifetime revenue â cost. Rental: monthly recurring revenue â vendor cost amortized over ",(m==null?void 0:m.amortizationMonths)||36," months."]})]})}),!b&&(m==null?void 0:m.hasInsufficientData)&&t.jsxs("div",{style:{marginBottom:12,padding:"10px 14px",background:"rgba(251,191,36,0.08)",border:"1px solid rgba(251,191,36,0.25)",borderRadius:8,display:"flex",alignItems:"center",gap:8},children:[t.jsx("span",{style:{fontSize:14},children:"â "}),t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:12,color:"#fbbf24",fontWeight:700},children:"Insufficient data for reliable margin calculation"}),t.jsxs("div",{style:{fontSize:11,color:"#94a3b8",marginTop:2},children:[m.insufficientDataReason,". Numbers below are illustrative only."]})]})]}),b?t.jsx(tn,{small:!0}):m?t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:14},children:[t.jsxs("div",{style:{background:"#0f1923",border:"1px solid #1e3a4f",borderTop:"3px solid #38bdf8",borderRadius:12,padding:"16px 18px",opacity:m.hasInsufficientData?.7:1},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:14},children:[t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:12,fontWeight:700,color:"#38bdf8",textTransform:"uppercase",letterSpacing:"0.06em"},children:"ð³ Purchase Margin"}),t.jsx("div",{style:{fontSize:10,color:"#475569",marginTop:2},children:"Lifetime · paid invoices vs vendor cost"})]}),m.purchase.isEstimate&&t.jsx("span",{style:{fontSize:9,padding:"2px 6px",borderRadius:4,background:"rgba(251,191,36,0.15)",color:"#fbbf24",fontWeight:700},children:"EST"})]}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:9,color:"#475569",fontWeight:700,textTransform:"uppercase",letterSpacing:"0.06em"},children:"Revenue"}),t.jsx("div",{style:{fontSize:18,fontWeight:800,color:"#e2e8f0",marginTop:4},children:Rt(m.purchase.revenue)}),t.jsxs("div",{style:{fontSize:10,color:"#475569",marginTop:2},children:[m.purchase.paymentCount," payment",m.purchase.paymentCount!==1?"s":""]})]}),t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:9,color:"#475569",fontWeight:700,textTransform:"uppercase",letterSpacing:"0.06em"},children:"Cost"}),t.jsx("div",{style:{fontSize:18,fontWeight:800,color:"#e2e8f0",marginTop:4},children:Rt(m.purchase.cost)}),t.jsxs("div",{style:{fontSize:10,color:"#475569",marginTop:2},children:[m.purchase.coveredUnits," covered",m.purchase.uncoveredUnits>0?`, ${m.purchase.uncoveredUnits} missing`:""]})]})]}),t.jsxs("div",{style:{marginTop:14,paddingTop:14,borderTop:"1px solid #1e3a4f",display:"flex",justifyContent:"space-between",alignItems:"baseline"},children:[t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:9,color:"#475569",fontWeight:700,textTransform:"uppercase",letterSpacing:"0.06em"},children:"Margin"}),t.jsx("div",{style:{fontSize:22,fontWeight:900,color:m.purchase.margin>=0?"#4ade80":"#f87171",marginTop:4},children:Rt(m.purchase.margin)})]}),t.jsxs("div",{style:{textAlign:"right"},children:[t.jsx("div",{style:{fontSize:9,color:"#475569",fontWeight:700,textTransform:"uppercase",letterSpacing:"0.06em"},children:"Margin %"}),t.jsxs("div",{style:{fontSize:22,fontWeight:900,color:m.purchase.marginPct>=50?"#4ade80":m.purchase.marginPct>=25?"#fbbf24":"#f87171",marginTop:4},children:[m.purchase.marginPct,"%"]})]})]})]}),t.jsxs("div",{style:{background:"#0f1923",border:"1px solid #1e3a4f",borderTop:"3px solid #4ade80",borderRadius:12,padding:"16px 18px",opacity:m.hasInsufficientData?.7:1},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:14},children:[t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:12,fontWeight:700,color:"#4ade80",textTransform:"uppercase",letterSpacing:"0.06em"},children:"ð Rental Margin (Monthly)"}
1148),t.jsxs("div",{style:{fontSize:10,color:"#475569",marginTop:2},children:["MRR vs vendor cost ÷ ",m.amortizationMonths,"mo"]})]}),m.rental.isEstimate&&t.jsx("span",{style:{fontSize:9,padding:"2px 6px",borderRadius:4,background:"rgba(251,191,36,0.15)",color:"#fbbf24",fontWeight:700},children:"EST"})]}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:9,color:"#475569",fontWeight:700,textTransform:"uppercase",letterSpacing:"0.06em"},children:"MRR"}),t.jsx("div",{style:{fontSize:18,fontWeight:800,color:"#e2e8f0",marginTop:4},children:Rt(m.rental.monthlyRevenue)}),t.jsxs("div",{style:{fontSize:10,color:"#475569",marginTop:2},children:[m.rental.activeContractCount," contract",m.rental.activeContractCount!==1?"s":""]})]}),t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:9,color:"#475569",fontWeight:700,textTransform:"uppercase",letterSpacing:"0.06em"},children:"Monthly Cost"}),t.jsx("div",{style:{fontSize:18,fontWeight:800,color:"#e2e8f0",marginTop:4},children:Rt(m.rental.monthlyAmortizedCost)}),t.jsxs("div",{style:{fontSize:10,color:"#475569",marginTop:2},children:["amortized over ",m.amortizationMonths,"mo"]})]})]}),t.jsxs("div",{style:{marginTop:14,paddingTop:14,borderTop:"1px solid #1e3a4f",display:"flex",justifyContent:"space-between",alignItems:"baseline"},children:[t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:9,color:"#475569",fontWeight:700,textTransform:"uppercase",letterSpacing:"0.06em"},children:"Monthly Margin"}),t.jsx("div",{style:{fontSize:22,fontWeight:900,color:m.rental.monthlyMargin>=0?"#4ade80":"#f87171",marginTop:4},children:Rt(m.rental.monthlyMargin)})]}),t.jsxs("div",{style:{textAlign:"right"},children:[t.jsx("div",{style:{fontSize:9,color:"#475569",fontWeight:700,textTransform:"uppercase",letterSpacing:"0.06em"},children:"Margin %"}),t.jsxs("div",{style:{fontSize:22,fontWeight:900,color:m.rental.marginPct>=50?"#4ade80":m.rental.marginPct>=25?"#fbbf24":"#f87171",marginTop:4},children:[m.rental.marginPct,"%"]})]})]})]})]}):null,!v&&A.length>0&&t.jsxs("div",{style:{marginTop:14,background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:12,overflow:"hidden"},children:[t.jsxs("div",{style:{padding:"12px 16px",background:"#162232",borderBottom:"1px solid #1e3a4f"},children:[t.jsx("span",{style:{fontSize:12,fontWeight:700,color:"#cbd5e1"},children:"Rental Payback Status"}),t.jsx("span",{style:{fontSize:11,color:"#475569",marginLeft:10},children:"Per active rental · cost recovery vs. months active"})]}),t.jsx("div",{style:{overflowX:"auto"},children:t.jsxs("table",{style:{width:"100%",borderCollapse:"collapse"},children:[t.jsx("thead",{children:t.jsx("tr",{children:["Contract","Customer","Monthly","Vendor Cost","Payback (mo)","Active (mo)","Progress","Status"].map(S=>t.jsx("th",{style:{padding:"9px 14px",textAlign:"left",fontSize:10,fontWeight:700,color:"#475569",textTransform:"uppercase",letterSpacing:"0.06em",borderBottom:"1px solid #1e3a4f",background:"#0d1a26",whiteSpace:"nowrap"},children:S},S))})}),t.jsx("tbody",{children:A.map(S=>{const T=S.status==="paid_off"?"#4ade80":S.progressPct>=75?"#22d3ee":S.progressPct>=50?"#fbbf24":"#fb923c";return t.jsxs("tr",{style:{borderBottom:"1px solid #0d1a26"},children:[t.jsx("td",{style:{padding:"10px 14px",fontSize:12,color:"#cbd5e1",fontWeight:600},children:S.contractNumber}),t.jsx("td",{style:{padding:"10px 14px",fontSize:12,color:"#cbd5e1"},children:S.customerName}),t.jsx("td",{style:{padding:"10px 14px",fontSize:12,color:"#e2e8f0",fontWeight:600},children:Rt(S.monthlyAmount)}),t.jsxs("td",{style:{padding:"10px 14px",fontSize:12,color:"#94a3b8"},children:[S.isEstimate?t.jsx("span",{style:{color:"#fbbf24"},children:"missing"}):Rt(S.vendorCost),S.unitCount>1&&t.jsxs("span",{style:{color:"#475569",fontSize:10,marginLeft:4},children:["(",S.unitCount," units)"]})]}),t.jsx("td",{style:{padding:"10px 14px",fontSize:12,color:"#94a3b8"},children:S.paybackMonths>0?`${S.paybackMonths}`:"â"}),t.jsx("td",{style:{padding:"10px 14px",fontSize:12,color:"#94a3b8"},children:S.monthsActive}),t.jsxs("td",{style:{padding:"10px 14px",minWidth:120},children:[t.jsx("div",{style:{height:8,background:"#0d1a26",borderRadius:4,overflow:"hidden"},children:t.jsx("div",{style:{height:"100%",width:`${S.progressPct}%`,background:T,borderRadius:4,boxShadow:`0 0 6px ${T}40`,transition:"width 0.4s ease"}})}),t.jsxs("div",{style:{fontSize:9,color:"#475569",marginTop:3,textAlign:"right"},children:[S.progressPct,"%"]})]}),t.jsx("td",{style:{padding:"10px 14px"},children:t.jsx("span",{style:{fontSize:10,padding:"2px 8px",borderRadius:20,fontWeight:700,background:S.status==="paid_off"?"rgba(74,222,128,0.15)":"rgba(251,146,60,0.15)",color:S.status==="paid_off"?"#4ade80":"#fb923c",border:`1px solid ${S.status==="paid_off"?"rgba(74,222,128,0.3)":"rgba(251,146,60,0.3)"}`},children:S.status==="paid_off"?"â Paid off":"Paying back"})})]},S.contractId)})})]})})]})]}),f?t.jsx(tn,{small:!0}):t.jsx(Ys,{columns:[{key:"full_name",label:"Customer"},{key:"phone",label:"Phone"},{key:"lifecycle_stage",label:"Status",render:S=>{const T=o2[S]||"#64748b";return t.jsx("span",{style:{fontSize:10,padding:"2px 8px",borderRadius:20,fontWeight:700,background:`${T}18`,color:T,border:`1px solid ${T}30`},children:a2[S]||S||"â"})}},{key:"contract",label:"Contract Type",render:S=>S?t.jsxs("span",{style:{fontSize:11,color:"#94a3b8"},children:[S.type," · ",S.monthly_amount?`$${Number(S.monthly_amount).toFixed(0)}/mo`:"â"]}):t.jsx("span",{style:{color:"#334155"},children:"None"})},{key:"systems",label:"Systems",render:S=>S!=null&&S.length?S.map(T=>l2[T.system_name]||T.system_name).join(", "):t.jsx("span",{style:{color:"#334155"},children:"None"})},{key:"last_payment_at",label:"Last Payment",render:S=>S?nr(S.split("T")[0]):t.jsx("span",{style:{color:"#f59e0b"},children:"None recorded"})},{key:"created_at",label:"Customer Since",render:S=>S?nr(S.split("T")[0]):"â"}],rows:c,emptyText:"No customers found",onExport:()=>js(c.map(S=>{var T,L;return{name:S.full_name,phone:S.phone,status:S.lifecycle_stage,contract_type:((T=S.contract)==null?void 0:T.type)||"",monthly:((L=S.contract)==null?void 0:L.monthly_amount)||"",systems:(S.systems||[]).map(E=>E.system_name).join("; "),last_payment:S.last_payment_at||"",customer_since:S.created_at||""}}),"customers.csv")})]})}function XX(){const{data:e=[],isLoading:n}=Ae({queryKey:["reports","rep_performance"],queryFn:()=>DX(),refetchInterval:12e4});if(n)return t.jsx(tn,{});const r=e.length?e.reduce((o,a)=>o.closeRate>
1148a.closeRate?o:a,e[0]):null,s=e.length?e.reduce((o,a)=>o.totalLeads>a.totalLeads?o:a,e[0]):null,i=e.length?e.reduce((o,a)=>o.quotesSent>a.quotesSent?o:a,e[0]):null;return t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[t.jsxs("div",{children:[t.jsx("h2",{style:{color:"#e2e8f0",fontWeight:800,fontSize:18,margin:0},children:"Rep Performance"}),t.jsx("p",{style:{color:"#475569",fontSize:12,marginTop:4,marginBottom:0},children:"Quote attribution is indirect â via lead assignment. Labeled approximate."})]}),e.length===0?t.jsx("div",{style:{padding:"40px",textAlign:"center",color:"#334155",fontSize:14},children:"No rep data available yet"}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(3, 1fr)",gap:12},children:[r&&t.jsx(ot,{label:"Best Close Rate",value:`${r.closeRate}%`,icon:"ð",accent:"#4ade80",sub:r.name}),s&&t.jsx(ot,{label:"Most Leads",value:String(s.totalLeads),icon:"⬡",accent:"#38bdf8",sub:s.name}),i&&t.jsx(ot,{label:"Most Quotes Sent",value:String(i.quotesSent),icon:"ð",accent:"#f472b6",sub:i.name})]}),t.jsxs("div",{style:{background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:12,overflow:"hidden"},children:[t.jsx("div",{style:{padding:"12px 16px",background:"#162232",borderBottom:"1px solid #1e3a4f"},children:t.jsxs("span",{style:{fontSize:12,fontWeight:700,color:"#64748b",textTransform:"uppercase",letterSpacing:"0.06em"},children:[e.length," rep",e.length!==1?"s":""]})}),t.jsx("div",{style:{overflowX:"auto"},children:t.jsxs("table",{style:{width:"100%",borderCollapse:"collapse"},children:[t.jsx("thead",{children:t.jsx("tr",{children:["Rep","Role","Leads","Won","Lost","Quotes Sent","Accepted","Close Rate","Deal Value","Installs"].map(o=>t.jsx("th",{style:{padding:"9px 14px",textAlign:"left",fontSize:10,fontWeight:700,color:"#475569",textTransform:"uppercase",letterSpacing:"0.06em",borderBottom:"1px solid #1e3a4f",background:"#0d1a26",whiteSpace:"nowrap"},children:o},o))})}),t.jsx("tbody",{children:e.map((o,a)=>t.jsxs("tr",{style:{borderBottom:"1px solid #0d1a26"},children:[t.jsx("td",{style:{padding:"10px 14px",fontSize:13,fontWeight:700,color:"#e2e8f0"},children:o.name}),t.jsx("td",{style:{padding:"10px 14px"},children:t.jsx("span",{style:{fontSize:10,padding:"2px 8px",borderRadius:20,fontWeight:700,background:o.role==="admin"?"rgba(13,126,163,0.15)":"rgba(100,116,139,0.15)",color:o.role==="admin"?"#0d7ea3":"#94a3b8"},children:o.role})}),t.jsx("td",{style:{padding:"10px 14px",fontSize:12,color:"#94a3b8"},children:o.totalLeads}),t.jsx("td",{style:{padding:"10px 14px",fontSize:12,fontWeight:700,color:"#4ade80"},children:o.wonLeads}),t.jsx("td",{style:{padding:"10px 14px",fontSize:12,color:"#f87171"},children:o.lostLeads}),t.jsx("td",{style:{padding:"10px 14px",fontSize:12,color:"#94a3b8"},children:o.quotesSent}),t.jsx("td",{style:{padding:"10px 14px",fontSize:12,fontWeight:700,color:"#4ade80"},children:o.quotesWon}),t.jsx("td",{style:{padding:"10px 14px"},children:t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[t.jsx("div",{style:{flex:1,height:6,background:"#0d1a26",borderRadius:3,overflow:"hidden",minWidth:60},children:t.jsx("div",{style:{height:"100%",width:`${o.closeRate}%`,background:o.closeRate>=50?"#4ade80":o.closeRate>=25?"#fbbf24":"#f87171",borderRadius:3}})}),t.jsxs("span",{style:{fontSize:12,fontWeight:700,color:o.closeRate>=50?"#4ade80":o.closeRate>=25?"#fbbf24":"#f87171",minWidth:32},children:[o.closeRate,"%"]})]})}),t.jsx("td",{style:{padding:"10px 14px",fontSize:12,color:"#a78bfa",fontWeight:600},children:Rt(o.totalValue)}),t.jsx("td",{style:{padding:"10px 14px",fontSize:12,color:"#94a3b8"},children:o.installs})]},o.id))})]})})]}),t.jsx("div",{style:{padding:"10px 14px",background:"rgba(99,102,241,0.06)",border:"1px solid rgba(99,102,241,0.15)",borderRadius:8,fontSize:11,color:"#64748b"},children:"â Quote close rate is approximate â quotes are attributed to reps via lead assignment. Quotes without a linked lead are excluded."})]})]})}function GX({range:e}){const{data:n,isLoading:r}=Ae({queryKey:["reports","quotes_summary"],queryFn:()=>OX()});if(r)return t.jsx(tn,{});const s=n==null?void 0:n.summary,i=(n==null?void 0:n.quotes)||[],o={draft:"#64748b",sent:"#38bdf8",viewed:"#a78bfa",accepted:"#4ade80",signed:"#4ade80",declined:"#f87171",expired:"#f59e0b"};return t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[t.jsxs("div",{children:[t.jsx("h2",{style:{color:"#e2e8f0",fontWeight:800,fontSize:18,margin:0},children:"Quotes & Commercial"}),t.jsx("p",{style:{color:"#475569",fontSize:12,marginTop:4,marginBottom:0},children:"Avg days to accept uses updated_at as proxy â approximate."})]}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(5, 1fr)",gap:12},children:[t.jsx(ot,{label:"Total Quotes",value:s?String(s.total):"â¦",icon:"ð",accent:"#22d3ee"}),t.jsx(ot,{label:"Acceptance Rate",value:s?`${s.acceptanceRate}%`:"â¦",icon:"â
",accent:s&&s.acceptanceRate>=30?"#4ade80":"#fbbf24",sub:"Sent â accepted"}),t.jsx(ot,{label:"Avg Days to Accept",value:s?String(s.avgDaysToAccept):"â¦",icon:"ð
",accent:"#a78bfa",sub:"Approximate",tooltip:"Based on updated_at when status changed to accepted. Approximate."}),t.jsx(ot,{label:"Avg Deal Value",value:s?Rt(s.avgQuoteValue):"â¦",icon:"ð°",accent:"#4ade80",sub:"Accepted quotes"}),t.jsx(ot,{label:"Open Pipeline Value",value:s?Rt(s.totalPipeline):"â¦",icon:"⬡",accent:"#38bdf8",sub:"Sent + viewed"})]}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:14},children:[t.jsxs("div",{style:{background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:12,padding:"16px 18px"},children:[t.jsx("div",{style:{fontSize:13,fontWeight:700,color:"#cbd5e1",marginBottom:14},children:"Quote Status Breakdown"}),s&&t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[{label:"Draft",count:s.draft,color:"#64748b"},{label:"Sent",count:s.sent,color:"#38bdf8"},{label:"Viewed",count:s.viewed,color:"#a78bfa"},{label:"Accepted",count:s.accepted,color:"#4ade80"},{label:"Declined",count:s.declined,color:"#f87171"},{label:"Expired",count:s.expired,color:"#f59e0b"}].filter(a=>a.count>0).map(a=>{const l=s.total>0?Math.round(a.count/s.total*100):0;return t.jsxs("div",{children:[t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:4},children:[t.jsx("span",{style:{fontSize:11,color:"#94a3b8"},children:a.label}),t.jsxs("div",{style:{display:"flex",gap:8},children:[t.jsx("span",{style:{fontSize:11,fontWeight:700,color:a.color},children:a.count}
1148),t.jsxs("span",{style:{fontSize:10,color:"#475569"},children:[l,"%"]})]})]}),t.jsx("div",{style:{height:8,background:"#0d1a26",borderRadius:4,overflow:"hidden"},children:t.jsx("div",{style:{height:"100%",width:`${l}%`,background:a.color,borderRadius:4,boxShadow:`0 0 6px ${a.color}40`}})})]},a.label)})})]}),t.jsxs("div",{style:{background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:12,padding:"16px 18px"},children:[t.jsx("div",{style:{fontSize:13,fontWeight:700,color:"#cbd5e1",marginBottom:14},children:"Commercial Type Split"}),s&&t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[{label:"Rental",count:s.rental,color:"#4ade80"},{label:"Purchase",count:s.purchase,color:"#38bdf8"},{label:"Financed",count:s.financed,color:"#a78bfa"}].filter(a=>a.count>0).map(a=>{const l=s.rental+s.purchase+s.financed,d=l>0?Math.round(a.count/l*100):0;return t.jsxs("div",{children:[t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:4},children:[t.jsx("span",{style:{fontSize:11,color:"#94a3b8"},children:a.label}),t.jsxs("div",{style:{display:"flex",gap:8},children:[t.jsx("span",{style:{fontSize:11,fontWeight:700,color:a.color},children:a.count}),t.jsxs("span",{style:{fontSize:10,color:"#475569"},children:[d,"%"]})]})]}),t.jsx("div",{style:{height:10,background:"#0d1a26",borderRadius:20,overflow:"hidden"},children:t.jsx("div",{style:{height:"100%",width:`${d}%`,background:`linear-gradient(90deg, ${a.color}99, ${a.color})`,borderRadius:20}})})]},a.label)})})]})]}),t.jsx(Ys,{columns:[{key:"created_at",label:"Date",render:a=>a?nr(a.split("T")[0]):"â"},{key:"status",label:"Status",render:a=>t.jsx("span",{style:{fontSize:10,padding:"2px 8px",borderRadius:20,fontWeight:700,background:`${o[a]||"#64748b"}18`,color:o[a]||"#94a3b8"},children:a})},{key:"commercial_type",label:"Type",render:a=>a||t.jsx("span",{style:{color:"#334155"},children:"â"})},{key:"monthly_rental_price",label:"Monthly",render:a=>a?Rt(Number(a)):"â"},{key:"total",label:"One-time",render:a=>a?Rt(Number(a)):"â"},{key:"view_count",label:"Views",render:a=>a||0}],rows:i.slice(0,100),emptyText:"No quotes found",onExport:()=>js(i.slice(0,100).map(a=>{var l;return{date:(l=a.created_at)==null?void 0:l.split("T")[0],status:a.status,type:a.commercial_type,monthly:a.monthly_rental_price,one_time:a.total,views:a.view_count}}),"quotes.csv")})]})}const c2=(e,n)=>[{key:e,label:n,render:r=>r||t.jsx("span",{style:{color:"#334155"},children:"â"})},{key:"total",label:"Leads"},{key:"active",label:"Active"},{key:"won",label:"Won",render:r=>t.jsx("span",{style:{color:"#4ade80",fontWeight:700},children:r})},{key:"lost",label:"Lost",render:r=>t.jsx("span",{style:{color:"#f87171"},children:r})},{key:"conversionRate",label:"Close Rate",render:r=>t.jsxs("span",{style:{fontWeight:700,color:r>=50?"#4ade80":r>=25?"#fbbf24":"#f87171"},children:[r,"%"]})}];function JX({range:e}){var f,p;const{data:n,isLoading:r}=Ae({queryKey:["reports","lead_sources",e.start,e.end],queryFn:()=>IX(e)});if(r)return t.jsx(tn,{});const s=(n==null?void 0:n.sources)||[],i=(n==null?void 0:n.utmSources)||[],o=(n==null?void 0:n.utmCampaigns)||[],a=(n==null?void 0:n.leadRows)||[],l=(n==null?void 0:n.totalLeads)||0,d=Math.max(...s.map(u=>u.total),1),c=["#38bdf8","#4ade80","#a78bfa","#fb923c","#f472b6","#22d3ee","#fbbf24","#f87171"];return t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[t.jsxs("div",{children:[t.jsx("h2",{style:{color:"#e2e8f0",fontWeight:800,fontSize:18,margin:0},children:"Marketing Sources"}),t.jsxs("p",{style:{color:"#475569",fontSize:12,marginTop:4,marginBottom:0},children:[e.label," · conversion rate = leads won / total leads. Revenue by source not available without contract-level payment linkage."]})]}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(4, 1fr)",gap:12},children:[t.jsx(ot,{label:"Total Leads",value:String(l),icon:"⬡",accent:"#38bdf8"}),t.jsx(ot,{label:"Lead Sources",value:String(s.length),icon:"ð¡",accent:"#a78bfa"}),t.jsx(ot,{label:"Best Source",value:((f=s[0])==null?void 0:f.source)||"â",icon:"ð",accent:"#4ade80",sub:s[0]?`${s[0].total} leads`:""}),t.jsx(ot,{label:"Best Conversion",value:s.length?`${Math.max(...s.map(u=>u.conversionRate))}%`:"â",icon:"â
",accent:"#34d399",sub:((p=[...s].sort((u,h)=>h.conversionRate-u.conversionRate)[0])==null?void 0:p.source)||""})]}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:14},children:[t.jsxs("div",{style:{background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:12,padding:"16px 18px"},children:[t.jsx("div",{style:{fontSize:13,fontWeight:700,color:"#cbd5e1",marginBottom:14},children:"Leads by Source"}),t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:10},children:s.slice(0,8).map((u,h)=>t.jsxs("div",{children:[t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:4},children:[t.jsx("span",{style:{fontSize:11,color:"#94a3b8",textTransform:"capitalize"},children:u.source.replace(/_/g," ")}),t.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center"},children:[t.jsx("span",{style:{fontSize:11,fontWeight:700,color:c[h%c.length]},children:u.total}
1148),t.jsxs("span",{style:{fontSize:10,color:"#4ade80",fontWeight:600},children:[u.won," won"]})]})]}),t.jsx("div",{style:{height:8,background:"#0d1a26",borderRadius:4,overflow:"hidden"},children:t.jsx("div",{style:{height:"100%",width:`${u.total/d*100}%`,background:c[h%c.length],borderRadius:4}})})]},u.source))})]}),t.jsxs("div",{style:{background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:12,padding:"16px 18px"},children:[t.jsx("div",{style:{fontSize:13,fontWeight:700,color:"#cbd5e1",marginBottom:14},children:"Conversion Rate by Source"}),t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[...s].sort((u,h)=>h.conversionRate-u.conversionRate).slice(0,8).map((u,h)=>{const y=u.conversionRate>=50?"#4ade80":u.conversionRate>=25?"#fbbf24":"#f87171";return t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[t.jsx("span",{style:{fontSize:11,color:"#94a3b8",width:120,flexShrink:0,textTransform:"capitalize",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:u.source.replace(/_/g," ")}),t.jsx("div",{style:{flex:1,height:8,background:"#0d1a26",borderRadius:4,overflow:"hidden"},children:t.jsx("div",{style:{height:"100%",width:`${u.conversionRate}%`,background:y,borderRadius:4}})}),t.jsxs("span",{style:{fontSize:12,fontWeight:700,color:y,width:36,textAlign:"right",flexShrink:0},children:[u.conversionRate,"%"]})]},u.source)})})]})]}),t.jsxs("div",{children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:10,flexWrap:"wrap",gap:8},children:[t.jsxs("div",{children:[t.jsx("h3",{style:{color:"#cbd5e1",fontWeight:700,fontSize:15,margin:0},children:"Paid Channels & Campaigns"}),t.jsx("p",{style:{color:"#475569",fontSize:11,marginTop:3,marginBottom:0},children:"Taken from the ad click that brought the lead in. Only populated for leads captured from 24 Sep 2026 onward."})]}),t.jsxs("div",{style:{display:"flex",gap:8},children:[t.jsx("button",{onClick:()=>$X(e),title:"Formatted workbook â source and campaign breakdown with definitions. No names, phones or emails.",style:{fontSize:11,padding:"6px 14px",borderRadius:6,cursor:"pointer",background:"rgba(74,222,128,0.1)",border:"1px solid rgba(74,222,128,0.3)",color:"#4ade80",fontWeight:600},children:"â Excel report"}),a.length>0&&t.jsx("button",{onClick:()=>js(a,`lead_attribution_${e.start}_${e.end}.csv`),title:"Raw rows, one per lead â for pasting elsewhere.",style:{fontSize:11,padding:"6px 14px",borderRadius:6,cursor:"pointer",background:"rgba(13,126,163,0.1)",border:"1px solid rgba(13,126,163,0.25)",color:"#0d7ea3",fontWeight:600},children:"â CSV"})]})]}),i.length===0&&o.length===0?t.jsx("div",{style:{padding:"18px 16px",background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:12,fontSize:12,color:"#475569",textAlign:"center"},children:"No campaign data in this period. Ad-click capture went live 24 Sep 2026 â leads captured before that carry no campaign."}):t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[t.jsx(Ys,{columns:c2("source","Channel"),rows:i,emptyText:"No channel data in this period",onExport:()=>js(i,`channels_${e.start}_${e.end}.csv`)}),t.jsx(Ys,{columns:c2("campaign","Campaign"),rows:o,emptyText:"No campaign data in this period",onExport:()=>js(o,`campaigns_${e.start}_${e.end}.csv`)})]})]}),t.jsx(Ys,{columns:[{key:"source",label:"Source",render:u=>t.jsx("span",{style:{textTransform:"capitalize"},children:u.replace(/_/g," ")})},{key:"total",label:"Total Leads"},{key:"active",label:"Active"},{key:"won",label:"Won",render:u=>t.jsx("span",{style:{color:"#4ade80",fontWeight:700},children:u})},{key:"lost",label:"Lost",render:u=>t.jsx("span",{style:{color:"#f87171"},children:u})},{key:"conversionRate",label:"Close Rate",render:u=>t.jsxs("span",{style:{fontWeight:700,color:u>=50?"#4ade80":u>=25?"#fbbf24":"#f87171"},children:[u,"%"]})}],rows:s,emptyText:"No lead source data",onExport:()=>js(s,"lead_sources.csv")})]})}function QX({range:e,onChange:n}){const r=[{label:"MTD",fn:B3},{label:"Last 30d",fn:hX},{label:"Last 90d",fn:fX},{label:"YTD",fn:gX}];return t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[t.jsx("span",{style:{fontSize:11,color:"#475569",fontWeight:700,textTransform:"uppercase",letterSpacing:"0.06em"},children:"Period:"}),r.map(s=>t.jsx("button",{onClick:()=>n(s.fn()),style:{padding:"5px 12px",borderRadius:8,fontSize:12,fontWeight:600,cursor:"pointer",background:e.label===s.label?"rgba(13,126,163,0.2)":"rgba(255,255,255,0.04)",border:`1px solid ${e.label===s.label?"#0d7ea3":"#1e3a4f"}`,color:e.label===s.label?"#0d7ea3":"#64748b"},children:s.label},s.label)),t.jsxs("span",{style:{fontSize:11,color:"#334155",marginLeft:4},children:[e.start," â ",e.end]})]})}const eG=[{id:"overview",label:"Executive Overview",icon:"â",color:"#38bdf8",bg:"rgba(56,189,248,0.12)"},{id:"revenue",label:"Revenue & Billing",icon:"ð°",color:"#4ade80",bg:"rgba(74,222,128,0.12)"},{id:"installs",label:"Installations",icon:"ð§",color:"#f59e0b",bg:"rgba(245,158,11,0.12)"},{id:"pipeline",label:"Pipeline Snapshot",icon:"⬡",color:"#a78bfa",bg:"rgba(167,139,250,0.12)"},{id:"customers",label:"Customers & Rentals",icon:"ð¥",color:"#34d399",bg:"rgba(52,211,153,0.12)"},{id:"reps",label:"Rep Performance",icon:"ð¤",color:"#f472b6",bg:"rgba(244,114,182,0.12)"},{id:"quotes",label:"Quotes & Commercial",icon:"ð",color:"#22d3ee",bg:"rgba(34,211,238,0.12)"},{id:"marketing",label:"Marketing Sources",icon:"ð¡",color:"#a78bfa",bg:"rgba(167,139,250,0.12)"},{id:"quality",label:"Data Quality",icon:"ð",color:"#fb923c",bg:"rgba(251,146,60,0.12)",adminOnly:!0}];function tG(){const{role:e}=Ee(),{userBranch:n,selectedBranchId:r,allBranches:s}=mu(),i=yt.viewAdminReports(e),[o,a]=g.useState("overview"),[l,d]=g.useState(B3()),c=eG.filter(u=>!u.adminOnly||i),f=i&&r?s.find(u=>
1148u.id===r):n,p=f?`${f.name}${f.city?` · ${f.city}, ${f.state}`:""}`:i&&!r?"Zenith Pure Solutions · All Branches":"Zenith Pure Solutions";return t.jsxs("div",{style:{width:"100%",display:"flex",flexDirection:"column",gap:0},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:16,flexWrap:"wrap",gap:12},children:[t.jsxs("div",{children:[t.jsx("h1",{style:{color:"#f1f5f9",fontWeight:800,fontSize:22,margin:0,letterSpacing:"-0.02em"},children:"Reports"}),t.jsx("p",{style:{color:"#475569",fontSize:13,marginTop:4,marginBottom:0},children:p})]}),t.jsx(QX,{range:l,onChange:d})]}),t.jsx(FX,{range:l}),t.jsx("div",{style:{display:"flex",gap:6,marginBottom:20,borderBottom:"1px solid #1e3a4f",paddingBottom:0,overflowX:"auto",scrollbarWidth:"none"},children:c.map(u=>{const h=o===u.id;return t.jsxs("button",{onClick:()=>a(u.id),style:{display:"flex",alignItems:"center",gap:8,padding:"10px 18px",cursor:"pointer",border:"none",borderBottom:`3px solid ${h?u.color:"transparent"}`,background:h?u.bg:"transparent",borderRadius:"8px 8px 0 0",color:h?u.color:"#475569",fontSize:13,fontWeight:h?700:500,flexShrink:0,transition:"all 0.15s"},onMouseEnter:y=>{h||(y.currentTarget.style.color="#94a3b8")},onMouseLeave:y=>{h||(y.currentTarget.style.color="#475569")},children:[t.jsx("span",{style:{fontSize:15},children:u.icon}),u.label,u.adminOnly&&t.jsx("span",{style:{fontSize:9,padding:"2px 6px",borderRadius:20,background:`${u.color}20`,color:u.color,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.05em"},children:"Admin"})]},u.id)})}),t.jsxs("div",{style:{minHeight:400},children:[o==="overview"&&t.jsx(UX,{range:l}),o==="revenue"&&t.jsx(HX,{range:l}),o==="installs"&&t.jsx(VX,{range:l}),o==="pipeline"&&t.jsx(ZX,{range:l}),o==="customers"&&t.jsx(YX,{range:l}),o==="reps"&&t.jsx(XX,{}),o==="quotes"&&t.jsx(GX,{range:l}),o==="marketing"&&t.jsx(JX,{range:l}),o==="quality"&&i&&t.jsx(KX,{})]})]})}const Uy="AIzaSyCz1Y0whXwppRuDAkEAfq01zzjSu3f-N9A",nG={lat:39.7684,lng:-86.1581},Mp={lead:{color:"#fbbf24",label:"Active Lead",emoji:"ðµ"},customer:{color:"#4ade80",label:"Customer",emoji:"â
"},lost:{color:"#f87171",label:"Lost / DND",emoji:"â"},install_complete:{color:"#a78bfa",label:"Completed Install",emoji:"ð§"},install_pending:{color:"#fb923c",label:"Install Pending",emoji:"â³"},site_visit:{color:"#38bdf8",label:"Site Visit",emoji:"ð
"}};async function rG(e){if(!e||!Uy)return null;try{const r=await(await fetch(`https://maps.googleapis.com/maps/api/geocode/json?address=${encodeURIComponent(e)}&key=${Uy}`)).json();if(r.status==="OK"&&r.results[0])return r.results[0].geometry.location}catch{}return null}function sG(){return new Promise((e,n)=>{var i;if((i=window.google)!=null&&i.maps){e();return}const r=document.getElementById("gmaps-script");if(r){r.addEventListener("load",()=>e());return}const s=document.createElement("script");s.id="gmaps-script",s.src=`https://maps.googleapis.com/maps/api/js?key=${Uy}`,s.async=!0,s.onload=()=>e(),s.onerror=()=>n(new Error("Google Maps failed to load")),document.head.appendChild(s)})}async function Vm(e,n){const r=new Map;if(n.length===0)return r;try{const{data:s}=await w.from("addresses").select("entity_id, address_line1, city, state, zip").eq("entity_type",e).eq("is_primary",!0).in("entity_id",n);for(const i of s||[])r.set(i.entity_id,{address_line1:i.address_line1,city:i.city,state:i.state,zip:i.zip})}catch{}return r}function iG(){const e=g.useRef(null),n=g.useRef(null),r=g.useRef([]),s=g.useRef(null),[i,o]=g.useState([]),[a,l]=g.useState(!0),[d,c]=g.useState(!1),[f,p]=g.useState(0),[u,h]=g.useState(0),[y,m]=g.useState(!1),[b,A]=g.useState(null),[v,x]=g.useState(!0),[_,j]=g.useState(!0),[C,S]=g.useState(!1),[T,L]=g.useState(!0),[E,R]=g.useState(!0),[N,O]=g.useState(!0);g.useEffect(()=>{async function M(){l(!0);const k=[];try{const{data:q}=await w.from("leads").select("id, full_name, phone, stage").not("stage","in","(lost,dnd,won)").limit(400),$=q||[],I=await Vm("lead",$.map(B=>B.id));for(const B of $){const J=I.get(B.id),ae=[J==null?void 0:J.address_line1,J==null?void 0:J.city,J==null?void 0:J.state,J==null?void 0:J.zip].filter(
1148Boolean).join(", ");ae&&k.push({id:B.id,name:B.full_name,address:ae,type:"lead",stage:B.stage,phone:B.phone})}}catch{}try{const{data:q}=await w.from("leads").select("id, full_name, phone, stage").in("stage",["lost","dnd"]).limit(200),$=q||[],I=await Vm("lead",$.map(B=>B.id));for(const B of $){const J=I.get(B.id),ae=[J==null?void 0:J.address_line1,J==null?void 0:J.city,J==null?void 0:J.state,J==null?void 0:J.zip].filter(Boolean).join(", ");ae&&k.push({id:B.id,name:B.full_name,address:ae,type:"lost",stage:B.stage,phone:B.phone})}}catch{}try{const{data:q}=await w.from("customers").select("id, full_name, phone, lifecycle_stage").limit(400),$=q||[],I=await Vm("customer",$.map(B=>B.id));for(const B of $){const J=I.get(B.id),ae=[J==null?void 0:J.address_line1,J==null?void 0:J.city,J==null?void 0:J.state,J==null?void 0:J.zip].filter(Boolean).join(", ");ae&&k.push({id:B.id,name:B.full_name,address:ae,type:"customer",lifecycle:B.lifecycle_stage,phone:B.phone})}}catch{}try{const{data:q}=await w.from("jobs").select("id, customer_name_snapshot, service_address_snapshot, job_status").eq("job_status","complete").not("service_address_snapshot","is",null).limit(300);for(const $ of q||[])$.service_address_snapshot&&k.push({id:$.id,name:$.customer_name_snapshot||"Completed Install",address:$.service_address_snapshot,type:"install_complete",stage:"complete"})}catch{}try{const{data:q}=await w.from("jobs").select("id, customer_name_snapshot, service_address_snapshot, job_status").in("job_status",["ready_to_schedule","scheduled","in_progress"]).not("service_address_snapshot","is",null).limit(200);for(const $ of q||[])$.service_address_snapshot&&k.push({id:$.id,name:$.customer_name_snapshot||"Pending Install",address:$.service_address_snapshot,type:"install_pending",stage:$.job_status})}catch{}try{const{data:q}=await w.from("site_visits").select("id, visit_date, status, customer_name_snapshot, address_snapshot, phone_snapshot").eq("status","scheduled").not("address_snapshot","is",null).limit(200);for(const $ of q||[])$.address_snapshot&&k.push({id:$.id,name:$.customer_name_snapshot||"Site Visit",address:$.address_snapshot,type:"site_visit",stage:$.visit_date?`Visit: ${new Date($.visit_date).toLocaleDateString()}`:"Scheduled",phone:$.phone_snapshot})}catch{}o(k),h(k.length),l(!1)}M()},[]),g.useEffect(()=>{if(a||i.length===0||!i.some($=>!$.lat||!$.lng))return;c(!0);let k=0;async function q(){const $=[...i];for(let I=0;I<$.length;I++){if($[I].lat&&$[I].lng){k++,p(k);continue}const B=await rG($[I].address);B&&($[I]={...$[I],...B}),k++,p(k),I%10===9&&await new Promise(J=>setTimeout(J,150))}o([...$]),c(!1)}q()},[a,i]),g.useEffect(()=>{sG().then(()=>m(!0)).catch(()=>A("Failed to load Google Maps. Verify API key."))},[]),g.useEffect(()=>{if(!y||!e.current||n.current)return;const M=window.google.maps;n.current=new M.Map(e.current,{center:nG,zoom:11,mapTypeId:"roadmap",styles:[{elementType:"geometry",stylers:[{color:"#162232"}]},{elementType:"labels.text.stroke",stylers:[{color:"#0f1923"}]},{elementType:"labels.text.fill",stylers:[{color:"#64748b"}]},{featureType:"administrative.locality",elementType:"labels.text.fill",stylers:[{color:"#94a3b8"}]},{featureType:"road",elementType:"geometry",stylers:[{color:"#1e3a4f"}]},{featureType:"road",elementType:"geometry.stroke",stylers:[{color:"#0d1a26"}]},{featureType:"road.highway",elementType:"geometry",stylers:[{color:"#253d5a"}]},{featureType:"road.highway",elementType:"labels.text.fill",stylers:[{color:"#60a5fa"}]},{featureType:"water",elementType:"geometry",stylers:[{color:"#0d1520"}]},{featureType:"poi",stylers:[{visibility:"off"}]},{featureType:"transit",stylers:[{visibility:"off"}]}]}),s.current=new M.InfoWindow},[y]),g.useEffect(()=>{var $;if(!n.current)return;const M=($=window.google)==null?void 0:$.maps;if(!M)return;for(const I of r.current)I.setMap(null);r.current=[];const k={lead:v,customer:_,lost:C,install_complete:T,install_pending:E,site_visit:N},q=i.filter(I=>!I.lat||!I.lng?!1:k[I.type]);for(const I of q){const B=Mp[I.type],J=B.color,ae=new M.Marker({position:{lat:I.lat,lng:I.lng},map:n.current,title:I.name,icon:{path:M.SymbolPath.CIRCLE,scale:8,fillColor:J,fillOpacity:.9,strokeColor:"#0f1923",strokeWeight:1.5}});ae.addListener("click",()=>{const te=I.stage?`<div style="color:#94a3b8;font-size:11px;margin-top:2px;">${I.stage.replace(/_/g," ")}</div>`:"",U=I.phone?`<div style="margin-top:6px;"><a href="tel:${I.phone}" style="color:#0d7ea3;font-size:12px;">${I.phone}</a></div>`:"";s.current.setContent(` 1149 <div style="background:#162232;border:1px solid #1e3a4f;border-radius:10px;padding:12px 14px;min-width:180px;font-family:Arial,sans-serif;"> 1150 <div style="font-weight:700;font-size:13px;color:#e2e8f0;margin-bottom:4px;">${I.name}</div> 1151 <div style="font-size:11px;font-weight:700;color:${J};">${B.emoji} ${B.label}</div> 1152 ${te} 1153 <div style="font-size:11px;color:#475569;margin-top:6px;line-height:1.4;">${I.address}</div> 1154 ${U} 1155 </div> 1156 `),s.current.open(n.current,ae)}),r.current.push(ae)}},[i,v,_,C,T,E,N,y]);const z=i.filter(M=>M.lat&&M.lng),P=Object.fromEntries(Object.keys(Mp).map(M=>[M,z.filter(k=>k.type===M).length])),D=[{type:"lead",show:v,set:x},{type:"customer",show:_,set:j},{type:"install_complete",show:T,set:L},{type:"install_pending",show:E,set:R},{type:"site_visit",show:N,set:O},{type:"lost",show:C,set:S}];return t.jsxs("div",{style:{minHeight:"100%",display:"flex",flexDirection:"column"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:16,flexWrap:"wrap",gap:12},children:[t.jsxs("div",{children:[t.jsx("h1",{style:{fontSize:22,fontWeight:800,color:"#e2e8f0",margin:0},children:"Location Map"}),t.jsx("p",{style:{fontSize:13,color:"#475569",marginTop:4,marginBottom:0},children:"Leads, customers, installs, and site visits across Indianapolis"})]}),d&&t.jsxs("div",{style:{background:"rgba(96,165,250,0.1)",border:"1px solid rgba(96,165,250,0.3)",borderRadius:10,padding:"8px 16px",fontSize:12,color:"#60a5fa"},children:["Geocoding addresses⦠",f,"/",u,t.jsx("div",{style:{height:3,background:"rgba(96,165,250,0.15)",borderRadius:4,marginTop:6,width:140},children:t.jsx("div",{style:{height:3,background:"#60a5fa",borderRadius:4,width:`${u?f/u*100:0}%`,transition:"width 0.3s"}})})]})]}),t.jsxs("div",{style:{display:"flex",gap:8,marginBottom:14,flexWrap:"wrap",alignItems:"center"},children:[D.map(M=>{const k=Mp[M.type];return t.jsxs("button",{onClick:()=>M.set(!M.show),style:{padding:"7px 14px",borderRadius:10,fontSize:12,fontWeight:600,cursor:"pointer",border:`1px solid ${M.show?k.color+"50":"rgba(255,255,255,0.06)"}`,background:M.show?`${k.color}18`:"rgba(255,255,255,0.03)",color:M.show?k.color:"#64748b",transition:"all 0.15s"},children:[k.emoji," ",k.label," (",P[M.type]||0,")"]},M.type)}),t.jsxs("div",{style:{marginLeft:"auto",fontSize:12,color:"#334155"},children:[z.length," of ",u," plotted"]})]}),t.jsxs("div",{style:{flex:1,minHeight:560,borderRadius:16,overflow:"hidden",border:"1px solid #1e3a4f",position:"relative",background:"#162232"},children:[b&&t.jsx("div",{style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",zIndex:10},children:t.jsxs("div",{style:{background:"#0f1923",border:"1px solid rgba(248,113,113,0.3)",borderRadius:14,padding:"24px 32px",textAlign:"center",maxWidth:400},children:[t.jsx("div",{style:{fontSize:32,marginBottom:12},children:"ðºï¸"}),t.jsx("div",{style:{color:"#f87171",fontWeight:700,fontSize:15,marginBottom:8},children:"Map Error"}),t.jsx("div",{style:{color:"#64748b",fontSize:13},children:b})]})}),a&&t.jsx("div",{style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",zIndex:10,background:"#162232"},children:t.jsxs("div",{style:{textAlign:"center"},children:[t.jsx("div",{style:{fontSize:32,marginBottom:12},children:"ðºï¸"}),t.jsx("div",{style:{color:"#64748b",fontSize:14},children:"Loading addressesâ¦"})]})}),t.jsx("div",{ref:e,style:{width:"100%",height:"100%",minHeight:560}})]}),t.jsxs("div",{style:{display:"flex",gap:16,marginTop:12,flexWrap:"wrap"},children:[Object.entries(Mp).map(([M,k])=>t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:5},children:[t.jsx("div",{style:{width:10,height:10,borderRadius:"50%",background:k.color,boxShadow:`0 0 6px ${k.color}60`}}),t.jsx("span",{style:{fontSize:11,color:"#64748b"},children:k.label})]},M)),t.jsx("span",{style:{fontSize:11,color:"#334155",marginLeft:"auto"},children:"Click any pin for details"})]})]})}function xf(e){if(!e)return"";const n=e.replace(/\D/g,"");return n.length===10?`(${n.slice(0,3)}) ${n.slice(3,6)}-${n.slice(6)}`:n.length===11&&n.startsWith("1")?`(${n.slice(1,4)}) ${n.slice(4,7)}-${n.slice(7)}`:e}function oG(e){const n=Math.floor((Date.now()-new Date(e).getTime())/6e4);if(n<1)return"now";if(n<60)return`${n}m`;const r=Math.floor(n/60);if(r<24)return`${r}h`;const s=Math.floor(r/24);return s<7?`${s}d`:new Date(e).toLocaleDateString("en-US",{month:"short",day:"numeric"})}function aG(e){const n=new Date(e),r=new Date,s=n.toDateString()===r.toDateString(),i=n.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit"});return s?i:`${n.toLocaleDateString("en-US",{month:"short",day:"numeric"})} ${i}`}const lG="4633005100",Z3=[{label:"Appointment Reminder",body:"Hi {name}, this is Zenith Pure Solutions. Just a reminder about your upcoming appointment. Please reply to confirm or call us at (317) 690-4172 to reschedule."},{label:"Quote Follow-Up",body:"Hi {name}, this is Zenith Pure Solutions. We sent you a quote recently â did
1156you have any questions? We'd love to help. Reply here or call (317) 690-4172."},{label:"Payment Reminder",body:"Hi {name}, this is Zenith Pure Solutions. We noticed a payment is due on your account. Please call us at (317) 690-4172 or reply to this message for assistance."},{label:"Install Scheduled",body:"Hi {name}, your installation with Zenith Pure Solutions is scheduled! Our technician will arrive at the confirmed time. Questions? Call (317) 690-4172."},{label:"Thank You",body:"Hi {name}, thank you for choosing Zenith Pure Solutions! If you have any questions about your water system, reply here or call (317) 690-4172."}];function dG({onClose:e,onSent:n,profile:r}){const[s,i]=g.useState(""),[o,a]=g.useState(""),[l,d]=g.useState(!1),[c,f]=g.useState(""),[p,u]=g.useState(!1),[h,y]=g.useState(!1);async function m(){if(!s||!o)return;const b=s.replace(/\D/g,"");if(b.length<10){f("Enter a valid 10-digit phone number");return}d(!0),f("");try{const A=await fetch("/api/openphone/send-sms",{method:"POST",headers:await At(),body:JSON.stringify({to:b,body:o,entity_type:"unknown",entity_id:null,sent_by:(r==null?void 0:r.id)||null,tenant_id:(r==null?void 0:r.tenant_id)||null})}),v=await A.json();if(!A.ok){f(v.error||"Failed to send"),d(!1);return}u(!0),setTimeout(()=>{n(),e()},1e3)}catch(A){f(A.message||"Network error")}d(!1)}return t.jsx("div",{style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.75)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:60,padding:16},children:t.jsxs("div",{style:{background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:16,width:"100%",maxWidth:480,overflow:"hidden"},children:[t.jsxs("div",{style:{padding:"20px 24px",borderBottom:"1px solid #1e3a4f",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[t.jsx("div",{style:{color:"#e2e8f0",fontWeight:800,fontSize:17},children:"New Text Message"}),t.jsx("button",{onClick:e,style:{background:"none",border:"none",color:"#64748b",fontSize:20,cursor:"pointer"},children:"Ã"})]}),t.jsxs("div",{style:{padding:"20px 24px"},children:[t.jsx("label",{style:{display:"block",fontSize:12,color:"#64748b",marginBottom:6,fontWeight:600},children:"Phone Number"}),t.jsx("input",{value:s,onChange:b=>i(b.target.value),placeholder:"(317) 555-1234",style:{width:"100%",background:"#162232",border:"1px solid #1e3a4f",borderRadius:8,color:"#e2e8f0",padding:"10px 14px",fontSize:14,outline:"none",boxSizing:"border-box",marginBottom:16}}),t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:6},children:[t.jsx("label",{style:{fontSize:12,color:"#64748b",fontWeight:600},children:"Message"}),t.jsx("button",{onClick:()=>y(!h),style:{fontSize:11,color:"#0d7ea3",background:"rgba(13,126,163,0.1)",border:"1px solid rgba(13,126,163,0.25)",borderRadius:6,padding:"3px 10px",cursor:"pointer",fontWeight:600},children:h?"Hide Templates":"Use Template"})]}),h&&t.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6,marginBottom:10},children:Z3.map(b=>t.jsx("button",{onClick:()=>{a(b.body),y(!1)},style:{fontSize:11,padding:"5px 10px",borderRadius:6,border:"1px solid #1e3a4f",background:"#162232",color:"#94a3b8",cursor:"pointer"},onMouseEnter:A=>{A.currentTarget.style.borderColor="#0d7ea3",A.currentTarget.style.color="#e2e8f0"},onMouseLeave:A=>{A.currentTarget.style.borderColor="#1e3a4f",A.currentTarget.style.color="#94a3b8"},children:b.label},b.label))}),t.jsx("textarea",{value:o,onChange:b=>a(b.target.value),placeholder:"Type your messageâ¦",rows:4,style:{width:"100%",background:"#162232",border:"1px solid #1e3a4f",borderRadius:8,color:"#e2e8f0",padding:"10px 14px",fontSize:14,outline:"none",boxSizing:"border-box",resize:"vertical",fontFamily:"inherit"}}),t.jsxs("div",{style:{fontSize:11,color:"#334155",marginTop:4},children:[o.length," characters · ",Math.ceil(o.length/160)||0," segment",Math.ceil(o.length/160)!==1?"s":""]}),c&&t.jsx("div",{style:{marginTop:12,padding:"10px 14px",borderRadius:8,background:"rgba(239,68,68,0.1)",border:"1px solid rgba(239,68,68,0.25)",color:"#f87171",fontSize:13},children:c}),p&&t.jsx("div",{style:{marginTop:12,padding:"10px 14px",borderRadius:8,background:"rgba(74,222,128,0.1)",border:"1px solid rgba(74,222,128,0.25)",color:"#4ade80",fontSize:13},children:"Message sent!"})]}),t.jsxs("div",{style:{padding:"16px 24px",borderTop:"1px solid #1e3a4f",dis
1156play:"flex",gap:10,justifyContent:"flex-end"},children:[t.jsx("button",{onClick:e,style:{padding:"9px 18px",fontSize:13,color:"#64748b",background:"none",border:"none",cursor:"pointer"},children:"Cancel"}),t.jsx("button",{onClick:m,disabled:l||!s||!o||p,style:{padding:"10px 24px",borderRadius:8,border:"none",cursor:"pointer",background:!s||!o||p?"#334155":"#0d7ea3",color:"#fff",fontWeight:700,fontSize:14,opacity:l?.5:1},children:l?"Sendingâ¦":p?"Sent!":"Send SMS"})]})]})})}function cG({phone:e,name:n,entityType:r,entityId:s,profile:i,onBack:o}){const a=gt(),[l,d]=g.useState([]),[c,f]=g.useState(!0),[p,u]=g.useState(""),[h,y]=g.useState(!1),[m,b]=g.useState(!1),A=g.useRef(null),v=g.useCallback(async()=>{f(!0);const{data:j}=await w.from("communications_log").select("*").or(`from_number.eq.${e},to_number.eq.${e}`).eq("channel","sms").order("created_at",{ascending:!0}).limit(100);d(j||[]),f(!1),setTimeout(()=>{var C;return(C=A.current)==null?void 0:C.scrollIntoView({behavior:"smooth"})},100),w.from("communications_log").update({read_at:new Date().toISOString()}).eq("channel","sms").eq("direction","inbound").is("read_at",null).eq("from_number",e).then(()=>{},()=>{})},[e]);g.useEffect(()=>{v()},[v]);async function x(){if(p.trim()){y(!0);try{(await fetch("/api/openphone/send-sms",{method:"POST",headers:await At(),body:JSON.stringify({to:e,body:p,entity_type:r||"unknown",entity_id:s||null,sent_by:(i==null?void 0:i.id)||null,tenant_id:(i==null?void 0:i.tenant_id)||null})})).ok&&(u(""),b(!1),setTimeout(v,500))}catch(j){console.error(j)}y(!1)}}const _=n||xf(e);return t.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[t.jsxs("div",{style:{flexShrink:0,display:"flex",alignItems:"center",gap:12,padding:"14px 18px",background:"#162232",borderBottom:"1px solid #1e3a4f",borderRadius:"12px 12px 0 0"},children:[t.jsx("button",{onClick:o,style:{background:"none",border:"none",color:"#64748b",fontSize:14,cursor:"pointer",padding:"4px 8px"},children:"â Back"}),t.jsx("div",{style:{width:36,height:36,borderRadius:"50%",background:"rgba(13,126,163,0.2)",border:"2px solid rgba(13,126,163,0.4)",display:"flex",alignItems:"center",justifyContent:"center",color:"#0d7ea3",fontWeight:800,fontSize:14},children:(n||"?").charAt(0).toUpperCase()}),t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsx("div",{style:{color:"#e2e8f0",fontWeight:700,fontSize:14},children:_}),t.jsxs("div",{style:{color:"#475569",fontSize:11},children:[xf(e),r&&r!=="unknown"?` · ${r}`:""]})]}),r&&s&&r!=="unknown"&&t.jsxs("button",{onClick:()=>a(r==="lead"?`/leads?lead=${s}`:`/customers/${s}`),style:{fontSize:11,padding:"5px 12px",borderRadius:6,border:"1px solid rgba(13,126,163,0.25)",background:"rgba(13,126,163,0.1)",color:"#0d7ea3",cursor:"pointer",fontWeight:600},children:["View ",r==="lead"?"Lead":"Customer"," â"]})]}),t.jsxs("div",{style:{flex:1,overflowY:"auto",padding:"16px 18px",display:"flex",flexDirection:"column",gap:8},children:[c?t.jsx("div",{style:{textAlign:"center",padding:40,color:"#64748b"},children:"Loading messagesâ¦"}):l.length===0?t.jsx("div",{style:{textAlign:"center",padding:40,color:"#334155",fontSize:13},children:"No messages yet. Send the first text below."}):l.map(j=>{const C=j.direction==="outbound";return t.jsx("div",{style:{display:"flex",justifyContent:C?"flex-end":"flex-start"},children:t.jsxs("div",{style:{maxWidth:"75%",padding:"10px 14px",borderRadius:C?"14px 14px 4px 14px":"14px 14px 14px 4px",background:C?"#0d7ea3":"#1e3a4f",color:C?"#ffffff":"#e2e8f0",fontSize:14,lineHeight:1.5},children:[t.jsx("div",{children:j.message}),t.jsxs("div",{style:{fontSize:10,marginTop:4,opacity:.6,textAlign:C?"right":"left"},children:[aG(j.created_at),C?" · Sent":""]})]})},j.id)}),t.jsx("div",{ref:A})]}),m&&t.jsx("div",{style:{flexShrink:0,padding:"8px 18px",borderTop:"1px solid #1e3a4f",background:"#0f1923",display:"flex",flexWrap:"wrap",gap:6},children:Z3.map(j=>t.jsx("button",{onClick:()=>{u(j.body.replace("{name}",n||"there")),b(!1)},style:{fontSize:11,padding:"5px 10px",borderRadius:6,border:"1px solid #1e3a4f",background:"#162232",color:"#94a3b8",curs
1156or:"pointer"},children:j.label},j.label))}),t.jsxs("div",{style:{flexShrink:0,padding:"12px 18px",borderTop:"1px solid #1e3a4f",background:"#0f1923",display:"flex",gap:10,alignItems:"flex-end"},children:[t.jsx("button",{onClick:()=>b(!m),style:{padding:"8px",borderRadius:8,border:"1px solid #1e3a4f",background:"#162232",color:"#64748b",cursor:"pointer",fontSize:14,flexShrink:0},title:"SMS Templates",children:"â¡"}),t.jsx("textarea",{value:p,onChange:j=>u(j.target.value),placeholder:"Type a messageâ¦",rows:1,onKeyDown:j=>{j.key==="Enter"&&!j.shiftKey&&(j.preventDefault(),x())},style:{flex:1,background:"#162232",border:"1px solid #1e3a4f",borderRadius:8,color:"#e2e8f0",padding:"10px 14px",fontSize:14,outline:"none",resize:"none",fontFamily:"inherit",minHeight:40,maxHeight:120}}),t.jsx("button",{onClick:x,disabled:h||!p.trim(),style:{padding:"10px 20px",borderRadius:8,border:"none",background:p.trim()?"#0d7ea3":"#334155",color:"#fff",fontWeight:700,fontSize:13,cursor:"pointer",flexShrink:0,opacity:h?.5:1},children:h?"â¦":"Send"})]})]})}function uG(){const{profile:e}=Ee(),[n,r]=g.useState([]),[s,i]=g.useState(!0),[o,a]=g.useState(""),[l,d]=g.useState(null),[c,f]=g.useState(null),[p,u]=g.useState(!1),h=g.useCallback(async()=>{i(!0);const{data:m}=await w.from("communications_log").select("*").eq("channel","sms").order("created_at",{ascending:!1}).limit(500);if(!m||m.length===0){r([]),i(!1);return}const b={};for(const _ of m){const j=_.direction==="inbound"?_.from_number:_.to_number;j&&j!==lG&&(b[j]||(b[j]={phone:j,name:null,entity_type:_.entity_type!=="unknown"?_.entity_type:null,entity_id:_.entity_id,lastMessage:_.message||"",lastTime:_.created_at,direction:_.direction,unread:0}),_.direction==="inbound"&&!_.read_at&&b[j].unread++)}const A=Object.keys(b),v=_=>(_||"").replace(/\D/g,"").slice(-10),x={};for(const _ of A)x[v(_)]=_;if(A.length>0){const{data:_}=await w.from("leads").select("id, full_name, phone");for(const C of _||[]){const S=x[v(C.phone)];S&&b[S]&&(b[S].name=C.full_name,b[S].entity_type="lead",b[S].entity_id=C.id)}const{data:j}=await w.from("customers").select("id, full_name, phone");for(const C of j||[]){const S=x[v(C.phone)];S&&b[S]&&(b[S].name=C.full_name,b[S].entity_type="customer",b[S].entity_id=C.id)}}r(Object.values(b).sort((_,j)=>new Date(j.lastTime).getTime()-new Date(_.lastTime).getTime())),i(!1)},[]);g.useEffect(()=>{h()},[h]),g.useEffect(()=>{const m=setInterval(h,15e3);return()=>clearInterval(m)},[h]);const y=n.filter(m=>{if(!o)return!0;const b=o.toLowerCase();return(m.name||"").toLowerCase().includes(b)||(m.phone||"").includes(b)||(m.lastMessage||"").toLowerCase().includes(b)});return l&&c?t.jsx("div",{style:{height:"100%",display:"flex",flexDirection:"column"},children:t.jsx(cG,{phone:l,name:c.name,entityType:c.entity_type,entityId:c.entity_id,profile:e,onBack:()=>{d(null),f(null),h()}})}):t.jsxs("div",{style:{height:"100%",display:"flex",flexDirection:"column"},children:[t.jsxs("div",{style:{flexShrink:0,display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,marginBottom:16,flexWrap:"wrap"},children:[t.jsxs("div",{children:[t.jsx("h1",{style:{fontSize:22,fontWeight:800,color:"#e2e8f0",margin:0},children:"Messages"}),t.jsxs("p",{style:{fontSize:13,color:"#475569",marginTop:4,marginBottom:0},children:["SMS conversations · (463) 300-5100 · ",n.length," thread",n.length!==1?"s":""]})]}),t.jsx("button",{onClick:()=>u(!0),style:{padding:"10px 20px",borderRadius:10,border:"none",background:"#0d7ea3",color:"#fff",fontWeight:700,fontSize:14,cursor:"pointer",display:"flex",alignItems:"center",gap:6},children:"+ New Message"})]}),t.jsx("div",{style:{flexShrink:0,marginBottom:14},children:t.jsx("input",{value:o,onChange:m=>a(m.target.value),placeholder:"Search by name, phone, or messageâ¦",style:{width:"100%",background:"#162232",border:"1px solid #1e3a4f",borderRadius:10,color:"#e2e8f0",padding:"10px 14px",fontSize:13,outline:"none",boxSizing:"border-box"}})}),t.jsx("div",{style:{flex:1,overflowY:"auto",overflowX:"hidden",background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:14},children:s?t.jsx("div",{style:{textAlign:"center",padding:60,color:"#64748b"},children:"Loading conversationsâ¦"}):y.length===0?t.jsxs("div",{style:{textAlign:"center",padding:60},children:[t.jsx("div",{style:{fontSize:36,marginBottom:12,opacity:.3},children:"ð¬"}),t.jsx("div",{style:{color:"#475569",fontSize:14,marginBottom:4},children:o?"No matches found":"No conversations yet"}),t.jsx("div",{style:{color:"#334155",fontSize:12},children:"Send a text or have someone text (463) 300-5100"})]}):y.map(m=>t.jsxs("div",{onClick:()=>{d(m.phone),f(m)},style:{display:"flex",alignItems:"center",gap:12,padding:"14px 18px",cursor:"pointer",borderBottom:"1px solid #0d1a26"},onMouseEnter:b=>{b.currentTarget.style.background="rgba(13,126,163,0.06)"},onMouseLeave:b=>{b.currentTarget.style.background="transparent"}
1156,children:[t.jsx("div",{style:{width:42,height:42,borderRadius:"50%",flexShrink:0,background:m.entity_type==="customer"?"rgba(74,222,128,0.15)":m.entity_type==="lead"?"rgba(96,165,250,0.15)":"rgba(100,116,139,0.15)",border:`2px solid ${m.entity_type==="customer"?"rgba(74,222,128,0.3)":m.entity_type==="lead"?"rgba(96,165,250,0.3)":"rgba(100,116,139,0.2)"}`,display:"flex",alignItems:"center",justifyContent:"center",color:m.entity_type==="customer"?"#4ade80":m.entity_type==="lead"?"#60a5fa":"#64748b",fontWeight:800,fontSize:15,textTransform:"uppercase"},children:(m.name||m.phone).charAt(0)}),t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[t.jsx("div",{style:{color:"#e2e8f0",fontWeight:700,fontSize:14,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:m.name||xf(m.phone)}),t.jsx("div",{style:{fontSize:11,color:"#475569",flexShrink:0},children:oG(m.lastTime)})]}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,marginTop:3},children:[m.direction==="outbound"&&t.jsx("span",{style:{fontSize:10,color:"#475569"},children:"You:"}),t.jsx("div",{style:{fontSize:12,color:"#64748b",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1},children:m.lastMessage||"No message"})]}),t.jsxs("div",{style:{display:"flex",gap:6,marginTop:4},children:[m.entity_type&&m.entity_type!=="unknown"&&t.jsx("span",{style:{fontSize:10,padding:"1px 7px",borderRadius:10,fontWeight:600,background:m.entity_type==="customer"?"rgba(74,222,128,0.12)":"rgba(96,165,250,0.12)",color:m.entity_type==="customer"?"#4ade80":"#60a5fa",border:`1px solid ${m.entity_type==="customer"?"rgba(74,222,128,0.25)":"rgba(96,165,250,0.25)"}`},children:m.entity_type}),t.jsx("span",{style:{fontSize:10,color:"#334155"},children:xf(m.phone)})]})]}),m.unread>0&&t.jsx("div",{style:{width:22,height:22,borderRadius:"50%",background:"#0d7ea3",color:"#fff",fontSize:11,fontWeight:800,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:m.unread})]},m.phone))}),p&&t.jsx(dG,{onClose:()=>u(!1),onSent:h,profile:e})]})}const u2=[{key:"newsletter",label:"Customers",who:"Everyone in Customers with an email address",icon:"ð£",hex:"#38bdf8"},{key:"winback",label:"Lost",who:"Leads marked Lost â re-engagement",icon:"â©ï¸",hex:"#fb7185"},{key:"followup",label:"Cold Lead",who:"Leads marked Cold Lead â re-engagement",icon:"â³",hex:"#fbbf24"}];async function p2(e){const{data:{session:n}}=await w.auth.getSession();if(!(n!=null&&n.access_token))throw new Error("Not signed in");const r=await fetch("/api/email/send-campaign",{method:"POST",headers:{Authorization:`Bearer ${n.access_token}`,"Content-Type":"application/json"},body:JSON.stringify(e)}),s=await r.json();if(!r.ok)throw new Error((s==null?void 0:s.error)||`Request failed (${r.status})`);return s}function pG(){const[e,n]=g.useState(null),[r,s]=g.useState(null),[i,o]=g.useState(null),[a,l]=g.useState(null),[d,c]=g.useState(null),[f,p]=g.useState(null),[u,h]=g.useState(!1),{profile:y}=Ee(),m=(y==null?void 0:y.role)==="admin"||(y==null?void 0:y.role)==="super_admin",[b,A]=g.useState(!1),[v,x]=g.useState(""),[_,j]=g.useState(""),[C,S]=g.useState(!1),[T,L]=g.useState("");function E(){x((r==null?void 0:r.subject)||""),j((r==null?void 0:r.body)||""),L(""),A(!0)}async function R(){if(e){if(!v.trim()){L("Subject cannot be empty.");return}S(!0),L("");try{const{data:P,error:D}=await w.from("message_templates").update({subject:v,body:_}).eq("channel","email").eq("key",e).select("subject, body, is_active");if(D)throw new Error(D.message);if(!P||P.length===0)throw new Error("No template row was updated - check permissions.");s(P[0]),A(!1),o(null),l(null),h(!1)}catch(P){L((P==null?void 0:P.message)||"Could not save.")}finally{S(!1)}}}g.useEffect(()=>{if(o(null),l(null),p(null),h(!1),s(null),!e)return;let P=!0;return(async()=>{const{data:D,error:M}=await w.from("message_templates").select("subject, body, is_active").eq("channel","email").eq("key",e).maybeSingle();P&&(M?p(M.message):s(D))})(),()=>{P=!1}},[e]);async function N(){if(e){c("preview"),p(null),l(null),h(!1);try{o(await p2({template_type:e,dry_run:!0}))}catch(P){p(P.message),o(null)}finally{c(null)}}}async function O(){if(e){c("send"),p(null),h(!1);try{const P=await p2({template_type:e});l(P),o(null)}catch(P){p(P.message)}finally{c(null)}}}const z=u2.find(P=>P.key===e);return t.jsxs("div",{style:{padding:"28px 32px",maxWidth:980,margin:"0 auto"},children:[t.jsx("h1",{style:{fontSize:22,fontWeight:800,color:"#f1f5f9",margin:0},children:"Campaigns"}),t.jsx("p",{style:{fontSize:13,color:"#64748b",margin:"4px 0 24px"},children:"Send a marketing email to a segment. Unsubscribed and do-not-contact people are always excluded."}),t.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(3, 1fr)",gap:12,marginBottom:24},children:u2.map(P=>{const D=e===P.key;return t.jsxs("button",{onClick:()=>n(P.key),style:{textAlign:"left",padding:"16px 18px",borderRadius:12,cursor:"pointer",background:D?`${P.hex}15`:"#0f1923",border:`1px solid ${D?P.hex:"#1e3a4f"}`},children:[t.jsx("div",{style:{fontSize:20,marginBottom:6},children:P.icon}),t.jsx("div",{style:{fontSize:14,fontWeight:700,color:D?P.hex:"#f1f5f9"},children:P.label}),t.jsx("div",{style:{fontSize:11,color:"#64748b",marginTop:3,lineHeight:1.4},children:P.who})]},P.key)})}),z&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{style:{background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:12,padding:20,marginBottom:16},children:[t.jsx("div",{style:{fontSize:11,fontWeight:700,color:"#64748b",letterSpacing:"0.06em",marginBottom:10},children:"TEMPLATE"}),r?t.jsxs(t.Fragment,{children:[!r.is_active&&t.jsx("div",{style:{fontSize:12,color:"#fbbf24",marginBottom:10},children:"This template is disabled â sending will fail. Enable it in Admin Settings â Email Templates."}),b?t.jsxs(t.Fragment,{children:[t.jsx("div",{style:{fontSize:11,fontWeight:700,color:"#64748b",letterSpacing:"0.06em",marginBottom:6},children:"SUBJECT"}
1156),t.jsx("input",{value:v,onChange:P=>x(P.target.value),style:{width:"100%",background:"#0a1420",border:"1px solid #1e3a4f",borderRadius:8,padding:"10px 12px",fontSize:14,color:"#e2e8f0",outline:"none",boxSizing:"border-box"}}),t.jsx("div",{style:{fontSize:11,fontWeight:700,color:"#64748b",letterSpacing:"0.06em",margin:"14px 0 6px"},children:"BODY (HTML)"}),t.jsx("textarea",{value:_,onChange:P=>j(P.target.value),rows:10,spellCheck:!1,style:{width:"100%",background:"#0a1420",border:"1px solid #1e3a4f",borderRadius:8,padding:"10px 12px",fontSize:12.5,lineHeight:1.6,color:"#e2e8f0",outline:"none",resize:"vertical",boxSizing:"border-box",fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"}}),t.jsxs("div",{style:{fontSize:11,color:"#475569",marginTop:6},children:["Available: ","{{first_name}}"," ","{{last_name}}"," ","{{company_name}}"," ","{{from_name}}",". Anything else renders blank."]}),t.jsx("div",{style:{fontSize:11,fontWeight:700,color:"#64748b",letterSpacing:"0.06em",margin:"16px 0 6px"},children:"PREVIEW"}),t.jsx("iframe",{title:"Email preview",srcDoc:'<body style="margin:0;background:#f1f5f9;padding:16px 8px;"><div style="max-width:600px;margin:0 auto;background:#ffffff;border-radius:10px;padding:28px 32px;font-family:Arial,sans-serif;font-size:15px;line-height:1.65;color:#1e293b;">'+_.replace(/\{\{first_name\}\}/g,"Sarah").replace(/\{\{company_name\}\}/g,"your company").replace(/\{\{last_name\}\}/g,"Miller").replace(/\{\{from_name\}\}/g,"the team")+"</div></body>",style:{width:"100%",height:320,border:"1px solid #1e3a4f",borderRadius:8,background:"#f1f5f9"}}),t.jsx("div",{style:{fontSize:11,color:"#475569",marginTop:6},children:"Body only, with sample values. Logo, footer, address and unsubscribe link are added when the campaign sends. Email clients render differently - send one to yourself before a real campaign."}),T&&t.jsx("div",{style:{fontSize:12,color:"#f87171",marginTop:10},children:T}),t.jsxs("div",{style:{display:"flex",gap:10,marginTop:14},children:[t.jsx("button",{onClick:()=>A(!1),disabled:C,style:{padding:"8px 16px",fontSize:13,color:"#64748b",background:"none",border:"1px solid #1e3a4f",borderRadius:8,cursor:"pointer"},children:"Cancel"}),t.jsx("button",{onClick:R,disabled:C,style:{padding:"8px 16px",fontSize:13,fontWeight:600,color:"#0f172a",background:C?"#475569":"#60a5fa",border:"none",borderRadius:8,cursor:"pointer"},children:C?"Saving...":"Save copy"})]})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:12,marginBottom:10},children:[t.jsx("div",{style:{fontSize:14,fontWeight:700,color:"#f1f5f9"},children:r.subject}),m&&t.jsx("button",{onClick:E,style:{flexShrink:0,fontSize:12,fontWeight:600,padding:"4px 10px",borderRadius:8,cursor:"pointer",color:"#60a5fa",background:"rgba(96,165,250,0.1)",border:"1px solid rgba(96,165,250,0.3)"},children:"Edit copy"})]}),t.jsx("div",{style:{fontSize:13,color:"#94a3b8",lineHeight:1.6,background:"#0a1420",borderRadius:8,padding:"12px 14px"},dangerouslySetInnerHTML:{__html:r.body||"<em>No body</em>"}}),t.jsxs("div",{style:{fontSize:11,color:"#475569",marginTop:10},children:["Placeholders like ","{{first_name}}"," are filled in per recipient. Header, footer, address and unsubscribe link are added automatically."]})]})]}):t.jsx("div",{style:{fontSize:13,color:"#64748b"},children:"Loadingâ¦"})]}),t.jsxs("div",{style:{display:"flex",gap:10,alignItems:"center",marginBottom:16},children:[t.jsx("button",{onClick:N,disabled:d!==null,style:{padding:"10px 18px",borderRadius:8,fontSize:13,fontWeight:700,cursor:d?"default":"pointer",background:"#162232",color:"#e2e8f0",border:"1px solid #1e3a4f",opacity:d?.6:1},children:d==="preview"?"Checkingâ¦":"Preview audience"}),t.jsx("button",{onClick:()=>h(!0),disabled:!i||i.count===0||d!==null||!(r!=null&&r.is_active),style:{padding:"10px 18px",borderRadius:8,fontSize:13,fontWeight:700,cursor:!i||i.count===0?"default":"pointer",background:!i||i.count===0?"#162232":z.hex,color:!i||i.count===0?"#475569":"#0a1420",border:"none"},children:d==="send"?"Sendingâ¦":"Send campaign"}),!i&&!a&&t.jsx("span",{style:{fontSize:12,color:"#475569"},children:"Preview the audience before sending."})]}),f&&t.jsx("div",{style:{background:"rgba(248,113,113,0.08)",border:"1px solid rgba(248,113,113,0.3)",borderRadius:8,padding:"12px 14px",fontSize:13,color:"#f87171",marginBottom:16},children:f}),i&&t.jsxs("div",{style:{background:"#0f1923",border:"1px solid #1e3a4f",borderRadius:12,padding:20,marginBottom:16},children:[t.jsxs("div",{style:{display:"flex",alignItems:"baseline",gap:10,marginBottom:4},children:[t.jsx("div",{style:{fontSize:26,fontWeight:800,color:z.hex},children:i.count}),t.jsx("div",{style:{fontSize:13,color:"#94a3b8"},children:i.count===1?"person will receive this":"people will receive this"})]}),t.jsxs("div",{style:{fontSize:11,color:"#64748b",marginBottom:12},children:["From ",i.from]}),(i.skipped.suppressed>0||i.skipped.duplicate>0||i.skipped.invalid_email>0)&&t.jsxs("div",{style:{fontSize:12,color:"#64748b",marginBottom:12,display:"flex",gap:14,flexWrap:"wrap"},children:[i.skipped.suppressed>0&&t.jsxs("span",{children:[i.skipped.suppressed," unsubscribed"]}),i.skipped.duplicate>0&&t.jsxs("span",{children:[i.skipped.duplicate," duplicate ",i.skipped.duplicate===1?"address":"addresses"]}),i.skipped.invalid_email>0&&t.jsxs("span",{children:[i.skipped.invalid_email," invalid"]}
1156),t.jsx("span",{style:{color:"#475569"},children:"â excluded"})]}),i.count>0&&t.jsx("div",{style:{maxHeight:160,overflowY:"auto",background:"#0a1420",borderRadius:8,padding:"10px 12px"},children:i.recipients.map(P=>t.jsx("div",{style:{fontSize:12,color:"#94a3b8",fontFamily:"monospace",padding:"2px 0"},children:P},P))}),i.count===0&&t.jsx("div",{style:{fontSize:13,color:"#64748b"},children:"Nobody in this segment is eligible right now."})]}),u&&i&&t.jsxs("div",{style:{background:"rgba(251,191,36,0.06)",border:"1px solid rgba(251,191,36,0.3)",borderRadius:12,padding:20,marginBottom:16},children:[t.jsxs("div",{style:{fontSize:14,fontWeight:700,color:"#fbbf24",marginBottom:6},children:["Send to ",i.count," ",i.count===1?"person":"people","?"]}),t.jsx("div",{style:{fontSize:12,color:"#94a3b8",marginBottom:14,lineHeight:1.5},children:"This sends real email immediately. It cannot be undone or recalled."}),t.jsxs("div",{style:{display:"flex",gap:10},children:[t.jsx("button",{onClick:O,disabled:d!==null,style:{padding:"9px 16px",borderRadius:8,fontSize:13,fontWeight:700,background:"#fbbf24",color:"#0a1420",border:"none",cursor:"pointer"},children:"Yes, send now"}),t.jsx("button",{onClick:()=>h(!1),style:{padding:"9px 16px",borderRadius:8,fontSize:13,fontWeight:700,background:"transparent",color:"#94a3b8",border:"1px solid #1e3a4f",cursor:"pointer"},children:"Cancel"})]})]}),a&&t.jsxs("div",{style:{background:a.failed>0?"rgba(251,191,36,0.06)":"rgba(74,222,128,0.06)",border:`1px solid ${a.failed>0?"rgba(251,191,36,0.3)":"rgba(74,222,128,0.3)"}`,borderRadius:12,padding:20},children:[t.jsxs("div",{style:{fontSize:14,fontWeight:700,color:a.failed>0?"#fbbf24":"#4ade80",marginBottom:6},children:[a.sent," sent",a.failed>0?`, ${a.failed} failed`:""]}),a.errors&&a.errors.length>0&&t.jsx("div",{style:{marginTop:10},children:a.errors.map((P,D)=>t.jsxs("div",{style:{fontSize:12,color:"#94a3b8",fontFamily:"monospace"},children:[P.email," â ",P.error]},D))}),t.jsx("div",{style:{fontSize:11,color:"#475569",marginTop:10},children:"Every send is recorded in the email log."})]})]})]})}function hG(){const{session:e,role:n,loading:r}=Ee();return r?t.jsx(UR,{}):t.jsxs(d4,{children:[t.jsx(Ve,{path:"/q/:token",element:t.jsx(LE,{})}),t.jsx(Ve,{path:"/book/:token",element:t.jsx(FE,{})}),t.jsx(Ve,{path:"/o/:token",element:t.jsx(JE,{})}),t.jsx(Ve,{path:"/f/:slug",element:t.jsx(_P,{})}),t.jsx(Ve,{path:"/lp/zenith-water",element:t.jsx(v9,{})}),t.jsx(Ve,{path:"/lp/zenith-repro",element:t.jsx(e9,{})}),t.jsx(Ve,{path:"/lp/zenith-multistep",element:t.jsx(n9,{})}),t.jsx(Ve,{path:"/lp/zenith-booking",element:t.jsx(s9,{})}),t.jsx(Ve,{path:"/lp/zenith-sections",element:t.jsx(o9,{})}),t.jsx(Ve,{path:"/lp/:slug",element:t.jsx(a9,{})}),t.jsx(Ve,{path:"/terms",element:t.jsx(k$,{})}),t.jsx(Ve,{path:"/t/:tenantSlug/terms",element:t.jsx(S$,{})}),t.jsx(Ve,{path:"/forgot-password",element:t.jsx($M,{})}),t.jsx(Ve,{path:"/update-password",element:t.jsx(MM,{})}),t.jsx(Ve,{path:"/*",element:e?t.jsx(fG,{role:n}):t.jsx(BR,{})})]})}function h2({title:e,body:n}){return t.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100vh",background:"#0d1117",padding:24},children:t.jsxs("div",{style:{maxWidth:420,textAlign:"center"},children:[t.jsx("div",{style:{fontSize:44,marginBottom:16},children:"ð"}),t.jsx("h1",{style:{color:"#e2e8f0",fontSize:22,fontWeight:800,marginBottom:10},children:e}),t.jsx("p",{style:{color:"#64748b",fontSize:14,lineHeight:1.6,marginBottom:24},children:n}),t.jsx("p",{style:{color:"#475569",fontSize:12},children:"Contact support to restore access."})]})})}function fG({role:e}){const{tenant:n}=Ee(),{userBranchActive:r}=mu(),{canAccess:s}=rs(),i=e==="admin"||e==="super_admin";if(e!=="super_admin"){if(n&&n.is_active===!1)return t.jsx(h2,{title:"Account suspended",body:"This account has been suspended. Your data is safe, but access is paused."});if(r===!1)return t.jsx(h2,{title:"Location suspended",body:"This location has been suspended. Other locations on your account may still be active."})}function o(a,l){return i||s(a)?l:t.jsx(ks,{to:"/dashboard",replace:!0})}return t.jsx(WR,{children:t.jsxs(d4,{children:[t.jsx(Ve,{path:"/",element:t.jsx(ks,{to:"/dashboard",replace:!0})}),t.jsx(Ve,{path:"/dashboard",element:t.jsx(xF,{})}),t.jsx(Ve,{path:"/schedule",element:t.jsx(G$,{})}),t.jsx(Ve,{path:"/calendar",element:t.jsx(TM,{})}),t.jsx(Ve,{path:"/leads",element:o("/leads",t.jsx(sV,{}))}),t.jsx(Ve,{path:"/dispatch",element:e==="technician"?t.jsx(ks,{to:"/installations",replace:!0}):o("/dispatch",t.jsx(OV,{}))}),t.jsx(Ve,{path:"/installations",element:o("/installations",t.jsx(LV,{}))}),t.jsx(Ve,{path:"/installations/:jobId",element:o("/installations",t.jsx(tZ,{}))}),t.jsx(Ve,{path:"/jobs",element:t.jsx(ks,{to:"/installations",replace:!0})}),t.jsx(Ve,{path:"/customers",element:o("/customers",t.jsx(cZ,{}))}),t.jsx(Ve,{path:"/customers/:customerId",element:o("/customers",t.jsx(gY,{}))}),t.jsx(Ve,{path:"/follow-ups",element:o("/follow-ups",t.jsx(TE,{}))}),t.jsx(Ve,{path:"/products",element:o("/products",t.jsx(yE,{}))}),t.jsx(Ve,{path:"/quotes",element:o("/quotes",t.jsx(bY,{}))}),t.jsx(Ve,{path:"/offers",element:o("/offers",t.jsx(hP,{}))}),t.jsx(Ve,{path:"/invoices",element:o("/invoices",t.jsx(sY,{}))}),t.jsx(Ve,{path:"/failed-payments",element:t.jsx($Y,{})}),t.jsx(Ve,{path:"/services",element:o("/services",t.jsx(zY,{}))}),t.jsx(Ve,{path:"/contracts/:id",element:o("/services",t.jsx(EY,{}))}),t.jsx(Ve,{path:"/accounting",element:o("/accounting",t.jsx(jY,{}))}),t.jsx(Ve,{path:"/inventory",element:o("/inventory",t.jsx(V$,{}))}),t.jsx(Ve,{path:"/shipping",element:o("/shipping",t.jsx(FY,{}))}),t.jsx(Ve,{path:"/fulfillment",element:o("/fulfillment",t.jsx(QY,{}))}),t.jsx(Ve,{path:"/service-due",element:o("/service-due",t.jsx(sX,{}))}),t.jsx(Ve,{path:"/service-board",element:o("/service-board",t.jsx(pX,{}))}),t.jsx(Ve,{path:"/campaigns",element:o("/campaigns",t.jsx(pG,{}))}),t.jsx(Ve,{path:"/reports",element:o("/reports",t.jsx(tG,{}))}),t.jsx(Ve,{path:"/heatmap",element:o("/heatmap",t.jsx(iG,{}))}),t.jsx(Ve,{path:"/communications",element:o("/communications",t.jsx(uG,{}))}),t.jsx(Ve,{path:"/admin/terms",element:i?t.jsx(i$,{}):t.jsx(ks,{to:"/dashboard",replace:!0})}),t.jsx(Ve,{path:"/admin/users",element:i?t.jsx(Y$,{}):t.jsx(ks,{to:"/dashboard",replace:!0})}),t.jsx(Ve,{path:"/admin/account",element:i?t.jsx(x$,{}):t.jsx(ks,{to:"/dashboard",replace:!0})}),t.jsx(Ve,{path:"/super-admin/tenants",element:e==="super_admin"?t.jsx(WM,{}):t.jsx(ks,{to:"/dashboard",replace:!0})}),t.jsx(Ve,{path:"*",element:t.jsx(ks,{to:"/dashboard",replace:!0})})]})})}const gG=new XS({defaultOptions:{queries:{staleTime:1e3*30,retry:1,refetchOnWindowFocus:!1}}});function mG(){return t.jsx(JS,{client:gG,children:t.jsx(Sz,{children:t.jsx(TR,{children:t.jsx(zR,{children:t.jsx(hG,{})})})})})}const xG=new XS({defaultOptions:{queries:{retry:1,staleTime:3e4}}});Zm.createRoot(document.getElementById("root")).render(t.jsx(ut.StrictMode,{children:t.jsx(JS,{client:xG,children:t.jsx(mG,{})})}));
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.