var yf=e=>{throw TypeError(e)};var Lc=(e,t,n)=>t.has(e)||yf("Cannot "+n);var T=(e,t,n)=>(Lc(e,t,"read from private field"),n?n.call(e):t.get(e)),de=(e,t,n)=>t.has(e)?yf("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),se=(e,t,n,r)=>(Lc(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),ve=(e,t,n)=>(Lc(e,t,"access private method"),n);var Ll=(e,t,n,r)=>({set _(a){se(e,t,a,n)},get _(){return T(e,t,r)}});function Vv(e,t){for(var n=0;nr[a]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))r(a);new MutationObserver(a=>{for(const i of a)if(i.type==="childList")for(const l of i.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&r(l)}).observe(document,{childList:!0,subtree:!0});function n(a){const i={};return a.integrity&&(i.integrity=a.integrity),a.referrerPolicy&&(i.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?i.credentials="include":a.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(a){if(a.ep)return;a.ep=!0;const i=n(a);fetch(a.href,i)}})();function Qv(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var tg={exports:{}},nc={},sg={exports:{}},Ee={};/** * @license React * react.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */var vl=Symbol.for("react.element"),Hv=Symbol.for("react.portal"),Wv=Symbol.for("react.fragment"),Gv=Symbol.for("react.strict_mode"),Zv=Symbol.for("react.profiler"),Jv=Symbol.for("react.provider"),Xv=Symbol.for("react.context"),Yv=Symbol.for("react.forward_ref"),ej=Symbol.for("react.suspense"),tj=Symbol.for("react.memo"),sj=Symbol.for("react.lazy"),vf=Symbol.iterator;function nj(e){return e===null||typeof e!="object"?null:(e=vf&&e[vf]||e["@@iterator"],typeof e=="function"?e:null)}var ng={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},rg=Object.assign,ag={};function Xa(e,t,n){this.props=e,this.context=t,this.refs=ag,this.updater=n||ng}Xa.prototype.isReactComponent={};Xa.prototype.setState=function(e,t){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,t,"setState")};Xa.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function ig(){}ig.prototype=Xa.prototype;function Ju(e,t,n){this.props=e,this.context=t,this.refs=ag,this.updater=n||ng}var Xu=Ju.prototype=new ig;Xu.constructor=Ju;rg(Xu,Xa.prototype);Xu.isPureReactComponent=!0;var jf=Array.isArray,lg=Object.prototype.hasOwnProperty,Yu={current:null},og={key:!0,ref:!0,__self:!0,__source:!0};function cg(e,t,n){var r,a={},i=null,l=null;if(t!=null)for(r in t.ref!==void 0&&(l=t.ref),t.key!==void 0&&(i=""+t.key),t)lg.call(t,r)&&!og.hasOwnProperty(r)&&(a[r]=t[r]);var o=arguments.length-2;if(o===1)a.children=n;else if(1>>1,oe=K[pe];if(0>>1;pea(it,H))Ca(et,it)?(K[pe]=et,K[C]=H,pe=C):(K[pe]=it,K[Oe]=H,pe=Oe);else if(Ca(et,H))K[pe]=et,K[C]=H,pe=C;else break e}}return Z}function a(K,Z){var H=K.sortIndex-Z.sortIndex;return H!==0?H:K.id-Z.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;e.unstable_now=function(){return i.now()}}else{var l=Date,o=l.now();e.unstable_now=function(){return l.now()-o}}var c=[],d=[],u=1,h=null,p=3,m=!1,f=!1,x=!1,b=typeof setTimeout=="function"?setTimeout:null,y=typeof clearTimeout=="function"?clearTimeout:null,g=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function v(K){for(var Z=n(d);Z!==null;){if(Z.callback===null)r(d);else if(Z.startTime<=K)r(d),Z.sortIndex=Z.expirationTime,t(c,Z);else break;Z=n(d)}}function N(K){if(x=!1,v(K),!f)if(n(c)!==null)f=!0,k(D);else{var Z=n(d);Z!==null&&_(N,Z.startTime-K)}}function D(K,Z){f=!1,x&&(x=!1,y(w),w=-1),m=!0;var H=p;try{for(v(Z),h=n(c);h!==null&&(!(h.expirationTime>Z)||K&&!z());){var pe=h.callback;if(typeof pe=="function"){h.callback=null,p=h.priorityLevel;var oe=pe(h.expirationTime<=Z);Z=e.unstable_now(),typeof oe=="function"?h.callback=oe:h===n(c)&&r(c),v(Z)}else r(c);h=n(c)}if(h!==null)var Ze=!0;else{var Oe=n(d);Oe!==null&&_(N,Oe.startTime-Z),Ze=!1}return Ze}finally{h=null,p=H,m=!1}}var A=!1,R=null,w=-1,S=5,E=-1;function z(){return!(e.unstable_now()-EK||125pe?(K.sortIndex=H,t(d,K),n(c)===null&&K===n(d)&&(x?(y(w),w=-1):x=!0,_(N,H-pe))):(K.sortIndex=oe,t(c,K),f||m||(f=!0,k(D))),K},e.unstable_shouldYield=z,e.unstable_wrapCallback=function(K){var Z=p;return function(){var H=p;p=Z;try{return K.apply(this,arguments)}finally{p=H}}}})(fg);hg.exports=fg;var pj=hg.exports;/** * @license React * react-dom.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */var xj=j,js=pj;function X(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),bd=Object.prototype.hasOwnProperty,gj=/^[: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]*$/,Nf={},wf={};function yj(e){return bd.call(wf,e)?!0:bd.call(Nf,e)?!1:gj.test(e)?wf[e]=!0:(Nf[e]=!0,!1)}function vj(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function jj(e,t,n,r){if(t===null||typeof t>"u"||vj(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function es(e,t,n,r,a,i,l){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=a,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=i,this.removeEmptyString=l}var Lt={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){Lt[e]=new es(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];Lt[t]=new es(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){Lt[e]=new es(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){Lt[e]=new es(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){Lt[e]=new es(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){Lt[e]=new es(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){Lt[e]=new es(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){Lt[e]=new es(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){Lt[e]=new es(e,5,!1,e.toLowerCase(),null,!1,!1)});var tm=/[\-:]([a-z])/g;function sm(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 t=e.replace(tm,sm);Lt[t]=new es(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(tm,sm);Lt[t]=new es(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(tm,sm);Lt[t]=new es(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){Lt[e]=new es(e,1,!1,e.toLowerCase(),null,!1,!1)});Lt.xlinkHref=new es("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){Lt[e]=new es(e,1,!1,e.toLowerCase(),null,!0,!0)});function nm(e,t,n,r){var a=Lt.hasOwnProperty(t)?Lt[t]:null;(a!==null?a.type!==0:r||!(2o||a[l]!==i[o]){var c=` `+a[l].replace(" at new "," at ");return e.displayName&&c.includes("")&&(c=c.replace("",e.displayName)),c}while(1<=l&&0<=o);break}}}finally{$c=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?vi(e):""}function bj(e){switch(e.tag){case 5:return vi(e.type);case 16:return vi("Lazy");case 13:return vi("Suspense");case 19:return vi("SuspenseList");case 0:case 2:case 15:return e=_c(e.type,!1),e;case 11:return e=_c(e.type.render,!1),e;case 1:return e=_c(e.type,!0),e;default:return""}}function kd(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 la:return"Fragment";case ia:return"Portal";case Nd:return"Profiler";case rm:return"StrictMode";case wd:return"Suspense";case Sd:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case gg:return(e.displayName||"Context")+".Consumer";case xg:return(e._context.displayName||"Context")+".Provider";case am:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case im:return t=e.displayName||null,t!==null?t:kd(e.type)||"Memo";case On:t=e._payload,e=e._init;try{return kd(e(t))}catch{}}return null}function Nj(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return kd(t);case 8:return t===rm?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function mr(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function vg(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function wj(e){var t=vg(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var a=n.get,i=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return a.call(this)},set:function(l){r=""+l,i.call(this,l)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(l){r=""+l},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function $l(e){e._valueTracker||(e._valueTracker=wj(e))}function jg(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=vg(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function wo(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 Cd(e,t){var n=t.checked;return at({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function kf(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=mr(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function bg(e,t){t=t.checked,t!=null&&nm(e,"checked",t,!1)}function Ed(e,t){bg(e,t);var n=mr(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?Dd(e,t.type,n):t.hasOwnProperty("defaultValue")&&Dd(e,t.type,mr(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function Cf(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function Dd(e,t,n){(t!=="number"||wo(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var ji=Array.isArray;function va(e,t,n,r){if(e=e.options,t){t={};for(var a=0;a"+t.valueOf().toString()+"",t=_l.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function zi(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var ki={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},Sj=["Webkit","ms","Moz","O"];Object.keys(ki).forEach(function(e){Sj.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),ki[t]=ki[e]})});function kg(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||ki.hasOwnProperty(e)&&ki[e]?(""+t).trim():t+"px"}function Cg(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,a=kg(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,a):e[n]=a}}var kj=at({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 Md(e,t){if(t){if(kj[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(X(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(X(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(X(61))}if(t.style!=null&&typeof t.style!="object")throw Error(X(62))}}function Td(e,t){if(e.indexOf("-")===-1)return typeof t.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 Fd=null;function lm(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var Id=null,ja=null,ba=null;function Pf(e){if(e=Nl(e)){if(typeof Id!="function")throw Error(X(280));var t=e.stateNode;t&&(t=oc(t),Id(e.stateNode,e.type,t))}}function Eg(e){ja?ba?ba.push(e):ba=[e]:ja=e}function Dg(){if(ja){var e=ja,t=ba;if(ba=ja=null,Pf(e),t)for(e=0;e>>=0,e===0?32:31-(Lj(e)/Oj|0)|0}var Kl=64,Ul=4194304;function bi(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 Eo(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,a=e.suspendedLanes,i=e.pingedLanes,l=n&268435455;if(l!==0){var o=l&~a;o!==0?r=bi(o):(i&=l,i!==0&&(r=bi(i)))}else l=n&~a,l!==0?r=bi(l):i!==0&&(r=bi(i));if(r===0)return 0;if(t!==0&&t!==r&&!(t&a)&&(a=r&-r,i=t&-t,a>=i||a===16&&(i&4194240)!==0))return t;if(r&4&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0n;n++)t.push(e);return t}function jl(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-Bs(t),e[t]=n}function Kj(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=Ei),zf=" ",$f=!1;function Wg(e,t){switch(e){case"keyup":return pb.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Gg(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var oa=!1;function gb(e,t){switch(e){case"compositionend":return Gg(t);case"keypress":return t.which!==32?null:($f=!0,zf);case"textInput":return e=t.data,e===zf&&$f?null:e;default:return null}}function yb(e,t){if(oa)return e==="compositionend"||!pm&&Wg(e,t)?(e=Qg(),lo=mm=Yn=null,oa=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=Bf(n)}}function Yg(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?Yg(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function ey(){for(var e=window,t=wo();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=wo(e.document)}return t}function xm(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function Eb(e){var t=ey(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&Yg(n.ownerDocument.documentElement,n)){if(r!==null&&xm(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var a=n.textContent.length,i=Math.min(r.start,a);r=r.end===void 0?i:Math.min(r.end,a),!e.extend&&i>r&&(a=r,r=i,i=a),a=qf(n,i);var l=qf(n,r);a&&l&&(e.rangeCount!==1||e.anchorNode!==a.node||e.anchorOffset!==a.offset||e.focusNode!==l.node||e.focusOffset!==l.offset)&&(t=t.createRange(),t.setStart(a.node,a.offset),e.removeAllRanges(),i>r?(e.addRange(t),e.extend(l.node,l.offset)):(t.setEnd(l.node,l.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,ca=null,_d=null,Pi=null,Kd=!1;function Vf(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;Kd||ca==null||ca!==wo(r)||(r=ca,"selectionStart"in r&&xm(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),Pi&&qi(Pi,r)||(Pi=r,r=Ao(_d,"onSelect"),0ma||(e.current=Hd[ma],Hd[ma]=null,ma--)}function Qe(e,t){ma++,Hd[ma]=e.current,e.current=t}var hr={},qt=xr(hr),os=xr(!1),Br=hr;function Ba(e,t){var n=e.type.contextTypes;if(!n)return hr;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var a={},i;for(i in n)a[i]=t[i];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=a),a}function cs(e){return e=e.childContextTypes,e!=null}function To(){Ge(os),Ge(qt)}function Xf(e,t,n){if(qt.current!==hr)throw Error(X(168));Qe(qt,t),Qe(os,n)}function cy(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var a in r)if(!(a in t))throw Error(X(108,Nj(e)||"Unknown",a));return at({},n,r)}function Fo(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||hr,Br=qt.current,Qe(qt,e),Qe(os,os.current),!0}function Yf(e,t,n){var r=e.stateNode;if(!r)throw Error(X(169));n?(e=cy(e,t,Br),r.__reactInternalMemoizedMergedChildContext=e,Ge(os),Ge(qt),Qe(qt,e)):Ge(os),Qe(os,n)}var fn=null,cc=!1,ed=!1;function dy(e){fn===null?fn=[e]:fn.push(e)}function $b(e){cc=!0,dy(e)}function gr(){if(!ed&&fn!==null){ed=!0;var e=0,t=Ue;try{var n=fn;for(Ue=1;e>=l,a-=l,jn=1<<32-Bs(t)+a|n<w?(S=R,R=null):S=R.sibling;var E=p(y,R,v[w],N);if(E===null){R===null&&(R=S);break}e&&R&&E.alternate===null&&t(y,R),g=i(E,g,w),A===null?D=E:A.sibling=E,A=E,R=S}if(w===v.length)return n(y,R),Xe&&br(y,w),D;if(R===null){for(;ww?(S=R,R=null):S=R.sibling;var z=p(y,R,E.value,N);if(z===null){R===null&&(R=S);break}e&&R&&z.alternate===null&&t(y,R),g=i(z,g,w),A===null?D=z:A.sibling=z,A=z,R=S}if(E.done)return n(y,R),Xe&&br(y,w),D;if(R===null){for(;!E.done;w++,E=v.next())E=h(y,E.value,N),E!==null&&(g=i(E,g,w),A===null?D=E:A.sibling=E,A=E);return Xe&&br(y,w),D}for(R=r(y,R);!E.done;w++,E=v.next())E=m(R,y,w,E.value,N),E!==null&&(e&&E.alternate!==null&&R.delete(E.key===null?w:E.key),g=i(E,g,w),A===null?D=E:A.sibling=E,A=E);return e&&R.forEach(function(I){return t(y,I)}),Xe&&br(y,w),D}function b(y,g,v,N){if(typeof v=="object"&&v!==null&&v.type===la&&v.key===null&&(v=v.props.children),typeof v=="object"&&v!==null){switch(v.$$typeof){case zl:e:{for(var D=v.key,A=g;A!==null;){if(A.key===D){if(D=v.type,D===la){if(A.tag===7){n(y,A.sibling),g=a(A,v.props.children),g.return=y,y=g;break e}}else if(A.elementType===D||typeof D=="object"&&D!==null&&D.$$typeof===On&&sp(D)===A.type){n(y,A.sibling),g=a(A,v.props),g.ref=fi(y,A,v),g.return=y,y=g;break e}n(y,A);break}else t(y,A);A=A.sibling}v.type===la?(g=_r(v.props.children,y.mode,N,v.key),g.return=y,y=g):(N=xo(v.type,v.key,v.props,null,y.mode,N),N.ref=fi(y,g,v),N.return=y,y=N)}return l(y);case ia:e:{for(A=v.key;g!==null;){if(g.key===A)if(g.tag===4&&g.stateNode.containerInfo===v.containerInfo&&g.stateNode.implementation===v.implementation){n(y,g.sibling),g=a(g,v.children||[]),g.return=y,y=g;break e}else{n(y,g);break}else t(y,g);g=g.sibling}g=od(v,y.mode,N),g.return=y,y=g}return l(y);case On:return A=v._init,b(y,g,A(v._payload),N)}if(ji(v))return f(y,g,v,N);if(ci(v))return x(y,g,v,N);Gl(y,v)}return typeof v=="string"&&v!==""||typeof v=="number"?(v=""+v,g!==null&&g.tag===6?(n(y,g.sibling),g=a(g,v),g.return=y,y=g):(n(y,g),g=ld(v,y.mode,N),g.return=y,y=g),l(y)):n(y,g)}return b}var Va=fy(!0),py=fy(!1),Lo=xr(null),Oo=null,pa=null,jm=null;function bm(){jm=pa=Oo=null}function Nm(e){var t=Lo.current;Ge(Lo),e._currentValue=t}function Zd(e,t,n){for(;e!==null;){var r=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,r!==null&&(r.childLanes|=t)):r!==null&&(r.childLanes&t)!==t&&(r.childLanes|=t),e===n)break;e=e.return}}function wa(e,t){Oo=e,jm=pa=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(ls=!0),e.firstContext=null)}function Ts(e){var t=e._currentValue;if(jm!==e)if(e={context:e,memoizedValue:t,next:null},pa===null){if(Oo===null)throw Error(X(308));pa=e,Oo.dependencies={lanes:0,firstContext:e}}else pa=pa.next=e;return t}var kr=null;function wm(e){kr===null?kr=[e]:kr.push(e)}function xy(e,t,n,r){var a=t.interleaved;return a===null?(n.next=n,wm(t)):(n.next=a.next,a.next=n),t.interleaved=n,En(e,r)}function En(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var zn=!1;function Sm(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function gy(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function wn(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function ir(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,Me&2){var a=r.pending;return a===null?t.next=t:(t.next=a.next,a.next=t),r.pending=t,En(e,n)}return a=r.interleaved,a===null?(t.next=t,wm(r)):(t.next=a.next,a.next=t),r.interleaved=t,En(e,n)}function co(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,(n&4194240)!==0)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,cm(e,n)}}function np(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var a=null,i=null;if(n=n.firstBaseUpdate,n!==null){do{var l={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};i===null?a=i=l:i=i.next=l,n=n.next}while(n!==null);i===null?a=i=t:i=i.next=t}else a=i=t;n={baseState:r.baseState,firstBaseUpdate:a,lastBaseUpdate:i,shared:r.shared,effects:r.effects},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function zo(e,t,n,r){var a=e.updateQueue;zn=!1;var i=a.firstBaseUpdate,l=a.lastBaseUpdate,o=a.shared.pending;if(o!==null){a.shared.pending=null;var c=o,d=c.next;c.next=null,l===null?i=d:l.next=d,l=c;var u=e.alternate;u!==null&&(u=u.updateQueue,o=u.lastBaseUpdate,o!==l&&(o===null?u.firstBaseUpdate=d:o.next=d,u.lastBaseUpdate=c))}if(i!==null){var h=a.baseState;l=0,u=d=c=null,o=i;do{var p=o.lane,m=o.eventTime;if((r&p)===p){u!==null&&(u=u.next={eventTime:m,lane:0,tag:o.tag,payload:o.payload,callback:o.callback,next:null});e:{var f=e,x=o;switch(p=t,m=n,x.tag){case 1:if(f=x.payload,typeof f=="function"){h=f.call(m,h,p);break e}h=f;break e;case 3:f.flags=f.flags&-65537|128;case 0:if(f=x.payload,p=typeof f=="function"?f.call(m,h,p):f,p==null)break e;h=at({},h,p);break e;case 2:zn=!0}}o.callback!==null&&o.lane!==0&&(e.flags|=64,p=a.effects,p===null?a.effects=[o]:p.push(o))}else m={eventTime:m,lane:p,tag:o.tag,payload:o.payload,callback:o.callback,next:null},u===null?(d=u=m,c=h):u=u.next=m,l|=p;if(o=o.next,o===null){if(o=a.shared.pending,o===null)break;p=o,o=p.next,p.next=null,a.lastBaseUpdate=p,a.shared.pending=null}}while(!0);if(u===null&&(c=h),a.baseState=c,a.firstBaseUpdate=d,a.lastBaseUpdate=u,t=a.shared.interleaved,t!==null){a=t;do l|=a.lane,a=a.next;while(a!==t)}else i===null&&(a.shared.lanes=0);Qr|=l,e.lanes=l,e.memoizedState=h}}function rp(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var r=sd.transition;sd.transition={};try{e(!1),t()}finally{Ue=n,sd.transition=r}}function Iy(){return Fs().memoizedState}function Bb(e,t,n){var r=or(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},Ry(e))Ly(t,n);else if(n=xy(e,t,n,r),n!==null){var a=Xt();qs(n,e,r,a),Oy(n,t,r)}}function qb(e,t,n){var r=or(e),a={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(Ry(e))Ly(t,a);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=t.lastRenderedReducer,i!==null))try{var l=t.lastRenderedState,o=i(l,n);if(a.hasEagerState=!0,a.eagerState=o,Vs(o,l)){var c=t.interleaved;c===null?(a.next=a,wm(t)):(a.next=c.next,c.next=a),t.interleaved=a;return}}catch{}finally{}n=xy(e,t,a,r),n!==null&&(a=Xt(),qs(n,e,r,a),Oy(n,t,r))}}function Ry(e){var t=e.alternate;return e===nt||t!==null&&t===nt}function Ly(e,t){Ai=_o=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function Oy(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,cm(e,n)}}var Ko={readContext:Ts,useCallback:$t,useContext:$t,useEffect:$t,useImperativeHandle:$t,useInsertionEffect:$t,useLayoutEffect:$t,useMemo:$t,useReducer:$t,useRef:$t,useState:$t,useDebugValue:$t,useDeferredValue:$t,useTransition:$t,useMutableSource:$t,useSyncExternalStore:$t,useId:$t,unstable_isNewReconciler:!1},Vb={readContext:Ts,useCallback:function(e,t){return Zs().memoizedState=[e,t===void 0?null:t],e},useContext:Ts,useEffect:ip,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,mo(4194308,4,Py.bind(null,t,e),n)},useLayoutEffect:function(e,t){return mo(4194308,4,e,t)},useInsertionEffect:function(e,t){return mo(4,2,e,t)},useMemo:function(e,t){var n=Zs();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=Zs();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=Bb.bind(null,nt,e),[r.memoizedState,e]},useRef:function(e){var t=Zs();return e={current:e},t.memoizedState=e},useState:ap,useDebugValue:Tm,useDeferredValue:function(e){return Zs().memoizedState=e},useTransition:function(){var e=ap(!1),t=e[0];return e=Ub.bind(null,e[1]),Zs().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=nt,a=Zs();if(Xe){if(n===void 0)throw Error(X(407));n=n()}else{if(n=t(),Pt===null)throw Error(X(349));Vr&30||by(r,t,n)}a.memoizedState=n;var i={value:n,getSnapshot:t};return a.queue=i,ip(wy.bind(null,r,i,e),[e]),r.flags|=2048,Xi(9,Ny.bind(null,r,i,n,t),void 0,null),n},useId:function(){var e=Zs(),t=Pt.identifierPrefix;if(Xe){var n=bn,r=jn;n=(r&~(1<<32-Bs(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=Zi++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=l.createElement(n,{is:r.is}):(e=l.createElement(n),n==="select"&&(l=e,r.multiple?l.multiple=!0:r.size&&(l.size=r.size))):e=l.createElementNS(e,n),e[tn]=t,e[Hi]=r,Hy(e,t,!1,!1),t.stateNode=e;e:{switch(l=Td(n,r),n){case"dialog":We("cancel",e),We("close",e),a=r;break;case"iframe":case"object":case"embed":We("load",e),a=r;break;case"video":case"audio":for(a=0;aWa&&(t.flags|=128,r=!0,pi(i,!1),t.lanes=4194304)}else{if(!r)if(e=$o(l),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),pi(i,!0),i.tail===null&&i.tailMode==="hidden"&&!l.alternate&&!Xe)return _t(t),null}else 2*pt()-i.renderingStartTime>Wa&&n!==1073741824&&(t.flags|=128,r=!0,pi(i,!1),t.lanes=4194304);i.isBackwards?(l.sibling=t.child,t.child=l):(n=i.last,n!==null?n.sibling=l:t.child=l,i.last=l)}return i.tail!==null?(t=i.tail,i.rendering=t,i.tail=t.sibling,i.renderingStartTime=pt(),t.sibling=null,n=st.current,Qe(st,r?n&1|2:n&1),t):(_t(t),null);case 22:case 23:return zm(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?ps&1073741824&&(_t(t),t.subtreeFlags&6&&(t.flags|=8192)):_t(t),null;case 24:return null;case 25:return null}throw Error(X(156,t.tag))}function Yb(e,t){switch(ym(t),t.tag){case 1:return cs(t.type)&&To(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Qa(),Ge(os),Ge(qt),Em(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Cm(t),null;case 13:if(Ge(st),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(X(340));qa()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return Ge(st),null;case 4:return Qa(),null;case 10:return Nm(t.type._context),null;case 22:case 23:return zm(),null;case 24:return null;default:return null}}var Jl=!1,Ut=!1,eN=typeof WeakSet=="function"?WeakSet:Set,ue=null;function xa(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){dt(e,t,r)}else n.current=null}function au(e,t,n){try{n()}catch(r){dt(e,t,r)}}var gp=!1;function tN(e,t){if(Ud=Do,e=ey(),xm(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var a=r.anchorOffset,i=r.focusNode;r=r.focusOffset;try{n.nodeType,i.nodeType}catch{n=null;break e}var l=0,o=-1,c=-1,d=0,u=0,h=e,p=null;t:for(;;){for(var m;h!==n||a!==0&&h.nodeType!==3||(o=l+a),h!==i||r!==0&&h.nodeType!==3||(c=l+r),h.nodeType===3&&(l+=h.nodeValue.length),(m=h.firstChild)!==null;)p=h,h=m;for(;;){if(h===e)break t;if(p===n&&++d===a&&(o=l),p===i&&++u===r&&(c=l),(m=h.nextSibling)!==null)break;h=p,p=h.parentNode}h=m}n=o===-1||c===-1?null:{start:o,end:c}}else n=null}n=n||{start:0,end:0}}else n=null;for(Bd={focusedElem:e,selectionRange:n},Do=!1,ue=t;ue!==null;)if(t=ue,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,ue=e;else for(;ue!==null;){t=ue;try{var f=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(f!==null){var x=f.memoizedProps,b=f.memoizedState,y=t.stateNode,g=y.getSnapshotBeforeUpdate(t.elementType===t.type?x:Ls(t.type,x),b);y.__reactInternalSnapshotBeforeUpdate=g}break;case 3:var v=t.stateNode.containerInfo;v.nodeType===1?v.textContent="":v.nodeType===9&&v.documentElement&&v.removeChild(v.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(X(163))}}catch(N){dt(t,t.return,N)}if(e=t.sibling,e!==null){e.return=t.return,ue=e;break}ue=t.return}return f=gp,gp=!1,f}function Mi(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var a=r=r.next;do{if((a.tag&e)===e){var i=a.destroy;a.destroy=void 0,i!==void 0&&au(t,n,i)}a=a.next}while(a!==r)}}function mc(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function iu(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function Zy(e){var t=e.alternate;t!==null&&(e.alternate=null,Zy(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[tn],delete t[Hi],delete t[Qd],delete t[Ob],delete t[zb])),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 Jy(e){return e.tag===5||e.tag===3||e.tag===4}function yp(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||Jy(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 lu(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=Mo));else if(r!==4&&(e=e.child,e!==null))for(lu(e,t,n),e=e.sibling;e!==null;)lu(e,t,n),e=e.sibling}function ou(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(ou(e,t,n),e=e.sibling;e!==null;)ou(e,t,n),e=e.sibling}var Mt=null,$s=!1;function Rn(e,t,n){for(n=n.child;n!==null;)Xy(e,t,n),n=n.sibling}function Xy(e,t,n){if(rn&&typeof rn.onCommitFiberUnmount=="function")try{rn.onCommitFiberUnmount(rc,n)}catch{}switch(n.tag){case 5:Ut||xa(n,t);case 6:var r=Mt,a=$s;Mt=null,Rn(e,t,n),Mt=r,$s=a,Mt!==null&&($s?(e=Mt,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):Mt.removeChild(n.stateNode));break;case 18:Mt!==null&&($s?(e=Mt,n=n.stateNode,e.nodeType===8?Yc(e.parentNode,n):e.nodeType===1&&Yc(e,n),Ui(e)):Yc(Mt,n.stateNode));break;case 4:r=Mt,a=$s,Mt=n.stateNode.containerInfo,$s=!0,Rn(e,t,n),Mt=r,$s=a;break;case 0:case 11:case 14:case 15:if(!Ut&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){a=r=r.next;do{var i=a,l=i.destroy;i=i.tag,l!==void 0&&(i&2||i&4)&&au(n,t,l),a=a.next}while(a!==r)}Rn(e,t,n);break;case 1:if(!Ut&&(xa(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(o){dt(n,t,o)}Rn(e,t,n);break;case 21:Rn(e,t,n);break;case 22:n.mode&1?(Ut=(r=Ut)||n.memoizedState!==null,Rn(e,t,n),Ut=r):Rn(e,t,n);break;default:Rn(e,t,n)}}function vp(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new eN),t.forEach(function(r){var a=dN.bind(null,e,r);n.has(r)||(n.add(r),r.then(a,a))})}}function Rs(e,t){var n=t.deletions;if(n!==null)for(var r=0;ra&&(a=l),r&=~i}if(r=a,r=pt()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*nN(r/1960))-r,10e?16:e,er===null)var r=!1;else{if(e=er,er=null,qo=0,Me&6)throw Error(X(331));var a=Me;for(Me|=4,ue=e.current;ue!==null;){var i=ue,l=i.child;if(ue.flags&16){var o=i.deletions;if(o!==null){for(var c=0;cpt()-Lm?$r(e,0):Rm|=n),ds(e,t)}function i0(e,t){t===0&&(e.mode&1?(t=Ul,Ul<<=1,!(Ul&130023424)&&(Ul=4194304)):t=1);var n=Xt();e=En(e,t),e!==null&&(jl(e,t,n),ds(e,n))}function cN(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),i0(e,n)}function dN(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,a=e.memoizedState;a!==null&&(n=a.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(X(314))}r!==null&&r.delete(t),i0(e,n)}var l0;l0=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||os.current)ls=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return ls=!1,Jb(e,t,n);ls=!!(e.flags&131072)}else ls=!1,Xe&&t.flags&1048576&&uy(t,Ro,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;ho(e,t),e=t.pendingProps;var a=Ba(t,qt.current);wa(t,n),a=Pm(null,t,r,e,a,n);var i=Am();return t.flags|=1,typeof a=="object"&&a!==null&&typeof a.render=="function"&&a.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,cs(r)?(i=!0,Fo(t)):i=!1,t.memoizedState=a.state!==null&&a.state!==void 0?a.state:null,Sm(t),a.updater=uc,t.stateNode=a,a._reactInternals=t,Xd(t,r,e,n),t=tu(null,t,r,!0,i,n)):(t.tag=0,Xe&&i&&gm(t),Jt(null,t,a,n),t=t.child),t;case 16:r=t.elementType;e:{switch(ho(e,t),e=t.pendingProps,a=r._init,r=a(r._payload),t.type=r,a=t.tag=mN(r),e=Ls(r,e),a){case 0:t=eu(null,t,r,e,n);break e;case 1:t=fp(null,t,r,e,n);break e;case 11:t=mp(null,t,r,e,n);break e;case 14:t=hp(null,t,r,Ls(r.type,e),n);break e}throw Error(X(306,r,""))}return t;case 0:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:Ls(r,a),eu(e,t,r,a,n);case 1:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:Ls(r,a),fp(e,t,r,a,n);case 3:e:{if(qy(t),e===null)throw Error(X(387));r=t.pendingProps,i=t.memoizedState,a=i.element,gy(e,t),zo(t,r,null,n);var l=t.memoizedState;if(r=l.element,i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:l.cache,pendingSuspenseBoundaries:l.pendingSuspenseBoundaries,transitions:l.transitions},t.updateQueue.baseState=i,t.memoizedState=i,t.flags&256){a=Ha(Error(X(423)),t),t=pp(e,t,r,n,a);break e}else if(r!==a){a=Ha(Error(X(424)),t),t=pp(e,t,r,n,a);break e}else for(ys=ar(t.stateNode.containerInfo.firstChild),vs=t,Xe=!0,_s=null,n=py(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(qa(),r===a){t=Dn(e,t,n);break e}Jt(e,t,r,n)}t=t.child}return t;case 5:return yy(t),e===null&&Gd(t),r=t.type,a=t.pendingProps,i=e!==null?e.memoizedProps:null,l=a.children,qd(r,a)?l=null:i!==null&&qd(r,i)&&(t.flags|=32),By(e,t),Jt(e,t,l,n),t.child;case 6:return e===null&&Gd(t),null;case 13:return Vy(e,t,n);case 4:return km(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=Va(t,null,r,n):Jt(e,t,r,n),t.child;case 11:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:Ls(r,a),mp(e,t,r,a,n);case 7:return Jt(e,t,t.pendingProps,n),t.child;case 8:return Jt(e,t,t.pendingProps.children,n),t.child;case 12:return Jt(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,a=t.pendingProps,i=t.memoizedProps,l=a.value,Qe(Lo,r._currentValue),r._currentValue=l,i!==null)if(Vs(i.value,l)){if(i.children===a.children&&!os.current){t=Dn(e,t,n);break e}}else for(i=t.child,i!==null&&(i.return=t);i!==null;){var o=i.dependencies;if(o!==null){l=i.child;for(var c=o.firstContext;c!==null;){if(c.context===r){if(i.tag===1){c=wn(-1,n&-n),c.tag=2;var d=i.updateQueue;if(d!==null){d=d.shared;var u=d.pending;u===null?c.next=c:(c.next=u.next,u.next=c),d.pending=c}}i.lanes|=n,c=i.alternate,c!==null&&(c.lanes|=n),Zd(i.return,n,t),o.lanes|=n;break}c=c.next}}else if(i.tag===10)l=i.type===t.type?null:i.child;else if(i.tag===18){if(l=i.return,l===null)throw Error(X(341));l.lanes|=n,o=l.alternate,o!==null&&(o.lanes|=n),Zd(l,n,t),l=i.sibling}else l=i.child;if(l!==null)l.return=i;else for(l=i;l!==null;){if(l===t){l=null;break}if(i=l.sibling,i!==null){i.return=l.return,l=i;break}l=l.return}i=l}Jt(e,t,a.children,n),t=t.child}return t;case 9:return a=t.type,r=t.pendingProps.children,wa(t,n),a=Ts(a),r=r(a),t.flags|=1,Jt(e,t,r,n),t.child;case 14:return r=t.type,a=Ls(r,t.pendingProps),a=Ls(r.type,a),hp(e,t,r,a,n);case 15:return Ky(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:Ls(r,a),ho(e,t),t.tag=1,cs(r)?(e=!0,Fo(t)):e=!1,wa(t,n),zy(t,r,a),Xd(t,r,a,n),tu(null,t,r,!0,e,n);case 19:return Qy(e,t,n);case 22:return Uy(e,t,n)}throw Error(X(156,t.tag))};function o0(e,t){return Rg(e,t)}function uN(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Ds(e,t,n,r){return new uN(e,t,n,r)}function _m(e){return e=e.prototype,!(!e||!e.isReactComponent)}function mN(e){if(typeof e=="function")return _m(e)?1:0;if(e!=null){if(e=e.$$typeof,e===am)return 11;if(e===im)return 14}return 2}function cr(e,t){var n=e.alternate;return n===null?(n=Ds(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function xo(e,t,n,r,a,i){var l=2;if(r=e,typeof e=="function")_m(e)&&(l=1);else if(typeof e=="string")l=5;else e:switch(e){case la:return _r(n.children,a,i,t);case rm:l=8,a|=8;break;case Nd:return e=Ds(12,n,t,a|2),e.elementType=Nd,e.lanes=i,e;case wd:return e=Ds(13,n,t,a),e.elementType=wd,e.lanes=i,e;case Sd:return e=Ds(19,n,t,a),e.elementType=Sd,e.lanes=i,e;case yg:return fc(n,a,i,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case xg:l=10;break e;case gg:l=9;break e;case am:l=11;break e;case im:l=14;break e;case On:l=16,r=null;break e}throw Error(X(130,e==null?e:typeof e,""))}return t=Ds(l,n,t,a),t.elementType=e,t.type=r,t.lanes=i,t}function _r(e,t,n,r){return e=Ds(7,e,r,t),e.lanes=n,e}function fc(e,t,n,r){return e=Ds(22,e,r,t),e.elementType=yg,e.lanes=n,e.stateNode={isHidden:!1},e}function ld(e,t,n){return e=Ds(6,e,null,t),e.lanes=n,e}function od(e,t,n){return t=Ds(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function hN(e,t,n,r,a){this.tag=t,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=Uc(0),this.expirationTimes=Uc(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Uc(0),this.identifierPrefix=r,this.onRecoverableError=a,this.mutableSourceEagerHydrationData=null}function Km(e,t,n,r,a,i,l,o,c){return e=new hN(e,t,n,o,c),t===1?(t=1,i===!0&&(t|=8)):t=0,i=Ds(3,null,null,t),e.current=i,i.stateNode=e,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},Sm(i),e}function fN(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(m0)}catch(e){console.error(e)}}m0(),mg.exports=bs;var vN=mg.exports,Ep=vN;jd.createRoot=Ep.createRoot,jd.hydrateRoot=Ep.hydrateRoot;/** * @remix-run/router v1.23.2 * * Copyright (c) Remix Software Inc. * * This source code is licensed under the MIT license found in the * LICENSE.md file in the root directory of this source tree. * * @license MIT */function el(){return el=Object.assign?Object.assign.bind():function(e){for(var t=1;t"u")throw new Error(t)}function Vm(e,t){if(!e){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function bN(){return Math.random().toString(36).substr(2,8)}function Pp(e,t){return{usr:e.state,key:e.key,idx:t}}function hu(e,t,n,r){return n===void 0&&(n=null),el({pathname:typeof e=="string"?e:e.pathname,search:"",hash:""},typeof t=="string"?ti(t):t,{state:n,key:t&&t.key||r||bN()})}function Ho(e){let{pathname:t="/",search:n="",hash:r=""}=e;return n&&n!=="?"&&(t+=n.charAt(0)==="?"?n:"?"+n),r&&r!=="#"&&(t+=r.charAt(0)==="#"?r:"#"+r),t}function ti(e){let t={};if(e){let n=e.indexOf("#");n>=0&&(t.hash=e.substr(n),e=e.substr(0,n));let r=e.indexOf("?");r>=0&&(t.search=e.substr(r),e=e.substr(0,r)),e&&(t.pathname=e)}return t}function NN(e,t,n,r){r===void 0&&(r={});let{window:a=document.defaultView,v5Compat:i=!1}=r,l=a.history,o=tr.Pop,c=null,d=u();d==null&&(d=0,l.replaceState(el({},l.state,{idx:d}),""));function u(){return(l.state||{idx:null}).idx}function h(){o=tr.Pop;let b=u(),y=b==null?null:b-d;d=b,c&&c({action:o,location:x.location,delta:y})}function p(b,y){o=tr.Push;let g=hu(x.location,b,y);d=u()+1;let v=Pp(g,d),N=x.createHref(g);try{l.pushState(v,"",N)}catch(D){if(D instanceof DOMException&&D.name==="DataCloneError")throw D;a.location.assign(N)}i&&c&&c({action:o,location:x.location,delta:1})}function m(b,y){o=tr.Replace;let g=hu(x.location,b,y);d=u();let v=Pp(g,d),N=x.createHref(g);l.replaceState(v,"",N),i&&c&&c({action:o,location:x.location,delta:0})}function f(b){let y=a.location.origin!=="null"?a.location.origin:a.location.href,g=typeof b=="string"?b:Ho(b);return g=g.replace(/ $/,"%20"),rt(y,"No window.location.(origin|href) available to create URL for href: "+g),new URL(g,y)}let x={get action(){return o},get location(){return e(a,l)},listen(b){if(c)throw new Error("A history only accepts one active listener");return a.addEventListener(Dp,h),c=b,()=>{a.removeEventListener(Dp,h),c=null}},createHref(b){return t(a,b)},createURL:f,encodeLocation(b){let y=f(b);return{pathname:y.pathname,search:y.search,hash:y.hash}},push:p,replace:m,go(b){return l.go(b)}};return x}var Ap;(function(e){e.data="data",e.deferred="deferred",e.redirect="redirect",e.error="error"})(Ap||(Ap={}));function wN(e,t,n){return n===void 0&&(n="/"),SN(e,t,n)}function SN(e,t,n,r){let a=typeof t=="string"?ti(t):t,i=Ga(a.pathname||"/",n);if(i==null)return null;let l=h0(e);kN(l);let o=null;for(let c=0;o==null&&c{let c={relativePath:o===void 0?i.path||"":o,caseSensitive:i.caseSensitive===!0,childrenIndex:l,route:i};c.relativePath.startsWith("/")&&(rt(c.relativePath.startsWith(r),'Absolute route path "'+c.relativePath+'" nested under path '+('"'+r+'" is not valid. An absolute child route path ')+"must start with the combined path of all its parent routes."),c.relativePath=c.relativePath.slice(r.length));let d=dr([r,c.relativePath]),u=n.concat(c);i.children&&i.children.length>0&&(rt(i.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+d+'".')),h0(i.children,t,u,d)),!(i.path==null&&!i.index)&&t.push({path:d,score:TN(d,i.index),routesMeta:u})};return e.forEach((i,l)=>{var o;if(i.path===""||!((o=i.path)!=null&&o.includes("?")))a(i,l);else for(let c of f0(i.path))a(i,l,c)}),t}function f0(e){let t=e.split("/");if(t.length===0)return[];let[n,...r]=t,a=n.endsWith("?"),i=n.replace(/\?$/,"");if(r.length===0)return a?[i,""]:[i];let l=f0(r.join("/")),o=[];return o.push(...l.map(c=>c===""?i:[i,c].join("/"))),a&&o.push(...l),o.map(c=>e.startsWith("/")&&c===""?"/":c)}function kN(e){e.sort((t,n)=>t.score!==n.score?n.score-t.score:FN(t.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}const CN=/^:[\w-]+$/,EN=3,DN=2,PN=1,AN=10,MN=-2,Mp=e=>e==="*";function TN(e,t){let n=e.split("/"),r=n.length;return n.some(Mp)&&(r+=MN),t&&(r+=DN),n.filter(a=>!Mp(a)).reduce((a,i)=>a+(CN.test(i)?EN:i===""?PN:AN),r)}function FN(e,t){return e.length===t.length&&e.slice(0,-1).every((r,a)=>r===t[a])?e[e.length-1]-t[t.length-1]:0}function IN(e,t,n){let{routesMeta:r}=e,a={},i="/",l=[];for(let o=0;o{let{paramName:p,isOptional:m}=u;if(p==="*"){let x=o[h]||"";l=i.slice(0,i.length-x.length).replace(/(.)\/+$/,"$1")}const f=o[h];return m&&!f?d[p]=void 0:d[p]=(f||"").replace(/%2F/g,"/"),d},{}),pathname:i,pathnameBase:l,pattern:e}}function RN(e,t,n){t===void 0&&(t=!1),n===void 0&&(n=!0),Vm(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 r=[],a="^"+e.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(l,o,c)=>(r.push({paramName:o,isOptional:c!=null}),c?"/?([^\\/]+)?":"/([^\\/]+)"));return e.endsWith("*")?(r.push({paramName:"*"}),a+=e==="*"||e==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):n?a+="\\/*$":e!==""&&e!=="/"&&(a+="(?:(?=\\/|$))"),[new RegExp(a,t?void 0:"i"),r]}function LN(e){try{return e.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return Vm(!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 ("+t+").")),e}}function Ga(e,t){if(t==="/")return e;if(!e.toLowerCase().startsWith(t.toLowerCase()))return null;let n=t.endsWith("/")?t.length-1:t.length,r=e.charAt(n);return r&&r!=="/"?null:e.slice(n)||"/"}const ON=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,zN=e=>ON.test(e);function $N(e,t){t===void 0&&(t="/");let{pathname:n,search:r="",hash:a=""}=typeof e=="string"?ti(e):e,i;if(n)if(zN(n))i=n;else{if(n.includes("//")){let l=n;n=n.replace(/\/\/+/g,"/"),Vm(!1,"Pathnames cannot have embedded double slashes - normalizing "+(l+" -> "+n))}n.startsWith("/")?i=Tp(n.substring(1),"/"):i=Tp(n,t)}else i=t;return{pathname:i,search:UN(r),hash:BN(a)}}function Tp(e,t){let n=t.replace(/\/+$/,"").split("/");return e.split("/").forEach(a=>{a===".."?n.length>1&&n.pop():a!=="."&&n.push(a)}),n.length>1?n.join("/"):"/"}function cd(e,t,n,r){return"Cannot include a '"+e+"' character in a manually specified "+("`to."+t+"` field ["+JSON.stringify(r)+"]. Please separate it out to the ")+("`to."+n+"` field. Alternatively you may provide the full path as ")+'a string in and the router will parse it for you.'}function _N(e){return e.filter((t,n)=>n===0||t.route.path&&t.route.path.length>0)}function Qm(e,t){let n=_N(e);return t?n.map((r,a)=>a===n.length-1?r.pathname:r.pathnameBase):n.map(r=>r.pathnameBase)}function Hm(e,t,n,r){r===void 0&&(r=!1);let a;typeof e=="string"?a=ti(e):(a=el({},e),rt(!a.pathname||!a.pathname.includes("?"),cd("?","pathname","search",a)),rt(!a.pathname||!a.pathname.includes("#"),cd("#","pathname","hash",a)),rt(!a.search||!a.search.includes("#"),cd("#","search","hash",a)));let i=e===""||a.pathname==="",l=i?"/":a.pathname,o;if(l==null)o=n;else{let h=t.length-1;if(!r&&l.startsWith("..")){let p=l.split("/");for(;p[0]==="..";)p.shift(),h-=1;a.pathname=p.join("/")}o=h>=0?t[h]:"/"}let c=$N(a,o),d=l&&l!=="/"&&l.endsWith("/"),u=(i||l===".")&&n.endsWith("/");return!c.pathname.endsWith("/")&&(d||u)&&(c.pathname+="/"),c}const dr=e=>e.join("/").replace(/\/\/+/g,"/"),KN=e=>e.replace(/\/+$/,"").replace(/^\/*/,"/"),UN=e=>!e||e==="?"?"":e.startsWith("?")?e:"?"+e,BN=e=>!e||e==="#"?"":e.startsWith("#")?e:"#"+e;function qN(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.internal=="boolean"&&"data"in e}const p0=["post","put","patch","delete"];new Set(p0);const VN=["get",...p0];new Set(VN);/** * React Router v6.30.3 * * Copyright (c) Remix Software Inc. * * This source code is licensed under the MIT license found in the * LICENSE.md file in the root directory of this source tree. * * @license MIT */function tl(){return tl=Object.assign?Object.assign.bind():function(e){for(var t=1;t{o.current=!0}),j.useCallback(function(d,u){if(u===void 0&&(u={}),!o.current)return;if(typeof d=="number"){r.go(d);return}let h=Hm(d,JSON.parse(l),i,u.relative==="path");e==null&&t!=="/"&&(h.pathname=h.pathname==="/"?t:dr([t,h.pathname])),(u.replace?r.replace:r.push)(h,u.state,u)},[t,r,l,i,e])}const WN=j.createContext(null);function GN(e){let t=j.useContext(on).outlet;return t&&j.createElement(WN.Provider,{value:e},t)}function bc(){let{matches:e}=j.useContext(on),t=e[e.length-1];return t?t.params:{}}function Nc(e,t){let{relative:n}=t===void 0?{}:t,{future:r}=j.useContext(Tn),{matches:a}=j.useContext(on),{pathname:i}=Fn(),l=JSON.stringify(Qm(a,r.v7_relativeSplatPath));return j.useMemo(()=>Hm(e,JSON.parse(l),i,n==="path"),[e,l,i,n])}function ZN(e,t){return JN(e,t)}function JN(e,t,n,r){si()||rt(!1);let{navigator:a}=j.useContext(Tn),{matches:i}=j.useContext(on),l=i[i.length-1],o=l?l.params:{};l&&l.pathname;let c=l?l.pathnameBase:"/";l&&l.route;let d=Fn(),u;if(t){var h;let b=typeof t=="string"?ti(t):t;c==="/"||(h=b.pathname)!=null&&h.startsWith(c)||rt(!1),u=b}else u=d;let p=u.pathname||"/",m=p;if(c!=="/"){let b=c.replace(/^\//,"").split("/");m="/"+p.replace(/^\//,"").split("/").slice(b.length).join("/")}let f=wN(e,{pathname:m}),x=sw(f&&f.map(b=>Object.assign({},b,{params:Object.assign({},o,b.params),pathname:dr([c,a.encodeLocation?a.encodeLocation(b.pathname).pathname:b.pathname]),pathnameBase:b.pathnameBase==="/"?c:dr([c,a.encodeLocation?a.encodeLocation(b.pathnameBase).pathname:b.pathnameBase])})),i,n,r);return t&&x?j.createElement(jc.Provider,{value:{location:tl({pathname:"/",search:"",hash:"",state:null,key:"default"},u),navigationType:tr.Pop}},x):x}function XN(){let e=iw(),t=qN(e)?e.status+" "+e.statusText:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null,a={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return j.createElement(j.Fragment,null,j.createElement("h2",null,"Unexpected Application Error!"),j.createElement("h3",{style:{fontStyle:"italic"}},t),n?j.createElement("pre",{style:a},n):null,null)}const YN=j.createElement(XN,null);class ew extends j.Component{constructor(t){super(t),this.state={location:t.location,revalidation:t.revalidation,error:t.error}}static getDerivedStateFromError(t){return{error:t}}static getDerivedStateFromProps(t,n){return n.location!==t.location||n.revalidation!=="idle"&&t.revalidation==="idle"?{error:t.error,location:t.location,revalidation:t.revalidation}:{error:t.error!==void 0?t.error:n.error,location:n.location,revalidation:t.revalidation||n.revalidation}}componentDidCatch(t,n){console.error("React Router caught the following error during render",t,n)}render(){return this.state.error!==void 0?j.createElement(on.Provider,{value:this.props.routeContext},j.createElement(g0.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function tw(e){let{routeContext:t,match:n,children:r}=e,a=j.useContext(vc);return a&&a.static&&a.staticContext&&(n.route.errorElement||n.route.ErrorBoundary)&&(a.staticContext._deepestRenderedBoundaryId=n.route.id),j.createElement(on.Provider,{value:t},r)}function sw(e,t,n,r){var a;if(t===void 0&&(t=[]),n===void 0&&(n=null),r===void 0&&(r=null),e==null){var i;if(!n)return null;if(n.errors)e=n.matches;else if((i=r)!=null&&i.v7_partialHydration&&t.length===0&&!n.initialized&&n.matches.length>0)e=n.matches;else return null}let l=e,o=(a=n)==null?void 0:a.errors;if(o!=null){let u=l.findIndex(h=>h.route.id&&(o==null?void 0:o[h.route.id])!==void 0);u>=0||rt(!1),l=l.slice(0,Math.min(l.length,u+1))}let c=!1,d=-1;if(n&&r&&r.v7_partialHydration)for(let u=0;u=0?l=l.slice(0,d+1):l=[l[0]];break}}}return l.reduceRight((u,h,p)=>{let m,f=!1,x=null,b=null;n&&(m=o&&h.route.id?o[h.route.id]:void 0,x=h.route.errorElement||YN,c&&(d<0&&p===0?(ow("route-fallback"),f=!0,b=null):d===p&&(f=!0,b=h.route.hydrateFallbackElement||null)));let y=t.concat(l.slice(0,p+1)),g=()=>{let v;return m?v=x:f?v=b:h.route.Component?v=j.createElement(h.route.Component,null):h.route.element?v=h.route.element:v=u,j.createElement(tw,{match:h,routeContext:{outlet:u,matches:y,isDataRoute:n!=null},children:v})};return n&&(h.route.ErrorBoundary||h.route.errorElement||p===0)?j.createElement(ew,{location:n.location,revalidation:n.revalidation,component:x,error:m,children:g(),routeContext:{outlet:null,matches:y,isDataRoute:!0}}):g()},null)}var v0=function(e){return e.UseBlocker="useBlocker",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e}(v0||{}),j0=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}(j0||{});function nw(e){let t=j.useContext(vc);return t||rt(!1),t}function rw(e){let t=j.useContext(x0);return t||rt(!1),t}function aw(e){let t=j.useContext(on);return t||rt(!1),t}function b0(e){let t=aw(),n=t.matches[t.matches.length-1];return n.route.id||rt(!1),n.route.id}function iw(){var e;let t=j.useContext(g0),n=rw(),r=b0();return t!==void 0?t:(e=n.errors)==null?void 0:e[r]}function lw(){let{router:e}=nw(v0.UseNavigateStable),t=b0(j0.UseNavigateStable),n=j.useRef(!1);return y0(()=>{n.current=!0}),j.useCallback(function(a,i){i===void 0&&(i={}),n.current&&(typeof a=="number"?e.navigate(a):e.navigate(a,tl({fromRouteId:t},i)))},[e,t])}const Fp={};function ow(e,t,n){Fp[e]||(Fp[e]=!0)}function cw(e,t){e==null||e.v7_startTransition,e==null||e.v7_relativeSplatPath}function ya(e){let{to:t,replace:n,state:r,relative:a}=e;si()||rt(!1);let{future:i,static:l}=j.useContext(Tn),{matches:o}=j.useContext(on),{pathname:c}=Fn(),d=ts(),u=Hm(t,Qm(o,i.v7_relativeSplatPath),c,a==="path"),h=JSON.stringify(u);return j.useEffect(()=>d(JSON.parse(h),{replace:n,state:r,relative:a}),[d,h,a,n,r]),null}function dw(e){return GN(e.context)}function ze(e){rt(!1)}function uw(e){let{basename:t="/",children:n=null,location:r,navigationType:a=tr.Pop,navigator:i,static:l=!1,future:o}=e;si()&&rt(!1);let c=t.replace(/^\/*/,"/"),d=j.useMemo(()=>({basename:c,navigator:i,static:l,future:tl({v7_relativeSplatPath:!1},o)}),[c,o,i,l]);typeof r=="string"&&(r=ti(r));let{pathname:u="/",search:h="",hash:p="",state:m=null,key:f="default"}=r,x=j.useMemo(()=>{let b=Ga(u,c);return b==null?null:{location:{pathname:b,search:h,hash:p,state:m,key:f},navigationType:a}},[c,u,h,p,m,f,a]);return x==null?null:j.createElement(Tn.Provider,{value:d},j.createElement(jc.Provider,{children:n,value:x}))}function mw(e){let{children:t,location:n}=e;return ZN(pu(t),n)}new Promise(()=>{});function pu(e,t){t===void 0&&(t=[]);let n=[];return j.Children.forEach(e,(r,a)=>{if(!j.isValidElement(r))return;let i=[...t,a];if(r.type===j.Fragment){n.push.apply(n,pu(r.props.children,i));return}r.type!==ze&&rt(!1),!r.props.index||!r.props.children||rt(!1);let l={id:r.props.id||i.join("-"),caseSensitive:r.props.caseSensitive,element:r.props.element,Component:r.props.Component,index:r.props.index,path:r.props.path,loader:r.props.loader,action:r.props.action,errorElement:r.props.errorElement,ErrorBoundary:r.props.ErrorBoundary,hasErrorBoundary:r.props.ErrorBoundary!=null||r.props.errorElement!=null,shouldRevalidate:r.props.shouldRevalidate,handle:r.props.handle,lazy:r.props.lazy};r.props.children&&(l.children=pu(r.props.children,i)),n.push(l)}),n}/** * React Router DOM v6.30.3 * * Copyright (c) Remix Software Inc. * * This source code is licensed under the MIT license found in the * LICENSE.md file in the root directory of this source tree. * * @license MIT */function Wo(){return Wo=Object.assign?Object.assign.bind():function(e){for(var t=1;t=0)&&(n[a]=e[a]);return n}function hw(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function fw(e,t){return e.button===0&&(!t||t==="_self")&&!hw(e)}function xu(e){return e===void 0&&(e=""),new URLSearchParams(typeof e=="string"||Array.isArray(e)||e instanceof URLSearchParams?e:Object.keys(e).reduce((t,n)=>{let r=e[n];return t.concat(Array.isArray(r)?r.map(a=>[n,a]):[[n,r]])},[]))}function pw(e,t){let n=xu(e);return t&&t.forEach((r,a)=>{n.has(a)||t.getAll(a).forEach(i=>{n.append(a,i)})}),n}const xw=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","viewTransition"],gw=["aria-current","caseSensitive","className","end","style","to","viewTransition","children"],yw="6";try{window.__reactRouterVersion=yw}catch{}const vw=j.createContext({isTransitioning:!1}),jw="startTransition",Ip=oj[jw];function bw(e){let{basename:t,children:n,future:r,window:a}=e,i=j.useRef();i.current==null&&(i.current=jN({window:a,v5Compat:!0}));let l=i.current,[o,c]=j.useState({action:l.action,location:l.location}),{v7_startTransition:d}=r||{},u=j.useCallback(h=>{d&&Ip?Ip(()=>c(h)):c(h)},[c,d]);return j.useLayoutEffect(()=>l.listen(u),[l,u]),j.useEffect(()=>cw(r),[r]),j.createElement(uw,{basename:t,children:n,location:o.location,navigationType:o.action,navigator:l,future:r})}const Nw=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",ww=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,ke=j.forwardRef(function(t,n){let{onClick:r,relative:a,reloadDocument:i,replace:l,state:o,target:c,to:d,preventScrollReset:u,viewTransition:h}=t,p=N0(t,xw),{basename:m}=j.useContext(Tn),f,x=!1;if(typeof d=="string"&&ww.test(d)&&(f=d,Nw))try{let v=new URL(window.location.href),N=d.startsWith("//")?new URL(v.protocol+d):new URL(d),D=Ga(N.pathname,m);N.origin===v.origin&&D!=null?d=D+N.search+N.hash:x=!0}catch{}let b=QN(d,{relative:a}),y=kw(d,{replace:l,state:o,target:c,preventScrollReset:u,relative:a,viewTransition:h});function g(v){r&&r(v),v.defaultPrevented||y(v)}return j.createElement("a",Wo({},p,{href:f||b,onClick:x||i?r:g,ref:n,target:c}))}),dd=j.forwardRef(function(t,n){let{"aria-current":r="page",caseSensitive:a=!1,className:i="",end:l=!1,style:o,to:c,viewTransition:d,children:u}=t,h=N0(t,gw),p=Nc(c,{relative:h.relative}),m=Fn(),f=j.useContext(x0),{navigator:x,basename:b}=j.useContext(Tn),y=f!=null&&Cw(p)&&d===!0,g=x.encodeLocation?x.encodeLocation(p).pathname:p.pathname,v=m.pathname,N=f&&f.navigation&&f.navigation.location?f.navigation.location.pathname:null;a||(v=v.toLowerCase(),N=N?N.toLowerCase():null,g=g.toLowerCase()),N&&b&&(N=Ga(N,b)||N);const D=g!=="/"&&g.endsWith("/")?g.length-1:g.length;let A=v===g||!l&&v.startsWith(g)&&v.charAt(D)==="/",R=N!=null&&(N===g||!l&&N.startsWith(g)&&N.charAt(g.length)==="/"),w={isActive:A,isPending:R,isTransitioning:y},S=A?r:void 0,E;typeof i=="function"?E=i(w):E=[i,A?"active":null,R?"pending":null,y?"transitioning":null].filter(Boolean).join(" ");let z=typeof o=="function"?o(w):o;return j.createElement(ke,Wo({},h,{"aria-current":S,className:E,ref:n,style:z,to:c,viewTransition:d}),typeof u=="function"?u(w):u)});var gu;(function(e){e.UseScrollRestoration="useScrollRestoration",e.UseSubmit="useSubmit",e.UseSubmitFetcher="useSubmitFetcher",e.UseFetcher="useFetcher",e.useViewTransitionState="useViewTransitionState"})(gu||(gu={}));var Rp;(function(e){e.UseFetcher="useFetcher",e.UseFetchers="useFetchers",e.UseScrollRestoration="useScrollRestoration"})(Rp||(Rp={}));function Sw(e){let t=j.useContext(vc);return t||rt(!1),t}function kw(e,t){let{target:n,replace:r,state:a,preventScrollReset:i,relative:l,viewTransition:o}=t===void 0?{}:t,c=ts(),d=Fn(),u=Nc(e,{relative:l});return j.useCallback(h=>{if(fw(h,n)){h.preventDefault();let p=r!==void 0?r:Ho(d)===Ho(u);c(e,{replace:p,state:a,preventScrollReset:i,relative:l,viewTransition:o})}},[d,c,u,r,a,n,e,i,l,o])}function wc(e){let t=j.useRef(xu(e)),n=j.useRef(!1),r=Fn(),a=j.useMemo(()=>pw(r.search,n.current?null:t.current),[r.search]),i=ts(),l=j.useCallback((o,c)=>{const d=xu(typeof o=="function"?o(a):o);n.current=!0,i("?"+d,c)},[i,a]);return[a,l]}function Cw(e,t){t===void 0&&(t={});let n=j.useContext(vw);n==null&&rt(!1);let{basename:r}=Sw(gu.useViewTransitionState),a=Nc(e,{relative:t.relative});if(!n.isTransitioning)return!1;let i=Ga(n.currentLocation.pathname,r)||n.currentLocation.pathname,l=Ga(n.nextLocation.pathname,r)||n.nextLocation.pathname;return fu(a.pathname,l)!=null||fu(a.pathname,i)!=null}var ea=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(){}},Ew={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},Bn,Zu,Bx,Dw=(Bx=class{constructor(){de(this,Bn,Ew);de(this,Zu,!1)}setTimeoutProvider(e){se(this,Bn,e)}setTimeout(e,t){return T(this,Bn).setTimeout(e,t)}clearTimeout(e){T(this,Bn).clearTimeout(e)}setInterval(e,t){return T(this,Bn).setInterval(e,t)}clearInterval(e){T(this,Bn).clearInterval(e)}},Bn=new WeakMap,Zu=new WeakMap,Bx),Er=new Dw;function Pw(e){setTimeout(e,0)}var Wr=typeof window>"u"||"Deno"in globalThis;function Kt(){}function Aw(e,t){return typeof e=="function"?e(t):e}function yu(e){return typeof e=="number"&&e>=0&&e!==1/0}function w0(e,t){return Math.max(e+(t||0)-Date.now(),0)}function ur(e,t){return typeof e=="function"?e(t):e}function ks(e,t){return typeof e=="function"?e(t):e}function Lp(e,t){const{type:n="all",exact:r,fetchStatus:a,predicate:i,queryKey:l,stale:o}=e;if(l){if(r){if(t.queryHash!==Wm(l,t.options))return!1}else if(!sl(t.queryKey,l))return!1}if(n!=="all"){const c=t.isActive();if(n==="active"&&!c||n==="inactive"&&c)return!1}return!(typeof o=="boolean"&&t.isStale()!==o||a&&a!==t.state.fetchStatus||i&&!i(t))}function Op(e,t){const{exact:n,status:r,predicate:a,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(Gr(t.options.mutationKey)!==Gr(i))return!1}else if(!sl(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||a&&!a(t))}function Wm(e,t){return((t==null?void 0:t.queryKeyHashFn)||Gr)(e)}function Gr(e){return JSON.stringify(e,(t,n)=>vu(n)?Object.keys(n).sort().reduce((r,a)=>(r[a]=n[a],r),{}):n)}function sl(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>sl(e[n],t[n])):!1}var Mw=Object.prototype.hasOwnProperty;function Gm(e,t,n=0){if(e===t)return e;if(n>500)return t;const r=zp(e)&&zp(t);if(!r&&!(vu(e)&&vu(t)))return t;const i=(r?e:Object.keys(e)).length,l=r?t:Object.keys(t),o=l.length,c=r?new Array(o):{};let d=0;for(let u=0;u{Er.setTimeout(t,e)})}function ju(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?Gm(e,t):t}function Fw(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function Iw(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var Zm=Symbol();function S0(e,t){return!e.queryFn&&(t!=null&&t.initialPromise)?()=>t.initialPromise:!e.queryFn||e.queryFn===Zm?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function Jm(e,t){return typeof e=="function"?e(...t):!!e}function Rw(e,t,n){let r=!1,a;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(a??(a=t()),r||(r=!0,a.aborted?n():a.addEventListener("abort",n,{once:!0})),a)}),e}var Ar,qn,Ea,qx,Lw=(qx=class extends ea{constructor(){super();de(this,Ar);de(this,qn);de(this,Ea);se(this,Ea,t=>{if(!Wr&&window.addEventListener){const n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){T(this,qn)||this.setEventListener(T(this,Ea))}onUnsubscribe(){var t;this.hasListeners()||((t=T(this,qn))==null||t.call(this),se(this,qn,void 0))}setEventListener(t){var n;se(this,Ea,t),(n=T(this,qn))==null||n.call(this),se(this,qn,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){T(this,Ar)!==t&&(se(this,Ar,t),this.onFocus())}onFocus(){const t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){var t;return typeof T(this,Ar)=="boolean"?T(this,Ar):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},Ar=new WeakMap,qn=new WeakMap,Ea=new WeakMap,qx),Xm=new Lw;function bu(){let e,t;const n=new Promise((a,i)=>{e=a,t=i});n.status="pending",n.catch(()=>{});function r(a){Object.assign(n,a),delete n.resolve,delete n.reject}return n.resolve=a=>{r({status:"fulfilled",value:a}),e(a)},n.reject=a=>{r({status:"rejected",reason:a}),t(a)},n}var Ow=Pw;function zw(){let e=[],t=0,n=o=>{o()},r=o=>{o()},a=Ow;const i=o=>{t?e.push(o):a(()=>{n(o)})},l=()=>{const o=e;e=[],o.length&&a(()=>{r(()=>{o.forEach(c=>{n(c)})})})};return{batch:o=>{let c;t++;try{c=o()}finally{t--,t||l()}return c},batchCalls:o=>(...c)=>{i(()=>{o(...c)})},schedule:i,setNotifyFunction:o=>{n=o},setBatchNotifyFunction:o=>{r=o},setScheduler:o=>{a=o}}}var mt=zw(),Da,Vn,Pa,Vx,$w=(Vx=class extends ea{constructor(){super();de(this,Da,!0);de(this,Vn);de(this,Pa);se(this,Pa,t=>{if(!Wr&&window.addEventListener){const n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}}})}onSubscribe(){T(this,Vn)||this.setEventListener(T(this,Pa))}onUnsubscribe(){var t;this.hasListeners()||((t=T(this,Vn))==null||t.call(this),se(this,Vn,void 0))}setEventListener(t){var n;se(this,Pa,t),(n=T(this,Vn))==null||n.call(this),se(this,Vn,t(this.setOnline.bind(this)))}setOnline(t){T(this,Da)!==t&&(se(this,Da,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return T(this,Da)}},Da=new WeakMap,Vn=new WeakMap,Pa=new WeakMap,Vx),Go=new $w;function _w(e){return Math.min(1e3*2**e,3e4)}function k0(e){return(e??"online")==="online"?Go.isOnline():!0}var Nu=class extends Error{constructor(e){super("CancelledError"),this.revert=e==null?void 0:e.revert,this.silent=e==null?void 0:e.silent}};function C0(e){let t=!1,n=0,r;const a=bu(),i=()=>a.status!=="pending",l=x=>{var b;if(!i()){const y=new Nu(x);p(y),(b=e.onCancel)==null||b.call(e,y)}},o=()=>{t=!0},c=()=>{t=!1},d=()=>Xm.isFocused()&&(e.networkMode==="always"||Go.isOnline())&&e.canRun(),u=()=>k0(e.networkMode)&&e.canRun(),h=x=>{i()||(r==null||r(),a.resolve(x))},p=x=>{i()||(r==null||r(),a.reject(x))},m=()=>new Promise(x=>{var b;r=y=>{(i()||d())&&x(y)},(b=e.onPause)==null||b.call(e)}).then(()=>{var x;r=void 0,i()||(x=e.onContinue)==null||x.call(e)}),f=()=>{if(i())return;let x;const b=n===0?e.initialPromise:void 0;try{x=b??e.fn()}catch(y){x=Promise.reject(y)}Promise.resolve(x).then(h).catch(y=>{var A;if(i())return;const g=e.retry??(Wr?0:3),v=e.retryDelay??_w,N=typeof v=="function"?v(n,y):v,D=g===!0||typeof g=="number"&&nd()?void 0:m()).then(()=>{t?p(y):f()})})};return{promise:a,status:()=>a.status,cancel:l,continue:()=>(r==null||r(),a),cancelRetry:o,continueRetry:c,canStart:u,start:()=>(u()?f():m().then(f),a)}}var Mr,Qx,E0=(Qx=class{constructor(){de(this,Mr)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),yu(this.gcTime)&&se(this,Mr,Er.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Wr?1/0:5*60*1e3))}clearGcTimeout(){T(this,Mr)&&(Er.clearTimeout(T(this,Mr)),se(this,Mr,void 0))}},Mr=new WeakMap,Qx),Tr,Aa,ws,Fr,kt,dl,Ir,Os,mn,Hx,Kw=(Hx=class extends E0{constructor(t){super();de(this,Os);de(this,Tr);de(this,Aa);de(this,ws);de(this,Fr);de(this,kt);de(this,dl);de(this,Ir);se(this,Ir,!1),se(this,dl,t.defaultOptions),this.setOptions(t.options),this.observers=[],se(this,Fr,t.client),se(this,ws,T(this,Fr).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,se(this,Tr,Kp(this.options)),this.state=t.state??T(this,Tr),this.scheduleGc()}get meta(){return this.options.meta}get promise(){var t;return(t=T(this,kt))==null?void 0:t.promise}setOptions(t){if(this.options={...T(this,dl),...t},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const n=Kp(this.options);n.data!==void 0&&(this.setState(_p(n.data,n.dataUpdatedAt)),se(this,Tr,n))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&T(this,ws).remove(this)}setData(t,n){const r=ju(this.state.data,t,this.options);return ve(this,Os,mn).call(this,{data:r,type:"success",dataUpdatedAt:n==null?void 0:n.updatedAt,manual:n==null?void 0:n.manual}),r}setState(t,n){ve(this,Os,mn).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){var r,a;const n=(r=T(this,kt))==null?void 0:r.promise;return(a=T(this,kt))==null||a.cancel(t),n?n.then(Kt).catch(Kt):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(T(this,Tr))}isActive(){return this.observers.some(t=>ks(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Zm||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>ur(t.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(t=>t.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(t=0){return this.state.data===void 0?!0:t==="static"?!1:this.state.isInvalidated?!0:!w0(this.state.dataUpdatedAt,t)}onFocus(){var n;const t=this.observers.find(r=>r.shouldFetchOnWindowFocus());t==null||t.refetch({cancelRefetch:!1}),(n=T(this,kt))==null||n.continue()}onOnline(){var n;const t=this.observers.find(r=>r.shouldFetchOnReconnect());t==null||t.refetch({cancelRefetch:!1}),(n=T(this,kt))==null||n.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),T(this,ws).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(n=>n!==t),this.observers.length||(T(this,kt)&&(T(this,Ir)?T(this,kt).cancel({revert:!0}):T(this,kt).cancelRetry()),this.scheduleGc()),T(this,ws).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||ve(this,Os,mn).call(this,{type:"invalidate"})}async fetch(t,n){var c,d,u,h,p,m,f,x,b,y,g,v;if(this.state.fetchStatus!=="idle"&&((c=T(this,kt))==null?void 0:c.status())!=="rejected"){if(this.state.data!==void 0&&(n!=null&&n.cancelRefetch))this.cancel({silent:!0});else if(T(this,kt))return T(this,kt).continueRetry(),T(this,kt).promise}if(t&&this.setOptions(t),!this.options.queryFn){const N=this.observers.find(D=>D.options.queryFn);N&&this.setOptions(N.options)}const r=new AbortController,a=N=>{Object.defineProperty(N,"signal",{enumerable:!0,get:()=>(se(this,Ir,!0),r.signal)})},i=()=>{const N=S0(this.options,n),A=(()=>{const R={client:T(this,Fr),queryKey:this.queryKey,meta:this.meta};return a(R),R})();return se(this,Ir,!1),this.options.persister?this.options.persister(N,A,this):N(A)},o=(()=>{const N={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:T(this,Fr),state:this.state,fetchFn:i};return a(N),N})();(d=this.options.behavior)==null||d.onFetch(o,this),se(this,Aa,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((u=o.fetchOptions)==null?void 0:u.meta))&&ve(this,Os,mn).call(this,{type:"fetch",meta:(h=o.fetchOptions)==null?void 0:h.meta}),se(this,kt,C0({initialPromise:n==null?void 0:n.initialPromise,fn:o.fetchFn,onCancel:N=>{N instanceof Nu&&N.revert&&this.setState({...T(this,Aa),fetchStatus:"idle"}),r.abort()},onFail:(N,D)=>{ve(this,Os,mn).call(this,{type:"failed",failureCount:N,error:D})},onPause:()=>{ve(this,Os,mn).call(this,{type:"pause"})},onContinue:()=>{ve(this,Os,mn).call(this,{type:"continue"})},retry:o.options.retry,retryDelay:o.options.retryDelay,networkMode:o.options.networkMode,canRun:()=>!0}));try{const N=await T(this,kt).start();if(N===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(N),(m=(p=T(this,ws).config).onSuccess)==null||m.call(p,N,this),(x=(f=T(this,ws).config).onSettled)==null||x.call(f,N,this.state.error,this),N}catch(N){if(N instanceof Nu){if(N.silent)return T(this,kt).promise;if(N.revert){if(this.state.data===void 0)throw N;return this.state.data}}throw ve(this,Os,mn).call(this,{type:"error",error:N}),(y=(b=T(this,ws).config).onError)==null||y.call(b,N,this),(v=(g=T(this,ws).config).onSettled)==null||v.call(g,this.state.data,N,this),N}finally{this.scheduleGc()}}},Tr=new WeakMap,Aa=new WeakMap,ws=new WeakMap,Fr=new WeakMap,kt=new WeakMap,dl=new WeakMap,Ir=new WeakMap,Os=new WeakSet,mn=function(t){const n=r=>{switch(t.type){case"failed":return{...r,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,...D0(r.data,this.options),fetchMeta:t.meta??null};case"success":const a={...r,..._p(t.data,t.dataUpdatedAt),dataUpdateCount:r.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return se(this,Aa,t.manual?a:void 0),a;case"error":const i=t.error;return{...r,error:i,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}};this.state=n(this.state),mt.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),T(this,ws).notify({query:this,type:"updated",action:t})})},Hx);function D0(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:k0(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function _p(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function Kp(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var ns,De,ul,Wt,Rr,Ma,xn,Qn,ml,Ta,Fa,Lr,Or,Hn,Ia,$e,wi,wu,Su,ku,Cu,Eu,Du,Pu,P0,Wx,Ym=(Wx=class extends ea{constructor(t,n){super();de(this,$e);de(this,ns);de(this,De);de(this,ul);de(this,Wt);de(this,Rr);de(this,Ma);de(this,xn);de(this,Qn);de(this,ml);de(this,Ta);de(this,Fa);de(this,Lr);de(this,Or);de(this,Hn);de(this,Ia,new Set);this.options=n,se(this,ns,t),se(this,Qn,null),se(this,xn,bu()),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(T(this,De).addObserver(this),Up(T(this,De),this.options)?ve(this,$e,wi).call(this):this.updateResult(),ve(this,$e,Cu).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Au(T(this,De),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Au(T(this,De),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,ve(this,$e,Eu).call(this),ve(this,$e,Du).call(this),T(this,De).removeObserver(this)}setOptions(t){const n=this.options,r=T(this,De);if(this.options=T(this,ns).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof ks(this.options.enabled,T(this,De))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");ve(this,$e,Pu).call(this),T(this,De).setOptions(this.options),n._defaulted&&!nl(this.options,n)&&T(this,ns).getQueryCache().notify({type:"observerOptionsUpdated",query:T(this,De),observer:this});const a=this.hasListeners();a&&Bp(T(this,De),r,this.options,n)&&ve(this,$e,wi).call(this),this.updateResult(),a&&(T(this,De)!==r||ks(this.options.enabled,T(this,De))!==ks(n.enabled,T(this,De))||ur(this.options.staleTime,T(this,De))!==ur(n.staleTime,T(this,De)))&&ve(this,$e,wu).call(this);const i=ve(this,$e,Su).call(this);a&&(T(this,De)!==r||ks(this.options.enabled,T(this,De))!==ks(n.enabled,T(this,De))||i!==T(this,Hn))&&ve(this,$e,ku).call(this,i)}getOptimisticResult(t){const n=T(this,ns).getQueryCache().build(T(this,ns),t),r=this.createResult(n,t);return Bw(this,r)&&(se(this,Wt,r),se(this,Ma,this.options),se(this,Rr,T(this,De).state)),r}getCurrentResult(){return T(this,Wt)}trackResult(t,n){return new Proxy(t,{get:(r,a)=>(this.trackProp(a),n==null||n(a),a==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&T(this,xn).status==="pending"&&T(this,xn).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(r,a))})}trackProp(t){T(this,Ia).add(t)}getCurrentQuery(){return T(this,De)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const n=T(this,ns).defaultQueryOptions(t),r=T(this,ns).getQueryCache().build(T(this,ns),n);return r.fetch().then(()=>this.createResult(r,n))}fetch(t){return ve(this,$e,wi).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),T(this,Wt)))}createResult(t,n){var S;const r=T(this,De),a=this.options,i=T(this,Wt),l=T(this,Rr),o=T(this,Ma),d=t!==r?t.state:T(this,ul),{state:u}=t;let h={...u},p=!1,m;if(n._optimisticResults){const E=this.hasListeners(),z=!E&&Up(t,n),I=E&&Bp(t,r,n,a);(z||I)&&(h={...h,...D0(u.data,t.options)}),n._optimisticResults==="isRestoring"&&(h.fetchStatus="idle")}let{error:f,errorUpdatedAt:x,status:b}=h;m=h.data;let y=!1;if(n.placeholderData!==void 0&&m===void 0&&b==="pending"){let E;i!=null&&i.isPlaceholderData&&n.placeholderData===(o==null?void 0:o.placeholderData)?(E=i.data,y=!0):E=typeof n.placeholderData=="function"?n.placeholderData((S=T(this,Fa))==null?void 0:S.state.data,T(this,Fa)):n.placeholderData,E!==void 0&&(b="success",m=ju(i==null?void 0:i.data,E,n),p=!0)}if(n.select&&m!==void 0&&!y)if(i&&m===(l==null?void 0:l.data)&&n.select===T(this,ml))m=T(this,Ta);else try{se(this,ml,n.select),m=n.select(m),m=ju(i==null?void 0:i.data,m,n),se(this,Ta,m),se(this,Qn,null)}catch(E){se(this,Qn,E)}T(this,Qn)&&(f=T(this,Qn),m=T(this,Ta),x=Date.now(),b="error");const g=h.fetchStatus==="fetching",v=b==="pending",N=b==="error",D=v&&g,A=m!==void 0,w={status:b,fetchStatus:h.fetchStatus,isPending:v,isSuccess:b==="success",isError:N,isInitialLoading:D,isLoading:D,data:m,dataUpdatedAt:h.dataUpdatedAt,error:f,errorUpdatedAt:x,failureCount:h.fetchFailureCount,failureReason:h.fetchFailureReason,errorUpdateCount:h.errorUpdateCount,isFetched:h.dataUpdateCount>0||h.errorUpdateCount>0,isFetchedAfterMount:h.dataUpdateCount>d.dataUpdateCount||h.errorUpdateCount>d.errorUpdateCount,isFetching:g,isRefetching:g&&!v,isLoadingError:N&&!A,isPaused:h.fetchStatus==="paused",isPlaceholderData:p,isRefetchError:N&&A,isStale:eh(t,n),refetch:this.refetch,promise:T(this,xn),isEnabled:ks(n.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){const E=w.data!==void 0,z=w.status==="error"&&!E,I=M=>{z?M.reject(w.error):E&&M.resolve(w.data)},B=()=>{const M=se(this,xn,w.promise=bu());I(M)},P=T(this,xn);switch(P.status){case"pending":t.queryHash===r.queryHash&&I(P);break;case"fulfilled":(z||w.data!==P.value)&&B();break;case"rejected":(!z||w.error!==P.reason)&&B();break}}return w}updateResult(){const t=T(this,Wt),n=this.createResult(T(this,De),this.options);if(se(this,Rr,T(this,De).state),se(this,Ma,this.options),T(this,Rr).data!==void 0&&se(this,Fa,T(this,De)),nl(n,t))return;se(this,Wt,n);const r=()=>{if(!t)return!0;const{notifyOnChangeProps:a}=this.options,i=typeof a=="function"?a():a;if(i==="all"||!i&&!T(this,Ia).size)return!0;const l=new Set(i??T(this,Ia));return this.options.throwOnError&&l.add("error"),Object.keys(T(this,Wt)).some(o=>{const c=o;return T(this,Wt)[c]!==t[c]&&l.has(c)})};ve(this,$e,P0).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&ve(this,$e,Cu).call(this)}},ns=new WeakMap,De=new WeakMap,ul=new WeakMap,Wt=new WeakMap,Rr=new WeakMap,Ma=new WeakMap,xn=new WeakMap,Qn=new WeakMap,ml=new WeakMap,Ta=new WeakMap,Fa=new WeakMap,Lr=new WeakMap,Or=new WeakMap,Hn=new WeakMap,Ia=new WeakMap,$e=new WeakSet,wi=function(t){ve(this,$e,Pu).call(this);let n=T(this,De).fetch(this.options,t);return t!=null&&t.throwOnError||(n=n.catch(Kt)),n},wu=function(){ve(this,$e,Eu).call(this);const t=ur(this.options.staleTime,T(this,De));if(Wr||T(this,Wt).isStale||!yu(t))return;const r=w0(T(this,Wt).dataUpdatedAt,t)+1;se(this,Lr,Er.setTimeout(()=>{T(this,Wt).isStale||this.updateResult()},r))},Su=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(T(this,De)):this.options.refetchInterval)??!1},ku=function(t){ve(this,$e,Du).call(this),se(this,Hn,t),!(Wr||ks(this.options.enabled,T(this,De))===!1||!yu(T(this,Hn))||T(this,Hn)===0)&&se(this,Or,Er.setInterval(()=>{(this.options.refetchIntervalInBackground||Xm.isFocused())&&ve(this,$e,wi).call(this)},T(this,Hn)))},Cu=function(){ve(this,$e,wu).call(this),ve(this,$e,ku).call(this,ve(this,$e,Su).call(this))},Eu=function(){T(this,Lr)&&(Er.clearTimeout(T(this,Lr)),se(this,Lr,void 0))},Du=function(){T(this,Or)&&(Er.clearInterval(T(this,Or)),se(this,Or,void 0))},Pu=function(){const t=T(this,ns).getQueryCache().build(T(this,ns),this.options);if(t===T(this,De))return;const n=T(this,De);se(this,De,t),se(this,ul,t.state),this.hasListeners()&&(n==null||n.removeObserver(this),t.addObserver(this))},P0=function(t){mt.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(T(this,Wt))}),T(this,ns).getQueryCache().notify({query:T(this,De),type:"observerResultsUpdated"})})},Wx);function Uw(e,t){return ks(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function Up(e,t){return Uw(e,t)||e.state.data!==void 0&&Au(e,t,t.refetchOnMount)}function Au(e,t,n){if(ks(t.enabled,e)!==!1&&ur(t.staleTime,e)!=="static"){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&eh(e,t)}return!1}function Bp(e,t,n,r){return(e!==t||ks(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&eh(e,n)}function eh(e,t){return ks(t.enabled,e)!==!1&&e.isStaleByTime(ur(t.staleTime,e))}function Bw(e,t){return!nl(e.getCurrentResult(),t)}function qp(e){return{onFetch:(t,n)=>{var u,h,p,m,f;const r=t.options,a=(p=(h=(u=t.fetchOptions)==null?void 0:u.meta)==null?void 0:h.fetchMore)==null?void 0:p.direction,i=((m=t.state.data)==null?void 0:m.pages)||[],l=((f=t.state.data)==null?void 0:f.pageParams)||[];let o={pages:[],pageParams:[]},c=0;const d=async()=>{let x=!1;const b=v=>{Rw(v,()=>t.signal,()=>x=!0)},y=S0(t.options,t.fetchOptions),g=async(v,N,D)=>{if(x)return Promise.reject();if(N==null&&v.pages.length)return Promise.resolve(v);const R=(()=>{const z={client:t.client,queryKey:t.queryKey,pageParam:N,direction:D?"backward":"forward",meta:t.options.meta};return b(z),z})(),w=await y(R),{maxPages:S}=t.options,E=D?Iw:Fw;return{pages:E(v.pages,w,S),pageParams:E(v.pageParams,N,S)}};if(a&&i.length){const v=a==="backward",N=v?qw:Vp,D={pages:i,pageParams:l},A=N(r,D);o=await g(D,A,v)}else{const v=e??i.length;do{const N=c===0?l[0]??r.initialPageParam:Vp(r,o);if(c>0&&N==null)break;o=await g(o,N),c++}while(c{var x,b;return(b=(x=t.options).persister)==null?void 0:b.call(x,d,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n)}:t.fetchFn=d}}}function Vp(e,{pages:t,pageParams:n}){const r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function qw(e,{pages:t,pageParams:n}){var r;return t.length>0?(r=e.getPreviousPageParam)==null?void 0:r.call(e,t[0],t,n[0],n):void 0}var hl,Xs,Gt,zr,Ys,Ln,Gx,Vw=(Gx=class extends E0{constructor(t){super();de(this,Ys);de(this,hl);de(this,Xs);de(this,Gt);de(this,zr);se(this,hl,t.client),this.mutationId=t.mutationId,se(this,Gt,t.mutationCache),se(this,Xs,[]),this.state=t.state||A0(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){T(this,Xs).includes(t)||(T(this,Xs).push(t),this.clearGcTimeout(),T(this,Gt).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){se(this,Xs,T(this,Xs).filter(n=>n!==t)),this.scheduleGc(),T(this,Gt).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){T(this,Xs).length||(this.state.status==="pending"?this.scheduleGc():T(this,Gt).remove(this))}continue(){var t;return((t=T(this,zr))==null?void 0:t.continue())??this.execute(this.state.variables)}async execute(t){var l,o,c,d,u,h,p,m,f,x,b,y,g,v,N,D,A,R,w,S;const n=()=>{ve(this,Ys,Ln).call(this,{type:"continue"})},r={client:T(this,hl),meta:this.options.meta,mutationKey:this.options.mutationKey};se(this,zr,C0({fn:()=>this.options.mutationFn?this.options.mutationFn(t,r):Promise.reject(new Error("No mutationFn found")),onFail:(E,z)=>{ve(this,Ys,Ln).call(this,{type:"failed",failureCount:E,error:z})},onPause:()=>{ve(this,Ys,Ln).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>T(this,Gt).canRun(this)}));const a=this.state.status==="pending",i=!T(this,zr).canStart();try{if(a)n();else{ve(this,Ys,Ln).call(this,{type:"pending",variables:t,isPaused:i}),await((o=(l=T(this,Gt).config).onMutate)==null?void 0:o.call(l,t,this,r));const z=await((d=(c=this.options).onMutate)==null?void 0:d.call(c,t,r));z!==this.state.context&&ve(this,Ys,Ln).call(this,{type:"pending",context:z,variables:t,isPaused:i})}const E=await T(this,zr).start();return await((h=(u=T(this,Gt).config).onSuccess)==null?void 0:h.call(u,E,t,this.state.context,this,r)),await((m=(p=this.options).onSuccess)==null?void 0:m.call(p,E,t,this.state.context,r)),await((x=(f=T(this,Gt).config).onSettled)==null?void 0:x.call(f,E,null,this.state.variables,this.state.context,this,r)),await((y=(b=this.options).onSettled)==null?void 0:y.call(b,E,null,t,this.state.context,r)),ve(this,Ys,Ln).call(this,{type:"success",data:E}),E}catch(E){try{await((v=(g=T(this,Gt).config).onError)==null?void 0:v.call(g,E,t,this.state.context,this,r))}catch(z){Promise.reject(z)}try{await((D=(N=this.options).onError)==null?void 0:D.call(N,E,t,this.state.context,r))}catch(z){Promise.reject(z)}try{await((R=(A=T(this,Gt).config).onSettled)==null?void 0:R.call(A,void 0,E,this.state.variables,this.state.context,this,r))}catch(z){Promise.reject(z)}try{await((S=(w=this.options).onSettled)==null?void 0:S.call(w,void 0,E,t,this.state.context,r))}catch(z){Promise.reject(z)}throw ve(this,Ys,Ln).call(this,{type:"error",error:E}),E}finally{T(this,Gt).runNext(this)}}},hl=new WeakMap,Xs=new WeakMap,Gt=new WeakMap,zr=new WeakMap,Ys=new WeakSet,Ln=function(t){const n=r=>{switch(t.type){case"failed":return{...r,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:t.isPaused,status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...r,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:t.error,failureCount:r.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=n(this.state),mt.batch(()=>{T(this,Xs).forEach(r=>{r.onMutationUpdate(t)}),T(this,Gt).notify({mutation:this,type:"updated",action:t})})},Gx);function A0(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var gn,zs,fl,Zx,Qw=(Zx=class extends ea{constructor(t={}){super();de(this,gn);de(this,zs);de(this,fl);this.config=t,se(this,gn,new Set),se(this,zs,new Map),se(this,fl,0)}build(t,n,r){const a=new Vw({client:t,mutationCache:this,mutationId:++Ll(this,fl)._,options:t.defaultMutationOptions(n),state:r});return this.add(a),a}add(t){T(this,gn).add(t);const n=eo(t);if(typeof n=="string"){const r=T(this,zs).get(n);r?r.push(t):T(this,zs).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(T(this,gn).delete(t)){const n=eo(t);if(typeof n=="string"){const r=T(this,zs).get(n);if(r)if(r.length>1){const a=r.indexOf(t);a!==-1&&r.splice(a,1)}else r[0]===t&&T(this,zs).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){const n=eo(t);if(typeof n=="string"){const r=T(this,zs).get(n),a=r==null?void 0:r.find(i=>i.state.status==="pending");return!a||a===t}else return!0}runNext(t){var r;const n=eo(t);if(typeof n=="string"){const a=(r=T(this,zs).get(n))==null?void 0:r.find(i=>i!==t&&i.state.isPaused);return(a==null?void 0:a.continue())??Promise.resolve()}else return Promise.resolve()}clear(){mt.batch(()=>{T(this,gn).forEach(t=>{this.notify({type:"removed",mutation:t})}),T(this,gn).clear(),T(this,zs).clear()})}getAll(){return Array.from(T(this,gn))}find(t){const n={exact:!0,...t};return this.getAll().find(r=>Op(n,r))}findAll(t={}){return this.getAll().filter(n=>Op(t,n))}notify(t){mt.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){const t=this.getAll().filter(n=>n.state.isPaused);return mt.batch(()=>Promise.all(t.map(n=>n.continue().catch(Kt))))}},gn=new WeakMap,zs=new WeakMap,fl=new WeakMap,Zx);function eo(e){var t;return(t=e.options.scope)==null?void 0:t.id}var yn,Wn,rs,vn,Sn,go,Mu,Jx,Hw=(Jx=class extends ea{constructor(n,r){super();de(this,Sn);de(this,yn);de(this,Wn);de(this,rs);de(this,vn);se(this,yn,n),this.setOptions(r),this.bindMethods(),ve(this,Sn,go).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(n){var a;const r=this.options;this.options=T(this,yn).defaultMutationOptions(n),nl(this.options,r)||T(this,yn).getMutationCache().notify({type:"observerOptionsUpdated",mutation:T(this,rs),observer:this}),r!=null&&r.mutationKey&&this.options.mutationKey&&Gr(r.mutationKey)!==Gr(this.options.mutationKey)?this.reset():((a=T(this,rs))==null?void 0:a.state.status)==="pending"&&T(this,rs).setOptions(this.options)}onUnsubscribe(){var n;this.hasListeners()||(n=T(this,rs))==null||n.removeObserver(this)}onMutationUpdate(n){ve(this,Sn,go).call(this),ve(this,Sn,Mu).call(this,n)}getCurrentResult(){return T(this,Wn)}reset(){var n;(n=T(this,rs))==null||n.removeObserver(this),se(this,rs,void 0),ve(this,Sn,go).call(this),ve(this,Sn,Mu).call(this)}mutate(n,r){var a;return se(this,vn,r),(a=T(this,rs))==null||a.removeObserver(this),se(this,rs,T(this,yn).getMutationCache().build(T(this,yn),this.options)),T(this,rs).addObserver(this),T(this,rs).execute(n)}},yn=new WeakMap,Wn=new WeakMap,rs=new WeakMap,vn=new WeakMap,Sn=new WeakSet,go=function(){var r;const n=((r=T(this,rs))==null?void 0:r.state)??A0();se(this,Wn,{...n,isPending:n.status==="pending",isSuccess:n.status==="success",isError:n.status==="error",isIdle:n.status==="idle",mutate:this.mutate,reset:this.reset})},Mu=function(n){mt.batch(()=>{var r,a,i,l,o,c,d,u;if(T(this,vn)&&this.hasListeners()){const h=T(this,Wn).variables,p=T(this,Wn).context,m={client:T(this,yn),meta:this.options.meta,mutationKey:this.options.mutationKey};if((n==null?void 0:n.type)==="success"){try{(a=(r=T(this,vn)).onSuccess)==null||a.call(r,n.data,h,p,m)}catch(f){Promise.reject(f)}try{(l=(i=T(this,vn)).onSettled)==null||l.call(i,n.data,null,h,p,m)}catch(f){Promise.reject(f)}}else if((n==null?void 0:n.type)==="error"){try{(c=(o=T(this,vn)).onError)==null||c.call(o,n.error,h,p,m)}catch(f){Promise.reject(f)}try{(u=(d=T(this,vn)).onSettled)==null||u.call(d,void 0,n.error,h,p,m)}catch(f){Promise.reject(f)}}}this.listeners.forEach(h=>{h(T(this,Wn))})})},Jx);function Qp(e,t){const n=new Set(t);return e.filter(r=>!n.has(r))}function Ww(e,t,n){const r=e.slice(0);return r[t]=n,r}var Ra,fs,La,Oa,Ss,Gn,pl,xl,gl,yl,Ot,Tu,Fu,Iu,Ru,Lu,Xx,Gw=(Xx=class extends ea{constructor(t,n,r){super();de(this,Ot);de(this,Ra);de(this,fs);de(this,La);de(this,Oa);de(this,Ss);de(this,Gn);de(this,pl);de(this,xl);de(this,gl);de(this,yl,[]);se(this,Ra,t),se(this,Oa,r),se(this,La,[]),se(this,Ss,[]),se(this,fs,[]),this.setQueries(n)}onSubscribe(){this.listeners.size===1&&T(this,Ss).forEach(t=>{t.subscribe(n=>{ve(this,Ot,Ru).call(this,t,n)})})}onUnsubscribe(){this.listeners.size||this.destroy()}destroy(){this.listeners=new Set,T(this,Ss).forEach(t=>{t.destroy()})}setQueries(t,n){se(this,La,t),se(this,Oa,n),mt.batch(()=>{const r=T(this,Ss),a=ve(this,Ot,Iu).call(this,T(this,La));a.forEach(h=>h.observer.setOptions(h.defaultedQueryOptions));const i=a.map(h=>h.observer),l=i.map(h=>h.getCurrentResult()),o=r.length!==i.length,c=i.some((h,p)=>h!==r[p]),d=o||c,u=d?!0:l.some((h,p)=>{const m=T(this,fs)[p];return!m||!nl(h,m)});!d&&!u||(d&&(se(this,yl,a),se(this,Ss,i)),se(this,fs,l),this.hasListeners()&&(d&&(Qp(r,i).forEach(h=>{h.destroy()}),Qp(i,r).forEach(h=>{h.subscribe(p=>{ve(this,Ot,Ru).call(this,h,p)})})),ve(this,Ot,Lu).call(this)))})}getCurrentResult(){return T(this,fs)}getQueries(){return T(this,Ss).map(t=>t.getCurrentQuery())}getObservers(){return T(this,Ss)}getOptimisticResult(t,n){const r=ve(this,Ot,Iu).call(this,t),a=r.map(l=>l.observer.getOptimisticResult(l.defaultedQueryOptions)),i=r.map(l=>l.defaultedQueryOptions.queryHash);return[a,l=>ve(this,Ot,Fu).call(this,l??a,n,i),()=>ve(this,Ot,Tu).call(this,a,r)]}},Ra=new WeakMap,fs=new WeakMap,La=new WeakMap,Oa=new WeakMap,Ss=new WeakMap,Gn=new WeakMap,pl=new WeakMap,xl=new WeakMap,gl=new WeakMap,yl=new WeakMap,Ot=new WeakSet,Tu=function(t,n){return n.map((r,a)=>{const i=t[a];return r.defaultedQueryOptions.notifyOnChangeProps?i:r.observer.trackResult(i,l=>{n.forEach(o=>{o.observer.trackProp(l)})})})},Fu=function(t,n,r){if(n){const a=T(this,gl),i=r!==void 0&&a!==void 0&&(a.length!==r.length||r.some((l,o)=>l!==a[o]));return(!T(this,Gn)||T(this,fs)!==T(this,xl)||i||n!==T(this,pl))&&(se(this,pl,n),se(this,xl,T(this,fs)),r!==void 0&&se(this,gl,r),se(this,Gn,Gm(T(this,Gn),n(t)))),T(this,Gn)}return t},Iu=function(t){const n=new Map;T(this,Ss).forEach(a=>{const i=a.options.queryHash;if(!i)return;const l=n.get(i);l?l.push(a):n.set(i,[a])});const r=[];return t.forEach(a=>{var c;const i=T(this,Ra).defaultQueryOptions(a),o=((c=n.get(i.queryHash))==null?void 0:c.shift())??new Ym(T(this,Ra),i);r.push({defaultedQueryOptions:i,observer:o})}),r},Ru=function(t,n){const r=T(this,Ss).indexOf(t);r!==-1&&(se(this,fs,Ww(T(this,fs),r,n)),ve(this,Ot,Lu).call(this))},Lu=function(){var t;if(this.hasListeners()){const n=T(this,Gn),r=ve(this,Ot,Tu).call(this,T(this,fs),T(this,yl)),a=ve(this,Ot,Fu).call(this,r,(t=T(this,Oa))==null?void 0:t.combine);n!==a&&mt.batch(()=>{this.listeners.forEach(i=>{i(T(this,fs))})})}},Xx),en,Yx,Zw=(Yx=class extends ea{constructor(t={}){super();de(this,en);this.config=t,se(this,en,new Map)}build(t,n,r){const a=n.queryKey,i=n.queryHash??Wm(a,n);let l=this.get(i);return l||(l=new Kw({client:t,queryKey:a,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(a)}),this.add(l)),l}add(t){T(this,en).has(t.queryHash)||(T(this,en).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const n=T(this,en).get(t.queryHash);n&&(t.destroy(),n===t&&T(this,en).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){mt.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return T(this,en).get(t)}getAll(){return[...T(this,en).values()]}find(t){const n={exact:!0,...t};return this.getAll().find(r=>Lp(n,r))}findAll(t={}){const n=this.getAll();return Object.keys(t).length>0?n.filter(r=>Lp(t,r)):n}notify(t){mt.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){mt.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){mt.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},en=new WeakMap,Yx),ot,Zn,Jn,za,$a,Xn,_a,Ka,eg,Jw=(eg=class{constructor(e={}){de(this,ot);de(this,Zn);de(this,Jn);de(this,za);de(this,$a);de(this,Xn);de(this,_a);de(this,Ka);se(this,ot,e.queryCache||new Zw),se(this,Zn,e.mutationCache||new Qw),se(this,Jn,e.defaultOptions||{}),se(this,za,new Map),se(this,$a,new Map),se(this,Xn,0)}mount(){Ll(this,Xn)._++,T(this,Xn)===1&&(se(this,_a,Xm.subscribe(async e=>{e&&(await this.resumePausedMutations(),T(this,ot).onFocus())})),se(this,Ka,Go.subscribe(async e=>{e&&(await this.resumePausedMutations(),T(this,ot).onOnline())})))}unmount(){var e,t;Ll(this,Xn)._--,T(this,Xn)===0&&((e=T(this,_a))==null||e.call(this),se(this,_a,void 0),(t=T(this,Ka))==null||t.call(this),se(this,Ka,void 0))}isFetching(e){return T(this,ot).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return T(this,Zn).findAll({...e,status:"pending"}).length}getQueryData(e){var n;const t=this.defaultQueryOptions({queryKey:e});return(n=T(this,ot).get(t.queryHash))==null?void 0:n.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=T(this,ot).build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(ur(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return T(this,ot).findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=this.defaultQueryOptions({queryKey:e}),a=T(this,ot).get(r.queryHash),i=a==null?void 0:a.state.data,l=Aw(t,i);if(l!==void 0)return T(this,ot).build(this,r).setData(l,{...n,manual:!0})}setQueriesData(e,t,n){return mt.batch(()=>T(this,ot).findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){var n;const t=this.defaultQueryOptions({queryKey:e});return(n=T(this,ot).get(t.queryHash))==null?void 0:n.state}removeQueries(e){const t=T(this,ot);mt.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=T(this,ot);return mt.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const n={revert:!0,...t},r=mt.batch(()=>T(this,ot).findAll(e).map(a=>a.cancel(n)));return Promise.all(r).then(Kt).catch(Kt)}invalidateQueries(e,t={}){return mt.batch(()=>(T(this,ot).findAll(e).forEach(n=>{n.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"},t)))}refetchQueries(e,t={}){const n={...t,cancelRefetch:t.cancelRefetch??!0},r=mt.batch(()=>T(this,ot).findAll(e).filter(a=>!a.isDisabled()&&!a.isStatic()).map(a=>{let i=a.fetch(void 0,n);return n.throwOnError||(i=i.catch(Kt)),a.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(Kt)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=T(this,ot).build(this,t);return n.isStaleByTime(ur(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Kt).catch(Kt)}fetchInfiniteQuery(e){return e.behavior=qp(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Kt).catch(Kt)}ensureInfiniteQueryData(e){return e.behavior=qp(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return Go.isOnline()?T(this,Zn).resumePausedMutations():Promise.resolve()}getQueryCache(){return T(this,ot)}getMutationCache(){return T(this,Zn)}getDefaultOptions(){return T(this,Jn)}setDefaultOptions(e){se(this,Jn,e)}setQueryDefaults(e,t){T(this,za).set(Gr(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...T(this,za).values()],n={};return t.forEach(r=>{sl(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){T(this,$a).set(Gr(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...T(this,$a).values()],n={};return t.forEach(r=>{sl(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;const t={...T(this,Jn).queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Wm(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===Zm&&(t.enabled=!1),t}defaultMutationOptions(e){return e!=null&&e._defaulted?e:{...T(this,Jn).mutations,...(e==null?void 0:e.mutationKey)&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){T(this,ot).clear(),T(this,Zn).clear()}},ot=new WeakMap,Zn=new WeakMap,Jn=new WeakMap,za=new WeakMap,$a=new WeakMap,Xn=new WeakMap,_a=new WeakMap,Ka=new WeakMap,eg),M0=j.createContext(void 0),xe=e=>{const t=j.useContext(M0);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},Xw=({client:e,children:t})=>(j.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),s.jsx(M0.Provider,{value:e,children:t})),T0=j.createContext(!1),F0=()=>j.useContext(T0);T0.Provider;function Yw(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var e1=j.createContext(Yw()),I0=()=>j.useContext(e1),R0=(e,t,n)=>{const r=n!=null&&n.state.error&&typeof e.throwOnError=="function"?Jm(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},L0=e=>{j.useEffect(()=>{e.clearReset()},[e])},O0=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:a})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(a&&e.data===void 0||Jm(n,[e.error,r])),z0=e=>{if(e.suspense){const n=a=>a==="static"?a:Math.max(a??1e3,1e3),r=e.staleTime;e.staleTime=typeof r=="function"?(...a)=>n(r(...a)):n(r),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},$0=(e,t)=>e.isLoading&&e.isFetching&&!t,Ou=(e,t)=>(e==null?void 0:e.suspense)&&t.isPending,Zo=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function t1({queries:e,...t},n){const r=xe(),a=F0(),i=I0(),l=j.useMemo(()=>e.map(x=>{const b=r.defaultQueryOptions(x);return b._optimisticResults=a?"isRestoring":"optimistic",b}),[e,r,a]);l.forEach(x=>{z0(x);const b=r.getQueryCache().get(x.queryHash);R0(x,i,b)}),L0(i);const[o]=j.useState(()=>new Gw(r,l,t)),[c,d,u]=o.getOptimisticResult(l,t.combine),h=!a&&t.subscribed!==!1;j.useSyncExternalStore(j.useCallback(x=>h?o.subscribe(mt.batchCalls(x)):Kt,[o,h]),()=>o.getCurrentResult(),()=>o.getCurrentResult()),j.useEffect(()=>{o.setQueries(l,t)},[l,t,o]);const m=c.some((x,b)=>Ou(l[b],x))?c.flatMap((x,b)=>{const y=l[b];if(y){const g=new Ym(r,y);if(Ou(y,x))return Zo(y,g,i);$0(x,a)&&Zo(y,g,i)}return[]}):[];if(m.length>0)throw Promise.all(m);const f=c.find((x,b)=>{const y=l[b];return y&&O0({result:x,errorResetBoundary:i,throwOnError:y.throwOnError,query:r.getQueryCache().get(y.queryHash),suspense:y.suspense})});if(f!=null&&f.error)throw f.error;return d(u())}function s1(e,t,n){var p,m,f,x;const r=F0(),a=I0(),i=xe(),l=i.defaultQueryOptions(e);(m=(p=i.getDefaultOptions().queries)==null?void 0:p._experimental_beforeQuery)==null||m.call(p,l);const o=i.getQueryCache().get(l.queryHash);l._optimisticResults=r?"isRestoring":"optimistic",z0(l),R0(l,a,o),L0(a);const c=!i.getQueryCache().get(l.queryHash),[d]=j.useState(()=>new t(i,l)),u=d.getOptimisticResult(l),h=!r&&e.subscribed!==!1;if(j.useSyncExternalStore(j.useCallback(b=>{const y=h?d.subscribe(mt.batchCalls(b)):Kt;return d.updateResult(),y},[d,h]),()=>d.getCurrentResult(),()=>d.getCurrentResult()),j.useEffect(()=>{d.setOptions(l)},[l,d]),Ou(l,u))throw Zo(l,d,a);if(O0({result:u,errorResetBoundary:a,throwOnError:l.throwOnError,query:o,suspense:l.suspense}))throw u.error;if((x=(f=i.getDefaultOptions().queries)==null?void 0:f._experimental_afterQuery)==null||x.call(f,l,u),l.experimental_prefetchInRender&&!Wr&&$0(u,r)){const b=c?Zo(l,d,a):o==null?void 0:o.promise;b==null||b.catch(Kt).finally(()=>{d.updateResult()})}return l.notifyOnChangeProps?u:d.trackResult(u)}function me(e,t){return s1(e,Ym)}function W(e,t){const n=xe(),[r]=j.useState(()=>new Hw(n,e));j.useEffect(()=>{r.setOptions(e)},[r,e]);const a=j.useSyncExternalStore(j.useCallback(l=>r.subscribe(mt.batchCalls(l)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),i=j.useCallback((l,o)=>{r.mutate(l,o).catch(Kt)},[r]);if(a.error&&Jm(r.options.throwOnError,[a.error]))throw a.error;return{...a,mutate:i,mutateAsync:a.mutate}}let n1={data:""},r1=e=>{if(typeof window=="object"){let t=(e?e.querySelector("#_goober"):window._goober)||Object.assign(document.createElement("style"),{innerHTML:" ",id:"_goober"});return t.nonce=window.__nonce__,t.parentNode||(e||document.head).appendChild(t),t.firstChild}return e||n1},a1=/(?:([\u0080-\uFFFF\w-%@]+) *:? *([^{;]+?);|([^;}{]*?) *{)|(}\s*)/g,i1=/\/\*[^]*?\*\/| +/g,Hp=/\n+/g,Kn=(e,t)=>{let n="",r="",a="";for(let i in e){let l=e[i];i[0]=="@"?i[1]=="i"?n=i+" "+l+";":r+=i[1]=="f"?Kn(l,i):i+"{"+Kn(l,i[1]=="k"?"":t)+"}":typeof l=="object"?r+=Kn(l,t?t.replace(/([^,])+/g,o=>i.replace(/([^,]*:\S+\([^)]*\))|([^,])+/g,c=>/&/.test(c)?c.replace(/&/g,o):o?o+" "+c:c)):i):l!=null&&(i=/^--/.test(i)?i:i.replace(/[A-Z]/g,"-$&").toLowerCase(),a+=Kn.p?Kn.p(i,l):i+":"+l+";")}return n+(t&&a?t+"{"+a+"}":a)+r},dn={},_0=e=>{if(typeof e=="object"){let t="";for(let n in e)t+=n+_0(e[n]);return t}return e},l1=(e,t,n,r,a)=>{let i=_0(e),l=dn[i]||(dn[i]=(c=>{let d=0,u=11;for(;d>>0;return"go"+u})(i));if(!dn[l]){let c=i!==e?e:(d=>{let u,h,p=[{}];for(;u=a1.exec(d.replace(i1,""));)u[4]?p.shift():u[3]?(h=u[3].replace(Hp," ").trim(),p.unshift(p[0][h]=p[0][h]||{})):p[0][u[1]]=u[2].replace(Hp," ").trim();return p[0]})(e);dn[l]=Kn(a?{["@keyframes "+l]:c}:c,n?"":"."+l)}let o=n&&dn.g?dn.g:null;return n&&(dn.g=dn[l]),((c,d,u,h)=>{h?d.data=d.data.replace(h,c):d.data.indexOf(c)===-1&&(d.data=u?c+d.data:d.data+c)})(dn[l],t,r,o),l},o1=(e,t,n)=>e.reduce((r,a,i)=>{let l=t[i];if(l&&l.call){let o=l(n),c=o&&o.props&&o.props.className||/^go/.test(o)&&o;l=c?"."+c:o&&typeof o=="object"?o.props?"":Kn(o,""):o===!1?"":o}return r+a+(l??"")},"");function Sc(e){let t=this||{},n=e.call?e(t.p):e;return l1(n.unshift?n.raw?o1(n,[].slice.call(arguments,1),t.p):n.reduce((r,a)=>Object.assign(r,a&&a.call?a(t.p):a),{}):n,r1(t.target),t.g,t.o,t.k)}let K0,zu,$u;Sc.bind({g:1});let Pn=Sc.bind({k:1});function c1(e,t,n,r){Kn.p=t,K0=e,zu=n,$u=r}function yr(e,t){let n=this||{};return function(){let r=arguments;function a(i,l){let o=Object.assign({},i),c=o.className||a.className;n.p=Object.assign({theme:zu&&zu()},o),n.o=/ *go\d+/.test(c),o.className=Sc.apply(n,r)+(c?" "+c:"");let d=e;return e[0]&&(d=o.as||e,delete o.as),$u&&d[0]&&$u(o),K0(d,o)}return a}}var d1=e=>typeof e=="function",Jo=(e,t)=>d1(e)?e(t):e,u1=(()=>{let e=0;return()=>(++e).toString()})(),U0=(()=>{let e;return()=>{if(e===void 0&&typeof window<"u"){let t=matchMedia("(prefers-reduced-motion: reduce)");e=!t||t.matches}return e}})(),m1=20,th="default",B0=(e,t)=>{let{toastLimit:n}=e.settings;switch(t.type){case 0:return{...e,toasts:[t.toast,...e.toasts].slice(0,n)};case 1:return{...e,toasts:e.toasts.map(l=>l.id===t.toast.id?{...l,...t.toast}:l)};case 2:let{toast:r}=t;return B0(e,{type:e.toasts.find(l=>l.id===r.id)?1:0,toast:r});case 3:let{toastId:a}=t;return{...e,toasts:e.toasts.map(l=>l.id===a||a===void 0?{...l,dismissed:!0,visible:!1}:l)};case 4:return t.toastId===void 0?{...e,toasts:[]}:{...e,toasts:e.toasts.filter(l=>l.id!==t.toastId)};case 5:return{...e,pausedAt:t.time};case 6:let i=t.time-(e.pausedAt||0);return{...e,pausedAt:void 0,toasts:e.toasts.map(l=>({...l,pauseDuration:l.pauseDuration+i}))}}},yo=[],q0={toasts:[],pausedAt:void 0,settings:{toastLimit:m1}},sn={},V0=(e,t=th)=>{sn[t]=B0(sn[t]||q0,e),yo.forEach(([n,r])=>{n===t&&r(sn[t])})},Q0=e=>Object.keys(sn).forEach(t=>V0(e,t)),h1=e=>Object.keys(sn).find(t=>sn[t].toasts.some(n=>n.id===e)),kc=(e=th)=>t=>{V0(t,e)},f1={blank:4e3,error:4e3,success:2e3,loading:1/0,custom:4e3},p1=(e={},t=th)=>{let[n,r]=j.useState(sn[t]||q0),a=j.useRef(sn[t]);j.useEffect(()=>(a.current!==sn[t]&&r(sn[t]),yo.push([t,r]),()=>{let l=yo.findIndex(([o])=>o===t);l>-1&&yo.splice(l,1)}),[t]);let i=n.toasts.map(l=>{var o,c,d;return{...e,...e[l.type],...l,removeDelay:l.removeDelay||((o=e[l.type])==null?void 0:o.removeDelay)||(e==null?void 0:e.removeDelay),duration:l.duration||((c=e[l.type])==null?void 0:c.duration)||(e==null?void 0:e.duration)||f1[l.type],style:{...e.style,...(d=e[l.type])==null?void 0:d.style,...l.style}}});return{...n,toasts:i}},x1=(e,t="blank",n)=>({createdAt:Date.now(),visible:!0,dismissed:!1,type:t,ariaProps:{role:"status","aria-live":"polite"},message:e,pauseDuration:0,...n,id:(n==null?void 0:n.id)||u1()}),Sl=e=>(t,n)=>{let r=x1(t,e,n);return kc(r.toasterId||h1(r.id))({type:2,toast:r}),r.id},Nt=(e,t)=>Sl("blank")(e,t);Nt.error=Sl("error");Nt.success=Sl("success");Nt.loading=Sl("loading");Nt.custom=Sl("custom");Nt.dismiss=(e,t)=>{let n={type:3,toastId:e};t?kc(t)(n):Q0(n)};Nt.dismissAll=e=>Nt.dismiss(void 0,e);Nt.remove=(e,t)=>{let n={type:4,toastId:e};t?kc(t)(n):Q0(n)};Nt.removeAll=e=>Nt.remove(void 0,e);Nt.promise=(e,t,n)=>{let r=Nt.loading(t.loading,{...n,...n==null?void 0:n.loading});return typeof e=="function"&&(e=e()),e.then(a=>{let i=t.success?Jo(t.success,a):void 0;return i?Nt.success(i,{id:r,...n,...n==null?void 0:n.success}):Nt.dismiss(r),a}).catch(a=>{let i=t.error?Jo(t.error,a):void 0;i?Nt.error(i,{id:r,...n,...n==null?void 0:n.error}):Nt.dismiss(r)}),e};var g1=1e3,y1=(e,t="default")=>{let{toasts:n,pausedAt:r}=p1(e,t),a=j.useRef(new Map).current,i=j.useCallback((h,p=g1)=>{if(a.has(h))return;let m=setTimeout(()=>{a.delete(h),l({type:4,toastId:h})},p);a.set(h,m)},[]);j.useEffect(()=>{if(r)return;let h=Date.now(),p=n.map(m=>{if(m.duration===1/0)return;let f=(m.duration||0)+m.pauseDuration-(h-m.createdAt);if(f<0){m.visible&&Nt.dismiss(m.id);return}return setTimeout(()=>Nt.dismiss(m.id,t),f)});return()=>{p.forEach(m=>m&&clearTimeout(m))}},[n,r,t]);let l=j.useCallback(kc(t),[t]),o=j.useCallback(()=>{l({type:5,time:Date.now()})},[l]),c=j.useCallback((h,p)=>{l({type:1,toast:{id:h,height:p}})},[l]),d=j.useCallback(()=>{r&&l({type:6,time:Date.now()})},[r,l]),u=j.useCallback((h,p)=>{let{reverseOrder:m=!1,gutter:f=8,defaultPosition:x}=p||{},b=n.filter(v=>(v.position||x)===(h.position||x)&&v.height),y=b.findIndex(v=>v.id===h.id),g=b.filter((v,N)=>Nv.visible).slice(...m?[g+1]:[0,g]).reduce((v,N)=>v+(N.height||0)+f,0)},[n]);return j.useEffect(()=>{n.forEach(h=>{if(h.dismissed)i(h.id,h.removeDelay);else{let p=a.get(h.id);p&&(clearTimeout(p),a.delete(h.id))}})},[n,i]),{toasts:n,handlers:{updateHeight:c,startPause:o,endPause:d,calculateOffset:u}}},v1=Pn` from { transform: scale(0) rotate(45deg); opacity: 0; } to { transform: scale(1) rotate(45deg); opacity: 1; }`,j1=Pn` from { transform: scale(0); opacity: 0; } to { transform: scale(1); opacity: 1; }`,b1=Pn` from { transform: scale(0) rotate(90deg); opacity: 0; } to { transform: scale(1) rotate(90deg); opacity: 1; }`,N1=yr("div")` width: 20px; opacity: 0; height: 20px; border-radius: 10px; background: ${e=>e.primary||"#ff4b4b"}; position: relative; transform: rotate(45deg); animation: ${v1} 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275) forwards; animation-delay: 100ms; &:after, &:before { content: ''; animation: ${j1} 0.15s ease-out forwards; animation-delay: 150ms; position: absolute; border-radius: 3px; opacity: 0; background: ${e=>e.secondary||"#fff"}; bottom: 9px; left: 4px; height: 2px; width: 12px; } &:before { animation: ${b1} 0.15s ease-out forwards; animation-delay: 180ms; transform: rotate(90deg); } `,w1=Pn` from { transform: rotate(0deg); } to { transform: rotate(360deg); } `,S1=yr("div")` width: 12px; height: 12px; box-sizing: border-box; border: 2px solid; border-radius: 100%; border-color: ${e=>e.secondary||"#e0e0e0"}; border-right-color: ${e=>e.primary||"#616161"}; animation: ${w1} 1s linear infinite; `,k1=Pn` from { transform: scale(0) rotate(45deg); opacity: 0; } to { transform: scale(1) rotate(45deg); opacity: 1; }`,C1=Pn` 0% { height: 0; width: 0; opacity: 0; } 40% { height: 0; width: 6px; opacity: 1; } 100% { opacity: 1; height: 10px; }`,E1=yr("div")` width: 20px; opacity: 0; height: 20px; border-radius: 10px; background: ${e=>e.primary||"#61d345"}; position: relative; transform: rotate(45deg); animation: ${k1} 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275) forwards; animation-delay: 100ms; &:after { content: ''; box-sizing: border-box; animation: ${C1} 0.2s ease-out forwards; opacity: 0; animation-delay: 200ms; position: absolute; border-right: 2px solid; border-bottom: 2px solid; border-color: ${e=>e.secondary||"#fff"}; bottom: 6px; left: 6px; height: 10px; width: 6px; } `,D1=yr("div")` position: absolute; `,P1=yr("div")` position: relative; display: flex; justify-content: center; align-items: center; min-width: 20px; min-height: 20px; `,A1=Pn` from { transform: scale(0.6); opacity: 0.4; } to { transform: scale(1); opacity: 1; }`,M1=yr("div")` position: relative; transform: scale(0.6); opacity: 0.4; min-width: 20px; animation: ${A1} 0.3s 0.12s cubic-bezier(0.175, 0.885, 0.32, 1.275) forwards; `,T1=({toast:e})=>{let{icon:t,type:n,iconTheme:r}=e;return t!==void 0?typeof t=="string"?j.createElement(M1,null,t):t:n==="blank"?null:j.createElement(P1,null,j.createElement(S1,{...r}),n!=="loading"&&j.createElement(D1,null,n==="error"?j.createElement(N1,{...r}):j.createElement(E1,{...r})))},F1=e=>` 0% {transform: translate3d(0,${e*-200}%,0) scale(.6); opacity:.5;} 100% {transform: translate3d(0,0,0) scale(1); opacity:1;} `,I1=e=>` 0% {transform: translate3d(0,0,-1px) scale(1); opacity:1;} 100% {transform: translate3d(0,${e*-150}%,-1px) scale(.6); opacity:0;} `,R1="0%{opacity:0;} 100%{opacity:1;}",L1="0%{opacity:1;} 100%{opacity:0;}",O1=yr("div")` display: flex; align-items: center; background: #fff; color: #363636; line-height: 1.3; will-change: transform; box-shadow: 0 3px 10px rgba(0, 0, 0, 0.1), 0 3px 3px rgba(0, 0, 0, 0.05); max-width: 350px; pointer-events: auto; padding: 8px 10px; border-radius: 8px; `,z1=yr("div")` display: flex; justify-content: center; margin: 4px 10px; color: inherit; flex: 1 1 auto; white-space: pre-line; `,$1=(e,t)=>{let n=e.includes("top")?1:-1,[r,a]=U0()?[R1,L1]:[F1(n),I1(n)];return{animation:t?`${Pn(r)} 0.35s cubic-bezier(.21,1.02,.73,1) forwards`:`${Pn(a)} 0.4s forwards cubic-bezier(.06,.71,.55,1)`}},_1=j.memo(({toast:e,position:t,style:n,children:r})=>{let a=e.height?$1(e.position||t||"top-center",e.visible):{opacity:0},i=j.createElement(T1,{toast:e}),l=j.createElement(z1,{...e.ariaProps},Jo(e.message,e));return j.createElement(O1,{className:e.className,style:{...a,...n,...e.style}},typeof r=="function"?r({icon:i,message:l}):j.createElement(j.Fragment,null,i,l))});c1(j.createElement);var K1=({id:e,className:t,style:n,onHeightUpdate:r,children:a})=>{let i=j.useCallback(l=>{if(l){let o=()=>{let c=l.getBoundingClientRect().height;r(e,c)};o(),new MutationObserver(o).observe(l,{subtree:!0,childList:!0,characterData:!0})}},[e,r]);return j.createElement("div",{ref:i,className:t,style:n},a)},U1=(e,t)=>{let n=e.includes("top"),r=n?{top:0}:{bottom:0},a=e.includes("center")?{justifyContent:"center"}:e.includes("right")?{justifyContent:"flex-end"}:{};return{left:0,right:0,display:"flex",position:"absolute",transition:U0()?void 0:"all 230ms cubic-bezier(.21,1.02,.73,1)",transform:`translateY(${t*(n?1:-1)}px)`,...r,...a}},B1=Sc` z-index: 9999; > * { pointer-events: auto; } `,to=16,q1=({reverseOrder:e,position:t="top-center",toastOptions:n,gutter:r,children:a,toasterId:i,containerStyle:l,containerClassName:o})=>{let{toasts:c,handlers:d}=y1(n,i);return j.createElement("div",{"data-rht-toaster":i||"",style:{position:"fixed",zIndex:9999,top:to,left:to,right:to,bottom:to,pointerEvents:"none",...l},className:o,onMouseEnter:d.startPause,onMouseLeave:d.endPause},c.map(u=>{let h=u.position||t,p=d.calculateOffset(u,{reverseOrder:e,gutter:r,defaultPosition:t}),m=U1(h,p);return j.createElement(K1,{id:u.id,key:u.id,onHeightUpdate:d.updateHeight,className:u.visible?B1:"",style:m},u.type==="custom"?Jo(u.message,u):a?a(u):j.createElement(_1,{toast:u,position:h}))}))},Ie=Nt;function H0(e,t){return function(){return e.apply(t,arguments)}}const{toString:V1}=Object.prototype,{getPrototypeOf:sh}=Object,{iterator:Cc,toStringTag:W0}=Symbol,Ec=(e=>t=>{const n=V1.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),Hs=e=>(e=e.toLowerCase(),t=>Ec(t)===e),Dc=e=>t=>typeof t===e,{isArray:ni}=Array,Za=Dc("undefined");function kl(e){return e!==null&&!Za(e)&&e.constructor!==null&&!Za(e.constructor)&&us(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const G0=Hs("ArrayBuffer");function Q1(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&G0(e.buffer),t}const H1=Dc("string"),us=Dc("function"),Z0=Dc("number"),Cl=e=>e!==null&&typeof e=="object",W1=e=>e===!0||e===!1,vo=e=>{if(Ec(e)!=="object")return!1;const t=sh(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(W0 in e)&&!(Cc in e)},G1=e=>{if(!Cl(e)||kl(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},Z1=Hs("Date"),J1=Hs("File"),X1=Hs("Blob"),Y1=Hs("FileList"),eS=e=>Cl(e)&&us(e.pipe),tS=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||us(e.append)&&((t=Ec(e))==="formdata"||t==="object"&&us(e.toString)&&e.toString()==="[object FormData]"))},sS=Hs("URLSearchParams"),[nS,rS,aS,iS]=["ReadableStream","Request","Response","Headers"].map(Hs),lS=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function El(e,t,{allOwnKeys:n=!1}={}){if(e===null||typeof e>"u")return;let r,a;if(typeof e!="object"&&(e=[e]),ni(e))for(r=0,a=e.length;r0;)if(a=n[r],t===a.toLowerCase())return a;return null}const Dr=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,X0=e=>!Za(e)&&e!==Dr;function _u(){const{caseless:e,skipUndefined:t}=X0(this)&&this||{},n={},r=(a,i)=>{const l=e&&J0(n,i)||i;vo(n[l])&&vo(a)?n[l]=_u(n[l],a):vo(a)?n[l]=_u({},a):ni(a)?n[l]=a.slice():(!t||!Za(a))&&(n[l]=a)};for(let a=0,i=arguments.length;a(El(t,(a,i)=>{n&&us(a)?e[i]=H0(a,n):e[i]=a},{allOwnKeys:r}),e),cS=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),dS=(e,t,n,r)=>{e.prototype=Object.create(t.prototype,r),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},uS=(e,t,n,r)=>{let a,i,l;const o={};if(t=t||{},e==null)return t;do{for(a=Object.getOwnPropertyNames(e),i=a.length;i-- >0;)l=a[i],(!r||r(l,e,t))&&!o[l]&&(t[l]=e[l],o[l]=!0);e=n!==!1&&sh(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},mS=(e,t,n)=>{e=String(e),(n===void 0||n>e.length)&&(n=e.length),n-=t.length;const r=e.indexOf(t,n);return r!==-1&&r===n},hS=e=>{if(!e)return null;if(ni(e))return e;let t=e.length;if(!Z0(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},fS=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&sh(Uint8Array)),pS=(e,t)=>{const r=(e&&e[Cc]).call(e);let a;for(;(a=r.next())&&!a.done;){const i=a.value;t.call(e,i[0],i[1])}},xS=(e,t)=>{let n;const r=[];for(;(n=e.exec(t))!==null;)r.push(n);return r},gS=Hs("HTMLFormElement"),yS=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,a){return r.toUpperCase()+a}),Wp=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),vS=Hs("RegExp"),Y0=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),r={};El(n,(a,i)=>{let l;(l=t(a,i,e))!==!1&&(r[i]=l||a)}),Object.defineProperties(e,r)},jS=e=>{Y0(e,(t,n)=>{if(us(e)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const r=e[n];if(us(r)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},bS=(e,t)=>{const n={},r=a=>{a.forEach(i=>{n[i]=!0})};return ni(e)?r(e):r(String(e).split(t)),n},NS=()=>{},wS=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function SS(e){return!!(e&&us(e.append)&&e[W0]==="FormData"&&e[Cc])}const kS=e=>{const t=new Array(10),n=(r,a)=>{if(Cl(r)){if(t.indexOf(r)>=0)return;if(kl(r))return r;if(!("toJSON"in r)){t[a]=r;const i=ni(r)?[]:{};return El(r,(l,o)=>{const c=n(l,a+1);!Za(c)&&(i[o]=c)}),t[a]=void 0,i}}return r};return n(e,0)},CS=Hs("AsyncFunction"),ES=e=>e&&(Cl(e)||us(e))&&us(e.then)&&us(e.catch),ev=((e,t)=>e?setImmediate:t?((n,r)=>(Dr.addEventListener("message",({source:a,data:i})=>{a===Dr&&i===n&&r.length&&r.shift()()},!1),a=>{r.push(a),Dr.postMessage(n,"*")}))(`axios@${Math.random()}`,[]):n=>setTimeout(n))(typeof setImmediate=="function",us(Dr.postMessage)),DS=typeof queueMicrotask<"u"?queueMicrotask.bind(Dr):typeof process<"u"&&process.nextTick||ev,PS=e=>e!=null&&us(e[Cc]),q={isArray:ni,isArrayBuffer:G0,isBuffer:kl,isFormData:tS,isArrayBufferView:Q1,isString:H1,isNumber:Z0,isBoolean:W1,isObject:Cl,isPlainObject:vo,isEmptyObject:G1,isReadableStream:nS,isRequest:rS,isResponse:aS,isHeaders:iS,isUndefined:Za,isDate:Z1,isFile:J1,isBlob:X1,isRegExp:vS,isFunction:us,isStream:eS,isURLSearchParams:sS,isTypedArray:fS,isFileList:Y1,forEach:El,merge:_u,extend:oS,trim:lS,stripBOM:cS,inherits:dS,toFlatObject:uS,kindOf:Ec,kindOfTest:Hs,endsWith:mS,toArray:hS,forEachEntry:pS,matchAll:xS,isHTMLForm:gS,hasOwnProperty:Wp,hasOwnProp:Wp,reduceDescriptors:Y0,freezeMethods:jS,toObjectSet:bS,toCamelCase:yS,noop:NS,toFiniteNumber:wS,findKey:J0,global:Dr,isContextDefined:X0,isSpecCompliantForm:SS,toJSONObject:kS,isAsyncFn:CS,isThenable:ES,setImmediate:ev,asap:DS,isIterable:PS};function Se(e,t,n,r,a){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),r&&(this.request=r),a&&(this.response=a,this.status=a.status?a.status:null)}q.inherits(Se,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:q.toJSONObject(this.config),code:this.code,status:this.status}}});const tv=Se.prototype,sv={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{sv[e]={value:e}});Object.defineProperties(Se,sv);Object.defineProperty(tv,"isAxiosError",{value:!0});Se.from=(e,t,n,r,a,i)=>{const l=Object.create(tv);q.toFlatObject(e,l,function(u){return u!==Error.prototype},d=>d!=="isAxiosError");const o=e&&e.message?e.message:"Error",c=t==null&&e?e.code:t;return Se.call(l,o,c,n,r,a),e&&l.cause==null&&Object.defineProperty(l,"cause",{value:e,configurable:!0}),l.name=e&&e.name||"Error",i&&Object.assign(l,i),l};const AS=null;function Ku(e){return q.isPlainObject(e)||q.isArray(e)}function nv(e){return q.endsWith(e,"[]")?e.slice(0,-2):e}function Gp(e,t,n){return e?e.concat(t).map(function(a,i){return a=nv(a),!n&&i?"["+a+"]":a}).join(n?".":""):t}function MS(e){return q.isArray(e)&&!e.some(Ku)}const TS=q.toFlatObject(q,{},null,function(t){return/^is[A-Z]/.test(t)});function Pc(e,t,n){if(!q.isObject(e))throw new TypeError("target must be an object");t=t||new FormData,n=q.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(x,b){return!q.isUndefined(b[x])});const r=n.metaTokens,a=n.visitor||u,i=n.dots,l=n.indexes,c=(n.Blob||typeof Blob<"u"&&Blob)&&q.isSpecCompliantForm(t);if(!q.isFunction(a))throw new TypeError("visitor must be a function");function d(f){if(f===null)return"";if(q.isDate(f))return f.toISOString();if(q.isBoolean(f))return f.toString();if(!c&&q.isBlob(f))throw new Se("Blob is not supported. Use a Buffer instead.");return q.isArrayBuffer(f)||q.isTypedArray(f)?c&&typeof Blob=="function"?new Blob([f]):Buffer.from(f):f}function u(f,x,b){let y=f;if(f&&!b&&typeof f=="object"){if(q.endsWith(x,"{}"))x=r?x:x.slice(0,-2),f=JSON.stringify(f);else if(q.isArray(f)&&MS(f)||(q.isFileList(f)||q.endsWith(x,"[]"))&&(y=q.toArray(f)))return x=nv(x),y.forEach(function(v,N){!(q.isUndefined(v)||v===null)&&t.append(l===!0?Gp([x],N,i):l===null?x:x+"[]",d(v))}),!1}return Ku(f)?!0:(t.append(Gp(b,x,i),d(f)),!1)}const h=[],p=Object.assign(TS,{defaultVisitor:u,convertValue:d,isVisitable:Ku});function m(f,x){if(!q.isUndefined(f)){if(h.indexOf(f)!==-1)throw Error("Circular reference detected in "+x.join("."));h.push(f),q.forEach(f,function(y,g){(!(q.isUndefined(y)||y===null)&&a.call(t,y,q.isString(g)?g.trim():g,x,p))===!0&&m(y,x?x.concat(g):[g])}),h.pop()}}if(!q.isObject(e))throw new TypeError("data must be an object");return m(e),t}function Zp(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(r){return t[r]})}function nh(e,t){this._pairs=[],e&&Pc(e,this,t)}const rv=nh.prototype;rv.append=function(t,n){this._pairs.push([t,n])};rv.toString=function(t){const n=t?function(r){return t.call(this,r,Zp)}:Zp;return this._pairs.map(function(a){return n(a[0])+"="+n(a[1])},"").join("&")};function FS(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function av(e,t,n){if(!t)return e;const r=n&&n.encode||FS;q.isFunction(n)&&(n={serialize:n});const a=n&&n.serialize;let i;if(a?i=a(t,n):i=q.isURLSearchParams(t)?t.toString():new nh(t,n).toString(r),i){const l=e.indexOf("#");l!==-1&&(e=e.slice(0,l)),e+=(e.indexOf("?")===-1?"?":"&")+i}return e}class Jp{constructor(){this.handlers=[]}use(t,n,r){return this.handlers.push({fulfilled:t,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){q.forEach(this.handlers,function(r){r!==null&&t(r)})}}const iv={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},IS=typeof URLSearchParams<"u"?URLSearchParams:nh,RS=typeof FormData<"u"?FormData:null,LS=typeof Blob<"u"?Blob:null,OS={isBrowser:!0,classes:{URLSearchParams:IS,FormData:RS,Blob:LS},protocols:["http","https","file","blob","url","data"]},rh=typeof window<"u"&&typeof document<"u",Uu=typeof navigator=="object"&&navigator||void 0,zS=rh&&(!Uu||["ReactNative","NativeScript","NS"].indexOf(Uu.product)<0),$S=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",_S=rh&&window.location.href||"http://localhost",KS=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:rh,hasStandardBrowserEnv:zS,hasStandardBrowserWebWorkerEnv:$S,navigator:Uu,origin:_S},Symbol.toStringTag,{value:"Module"})),Bt={...KS,...OS};function US(e,t){return Pc(e,new Bt.classes.URLSearchParams,{visitor:function(n,r,a,i){return Bt.isNode&&q.isBuffer(n)?(this.append(r,n.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)},...t})}function BS(e){return q.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function qS(e){const t={},n=Object.keys(e);let r;const a=n.length;let i;for(r=0;r=n.length;return l=!l&&q.isArray(a)?a.length:l,c?(q.hasOwnProp(a,l)?a[l]=[a[l],r]:a[l]=r,!o):((!a[l]||!q.isObject(a[l]))&&(a[l]=[]),t(n,r,a[l],i)&&q.isArray(a[l])&&(a[l]=qS(a[l])),!o)}if(q.isFormData(e)&&q.isFunction(e.entries)){const n={};return q.forEachEntry(e,(r,a)=>{t(BS(r),a,n,0)}),n}return null}function VS(e,t,n){if(q.isString(e))try{return(t||JSON.parse)(e),q.trim(e)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(e)}const Dl={transitional:iv,adapter:["xhr","http","fetch"],transformRequest:[function(t,n){const r=n.getContentType()||"",a=r.indexOf("application/json")>-1,i=q.isObject(t);if(i&&q.isHTMLForm(t)&&(t=new FormData(t)),q.isFormData(t))return a?JSON.stringify(lv(t)):t;if(q.isArrayBuffer(t)||q.isBuffer(t)||q.isStream(t)||q.isFile(t)||q.isBlob(t)||q.isReadableStream(t))return t;if(q.isArrayBufferView(t))return t.buffer;if(q.isURLSearchParams(t))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let o;if(i){if(r.indexOf("application/x-www-form-urlencoded")>-1)return US(t,this.formSerializer).toString();if((o=q.isFileList(t))||r.indexOf("multipart/form-data")>-1){const c=this.env&&this.env.FormData;return Pc(o?{"files[]":t}:t,c&&new c,this.formSerializer)}}return i||a?(n.setContentType("application/json",!1),VS(t)):t}],transformResponse:[function(t){const n=this.transitional||Dl.transitional,r=n&&n.forcedJSONParsing,a=this.responseType==="json";if(q.isResponse(t)||q.isReadableStream(t))return t;if(t&&q.isString(t)&&(r&&!this.responseType||a)){const l=!(n&&n.silentJSONParsing)&&a;try{return JSON.parse(t,this.parseReviver)}catch(o){if(l)throw o.name==="SyntaxError"?Se.from(o,Se.ERR_BAD_RESPONSE,this,null,this.response):o}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Bt.classes.FormData,Blob:Bt.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};q.forEach(["delete","get","head","post","put","patch"],e=>{Dl.headers[e]={}});const QS=q.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),HS=e=>{const t={};let n,r,a;return e&&e.split(` `).forEach(function(l){a=l.indexOf(":"),n=l.substring(0,a).trim().toLowerCase(),r=l.substring(a+1).trim(),!(!n||t[n]&&QS[n])&&(n==="set-cookie"?t[n]?t[n].push(r):t[n]=[r]:t[n]=t[n]?t[n]+", "+r:r)}),t},Xp=Symbol("internals");function gi(e){return e&&String(e).trim().toLowerCase()}function jo(e){return e===!1||e==null?e:q.isArray(e)?e.map(jo):String(e)}function WS(e){const t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(e);)t[r[1]]=r[2];return t}const GS=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function ud(e,t,n,r,a){if(q.isFunction(r))return r.call(this,t,n);if(a&&(t=n),!!q.isString(t)){if(q.isString(r))return t.indexOf(r)!==-1;if(q.isRegExp(r))return r.test(t)}}function ZS(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,n,r)=>n.toUpperCase()+r)}function JS(e,t){const n=q.toCamelCase(" "+t);["get","set","has"].forEach(r=>{Object.defineProperty(e,r+n,{value:function(a,i,l){return this[r].call(this,t,a,i,l)},configurable:!0})})}let ms=class{constructor(t){t&&this.set(t)}set(t,n,r){const a=this;function i(o,c,d){const u=gi(c);if(!u)throw new Error("header name must be a non-empty string");const h=q.findKey(a,u);(!h||a[h]===void 0||d===!0||d===void 0&&a[h]!==!1)&&(a[h||c]=jo(o))}const l=(o,c)=>q.forEach(o,(d,u)=>i(d,u,c));if(q.isPlainObject(t)||t instanceof this.constructor)l(t,n);else if(q.isString(t)&&(t=t.trim())&&!GS(t))l(HS(t),n);else if(q.isObject(t)&&q.isIterable(t)){let o={},c,d;for(const u of t){if(!q.isArray(u))throw TypeError("Object iterator must return a key-value pair");o[d=u[0]]=(c=o[d])?q.isArray(c)?[...c,u[1]]:[c,u[1]]:u[1]}l(o,n)}else t!=null&&i(n,t,r);return this}get(t,n){if(t=gi(t),t){const r=q.findKey(this,t);if(r){const a=this[r];if(!n)return a;if(n===!0)return WS(a);if(q.isFunction(n))return n.call(this,a,r);if(q.isRegExp(n))return n.exec(a);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,n){if(t=gi(t),t){const r=q.findKey(this,t);return!!(r&&this[r]!==void 0&&(!n||ud(this,this[r],r,n)))}return!1}delete(t,n){const r=this;let a=!1;function i(l){if(l=gi(l),l){const o=q.findKey(r,l);o&&(!n||ud(r,r[o],o,n))&&(delete r[o],a=!0)}}return q.isArray(t)?t.forEach(i):i(t),a}clear(t){const n=Object.keys(this);let r=n.length,a=!1;for(;r--;){const i=n[r];(!t||ud(this,this[i],i,t,!0))&&(delete this[i],a=!0)}return a}normalize(t){const n=this,r={};return q.forEach(this,(a,i)=>{const l=q.findKey(r,i);if(l){n[l]=jo(a),delete n[i];return}const o=t?ZS(i):String(i).trim();o!==i&&delete n[i],n[o]=jo(a),r[o]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){const n=Object.create(null);return q.forEach(this,(r,a)=>{r!=null&&r!==!1&&(n[a]=t&&q.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,n])=>t+": "+n).join(` `)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...n){const r=new this(t);return n.forEach(a=>r.set(a)),r}static accessor(t){const r=(this[Xp]=this[Xp]={accessors:{}}).accessors,a=this.prototype;function i(l){const o=gi(l);r[o]||(JS(a,l),r[o]=!0)}return q.isArray(t)?t.forEach(i):i(t),this}};ms.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);q.reduceDescriptors(ms.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}});q.freezeMethods(ms);function md(e,t){const n=this||Dl,r=t||n,a=ms.from(r.headers);let i=r.data;return q.forEach(e,function(o){i=o.call(n,i,a.normalize(),t?t.status:void 0)}),a.normalize(),i}function ov(e){return!!(e&&e.__CANCEL__)}function ri(e,t,n){Se.call(this,e??"canceled",Se.ERR_CANCELED,t,n),this.name="CanceledError"}q.inherits(ri,Se,{__CANCEL__:!0});function cv(e,t,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new Se("Request failed with status code "+n.status,[Se.ERR_BAD_REQUEST,Se.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function XS(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function YS(e,t){e=e||10;const n=new Array(e),r=new Array(e);let a=0,i=0,l;return t=t!==void 0?t:1e3,function(c){const d=Date.now(),u=r[i];l||(l=d),n[a]=c,r[a]=d;let h=i,p=0;for(;h!==a;)p+=n[h++],h=h%e;if(a=(a+1)%e,a===i&&(i=(i+1)%e),d-l{n=u,a=null,i&&(clearTimeout(i),i=null),e(...d)};return[(...d)=>{const u=Date.now(),h=u-n;h>=r?l(d,u):(a=d,i||(i=setTimeout(()=>{i=null,l(a)},r-h)))},()=>a&&l(a)]}const Xo=(e,t,n=3)=>{let r=0;const a=YS(50,250);return e2(i=>{const l=i.loaded,o=i.lengthComputable?i.total:void 0,c=l-r,d=a(c),u=l<=o;r=l;const h={loaded:l,total:o,progress:o?l/o:void 0,bytes:c,rate:d||void 0,estimated:d&&o&&u?(o-l)/d:void 0,event:i,lengthComputable:o!=null,[t?"download":"upload"]:!0};e(h)},n)},Yp=(e,t)=>{const n=e!=null;return[r=>t[0]({lengthComputable:n,total:e,loaded:r}),t[1]]},ex=e=>(...t)=>q.asap(()=>e(...t)),t2=Bt.hasStandardBrowserEnv?((e,t)=>n=>(n=new URL(n,Bt.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new URL(Bt.origin),Bt.navigator&&/(msie|trident)/i.test(Bt.navigator.userAgent)):()=>!0,s2=Bt.hasStandardBrowserEnv?{write(e,t,n,r,a,i,l){if(typeof document>"u")return;const o=[`${e}=${encodeURIComponent(t)}`];q.isNumber(n)&&o.push(`expires=${new Date(n).toUTCString()}`),q.isString(r)&&o.push(`path=${r}`),q.isString(a)&&o.push(`domain=${a}`),i===!0&&o.push("secure"),q.isString(l)&&o.push(`SameSite=${l}`),document.cookie=o.join("; ")},read(e){if(typeof document>"u")return null;const t=document.cookie.match(new RegExp("(?:^|; )"+e+"=([^;]*)"));return t?decodeURIComponent(t[1]):null},remove(e){this.write(e,"",Date.now()-864e5,"/")}}:{write(){},read(){return null},remove(){}};function n2(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function r2(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function dv(e,t,n){let r=!n2(t);return e&&(r||n==!1)?r2(e,t):t}const tx=e=>e instanceof ms?{...e}:e;function Zr(e,t){t=t||{};const n={};function r(d,u,h,p){return q.isPlainObject(d)&&q.isPlainObject(u)?q.merge.call({caseless:p},d,u):q.isPlainObject(u)?q.merge({},u):q.isArray(u)?u.slice():u}function a(d,u,h,p){if(q.isUndefined(u)){if(!q.isUndefined(d))return r(void 0,d,h,p)}else return r(d,u,h,p)}function i(d,u){if(!q.isUndefined(u))return r(void 0,u)}function l(d,u){if(q.isUndefined(u)){if(!q.isUndefined(d))return r(void 0,d)}else return r(void 0,u)}function o(d,u,h){if(h in t)return r(d,u);if(h in e)return r(void 0,d)}const c={url:i,method:i,data:i,baseURL:l,transformRequest:l,transformResponse:l,paramsSerializer:l,timeout:l,timeoutMessage:l,withCredentials:l,withXSRFToken:l,adapter:l,responseType:l,xsrfCookieName:l,xsrfHeaderName:l,onUploadProgress:l,onDownloadProgress:l,decompress:l,maxContentLength:l,maxBodyLength:l,beforeRedirect:l,transport:l,httpAgent:l,httpsAgent:l,cancelToken:l,socketPath:l,responseEncoding:l,validateStatus:o,headers:(d,u,h)=>a(tx(d),tx(u),h,!0)};return q.forEach(Object.keys({...e,...t}),function(u){const h=c[u]||a,p=h(e[u],t[u],u);q.isUndefined(p)&&h!==o||(n[u]=p)}),n}const uv=e=>{const t=Zr({},e);let{data:n,withXSRFToken:r,xsrfHeaderName:a,xsrfCookieName:i,headers:l,auth:o}=t;if(t.headers=l=ms.from(l),t.url=av(dv(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),o&&l.set("Authorization","Basic "+btoa((o.username||"")+":"+(o.password?unescape(encodeURIComponent(o.password)):""))),q.isFormData(n)){if(Bt.hasStandardBrowserEnv||Bt.hasStandardBrowserWebWorkerEnv)l.setContentType(void 0);else if(q.isFunction(n.getHeaders)){const c=n.getHeaders(),d=["content-type","content-length"];Object.entries(c).forEach(([u,h])=>{d.includes(u.toLowerCase())&&l.set(u,h)})}}if(Bt.hasStandardBrowserEnv&&(r&&q.isFunction(r)&&(r=r(t)),r||r!==!1&&t2(t.url))){const c=a&&i&&s2.read(i);c&&l.set(a,c)}return t},a2=typeof XMLHttpRequest<"u",i2=a2&&function(e){return new Promise(function(n,r){const a=uv(e);let i=a.data;const l=ms.from(a.headers).normalize();let{responseType:o,onUploadProgress:c,onDownloadProgress:d}=a,u,h,p,m,f;function x(){m&&m(),f&&f(),a.cancelToken&&a.cancelToken.unsubscribe(u),a.signal&&a.signal.removeEventListener("abort",u)}let b=new XMLHttpRequest;b.open(a.method.toUpperCase(),a.url,!0),b.timeout=a.timeout;function y(){if(!b)return;const v=ms.from("getAllResponseHeaders"in b&&b.getAllResponseHeaders()),D={data:!o||o==="text"||o==="json"?b.responseText:b.response,status:b.status,statusText:b.statusText,headers:v,config:e,request:b};cv(function(R){n(R),x()},function(R){r(R),x()},D),b=null}"onloadend"in b?b.onloadend=y:b.onreadystatechange=function(){!b||b.readyState!==4||b.status===0&&!(b.responseURL&&b.responseURL.indexOf("file:")===0)||setTimeout(y)},b.onabort=function(){b&&(r(new Se("Request aborted",Se.ECONNABORTED,e,b)),b=null)},b.onerror=function(N){const D=N&&N.message?N.message:"Network Error",A=new Se(D,Se.ERR_NETWORK,e,b);A.event=N||null,r(A),b=null},b.ontimeout=function(){let N=a.timeout?"timeout of "+a.timeout+"ms exceeded":"timeout exceeded";const D=a.transitional||iv;a.timeoutErrorMessage&&(N=a.timeoutErrorMessage),r(new Se(N,D.clarifyTimeoutError?Se.ETIMEDOUT:Se.ECONNABORTED,e,b)),b=null},i===void 0&&l.setContentType(null),"setRequestHeader"in b&&q.forEach(l.toJSON(),function(N,D){b.setRequestHeader(D,N)}),q.isUndefined(a.withCredentials)||(b.withCredentials=!!a.withCredentials),o&&o!=="json"&&(b.responseType=a.responseType),d&&([p,f]=Xo(d,!0),b.addEventListener("progress",p)),c&&b.upload&&([h,m]=Xo(c),b.upload.addEventListener("progress",h),b.upload.addEventListener("loadend",m)),(a.cancelToken||a.signal)&&(u=v=>{b&&(r(!v||v.type?new ri(null,e,b):v),b.abort(),b=null)},a.cancelToken&&a.cancelToken.subscribe(u),a.signal&&(a.signal.aborted?u():a.signal.addEventListener("abort",u)));const g=XS(a.url);if(g&&Bt.protocols.indexOf(g)===-1){r(new Se("Unsupported protocol "+g+":",Se.ERR_BAD_REQUEST,e));return}b.send(i||null)})},l2=(e,t)=>{const{length:n}=e=e?e.filter(Boolean):[];if(t||n){let r=new AbortController,a;const i=function(d){if(!a){a=!0,o();const u=d instanceof Error?d:this.reason;r.abort(u instanceof Se?u:new ri(u instanceof Error?u.message:u))}};let l=t&&setTimeout(()=>{l=null,i(new Se(`timeout ${t} of ms exceeded`,Se.ETIMEDOUT))},t);const o=()=>{e&&(l&&clearTimeout(l),l=null,e.forEach(d=>{d.unsubscribe?d.unsubscribe(i):d.removeEventListener("abort",i)}),e=null)};e.forEach(d=>d.addEventListener("abort",i));const{signal:c}=r;return c.unsubscribe=()=>q.asap(o),c}},o2=function*(e,t){let n=e.byteLength;if(n{const a=c2(e,t);let i=0,l,o=c=>{l||(l=!0,r&&r(c))};return new ReadableStream({async pull(c){try{const{done:d,value:u}=await a.next();if(d){o(),c.close();return}let h=u.byteLength;if(n){let p=i+=h;n(p)}c.enqueue(new Uint8Array(u))}catch(d){throw o(d),d}},cancel(c){return o(c),a.return()}},{highWaterMark:2})},nx=64*1024,{isFunction:so}=q,u2=(({Request:e,Response:t})=>({Request:e,Response:t}))(q.global),{ReadableStream:rx,TextEncoder:ax}=q.global,ix=(e,...t)=>{try{return!!e(...t)}catch{return!1}},m2=e=>{e=q.merge.call({skipUndefined:!0},u2,e);const{fetch:t,Request:n,Response:r}=e,a=t?so(t):typeof fetch=="function",i=so(n),l=so(r);if(!a)return!1;const o=a&&so(rx),c=a&&(typeof ax=="function"?(f=>x=>f.encode(x))(new ax):async f=>new Uint8Array(await new n(f).arrayBuffer())),d=i&&o&&ix(()=>{let f=!1;const x=new n(Bt.origin,{body:new rx,method:"POST",get duplex(){return f=!0,"half"}}).headers.has("Content-Type");return f&&!x}),u=l&&o&&ix(()=>q.isReadableStream(new r("").body)),h={stream:u&&(f=>f.body)};a&&["text","arrayBuffer","blob","formData","stream"].forEach(f=>{!h[f]&&(h[f]=(x,b)=>{let y=x&&x[f];if(y)return y.call(x);throw new Se(`Response type '${f}' is not supported`,Se.ERR_NOT_SUPPORT,b)})});const p=async f=>{if(f==null)return 0;if(q.isBlob(f))return f.size;if(q.isSpecCompliantForm(f))return(await new n(Bt.origin,{method:"POST",body:f}).arrayBuffer()).byteLength;if(q.isArrayBufferView(f)||q.isArrayBuffer(f))return f.byteLength;if(q.isURLSearchParams(f)&&(f=f+""),q.isString(f))return(await c(f)).byteLength},m=async(f,x)=>{const b=q.toFiniteNumber(f.getContentLength());return b??p(x)};return async f=>{let{url:x,method:b,data:y,signal:g,cancelToken:v,timeout:N,onDownloadProgress:D,onUploadProgress:A,responseType:R,headers:w,withCredentials:S="same-origin",fetchOptions:E}=uv(f),z=t||fetch;R=R?(R+"").toLowerCase():"text";let I=l2([g,v&&v.toAbortSignal()],N),B=null;const P=I&&I.unsubscribe&&(()=>{I.unsubscribe()});let M;try{if(A&&d&&b!=="get"&&b!=="head"&&(M=await m(w,y))!==0){let pe=new n(x,{method:"POST",body:y,duplex:"half"}),oe;if(q.isFormData(y)&&(oe=pe.headers.get("content-type"))&&w.setContentType(oe),pe.body){const[Ze,Oe]=Yp(M,Xo(ex(A)));y=sx(pe.body,nx,Ze,Oe)}}q.isString(S)||(S=S?"include":"omit");const k=i&&"credentials"in n.prototype,_={...E,signal:I,method:b.toUpperCase(),headers:w.normalize().toJSON(),body:y,duplex:"half",credentials:k?S:void 0};B=i&&new n(x,_);let K=await(i?z(B,E):z(x,_));const Z=u&&(R==="stream"||R==="response");if(u&&(D||Z&&P)){const pe={};["status","statusText","headers"].forEach(it=>{pe[it]=K[it]});const oe=q.toFiniteNumber(K.headers.get("content-length")),[Ze,Oe]=D&&Yp(oe,Xo(ex(D),!0))||[];K=new r(sx(K.body,nx,Ze,()=>{Oe&&Oe(),P&&P()}),pe)}R=R||"text";let H=await h[q.findKey(h,R)||"text"](K,f);return!Z&&P&&P(),await new Promise((pe,oe)=>{cv(pe,oe,{data:H,headers:ms.from(K.headers),status:K.status,statusText:K.statusText,config:f,request:B})})}catch(k){throw P&&P(),k&&k.name==="TypeError"&&/Load failed|fetch/i.test(k.message)?Object.assign(new Se("Network Error",Se.ERR_NETWORK,f,B),{cause:k.cause||k}):Se.from(k,k&&k.code,f,B)}}},h2=new Map,mv=e=>{let t=e&&e.env||{};const{fetch:n,Request:r,Response:a}=t,i=[r,a,n];let l=i.length,o=l,c,d,u=h2;for(;o--;)c=i[o],d=u.get(c),d===void 0&&u.set(c,d=o?new Map:m2(t)),u=d;return d};mv();const ah={http:AS,xhr:i2,fetch:{get:mv}};q.forEach(ah,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const lx=e=>`- ${e}`,f2=e=>q.isFunction(e)||e===null||e===!1;function p2(e,t){e=q.isArray(e)?e:[e];const{length:n}=e;let r,a;const i={};for(let l=0;l`adapter ${c} `+(d===!1?"is not supported by the environment":"is not available in the build"));let o=n?l.length>1?`since : `+l.map(lx).join(` `):" "+lx(l[0]):"as no adapter specified";throw new Se("There is no suitable adapter to dispatch the request "+o,"ERR_NOT_SUPPORT")}return a}const hv={getAdapter:p2,adapters:ah};function hd(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new ri(null,e)}function ox(e){return hd(e),e.headers=ms.from(e.headers),e.data=md.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),hv.getAdapter(e.adapter||Dl.adapter,e)(e).then(function(r){return hd(e),r.data=md.call(e,e.transformResponse,r),r.headers=ms.from(r.headers),r},function(r){return ov(r)||(hd(e),r&&r.response&&(r.response.data=md.call(e,e.transformResponse,r.response),r.response.headers=ms.from(r.response.headers))),Promise.reject(r)})}const fv="1.13.2",Ac={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{Ac[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const cx={};Ac.transitional=function(t,n,r){function a(i,l){return"[Axios v"+fv+"] Transitional option '"+i+"'"+l+(r?". "+r:"")}return(i,l,o)=>{if(t===!1)throw new Se(a(l," has been removed"+(n?" in "+n:"")),Se.ERR_DEPRECATED);return n&&!cx[l]&&(cx[l]=!0,console.warn(a(l," has been deprecated since v"+n+" and will be removed in the near future"))),t?t(i,l,o):!0}};Ac.spelling=function(t){return(n,r)=>(console.warn(`${r} is likely a misspelling of ${t}`),!0)};function x2(e,t,n){if(typeof e!="object")throw new Se("options must be an object",Se.ERR_BAD_OPTION_VALUE);const r=Object.keys(e);let a=r.length;for(;a-- >0;){const i=r[a],l=t[i];if(l){const o=e[i],c=o===void 0||l(o,i,e);if(c!==!0)throw new Se("option "+i+" must be "+c,Se.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new Se("Unknown option "+i,Se.ERR_BAD_OPTION)}}const bo={assertOptions:x2,validators:Ac},Gs=bo.validators;let Kr=class{constructor(t){this.defaults=t||{},this.interceptors={request:new Jp,response:new Jp}}async request(t,n){try{return await this._request(t,n)}catch(r){if(r instanceof Error){let a={};Error.captureStackTrace?Error.captureStackTrace(a):a=new Error;const i=a.stack?a.stack.replace(/^.+\n/,""):"";try{r.stack?i&&!String(r.stack).endsWith(i.replace(/^.+\n.+\n/,""))&&(r.stack+=` `+i):r.stack=i}catch{}}throw r}}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=Zr(this.defaults,n);const{transitional:r,paramsSerializer:a,headers:i}=n;r!==void 0&&bo.assertOptions(r,{silentJSONParsing:Gs.transitional(Gs.boolean),forcedJSONParsing:Gs.transitional(Gs.boolean),clarifyTimeoutError:Gs.transitional(Gs.boolean)},!1),a!=null&&(q.isFunction(a)?n.paramsSerializer={serialize:a}:bo.assertOptions(a,{encode:Gs.function,serialize:Gs.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),bo.assertOptions(n,{baseUrl:Gs.spelling("baseURL"),withXsrfToken:Gs.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let l=i&&q.merge(i.common,i[n.method]);i&&q.forEach(["delete","get","head","post","put","patch","common"],f=>{delete i[f]}),n.headers=ms.concat(l,i);const o=[];let c=!0;this.interceptors.request.forEach(function(x){typeof x.runWhen=="function"&&x.runWhen(n)===!1||(c=c&&x.synchronous,o.unshift(x.fulfilled,x.rejected))});const d=[];this.interceptors.response.forEach(function(x){d.push(x.fulfilled,x.rejected)});let u,h=0,p;if(!c){const f=[ox.bind(this),void 0];for(f.unshift(...o),f.push(...d),p=f.length,u=Promise.resolve(n);h{if(!r._listeners)return;let i=r._listeners.length;for(;i-- >0;)r._listeners[i](a);r._listeners=null}),this.promise.then=a=>{let i;const l=new Promise(o=>{r.subscribe(o),i=o}).then(a);return l.cancel=function(){r.unsubscribe(i)},l},t(function(i,l,o){r.reason||(r.reason=new ri(i,l,o),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const t=new AbortController,n=r=>{t.abort(r)};return this.subscribe(n),t.signal.unsubscribe=()=>this.unsubscribe(n),t.signal}static source(){let t;return{token:new pv(function(a){t=a}),cancel:t}}};function y2(e){return function(n){return e.apply(null,n)}}function v2(e){return q.isObject(e)&&e.isAxiosError===!0}const Bu={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(Bu).forEach(([e,t])=>{Bu[t]=e});function xv(e){const t=new Kr(e),n=H0(Kr.prototype.request,t);return q.extend(n,Kr.prototype,t,{allOwnKeys:!0}),q.extend(n,t,null,{allOwnKeys:!0}),n.create=function(a){return xv(Zr(e,a))},n}const xt=xv(Dl);xt.Axios=Kr;xt.CanceledError=ri;xt.CancelToken=g2;xt.isCancel=ov;xt.VERSION=fv;xt.toFormData=Pc;xt.AxiosError=Se;xt.Cancel=xt.CanceledError;xt.all=function(t){return Promise.all(t)};xt.spread=y2;xt.isAxiosError=v2;xt.mergeConfig=Zr;xt.AxiosHeaders=ms;xt.formToJSON=e=>lv(q.isHTMLForm(e)?new FormData(e):e);xt.getAdapter=hv.getAdapter;xt.HttpStatusCode=Bu;xt.default=xt;const{Axios:u4,AxiosError:m4,CanceledError:h4,isCancel:f4,CancelToken:p4,VERSION:x4,all:g4,Cancel:y4,isAxiosError:v4,spread:j4,toFormData:b4,AxiosHeaders:N4,HttpStatusCode:w4,formToJSON:S4,getAdapter:k4,mergeConfig:C4}=xt,$=xt.create({baseURL:"/api",headers:{"Content-Type":"application/json"}});$.interceptors.request.use(e=>{const t=localStorage.getItem("token");return t&&(e.headers.Authorization=`Bearer ${t}`),e});$.interceptors.response.use(e=>e,e=>{var a,i,l,o,c,d,u;const t=((i=(a=e.config)==null?void 0:a.url)==null?void 0:i.includes("/auth/login"))||((o=(l=e.config)==null?void 0:l.url)==null?void 0:o.includes("/auth/customer-login"));((c=e.response)==null?void 0:c.status)===401&&!t&&(localStorage.removeItem("token"),localStorage.removeItem("user"),window.location.href="/login");const n=((u=(d=e.response)==null?void 0:d.data)==null?void 0:u.error)||e.message||"Ein Fehler ist aufgetreten",r=new Error(n);return Promise.reject(r)});const no={login:async(e,t)=>(await $.post("/auth/login",{email:e,password:t})).data,customerLogin:async(e,t)=>(await $.post("/auth/customer-login",{email:e,password:t})).data,me:async()=>(await $.get("/auth/me")).data},Dt={getAll:async e=>(await $.get("/customers",{params:e})).data,getById:async e=>(await $.get(`/customers/${e}`)).data,create:async e=>(await $.post("/customers",e)).data,update:async(e,t)=>(await $.put(`/customers/${e}`,t)).data,delete:async e=>(await $.delete(`/customers/${e}`)).data,getPortalSettings:async e=>(await $.get(`/customers/${e}/portal`)).data,updatePortalSettings:async(e,t)=>(await $.put(`/customers/${e}/portal`,t)).data,setPortalPassword:async(e,t)=>(await $.post(`/customers/${e}/portal/password`,{password:t})).data,getPortalPassword:async e=>(await $.get(`/customers/${e}/portal/password`)).data,getRepresentatives:async e=>(await $.get(`/customers/${e}/representatives`)).data,addRepresentative:async(e,t,n)=>(await $.post(`/customers/${e}/representatives`,{representativeId:t,notes:n})).data,removeRepresentative:async(e,t)=>(await $.delete(`/customers/${e}/representatives/${t}`)).data,searchForRepresentative:async(e,t)=>(await $.get(`/customers/${e}/representatives/search`,{params:{search:t}})).data},qu={getByCustomer:async e=>(await $.get(`/customers/${e}/addresses`)).data,create:async(e,t)=>(await $.post(`/customers/${e}/addresses`,t)).data,update:async(e,t)=>(await $.put(`/addresses/${e}`,t)).data,delete:async e=>(await $.delete(`/addresses/${e}`)).data},Yo={getByCustomer:async(e,t=!1)=>(await $.get(`/customers/${e}/bank-cards`,{params:{showInactive:t}})).data,create:async(e,t)=>(await $.post(`/customers/${e}/bank-cards`,t)).data,update:async(e,t)=>(await $.put(`/bank-cards/${e}`,t)).data,delete:async e=>(await $.delete(`/bank-cards/${e}`)).data},ec={getByCustomer:async(e,t=!1)=>(await $.get(`/customers/${e}/documents`,{params:{showInactive:t}})).data,create:async(e,t)=>(await $.post(`/customers/${e}/documents`,t)).data,update:async(e,t)=>(await $.put(`/documents/${e}`,t)).data,delete:async e=>(await $.delete(`/documents/${e}`)).data},ln={getByCustomer:async(e,t=!1)=>(await $.get(`/customers/${e}/meters`,{params:{showInactive:t}})).data,create:async(e,t)=>(await $.post(`/customers/${e}/meters`,t)).data,update:async(e,t)=>(await $.put(`/meters/${e}`,t)).data,delete:async e=>(await $.delete(`/meters/${e}`)).data,getReadings:async e=>(await $.get(`/meters/${e}/readings`)).data,addReading:async(e,t)=>(await $.post(`/meters/${e}/readings`,t)).data,updateReading:async(e,t,n)=>(await $.put(`/meters/${e}/readings/${t}`,n)).data,deleteReading:async(e,t)=>(await $.delete(`/meters/${e}/readings/${t}`)).data},ra={getInvoices:async e=>(await $.get(`/energy-details/${e}/invoices`)).data,addInvoice:async(e,t)=>(await $.post(`/energy-details/${e}/invoices`,t)).data,updateInvoice:async(e,t,n)=>(await $.put(`/energy-details/${e}/invoices/${t}`,n)).data,deleteInvoice:async(e,t)=>(await $.delete(`/energy-details/${e}/invoices/${t}`)).data,uploadDocument:async(e,t)=>{const n=new FormData;return n.append("document",t),(await $.post(`/upload/invoices/${e}`,n,{headers:{"Content-Type":"multipart/form-data"}})).data},deleteDocument:async e=>(await $.delete(`/upload/invoices/${e}`)).data},xs={getByCustomer:async(e,t=!1)=>(await $.get(`/customers/${e}/stressfrei-emails`,{params:{includeInactive:t}})).data,create:async(e,t)=>(await $.post(`/customers/${e}/stressfrei-emails`,t)).data,update:async(e,t)=>(await $.put(`/stressfrei-emails/${e}`,t)).data,delete:async e=>(await $.delete(`/stressfrei-emails/${e}`)).data,enableMailbox:async e=>(await $.post(`/stressfrei-emails/${e}/enable-mailbox`)).data,syncMailboxStatus:async e=>(await $.post(`/stressfrei-emails/${e}/sync-mailbox-status`)).data,getMailboxCredentials:async e=>(await $.get(`/stressfrei-emails/${e}/credentials`)).data,resetPassword:async e=>(await $.post(`/stressfrei-emails/${e}/reset-password`)).data,syncEmails:async(e,t=!1)=>(await $.post(`/stressfrei-emails/${e}/sync`,{},{params:{full:t}})).data,sendEmail:async(e,t)=>(await $.post(`/stressfrei-emails/${e}/send`,t)).data,getFolderCounts:async e=>(await $.get(`/stressfrei-emails/${e}/folder-counts`)).data},Ae={getForCustomer:async(e,t)=>(await $.get(`/customers/${e}/emails`,{params:t})).data,getForContract:async(e,t)=>(await $.get(`/contracts/${e}/emails`,{params:t})).data,getContractFolderCounts:async e=>(await $.get(`/contracts/${e}/emails/folder-counts`)).data,getMailboxAccounts:async e=>(await $.get(`/customers/${e}/mailbox-accounts`)).data,getById:async e=>(await $.get(`/emails/${e}`)).data,getThread:async e=>(await $.get(`/emails/${e}/thread`)).data,markAsRead:async(e,t)=>(await $.patch(`/emails/${e}/read`,{isRead:t})).data,toggleStar:async e=>(await $.post(`/emails/${e}/star`)).data,assignToContract:async(e,t)=>(await $.post(`/emails/${e}/assign`,{contractId:t})).data,unassignFromContract:async e=>(await $.delete(`/emails/${e}/assign`)).data,delete:async e=>(await $.delete(`/emails/${e}`)).data,getAttachmentUrl:(e,t,n)=>{const r=localStorage.getItem("token"),a=encodeURIComponent(t),i=n?"&view=true":"";return`${$.defaults.baseURL}/emails/${e}/attachments/${a}?token=${r}${i}`},getUnreadCount:async e=>(await $.get("/emails/unread-count",{params:e})).data,getTrash:async e=>(await $.get(`/customers/${e}/emails/trash`)).data,getTrashCount:async e=>(await $.get(`/customers/${e}/emails/trash/count`)).data,restore:async e=>(await $.post(`/emails/${e}/restore`)).data,permanentDelete:async e=>(await $.delete(`/emails/${e}/permanent`)).data,getAttachmentTargets:async e=>(await $.get(`/emails/${e}/attachment-targets`)).data,saveAttachmentTo:async(e,t,n)=>{const r=encodeURIComponent(t);return(await $.post(`/emails/${e}/attachments/${r}/save-to`,n)).data},saveEmailAsPdf:async(e,t)=>(await $.post(`/emails/${e}/save-as-pdf`,t)).data,saveEmailAsInvoice:async(e,t)=>(await $.post(`/emails/${e}/save-as-invoice`,t)).data,saveAttachmentAsInvoice:async(e,t,n)=>{const r=encodeURIComponent(t);return(await $.post(`/emails/${e}/attachments/${r}/save-as-invoice`,n)).data}},Le={getAll:async e=>(await $.get("/contracts",{params:e})).data,getTreeForCustomer:async e=>(await $.get("/contracts",{params:{customerId:e,tree:"true"}})).data,getById:async e=>(await $.get(`/contracts/${e}`)).data,create:async e=>(await $.post("/contracts",e)).data,update:async(e,t)=>(await $.put(`/contracts/${e}`,t)).data,delete:async e=>(await $.delete(`/contracts/${e}`)).data,createFollowUp:async e=>(await $.post(`/contracts/${e}/follow-up`)).data,getPassword:async e=>(await $.get(`/contracts/${e}/password`)).data,getSimCardCredentials:async e=>(await $.get(`/contracts/simcard/${e}/credentials`)).data,getInternetCredentials:async e=>(await $.get(`/contracts/${e}/internet-credentials`)).data,getSipCredentials:async e=>(await $.get(`/contracts/phonenumber/${e}/sip-credentials`)).data,getCockpit:async()=>(await $.get("/contracts/cockpit")).data,snooze:async(e,t)=>(await $.patch(`/contracts/${e}/snooze`,t)).data},ut={getAll:async e=>(await $.get("/tasks",{params:e})).data,getStats:async()=>(await $.get("/tasks/stats")).data,getByContract:async(e,t)=>(await $.get(`/contracts/${e}/tasks`,{params:{status:t}})).data,create:async(e,t)=>(await $.post(`/contracts/${e}/tasks`,t)).data,update:async(e,t)=>(await $.put(`/tasks/${e}`,t)).data,complete:async e=>(await $.post(`/tasks/${e}/complete`)).data,reopen:async e=>(await $.post(`/tasks/${e}/reopen`)).data,delete:async e=>(await $.delete(`/tasks/${e}`)).data,createSubtask:async(e,t)=>(await $.post(`/tasks/${e}/subtasks`,{title:t})).data,createReply:async(e,t)=>(await $.post(`/tasks/${e}/reply`,{title:t})).data,updateSubtask:async(e,t)=>(await $.put(`/subtasks/${e}`,{title:t})).data,completeSubtask:async e=>(await $.post(`/subtasks/${e}/complete`)).data,reopenSubtask:async e=>(await $.post(`/subtasks/${e}/reopen`)).data,deleteSubtask:async e=>(await $.delete(`/subtasks/${e}`)).data,createSupportTicket:async(e,t)=>(await $.post(`/contracts/${e}/support-ticket`,t)).data},Jr={getPublic:async()=>(await $.get("/settings/public")).data,getAll:async()=>(await $.get("/settings")).data,update:async e=>(await $.put("/settings",e)).data,updateOne:async(e,t)=>(await $.put(`/settings/${e}`,{value:t})).data},jr={list:async()=>(await $.get("/settings/backups")).data,create:async()=>(await $.post("/settings/backup")).data,restore:async e=>(await $.post(`/settings/backup/${e}/restore`)).data,delete:async e=>(await $.delete(`/settings/backup/${e}`)).data,getDownloadUrl:e=>`/api/settings/backup/${e}/download`,upload:async e=>{const t=new FormData;return t.append("backup",e),(await $.post("/settings/backup/upload",t,{headers:{"Content-Type":"multipart/form-data"}})).data},factoryReset:async()=>(await $.post("/settings/factory-reset")).data},rl={getAll:async(e=!1)=>(await $.get("/platforms",{params:{includeInactive:e}})).data,getById:async e=>(await $.get(`/platforms/${e}`)).data,create:async e=>(await $.post("/platforms",e)).data,update:async(e,t)=>(await $.put(`/platforms/${e}`,t)).data,delete:async e=>(await $.delete(`/platforms/${e}`)).data},al={getAll:async(e=!1)=>(await $.get("/cancellation-periods",{params:{includeInactive:e}})).data,getById:async e=>(await $.get(`/cancellation-periods/${e}`)).data,create:async e=>(await $.post("/cancellation-periods",e)).data,update:async(e,t)=>(await $.put(`/cancellation-periods/${e}`,t)).data,delete:async e=>(await $.delete(`/cancellation-periods/${e}`)).data},il={getAll:async(e=!1)=>(await $.get("/contract-durations",{params:{includeInactive:e}})).data,getById:async e=>(await $.get(`/contract-durations/${e}`)).data,create:async e=>(await $.post("/contract-durations",e)).data,update:async(e,t)=>(await $.put(`/contract-durations/${e}`,t)).data,delete:async e=>(await $.delete(`/contract-durations/${e}`)).data},ll={getAll:async(e=!1)=>(await $.get("/contract-categories",{params:{includeInactive:e}})).data,getById:async e=>(await $.get(`/contract-categories/${e}`)).data,create:async e=>(await $.post("/contract-categories",e)).data,update:async(e,t)=>(await $.put(`/contract-categories/${e}`,t)).data,delete:async e=>(await $.delete(`/contract-categories/${e}`)).data},Ja={getAll:async(e=!1)=>(await $.get("/providers",{params:{includeInactive:e}})).data,getById:async e=>(await $.get(`/providers/${e}`)).data,create:async e=>(await $.post("/providers",e)).data,update:async(e,t)=>(await $.put(`/providers/${e}`,t)).data,delete:async e=>(await $.delete(`/providers/${e}`)).data,getTariffs:async(e,t=!1)=>(await $.get(`/providers/${e}/tariffs`,{params:{includeInactive:t}})).data,createTariff:async(e,t)=>(await $.post(`/providers/${e}/tariffs`,t)).data},gv={getById:async e=>(await $.get(`/tariffs/${e}`)).data,update:async(e,t)=>(await $.put(`/tariffs/${e}`,t)).data,delete:async e=>(await $.delete(`/tariffs/${e}`)).data},ct={uploadBankCardDocument:async(e,t)=>{const n=new FormData;return n.append("document",t),(await $.post(`/upload/bank-cards/${e}`,n,{headers:{"Content-Type":"multipart/form-data"}})).data},uploadIdentityDocument:async(e,t)=>{const n=new FormData;return n.append("document",t),(await $.post(`/upload/documents/${e}`,n,{headers:{"Content-Type":"multipart/form-data"}})).data},deleteBankCardDocument:async e=>(await $.delete(`/upload/bank-cards/${e}`)).data,deleteIdentityDocument:async e=>(await $.delete(`/upload/documents/${e}`)).data,uploadBusinessRegistration:async(e,t)=>{const n=new FormData;return n.append("document",t),(await $.post(`/upload/customers/${e}/business-registration`,n,{headers:{"Content-Type":"multipart/form-data"}})).data},deleteBusinessRegistration:async e=>(await $.delete(`/upload/customers/${e}/business-registration`)).data,uploadCommercialRegister:async(e,t)=>{const n=new FormData;return n.append("document",t),(await $.post(`/upload/customers/${e}/commercial-register`,n,{headers:{"Content-Type":"multipart/form-data"}})).data},deleteCommercialRegister:async e=>(await $.delete(`/upload/customers/${e}/commercial-register`)).data,uploadPrivacyPolicy:async(e,t)=>{const n=new FormData;return n.append("document",t),(await $.post(`/upload/customers/${e}/privacy-policy`,n,{headers:{"Content-Type":"multipart/form-data"}})).data},deletePrivacyPolicy:async e=>(await $.delete(`/upload/customers/${e}/privacy-policy`)).data,uploadCancellationLetter:async(e,t)=>{const n=new FormData;return n.append("document",t),(await $.post(`/upload/contracts/${e}/cancellation-letter`,n,{headers:{"Content-Type":"multipart/form-data"}})).data},deleteCancellationLetter:async e=>(await $.delete(`/upload/contracts/${e}/cancellation-letter`)).data,uploadCancellationConfirmation:async(e,t)=>{const n=new FormData;return n.append("document",t),(await $.post(`/upload/contracts/${e}/cancellation-confirmation`,n,{headers:{"Content-Type":"multipart/form-data"}})).data},deleteCancellationConfirmation:async e=>(await $.delete(`/upload/contracts/${e}/cancellation-confirmation`)).data,uploadCancellationLetterOptions:async(e,t)=>{const n=new FormData;return n.append("document",t),(await $.post(`/upload/contracts/${e}/cancellation-letter-options`,n,{headers:{"Content-Type":"multipart/form-data"}})).data},deleteCancellationLetterOptions:async e=>(await $.delete(`/upload/contracts/${e}/cancellation-letter-options`)).data,uploadCancellationConfirmationOptions:async(e,t)=>{const n=new FormData;return n.append("document",t),(await $.post(`/upload/contracts/${e}/cancellation-confirmation-options`,n,{headers:{"Content-Type":"multipart/form-data"}})).data},deleteCancellationConfirmationOptions:async e=>(await $.delete(`/upload/contracts/${e}/cancellation-confirmation-options`)).data},Ii={getAll:async e=>(await $.get("/users",{params:e})).data,getById:async e=>(await $.get(`/users/${e}`)).data,create:async e=>(await $.post("/users",e)).data,update:async(e,t)=>(await $.put(`/users/${e}`,t)).data,delete:async e=>(await $.delete(`/users/${e}`)).data,getRoles:async()=>(await $.get("/users/roles/list")).data},Si={getSchema:async()=>(await $.get("/developer/schema")).data,getTableData:async(e,t=1,n=50)=>(await $.get(`/developer/table/${e}`,{params:{page:t,limit:n}})).data,updateRow:async(e,t,n)=>(await $.put(`/developer/table/${e}/${t}`,n)).data,deleteRow:async(e,t)=>(await $.delete(`/developer/table/${e}/${t}`)).data,getReference:async e=>(await $.get(`/developer/reference/${e}`)).data},pn={getConfigs:async()=>(await $.get("/email-providers/configs")).data,getConfig:async e=>(await $.get(`/email-providers/configs/${e}`)).data,createConfig:async e=>(await $.post("/email-providers/configs",e)).data,updateConfig:async(e,t)=>(await $.put(`/email-providers/configs/${e}`,t)).data,deleteConfig:async e=>(await $.delete(`/email-providers/configs/${e}`)).data,testConnection:async e=>{const t=e!=null&&e.testData?{...e.testData}:e!=null&&e.id?{id:e.id}:{};return(await $.post("/email-providers/test-connection",t)).data},getDomain:async()=>(await $.get("/email-providers/domain")).data,checkEmailExists:async e=>(await $.get(`/email-providers/check/${e}`)).data,provisionEmail:async(e,t)=>(await $.post("/email-providers/provision",{localPart:e,customerEmail:t})).data,deprovisionEmail:async e=>(await $.delete(`/email-providers/deprovision/${e}`)).data},yv=j.createContext(null);function j2({children:e}){const[t,n]=j.useState(null),[r,a]=j.useState(!0),[i,l]=j.useState(()=>localStorage.getItem("developerMode")==="true"),o=x=>{l(x),localStorage.setItem("developerMode",String(x))};j.useEffect(()=>{var x;console.log("useEffect check - user:",t==null?void 0:t.email,"developerMode:",i,"has developer:access:",(x=t==null?void 0:t.permissions)==null?void 0:x.includes("developer:access")),t&&i&&!t.permissions.includes("developer:access")&&(console.log("Disabling developer mode because user lacks developer:access permission"),o(!1))},[t,i]),j.useEffect(()=>{localStorage.getItem("token")?no.me().then(b=>{b.success&&b.data?n(b.data):localStorage.removeItem("token")}).catch(()=>{localStorage.removeItem("token")}).finally(()=>{a(!1)}):a(!1)},[]);const c=async(x,b)=>{const y=await no.login(x,b);if(y.success&&y.data)localStorage.setItem("token",y.data.token),n(y.data.user);else throw new Error(y.error||"Login fehlgeschlagen")},d=async(x,b)=>{const y=await no.customerLogin(x,b);if(y.success&&y.data)localStorage.setItem("token",y.data.token),n(y.data.user);else throw new Error(y.error||"Login fehlgeschlagen")},u=()=>{localStorage.removeItem("token"),n(null)},h=async()=>{var b;if(localStorage.getItem("token"))try{const y=await no.me();console.log("refreshUser response:",y),console.log("permissions:",(b=y.data)==null?void 0:b.permissions),y.success&&y.data&&n(y.data)}catch(y){console.error("refreshUser error:",y)}},p=x=>t?t.permissions.includes(x):!1,m=!!(t!=null&&t.customerId),f=!!(t!=null&&t.isCustomerPortal);return s.jsx(yv.Provider,{value:{user:t,isLoading:r,isAuthenticated:!!t,login:c,customerLogin:d,logout:u,hasPermission:p,isCustomer:m,isCustomerPortal:f,developerMode:i,setDeveloperMode:o,refreshUser:h},children:e})}function He(){const e=j.useContext(yv);if(!e)throw new Error("useAuth must be used within an AuthProvider");return e}const fd={scrollToTopThreshold:.7},vv=j.createContext(void 0),dx="opencrm_app_settings";function b2({children:e}){const[t,n]=j.useState(()=>{const a=localStorage.getItem(dx);if(a)try{return{...fd,...JSON.parse(a)}}catch{return fd}return fd});j.useEffect(()=>{localStorage.setItem(dx,JSON.stringify(t))},[t]);const r=a=>{n(i=>({...i,...a}))};return s.jsx(vv.Provider,{value:{settings:t,updateSettings:r},children:e})}function jv(){const e=j.useContext(vv);if(!e)throw new Error("useAppSettings must be used within AppSettingsProvider");return e}function N2(){const{pathname:e}=Fn();return j.useEffect(()=>{window.scrollTo(0,0)},[e]),null}/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const w2=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),bv=(...e)=>e.filter((t,n,r)=>!!t&&t.trim()!==""&&r.indexOf(t)===n).join(" ").trim();/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */var S2={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const k2=j.forwardRef(({color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:r,className:a="",children:i,iconNode:l,...o},c)=>j.createElement("svg",{ref:c,...S2,width:t,height:t,stroke:e,strokeWidth:r?Number(n)*24/Number(t):n,className:bv("lucide",a),...o},[...l.map(([d,u])=>j.createElement(d,u)),...Array.isArray(i)?i:[i]]));/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const re=(e,t)=>{const n=j.forwardRef(({className:r,...a},i)=>j.createElement(k2,{ref:i,iconNode:t,className:bv(`lucide-${w2(e)}`,r),...a}));return n.displayName=`${e}`,n};/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const C2=re("Archive",[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8",key:"1s80jp"}],["path",{d:"M10 12h4",key:"a56b0p"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Qs=re("ArrowLeft",[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Nv=re("ArrowRight",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const wv=re("BellOff",[["path",{d:"M8.7 3A6 6 0 0 1 18 8a21.3 21.3 0 0 0 .6 5",key:"o7mx20"}],["path",{d:"M17 17H3s3-2 3-9a4.67 4.67 0 0 1 .3-1.7",key:"16f1lm"}],["path",{d:"M10.3 21a1.94 1.94 0 0 0 3.4 0",key:"qgo35s"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const E2=re("Building2",[["path",{d:"M6 22V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v18Z",key:"1b4qmf"}],["path",{d:"M6 12H4a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h2",key:"i71pzd"}],["path",{d:"M18 9h2a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-2",key:"10jefs"}],["path",{d:"M10 6h4",key:"1itunk"}],["path",{d:"M10 10h4",key:"tcdvrf"}],["path",{d:"M10 14h4",key:"kelpxr"}],["path",{d:"M10 18h4",key:"1ulq68"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const D2=re("Cable",[["path",{d:"M17 21v-2a1 1 0 0 1-1-1v-1a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2v1a1 1 0 0 1-1 1",key:"10bnsj"}],["path",{d:"M19 15V6.5a1 1 0 0 0-7 0v11a1 1 0 0 1-7 0V9",key:"1eqmu1"}],["path",{d:"M21 21v-2h-4",key:"14zm7j"}],["path",{d:"M3 5h4V3",key:"z442eg"}],["path",{d:"M7 5a1 1 0 0 1 1 1v1a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V6a1 1 0 0 1 1-1V3",key:"ebdjd7"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const P2=re("Calculator",[["rect",{width:"16",height:"20",x:"4",y:"2",rx:"2",key:"1nb95v"}],["line",{x1:"8",x2:"16",y1:"6",y2:"6",key:"x4nwl0"}],["line",{x1:"16",x2:"16",y1:"14",y2:"18",key:"wjye3r"}],["path",{d:"M16 10h.01",key:"1m94wz"}],["path",{d:"M12 10h.01",key:"1nrarc"}],["path",{d:"M8 10h.01",key:"19clt8"}],["path",{d:"M12 14h.01",key:"1etili"}],["path",{d:"M8 14h.01",key:"6423bh"}],["path",{d:"M12 18h.01",key:"mhygvu"}],["path",{d:"M8 18h.01",key:"lrp35t"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Sv=re("Calendar",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const kv=re("Car",[["path",{d:"M19 17h2c.6 0 1-.4 1-1v-3c0-.9-.7-1.7-1.5-1.9C18.7 10.6 16 10 16 10s-1.3-1.4-2.2-2.3c-.5-.4-1.1-.7-1.8-.7H5c-.6 0-1.1.4-1.4.9l-1.4 2.9A3.7 3.7 0 0 0 2 12v4c0 .6.4 1 1 1h2",key:"5owen"}],["circle",{cx:"7",cy:"17",r:"2",key:"u2ysq9"}],["path",{d:"M9 17h6",key:"r8uit2"}],["circle",{cx:"17",cy:"17",r:"2",key:"axvx0g"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fr=re("Check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const In=re("ChevronDown",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const A2=re("ChevronLeft",[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ft=re("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ih=re("ChevronUp",[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Nn=re("CircleAlert",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ps=re("CircleCheckBig",[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ux=re("CircleX",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const No=re("Circle",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ol=re("ClipboardList",[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1",key:"tgr4d6"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2",key:"116196"}],["path",{d:"M12 11h4",key:"1jrz19"}],["path",{d:"M12 16h4",key:"n85exb"}],["path",{d:"M8 11h.01",key:"1dfujw"}],["path",{d:"M8 16h.01",key:"18s6g9"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const An=re("Clock",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 16 14",key:"68esgv"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Mc=re("Code",[["polyline",{points:"16 18 22 12 16 6",key:"z7tu5w"}],["polyline",{points:"8 6 2 12 8 18",key:"1eg1df"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const lh=re("Copy",[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const oh=re("CreditCard",[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Tc=re("Database",[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const As=re("Download",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"7 10 12 15 17 10",key:"2ggqvy"}],["line",{x1:"12",x2:"12",y1:"15",y2:"3",key:"1vk2je"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ch=re("ExternalLink",[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const It=re("EyeOff",[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49",key:"ct8e1f"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242",key:"151rxh"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143",key:"13bj9a"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Pe=re("Eye",[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const M2=re("FileDown",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M12 18v-6",key:"17g6i2"}],["path",{d:"m9 15 3 3 3-3",key:"1npd3o"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ke=re("FileText",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const T2=re("FileType",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M9 13v-1h6v1",key:"1bb014"}],["path",{d:"M12 12v6",key:"3ahymv"}],["path",{d:"M11 18h2",key:"12mj7e"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Cv=re("Flame",[["path",{d:"M8.5 14.5A2.5 2.5 0 0 0 11 12c0-1.38-.5-2-1-3-1.072-2.143-.224-4.054 2-6 .5 2.5 2 4.9 4 6.5 2 1.6 3 3.5 3 5.5a7 7 0 1 1-14 0c0-1.153.433-2.294 1-3a2.5 2.5 0 0 0 2.5 2.5z",key:"96xj49"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const F2=re("FolderOpen",[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2",key:"usdka0"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ev=re("Gauge",[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const mx=re("GitBranch",[["line",{x1:"6",x2:"6",y1:"3",y2:"15",key:"17qcm7"}],["circle",{cx:"18",cy:"6",r:"3",key:"1h7g24"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["path",{d:"M18 9a9 9 0 0 1-9 9",key:"n2h4wq"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const dh=re("Globe",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const I2=re("GripVertical",[["circle",{cx:"9",cy:"12",r:"1",key:"1vctgf"}],["circle",{cx:"9",cy:"5",r:"1",key:"hp0tcf"}],["circle",{cx:"9",cy:"19",r:"1",key:"fkjjf6"}],["circle",{cx:"15",cy:"12",r:"1",key:"1tmaij"}],["circle",{cx:"15",cy:"5",r:"1",key:"19l28e"}],["circle",{cx:"15",cy:"19",r:"1",key:"f4zoj3"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hx=re("HardDrive",[["line",{x1:"22",x2:"2",y1:"12",y2:"12",key:"1y58io"}],["path",{d:"M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z",key:"oot6mr"}],["line",{x1:"6",x2:"6.01",y1:"16",y2:"16",key:"sgf278"}],["line",{x1:"10",x2:"10.01",y1:"16",y2:"16",key:"1l4acy"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Dv=re("IdCard",[["path",{d:"M16 10h2",key:"8sgtl7"}],["path",{d:"M16 14h2",key:"epxaof"}],["path",{d:"M6.17 15a3 3 0 0 1 5.66 0",key:"n6f512"}],["circle",{cx:"9",cy:"11",r:"2",key:"yxgjnd"}],["rect",{x:"2",y:"5",width:"20",height:"14",rx:"2",key:"qneu4z"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ur=re("Inbox",[["polyline",{points:"22 12 16 12 14 15 10 15 8 12 2 12",key:"o97t9d"}],["path",{d:"M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z",key:"oot6mr"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Pl=re("Info",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const R2=re("Key",[["path",{d:"m15.5 7.5 2.3 2.3a1 1 0 0 0 1.4 0l2.1-2.1a1 1 0 0 0 0-1.4L19 4",key:"g0fldk"}],["path",{d:"m21 2-9.6 9.6",key:"1j0ho8"}],["circle",{cx:"7.5",cy:"15.5",r:"5.5",key:"yqb3hr"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const L2=re("LayoutDashboard",[["rect",{width:"7",height:"9",x:"3",y:"3",rx:"1",key:"10lvy0"}],["rect",{width:"7",height:"5",x:"14",y:"3",rx:"1",key:"16une8"}],["rect",{width:"7",height:"9",x:"14",y:"12",rx:"1",key:"1hutg5"}],["rect",{width:"7",height:"5",x:"3",y:"16",rx:"1",key:"ldoo1y"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fx=re("Link2",[["path",{d:"M9 17H7A5 5 0 0 1 7 7h2",key:"8i5ue5"}],["path",{d:"M15 7h2a5 5 0 1 1 0 10h-2",key:"1b9ql8"}],["line",{x1:"8",x2:"16",y1:"12",y2:"12",key:"1jonct"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const O2=re("LogOut",[["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}],["polyline",{points:"16 17 21 12 16 7",key:"1gabdz"}],["line",{x1:"21",x2:"9",y1:"12",y2:"12",key:"1uyos4"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Pv=re("MailOpen",[["path",{d:"M21.2 8.4c.5.38.8.97.8 1.6v10a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V10a2 2 0 0 1 .8-1.6l8-6a2 2 0 0 1 2.4 0l8 6Z",key:"1jhwl8"}],["path",{d:"m22 10-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 10",key:"1qfld7"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const nn=re("Mail",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const z2=re("MapPin",[["path",{d:"M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0",key:"1r0f0z"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $2=re("Maximize2",[["polyline",{points:"15 3 21 3 21 9",key:"mznyad"}],["polyline",{points:"9 21 3 21 3 15",key:"1avn1i"}],["line",{x1:"21",x2:"14",y1:"3",y2:"10",key:"ota7mn"}],["line",{x1:"3",x2:"10",y1:"21",y2:"14",key:"1atl0r"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const cl=re("MessageSquare",[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _2=re("Move",[["path",{d:"M12 2v20",key:"t6zp3m"}],["path",{d:"m15 19-3 3-3-3",key:"11eu04"}],["path",{d:"m19 9 3 3-3 3",key:"1mg7y2"}],["path",{d:"M2 12h20",key:"9i4pu4"}],["path",{d:"m5 9-3 3 3 3",key:"j64kie"}],["path",{d:"m9 5 3-3 3 3",key:"l8vdw6"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const K2=re("Network",[["rect",{x:"16",y:"16",width:"6",height:"6",rx:"1",key:"4q2zg0"}],["rect",{x:"2",y:"16",width:"6",height:"6",rx:"1",key:"8cvhb9"}],["rect",{x:"9",y:"2",width:"6",height:"6",rx:"1",key:"1egb70"}],["path",{d:"M5 16v-3a1 1 0 0 1 1-1h12a1 1 0 0 1 1 1v3",key:"1jsf9p"}],["path",{d:"M12 12V8",key:"2874zd"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Fc=re("Paperclip",[["path",{d:"m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48",key:"1u3ebp"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Be=re("Plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const uh=re("Receipt",[["path",{d:"M4 2v20l2-1 2 1 2-1 2 1 2-1 2 1 2-1 2 1V2l-2 1-2-1-2 1-2-1-2 1-2-1-2 1Z",key:"q3az6g"}],["path",{d:"M16 8h-6a2 2 0 1 0 0 4h4a2 2 0 1 1 0 4H8",key:"1h4pet"}],["path",{d:"M12 17.5v-11",key:"1jc1ny"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const wr=re("RefreshCw",[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const U2=re("Reply",[["polyline",{points:"9 17 4 12 9 7",key:"hvgpf2"}],["path",{d:"M20 18v-2a4 4 0 0 0-4-4H4",key:"5vmcpk"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const mh=re("RotateCcw",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Av=re("Save",[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Al=re("Search",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ml=re("Send",[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Mv=re("Settings",[["path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z",key:"1qme2f"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hh=re("Smartphone",[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2",key:"1yt0o3"}],["path",{d:"M12 18h.01",key:"mhygvu"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ye=re("SquarePen",[["path",{d:"M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7",key:"1m0v6g"}],["path",{d:"M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z",key:"ohrbg2"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fh=re("Star",[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z",key:"r04s7s"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const B2=re("Store",[["path",{d:"m2 7 4.41-4.41A2 2 0 0 1 7.83 2h8.34a2 2 0 0 1 1.42.59L22 7",key:"ztvudi"}],["path",{d:"M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8",key:"1b2hhj"}],["path",{d:"M15 22v-4a2 2 0 0 0-2-2h-2a2 2 0 0 0-2 2v4",key:"2ebpfo"}],["path",{d:"M2 7h20",key:"1fcdvo"}],["path",{d:"M22 7v3a2 2 0 0 1-2 2a2.7 2.7 0 0 1-1.59-.63.7.7 0 0 0-.82 0A2.7 2.7 0 0 1 16 12a2.7 2.7 0 0 1-1.59-.63.7.7 0 0 0-.82 0A2.7 2.7 0 0 1 12 12a2.7 2.7 0 0 1-1.59-.63.7.7 0 0 0-.82 0A2.7 2.7 0 0 1 8 12a2.7 2.7 0 0 1-1.59-.63.7.7 0 0 0-.82 0A2.7 2.7 0 0 1 4 12a2 2 0 0 1-2-2V7",key:"6c3vgh"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const q2=re("Table",[["path",{d:"M12 3v18",key:"108xh3"}],["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9h18",key:"1pudct"}],["path",{d:"M3 15h18",key:"5xshup"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const be=re("Trash2",[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6",key:"4alrt4"}],["path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2",key:"v07s0e"}],["line",{x1:"10",x2:"10",y1:"11",y2:"17",key:"1uufr5"}],["line",{x1:"14",x2:"14",y1:"11",y2:"17",key:"xtxkd"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hs=re("TriangleAlert",[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Tv=re("Tv",[["rect",{width:"20",height:"15",x:"2",y:"7",rx:"2",ry:"2",key:"10ag99"}],["polyline",{points:"17 2 12 7 7 2",key:"11pgbg"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Fv=re("Undo2",[["path",{d:"M9 14 4 9l5-5",key:"102s5s"}],["path",{d:"M4 9h10.5a5.5 5.5 0 0 1 5.5 5.5a5.5 5.5 0 0 1-5.5 5.5H11",key:"f3b9sd"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Vu=re("Upload",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"17 8 12 3 7 8",key:"t8dd8p"}],["line",{x1:"12",x2:"12",y1:"3",y2:"15",key:"widbto"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const V2=re("UserCog",[["circle",{cx:"18",cy:"15",r:"3",key:"gjjjvw"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M10 15H6a4 4 0 0 0-4 4v2",key:"1nfge6"}],["path",{d:"m21.7 16.4-.9-.3",key:"12j9ji"}],["path",{d:"m15.2 13.9-.9-.3",key:"1fdjdi"}],["path",{d:"m16.6 18.7.3-.9",key:"heedtr"}],["path",{d:"m19.1 12.2.3-.9",key:"1af3ki"}],["path",{d:"m19.6 18.7-.4-1",key:"1x9vze"}],["path",{d:"m16.8 12.3-.4-1",key:"vqeiwj"}],["path",{d:"m14.3 16.6 1-.4",key:"1qlj63"}],["path",{d:"m20.7 13.8 1-.4",key:"1v5t8k"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Q2=re("UserPlus",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["line",{x1:"19",x2:"19",y1:"8",y2:"14",key:"1bvyxn"}],["line",{x1:"22",x2:"16",y1:"11",y2:"11",key:"1shjgl"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Tl=re("User",[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2",key:"975kel"}],["circle",{cx:"12",cy:"7",r:"4",key:"17ys0d"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ka=re("Users",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["path",{d:"M16 3.13a4 4 0 0 1 0 7.75",key:"1da9ce"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const px=re("WifiOff",[["path",{d:"M12 20h.01",key:"zekei9"}],["path",{d:"M8.5 16.429a5 5 0 0 1 7 0",key:"1bycff"}],["path",{d:"M5 12.859a10 10 0 0 1 5.17-2.69",key:"1dl1wf"}],["path",{d:"M19 12.859a10 10 0 0 0-2.007-1.523",key:"4k23kn"}],["path",{d:"M2 8.82a15 15 0 0 1 4.177-2.643",key:"1grhjp"}],["path",{d:"M22 8.82a15 15 0 0 0-11.288-3.764",key:"z3jwby"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ca=re("Wifi",[["path",{d:"M12 20h.01",key:"zekei9"}],["path",{d:"M2 8.82a15 15 0 0 1 20 0",key:"dnpr2z"}],["path",{d:"M5 12.859a10 10 0 0 1 14 0",key:"1x1e6c"}],["path",{d:"M8.5 16.429a5 5 0 0 1 7 0",key:"1bycff"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Vt=re("X",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ph=re("Zap",[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const H2=re("ZoomIn",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["line",{x1:"21",x2:"16.65",y1:"21",y2:"16.65",key:"13gj7c"}],["line",{x1:"11",x2:"11",y1:"8",y2:"14",key:"1vmskp"}],["line",{x1:"8",x2:"14",y1:"11",y2:"11",key:"durymu"}]]);/** * @license lucide-react v0.454.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const W2=re("ZoomOut",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["line",{x1:"21",x2:"16.65",y1:"21",y2:"16.65",key:"13gj7c"}],["line",{x1:"8",x2:"14",y1:"11",y2:"11",key:"durymu"}]]);function G2(){const{user:e,logout:t,hasPermission:n,isCustomer:r,developerMode:a}=He(),i=[{to:"/",icon:L2,label:"Dashboard",show:!0,end:!0},{to:"/customers",icon:ka,label:"Kunden",show:n("customers:read")&&!r},{to:"/contracts",icon:Ke,label:"Verträge",show:n("contracts:read"),end:!0},{to:"/contracts/cockpit",icon:Nn,label:"Vertrags-Cockpit",show:n("contracts:read")&&!r},{to:"/tasks",icon:r?cl:ol,label:r?"Support-Anfragen":"Aufgaben",show:n("contracts:read")}],l=[{to:"/developer/database",icon:Tc,label:"Datenbankstruktur"}];return s.jsxs("aside",{className:"w-64 bg-gray-900 text-white min-h-screen flex flex-col",children:[s.jsx("div",{className:"p-4 border-b border-gray-800",children:s.jsx("h1",{className:"text-xl font-bold",children:"OpenCRM"})}),s.jsxs("nav",{className:"flex-1 p-4 overflow-y-auto",children:[s.jsx("ul",{className:"space-y-2",children:i.filter(o=>o.show).map(o=>s.jsx("li",{children:s.jsxs(dd,{to:o.to,end:o.end,className:({isActive:c})=>`flex items-center gap-3 px-4 py-2 rounded-lg transition-colors ${c?"bg-blue-600 text-white":"text-gray-300 hover:bg-gray-800"}`,children:[s.jsx(o.icon,{className:"w-5 h-5"}),o.label]})},o.to))}),a&&n("developer:access")&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"mt-6 mb-2 px-4",children:s.jsxs("p",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider flex items-center gap-2",children:[s.jsx(Mc,{className:"w-3 h-3"}),"Entwickler"]})}),s.jsx("ul",{className:"space-y-2",children:l.map(o=>s.jsx("li",{children:s.jsxs(dd,{to:o.to,className:({isActive:c})=>`flex items-center gap-3 px-4 py-2 rounded-lg transition-colors ${c?"bg-purple-600 text-white":"text-purple-300 hover:bg-gray-800"}`,children:[s.jsx(o.icon,{className:"w-5 h-5"}),o.label]})},o.to))})]}),s.jsx("div",{className:"mt-6 pt-6 border-t border-gray-800",children:s.jsxs(dd,{to:"/settings",className:({isActive:o})=>`flex items-center gap-3 px-4 py-2 rounded-lg transition-colors ${o?"bg-blue-600 text-white":"text-gray-300 hover:bg-gray-800"}`,children:[s.jsx(Mv,{className:"w-5 h-5"}),"Einstellungen"]})})]}),s.jsxs("div",{className:"p-4 border-t border-gray-800",children:[s.jsxs("div",{className:"mb-4 text-sm",children:[s.jsx("p",{className:"text-gray-400",children:"Angemeldet als"}),s.jsxs("p",{className:"font-medium",children:[e==null?void 0:e.firstName," ",e==null?void 0:e.lastName]})]}),s.jsxs("button",{onClick:t,className:"flex items-center gap-3 w-full px-4 py-2 text-gray-300 hover:bg-gray-800 rounded-lg transition-colors",children:[s.jsx(O2,{className:"w-5 h-5"}),"Abmelden"]})]})]})}function Z2(){const{settings:e}=jv(),[t,n]=j.useState(!1);j.useEffect(()=>{const a=()=>{window.scrollY>window.innerHeight*e.scrollToTopThreshold?n(!0):n(!1)};return window.addEventListener("scroll",a),()=>window.removeEventListener("scroll",a)},[e.scrollToTopThreshold]);const r=()=>{window.scrollTo({top:0,behavior:"smooth"})};return t?s.jsx("button",{onClick:r,className:"fixed bottom-6 right-6 p-3 bg-gray-200 hover:bg-gray-300 text-gray-600 rounded-full shadow-md transition-all duration-300 opacity-70 hover:opacity-100 z-50","aria-label":"Nach oben scrollen",title:"Nach oben",children:s.jsx(ih,{className:"w-5 h-5"})}):null}function J2(){return s.jsxs("div",{className:"flex min-h-screen",children:[s.jsx(G2,{}),s.jsx("main",{className:"flex-1 p-8 overflow-auto",children:s.jsx(dw,{})}),s.jsx(Z2,{})]})}const F=j.forwardRef(({className:e="",variant:t="primary",size:n="md",children:r,disabled:a,...i},l)=>{const o="inline-flex items-center justify-center font-medium rounded-lg transition-colors focus:outline-none focus:ring-2 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed",c={primary:"bg-blue-600 text-white hover:bg-blue-700 focus:ring-blue-500",secondary:"bg-gray-200 text-gray-900 hover:bg-gray-300 focus:ring-gray-500",danger:"bg-red-600 text-white hover:bg-red-700 focus:ring-red-500",ghost:"bg-transparent text-gray-700 hover:bg-gray-100 focus:ring-gray-500"},d={sm:"px-3 py-1.5 text-sm",md:"px-4 py-2 text-sm",lg:"px-6 py-3 text-base"};return s.jsx("button",{ref:l,className:`${o} ${c[t]} ${d[n]} ${e}`,disabled:a,...i,children:r})});F.displayName="Button";const V=j.forwardRef(({className:e="",label:t,error:n,id:r,onClear:a,...i},l)=>{const o=r||i.name,c=i.type==="date",d=i.value!==void 0&&i.value!==null&&i.value!=="",u=c&&a&&d;return s.jsxs("div",{className:"w-full",children:[t&&s.jsx("label",{htmlFor:o,className:"block text-sm font-medium text-gray-700 mb-1",children:t}),s.jsxs("div",{className:u?"flex gap-2":"",children:[s.jsx("input",{ref:l,id:o,className:`block w-full px-3 py-2 border rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 ${n?"border-red-500":"border-gray-300"} ${e}`,...i}),u&&s.jsx("button",{type:"button",onClick:a,className:"px-3 py-2 text-gray-400 hover:text-red-500 hover:bg-red-50 border border-gray-300 rounded-lg transition-colors",title:"Datum löschen",children:s.jsx(be,{className:"w-4 h-4"})})]}),n&&s.jsx("p",{className:"mt-1 text-sm text-red-600",children:n})]})});V.displayName="Input";function Y({children:e,className:t="",title:n,actions:r}){return s.jsxs("div",{className:`bg-white rounded-lg shadow ${t}`,children:[(n||r)&&s.jsxs("div",{className:"px-6 py-4 border-b border-gray-200 flex items-center justify-between",children:[n&&s.jsx("div",{className:"text-lg font-medium text-gray-900",children:n}),r&&s.jsx("div",{className:"flex items-center gap-2",children:r})]}),s.jsx("div",{className:"p-6",children:e})]})}function X2(){const[e,t]=j.useState(""),[n,r]=j.useState(""),[a,i]=j.useState(""),[l,o]=j.useState(!1),{login:c,customerLogin:d}=He(),u=ts(),h=async p=>{p.preventDefault(),i(""),o(!0);try{await c(e,n),u("/");return}catch{}try{await d(e,n),u("/")}catch{i("Ungültige Anmeldedaten"),o(!1)}};return s.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gray-100",children:s.jsxs(Y,{className:"w-full max-w-md",children:[s.jsxs("div",{className:"text-center mb-8",children:[s.jsx("h1",{className:"text-2xl font-bold text-gray-900",children:"OpenCRM"}),s.jsx("p",{className:"text-gray-600 mt-2",children:"Melden Sie sich an"})]}),a&&s.jsx("div",{className:"mb-4 p-4 bg-red-50 border border-red-200 text-red-700 rounded-lg",children:a}),s.jsxs("form",{onSubmit:h,className:"space-y-4",children:[s.jsx(V,{label:"E-Mail",type:"email",value:e,onChange:p=>t(p.target.value),required:!0,autoComplete:"email"}),s.jsx(V,{label:"Passwort",type:"password",value:n,onChange:p=>r(p.target.value),required:!0,autoComplete:"current-password"}),s.jsx(F,{type:"submit",className:"w-full",disabled:l,children:l?"Anmeldung...":"Anmelden"})]})]})})}function Ve({isOpen:e,onClose:t,title:n,children:r,size:a="md"}){if(j.useEffect(()=>(e?document.body.style.overflow="hidden":document.body.style.overflow="",()=>{document.body.style.overflow=""}),[e]),!e)return null;const i={sm:"max-w-md",md:"max-w-lg",lg:"max-w-2xl",xl:"max-w-4xl"};return s.jsx("div",{className:"fixed inset-0 z-50 overflow-y-auto",children:s.jsxs("div",{className:"flex min-h-full items-center justify-center p-4",children:[s.jsx("div",{className:"fixed inset-0 bg-black/50",onClick:t}),s.jsxs("div",{className:`relative bg-white rounded-lg shadow-xl w-full ${i[a]}`,children:[s.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b",children:[s.jsx("h2",{className:"text-lg font-semibold",children:n}),s.jsx(F,{variant:"ghost",size:"sm",onClick:t,children:s.jsx(Vt,{className:"w-5 h-5"})})]}),s.jsx("div",{className:"p-6",children:r})]})]})})}function Y2(){var w,S,E,z,I,B;const{user:e,isCustomer:t,isCustomerPortal:n}=He(),[r,a]=j.useState(!1),{data:i,isLoading:l}=me({queryKey:["app-settings-public"],queryFn:()=>Jr.getPublic(),enabled:n,staleTime:0}),o=!l&&((w=i==null?void 0:i.data)==null?void 0:w.customerSupportTicketsEnabled)==="true",{data:c}=me({queryKey:["customers-count"],queryFn:()=>Dt.getAll({limit:1}),enabled:!t}),{data:d}=me({queryKey:["contracts",t?e==null?void 0:e.customerId:void 0],queryFn:()=>Le.getAll(t?{customerId:e==null?void 0:e.customerId}:{limit:1})}),{data:u}=me({queryKey:["contracts-active",t?e==null?void 0:e.customerId:void 0],queryFn:()=>Le.getAll({status:"ACTIVE",...t?{customerId:e==null?void 0:e.customerId}:{limit:1}})}),{data:h}=me({queryKey:["contracts-pending",t?e==null?void 0:e.customerId:void 0],queryFn:()=>Le.getAll({status:"PENDING",...t?{customerId:e==null?void 0:e.customerId}:{limit:1}})}),{data:p}=me({queryKey:["task-stats"],queryFn:()=>ut.getStats()}),{data:m}=me({queryKey:["contract-cockpit"],queryFn:()=>Le.getCockpit(),enabled:!t,staleTime:0}),{ownContracts:f,representedContracts:x}=j.useMemo(()=>{if(!n||!(d!=null&&d.data))return{ownContracts:[],representedContracts:[]};const P=[],M={};for(const k of d.data)if(k.customerId===(e==null?void 0:e.customerId))P.push(k);else{const _=k.customerId;if(!M[_]){const K=k.customer?k.customer.companyName||`${k.customer.firstName} ${k.customer.lastName}`:`Kunde ${_}`;M[_]={customerName:K,contracts:[]}}M[_].contracts.push(k)}return{ownContracts:P,representedContracts:Object.values(M).sort((k,_)=>k.customerName.localeCompare(_.customerName))}},[d==null?void 0:d.data,n,e==null?void 0:e.customerId]),b=j.useMemo(()=>f.filter(P=>P.status==="ACTIVE").length,[f]),y=j.useMemo(()=>f.filter(P=>P.status==="PENDING").length,[f]),g=j.useMemo(()=>f.filter(P=>P.status==="EXPIRED").length,[f]),v=j.useMemo(()=>x.reduce((P,M)=>P+M.contracts.length,0),[x]),N=j.useMemo(()=>x.reduce((P,M)=>P+M.contracts.filter(k=>k.status==="ACTIVE").length,0),[x]),D=j.useMemo(()=>x.reduce((P,M)=>P+M.contracts.filter(k=>k.status==="EXPIRED").length,0),[x]),A=((S=p==null?void 0:p.data)==null?void 0:S.openCount)||0,R=P=>s.jsx(Y,{className:P.link?"cursor-pointer hover:shadow-md transition-shadow":"",children:P.link?s.jsx(ke,{to:P.link,className:"block",children:s.jsxs("div",{className:"flex items-center",children:[s.jsx("div",{className:`p-3 rounded-lg ${P.color}`,children:s.jsx(P.icon,{className:"w-6 h-6 text-white"})}),s.jsxs("div",{className:"ml-4",children:[s.jsx("p",{className:"text-sm text-gray-500",children:P.label}),s.jsx("p",{className:"text-2xl font-bold",children:P.value})]})]})}):s.jsxs("div",{className:"flex items-center",children:[s.jsx("div",{className:`p-3 rounded-lg ${P.color}`,children:s.jsx(P.icon,{className:"w-6 h-6 text-white"})}),s.jsxs("div",{className:"ml-4",children:[s.jsx("p",{className:"text-sm text-gray-500",children:P.label}),s.jsx("p",{className:"text-2xl font-bold",children:P.value})]})]})},P.label);return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center justify-between mb-6",children:[s.jsxs("h1",{className:"text-2xl font-bold",children:["Willkommen, ",e==null?void 0:e.firstName,"!"]}),n&&o&&s.jsxs(F,{onClick:()=>a(!0),children:[s.jsx(Be,{className:"w-4 h-4 mr-2"}),"Support-Anfrage"]})]}),n?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"mb-6",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[s.jsx(Tl,{className:"w-5 h-5 text-blue-600"}),s.jsx("h2",{className:"text-lg font-semibold",children:"Meine Verträge"})]}),s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[R({label:"Eigene Verträge",value:f.length,icon:Ke,color:"bg-blue-500",link:"/contracts"}),R({label:"Davon aktiv",value:b,icon:Ps,color:"bg-green-500"}),R({label:"Davon ausstehend",value:y,icon:An,color:"bg-yellow-500"}),R({label:"Davon abgelaufen",value:g,icon:ux,color:"bg-red-500"})]})]}),v>0&&s.jsxs("div",{className:"mb-6",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[s.jsx(ka,{className:"w-5 h-5 text-purple-600"}),s.jsx("h2",{className:"text-lg font-semibold",children:"Fremdverträge"})]}),s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[R({label:"Fremdverträge",value:v,icon:ka,color:"bg-purple-500",link:"/contracts"}),R({label:"Davon aktiv",value:N,icon:Ps,color:"bg-green-500"}),s.jsx("div",{className:"hidden lg:block"}),R({label:"Davon abgelaufen",value:D,icon:ux,color:"bg-red-500"})]})]}),s.jsxs("div",{className:"mb-6",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[s.jsx(cl,{className:"w-5 h-5 text-orange-600"}),s.jsx("h2",{className:"text-lg font-semibold",children:"Support-Anfragen"})]}),s.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:R({label:"Offene Anfragen",value:A,icon:cl,color:"bg-orange-500",link:"/tasks"})})]})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-6",children:[R({label:"Kunden",value:((E=c==null?void 0:c.pagination)==null?void 0:E.total)||0,icon:ka,color:"bg-blue-500",link:"/customers"}),R({label:"Verträge gesamt",value:((z=d==null?void 0:d.pagination)==null?void 0:z.total)||0,icon:Ke,color:"bg-purple-500",link:"/contracts"}),R({label:"Aktive Verträge",value:((I=u==null?void 0:u.pagination)==null?void 0:I.total)||0,icon:Ps,color:"bg-green-500"}),R({label:"Ausstehende Verträge",value:((B=h==null?void 0:h.pagination)==null?void 0:B.total)||0,icon:Nn,color:"bg-yellow-500"})]}),(m==null?void 0:m.data)&&s.jsxs("div",{className:"mb-6",children:[s.jsxs("div",{className:"flex items-center justify-between mb-3",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Nn,{className:"w-5 h-5 text-red-500"}),s.jsx("h2",{className:"text-lg font-semibold",children:"Vertrags-Cockpit"})]}),s.jsx(ke,{to:"/contracts/cockpit",className:"text-sm text-blue-600 hover:underline",children:"Alle anzeigen"})]}),s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[s.jsx(Y,{className:"cursor-pointer hover:shadow-md transition-shadow",children:s.jsx(ke,{to:"/contracts/cockpit?filter=critical",className:"block",children:s.jsxs("div",{className:"flex items-center",children:[s.jsx("div",{className:"p-3 rounded-lg bg-red-100",children:s.jsx(Nn,{className:"w-6 h-6 text-red-500"})}),s.jsxs("div",{className:"ml-4",children:[s.jsxs("p",{className:"text-sm text-gray-500",children:["Kritisch (<",m.data.thresholds.criticalDays," Tage)"]}),s.jsx("p",{className:"text-2xl font-bold text-red-600",children:m.data.summary.criticalCount})]})]})})}),s.jsx(Y,{className:"cursor-pointer hover:shadow-md transition-shadow",children:s.jsx(ke,{to:"/contracts/cockpit?filter=warning",className:"block",children:s.jsxs("div",{className:"flex items-center",children:[s.jsx("div",{className:"p-3 rounded-lg bg-yellow-100",children:s.jsx(hs,{className:"w-6 h-6 text-yellow-500"})}),s.jsxs("div",{className:"ml-4",children:[s.jsxs("p",{className:"text-sm text-gray-500",children:["Warnung (<",m.data.thresholds.warningDays," Tage)"]}),s.jsx("p",{className:"text-2xl font-bold text-yellow-600",children:m.data.summary.warningCount})]})]})})}),s.jsx(Y,{className:"cursor-pointer hover:shadow-md transition-shadow",children:s.jsx(ke,{to:"/contracts/cockpit?filter=ok",className:"block",children:s.jsxs("div",{className:"flex items-center",children:[s.jsx("div",{className:"p-3 rounded-lg bg-green-100",children:s.jsx(Ps,{className:"w-6 h-6 text-green-500"})}),s.jsxs("div",{className:"ml-4",children:[s.jsxs("p",{className:"text-sm text-gray-500",children:["OK (<",m.data.thresholds.okDays," Tage)"]}),s.jsx("p",{className:"text-2xl font-bold text-green-600",children:m.data.summary.okCount})]})]})})}),s.jsx(Y,{className:"cursor-pointer hover:shadow-md transition-shadow",children:s.jsx(ke,{to:"/contracts/cockpit",className:"block",children:s.jsxs("div",{className:"flex items-center",children:[s.jsx("div",{className:"p-3 rounded-lg bg-gray-100",children:s.jsx(Ke,{className:"w-6 h-6 text-gray-500"})}),s.jsxs("div",{className:"ml-4",children:[s.jsx("p",{className:"text-sm text-gray-500",children:"Handlungsbedarf"}),s.jsx("p",{className:"text-2xl font-bold text-gray-600",children:m.data.summary.totalContracts})]})]})})})]})]}),s.jsxs("div",{className:"mb-6",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[s.jsx(ol,{className:"w-5 h-5 text-orange-600"}),s.jsx("h2",{className:"text-lg font-semibold",children:"Aufgaben"})]}),s.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:R({label:"Offene Aufgaben",value:A,icon:ol,color:"bg-orange-500",link:"/tasks"})})]})]}),n&&s.jsx(ek,{isOpen:r,onClose:()=>a(!1)})]})}function ek({isOpen:e,onClose:t}){const{user:n}=He(),r=ts(),a=xe(),[i,l]=j.useState("own"),[o,c]=j.useState(null),[d,u]=j.useState(""),[h,p]=j.useState(""),[m,f]=j.useState(!1),[x,b]=j.useState(""),{data:y}=me({queryKey:["contracts",n==null?void 0:n.customerId],queryFn:()=>Le.getAll({customerId:n==null?void 0:n.customerId}),enabled:e}),g=j.useMemo(()=>{if(!(y!=null&&y.data))return{own:[],represented:{}};const w=[],S={};for(const E of y.data)if(E.customerId===(n==null?void 0:n.customerId))w.push(E);else{if(!S[E.customerId]){const z=E.customer?E.customer.companyName||`${E.customer.firstName} ${E.customer.lastName}`:`Kunde ${E.customerId}`;S[E.customerId]={name:z,contracts:[]}}S[E.customerId].contracts.push(E)}return{own:w,represented:S}},[y==null?void 0:y.data,n==null?void 0:n.customerId]),v=Object.keys(g.represented).length>0,N=j.useMemo(()=>{var w;return i==="own"?g.own:((w=g.represented[i])==null?void 0:w.contracts)||[]},[i,g]),D=j.useMemo(()=>{if(!x)return N;const w=x.toLowerCase();return N.filter(S=>S.contractNumber.toLowerCase().includes(w)||(S.providerName||"").toLowerCase().includes(w)||(S.tariffName||"").toLowerCase().includes(w))},[N,x]),A=async()=>{if(!(!o||!d.trim())){f(!0);try{await ut.createSupportTicket(o,{title:d.trim(),description:h.trim()||void 0}),a.invalidateQueries({queryKey:["task-stats"]}),a.invalidateQueries({queryKey:["all-tasks"]}),t(),u(""),p(""),c(null),l("own"),r(`/contracts/${o}`)}catch(w){console.error("Fehler beim Erstellen der Support-Anfrage:",w),alert("Fehler beim Erstellen der Support-Anfrage. Bitte versuchen Sie es erneut.")}finally{f(!1)}}},R=()=>{u(""),p(""),c(null),l("own"),b(""),t()};return s.jsx(Ve,{isOpen:e,onClose:R,title:"Neue Support-Anfrage",children:s.jsxs("div",{className:"space-y-4",children:[v&&s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Kunde"}),s.jsxs("select",{value:i,onChange:w=>{const S=w.target.value;l(S==="own"?"own":parseInt(S)),c(null),b("")},className:"w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500",children:[s.jsx("option",{value:"own",children:"Eigene Verträge"}),Object.entries(g.represented).map(([w,{name:S}])=>s.jsx("option",{value:w,children:S},w))]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Vertrag *"}),s.jsx(V,{placeholder:"Vertrag suchen...",value:x,onChange:w=>b(w.target.value),className:"mb-2"}),s.jsx("div",{className:"max-h-48 overflow-y-auto border rounded-lg",children:D.length>0?D.map(w=>s.jsxs("div",{onClick:()=>c(w.id),className:`p-3 cursor-pointer border-b last:border-b-0 hover:bg-gray-50 ${o===w.id?"bg-blue-50 border-blue-200":""}`,children:[s.jsx("div",{className:"font-medium",children:w.contractNumber}),s.jsxs("div",{className:"text-sm text-gray-500",children:[w.providerName||"Kein Anbieter",w.tariffName&&` - ${w.tariffName}`]})]},w.id)):s.jsx("div",{className:"p-3 text-gray-500 text-center",children:"Keine Verträge gefunden."})})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Titel *"}),s.jsx(V,{value:d,onChange:w=>u(w.target.value),placeholder:"Kurze Beschreibung Ihres Anliegens"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Beschreibung"}),s.jsx("textarea",{value:h,onChange:w=>p(w.target.value),placeholder:"Detaillierte Beschreibung (optional)",rows:4,className:"w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"})]}),s.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[s.jsx(F,{variant:"secondary",onClick:R,children:"Abbrechen"}),s.jsx(F,{onClick:A,disabled:!o||!d.trim()||m,children:m?"Wird erstellt...":"Anfrage erstellen"})]})]})})}function ye({children:e,variant:t="default",className:n="",onClick:r}){const a={default:"bg-gray-100 text-gray-800",success:"bg-green-100 text-green-800",warning:"bg-yellow-100 text-yellow-800",danger:"bg-red-100 text-red-800",info:"bg-blue-100 text-blue-800"};return s.jsx("span",{className:`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${a[t]} ${n}`,onClick:r,children:e})}function tk(){const[e,t]=j.useState(""),[n,r]=j.useState(""),[a,i]=j.useState(1),{hasPermission:l}=He(),{data:o,isLoading:c}=me({queryKey:["customers",e,n,a],queryFn:()=>Dt.getAll({search:e,type:n||void 0,page:a,limit:20})});return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center justify-between mb-6",children:[s.jsx("h1",{className:"text-2xl font-bold",children:"Kunden"}),l("customers:create")&&s.jsx(ke,{to:"/customers/new",children:s.jsxs(F,{children:[s.jsx(Be,{className:"w-4 h-4 mr-2"}),"Neuer Kunde"]})})]}),s.jsx(Y,{className:"mb-6",children:s.jsxs("div",{className:"flex gap-2 items-center",children:[s.jsx(V,{placeholder:"Suchen...",value:e,onChange:d=>t(d.target.value),className:"flex-1"}),s.jsxs("select",{value:n,onChange:d=>r(d.target.value),className:"px-3 py-2 border border-gray-300 rounded-lg w-28 flex-shrink-0",children:[s.jsx("option",{value:"",children:"Alle"}),s.jsx("option",{value:"PRIVATE",children:"Privat"}),s.jsx("option",{value:"BUSINESS",children:"Firma"})]}),s.jsx(F,{variant:"secondary",className:"flex-shrink-0",children:s.jsx(Al,{className:"w-4 h-4"})})]})}),s.jsx(Y,{children:c?s.jsx("div",{className:"text-center py-8 text-gray-500",children:"Laden..."}):o!=null&&o.data&&o.data.length>0?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"overflow-x-auto",children:s.jsxs("table",{className:"w-full",children:[s.jsx("thead",{children:s.jsxs("tr",{className:"border-b",children:[s.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"Kundennr."}),s.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"Name"}),s.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"Typ"}),s.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"E-Mail"}),s.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"Verträge"}),s.jsx("th",{className:"text-right py-3 px-4 font-medium text-gray-600",children:"Aktionen"})]})}),s.jsx("tbody",{children:o.data.map(d=>{var u;return s.jsxs("tr",{className:"border-b hover:bg-gray-50",children:[s.jsx("td",{className:"py-3 px-4 font-mono text-sm",children:d.customerNumber}),s.jsx("td",{className:"py-3 px-4",children:d.type==="BUSINESS"&&d.companyName?d.companyName:`${d.firstName} ${d.lastName}`}),s.jsx("td",{className:"py-3 px-4",children:s.jsx(ye,{variant:d.type==="BUSINESS"?"info":"default",children:d.type==="BUSINESS"?"Firma":"Privat"})}),s.jsx("td",{className:"py-3 px-4",children:d.email||"-"}),s.jsx("td",{className:"py-3 px-4",children:((u=d._count)==null?void 0:u.contracts)||0}),s.jsx("td",{className:"py-3 px-4 text-right",children:s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx(ke,{to:`/customers/${d.id}`,children:s.jsx(F,{variant:"ghost",size:"sm",children:s.jsx(Pe,{className:"w-4 h-4"})})}),l("customers:update")&&s.jsx(ke,{to:`/customers/${d.id}/edit`,children:s.jsx(F,{variant:"ghost",size:"sm",children:s.jsx(Ye,{className:"w-4 h-4"})})})]})})]},d.id)})})]})}),o.pagination&&o.pagination.totalPages>1&&s.jsxs("div",{className:"mt-4 flex items-center justify-between",children:[s.jsxs("p",{className:"text-sm text-gray-500",children:["Seite ",o.pagination.page," von ",o.pagination.totalPages," (",o.pagination.total," Einträge)"]}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx(F,{variant:"secondary",size:"sm",onClick:()=>i(d=>Math.max(1,d-1)),disabled:a===1,children:"Zurück"}),s.jsx(F,{variant:"secondary",size:"sm",onClick:()=>i(d=>d+1),disabled:a>=o.pagination.totalPages,children:"Weiter"})]})]})]}):s.jsx("div",{className:"text-center py-8 text-gray-500",children:"Keine Kunden gefunden."})})]})}function sk({emails:e,selectedEmailId:t,onSelectEmail:n,onEmailDeleted:r,isLoading:a,folder:i="INBOX",accountId:l}){const o=i==="SENT",[c,d]=j.useState(null),{hasPermission:u}=He(),h=S=>{if(o)try{const E=JSON.parse(S.toAddresses);if(E.length>0)return`An: ${E[0]}${E.length>1?` (+${E.length-1})`:""}`}catch{return"An: (Unbekannt)"}return S.fromName||S.fromAddress},p=xe(),m=W({mutationFn:S=>Ae.toggleStar(S),onSuccess:(S,E)=>{p.invalidateQueries({queryKey:["emails"]}),p.invalidateQueries({queryKey:["email",E]})}}),f=W({mutationFn:({emailId:S,isRead:E})=>Ae.markAsRead(S,E),onSuccess:(S,E)=>{p.invalidateQueries({queryKey:["emails"]}),p.invalidateQueries({queryKey:["email",E.emailId]}),l&&p.invalidateQueries({queryKey:["folder-counts",l]})}}),x=W({mutationFn:S=>Ae.delete(S),onSuccess:(S,E)=>{p.invalidateQueries({queryKey:["emails"]}),l&&p.invalidateQueries({queryKey:["folder-counts",l]}),Ie.success("E-Mail in Papierkorb verschoben"),d(null),r==null||r(E)},onError:S=>{console.error("Delete error:",S),Ie.error(S.message||"Fehler beim Löschen der E-Mail"),d(null)}}),b=W({mutationFn:S=>Ae.unassignFromContract(S),onSuccess:()=>{p.invalidateQueries({queryKey:["emails"]}),Ie.success("Vertragszuordnung aufgehoben")},onError:S=>{console.error("Unassign error:",S),Ie.error(S.message||"Fehler beim Aufheben der Zuordnung")}}),y=(S,E)=>{S.stopPropagation(),b.mutate(E)},g=(S,E)=>{S.stopPropagation(),d(E)},v=S=>{S.stopPropagation(),c&&x.mutate(c)},N=S=>{S.stopPropagation(),d(null)},D=S=>{const E=new Date(S),z=new Date;return E.toDateString()===z.toDateString()?E.toLocaleTimeString("de-DE",{hour:"2-digit",minute:"2-digit"}):E.toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit"})},A=(S,E)=>{S.stopPropagation(),m.mutate(E)},R=(S,E)=>{S.stopPropagation(),f.mutate({emailId:E.id,isRead:!E.isRead})},w=S=>{S.isRead||f.mutate({emailId:S.id,isRead:!0}),n(S)};return a?s.jsx("div",{className:"flex items-center justify-center h-64",children:s.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"})}):e.length===0?s.jsxs("div",{className:"flex flex-col items-center justify-center h-64 text-gray-500",children:[s.jsx(nn,{className:"w-12 h-12 mb-2 opacity-50"}),s.jsx("p",{children:"Keine E-Mails vorhanden"})]}):s.jsxs("div",{className:"divide-y divide-gray-200",children:[e.map(S=>s.jsxs("div",{onClick:()=>w(S),className:["flex items-start gap-3 p-3 cursor-pointer transition-colors",t===S.id?"bg-blue-100":["hover:bg-gray-100",S.isRead?"bg-gray-50/50":"bg-white"].join(" ")].join(" "),style:{borderLeft:t===S.id?"4px solid #2563eb":"4px solid transparent"},children:[s.jsx("button",{onClick:E=>R(E,S),className:` flex-shrink-0 mt-1 p-1 -ml-1 rounded hover:bg-gray-200 ${S.isRead?"text-gray-400":"text-blue-600"} `,title:S.isRead?"Als ungelesen markieren":"Als gelesen markieren",children:S.isRead?s.jsx(Pv,{className:"w-4 h-4"}):s.jsx(nn,{className:"w-4 h-4"})}),s.jsx("button",{onClick:E=>A(E,S.id),className:` flex-shrink-0 mt-1 p-1 -ml-1 rounded hover:bg-gray-200 ${S.isStarred?"text-yellow-500":"text-gray-400"} `,title:S.isStarred?"Stern entfernen":"Als wichtig markieren",children:s.jsx(fh,{className:`w-4 h-4 ${S.isStarred?"fill-current":""}`})}),u("emails:delete")&&s.jsx("button",{onClick:E=>g(E,S.id),className:"flex-shrink-0 mt-1 p-1 -ml-1 rounded hover:bg-red-100 text-gray-400 hover:text-red-600",title:"E-Mail löschen",children:s.jsx(be,{className:"w-4 h-4"})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2 mb-1",children:[s.jsx("span",{className:`text-sm truncate ${S.isRead?"text-gray-700":"font-semibold text-gray-900"}`,children:h(S)}),s.jsx("span",{className:"text-xs text-gray-500 flex-shrink-0",children:D(S.receivedAt)})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:`text-sm truncate ${S.isRead?"text-gray-600":"font-medium text-gray-900"}`,children:S.subject||"(Kein Betreff)"}),S.hasAttachments&&s.jsx(Fc,{className:"w-3 h-3 text-gray-400 flex-shrink-0"})]}),S.contract&&s.jsxs("div",{className:"mt-1 flex items-center gap-1",children:[s.jsx("span",{className:"inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-green-100 text-green-800",children:S.contract.contractNumber}),(i==="INBOX"||i==="SENT"&&!S.isAutoAssigned)&&s.jsx("button",{onClick:E=>y(E,S.id),className:"p-0.5 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded",title:"Zuordnung aufheben",disabled:b.isPending,children:s.jsx(Vt,{className:"w-3.5 h-3.5"})})]})]}),s.jsx(Ft,{className:"w-4 h-4 text-gray-400 flex-shrink-0 mt-2"})]},S.id)),c&&s.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:s.jsxs("div",{className:"bg-white rounded-lg shadow-xl p-6 max-w-md mx-4",children:[s.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"E-Mail löschen?"}),s.jsx("p",{className:"text-gray-600 mb-4",children:"Die E-Mail wird in den Papierkorb verschoben."}),s.jsxs("div",{className:"flex justify-end gap-3",children:[s.jsx(F,{variant:"secondary",onClick:N,disabled:x.isPending,children:"Abbrechen"}),s.jsx(F,{variant:"danger",onClick:v,disabled:x.isPending,children:x.isPending?"Löschen...":"Löschen"})]})]})})]})}const Re=j.forwardRef(({className:e="",label:t,error:n,options:r,id:a,placeholder:i="Bitte wählen...",...l},o)=>{const c=a||l.name,d=/\bw-\d+\b|\bw-\[|\bflex-/.test(e);return s.jsxs("div",{className:d?e:"w-full",children:[t&&s.jsx("label",{htmlFor:c,className:"block text-sm font-medium text-gray-700 mb-1",children:t}),s.jsxs("select",{ref:o,id:c,className:`block w-full px-3 py-2 border rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 ${n?"border-red-500":"border-gray-300"}`,...l,children:[s.jsx("option",{value:"",children:i}),r.map(u=>s.jsx("option",{value:u.value,children:u.label},u.value))]}),n&&s.jsx("p",{className:"mt-1 text-sm text-red-600",children:n})]})});Re.displayName="Select";function nk({isOpen:e,onClose:t,emailId:n,attachmentFilename:r,onSuccess:a}){var z,I,B;const[i,l]=j.useState(null),[o,c]=j.useState(new Set(["customer"])),[d,u]=j.useState("document"),[h,p]=j.useState({invoiceDate:new Date().toISOString().split("T")[0],invoiceType:"INTERIM",notes:""}),m=xe(),{data:f,isLoading:x,error:b}=me({queryKey:["attachment-targets",n],queryFn:()=>Ae.getAttachmentTargets(n),enabled:e}),y=f==null?void 0:f.data,g=((z=y==null?void 0:y.contract)==null?void 0:z.type)==="ELECTRICITY"||((I=y==null?void 0:y.contract)==null?void 0:I.type)==="GAS",v=W({mutationFn:()=>{if(!i)throw new Error("Kein Ziel ausgewählt");return Ae.saveAttachmentTo(n,r,{entityType:i.entityType,entityId:i.entityId,targetKey:i.targetKey})},onSuccess:()=>{var P,M;Ie.success("Anhang gespeichert"),m.invalidateQueries({queryKey:["attachment-targets",n]}),m.invalidateQueries({queryKey:["customers"]}),m.invalidateQueries({queryKey:["contracts"]}),(P=y==null?void 0:y.customer)!=null&&P.id&&m.invalidateQueries({queryKey:["customer",y.customer.id.toString()]}),(M=y==null?void 0:y.contract)!=null&&M.id&&m.invalidateQueries({queryKey:["contract",y.contract.id.toString()]}),a==null||a(),D()},onError:P=>{Ie.error(P.message||"Fehler beim Speichern")}}),N=W({mutationFn:()=>Ae.saveAttachmentAsInvoice(n,r,{invoiceDate:h.invoiceDate,invoiceType:h.invoiceType,notes:h.notes||void 0}),onSuccess:()=>{var P;Ie.success("Anhang als Rechnung gespeichert"),m.invalidateQueries({queryKey:["attachment-targets",n]}),m.invalidateQueries({queryKey:["customers"]}),m.invalidateQueries({queryKey:["contracts"]}),(P=y==null?void 0:y.contract)!=null&&P.id&&m.invalidateQueries({queryKey:["contract",y.contract.id.toString()]}),a==null||a(),D()},onError:P=>{Ie.error(P.message||"Fehler beim Speichern der Rechnung")}}),D=()=>{l(null),u("document"),p({invoiceDate:new Date().toISOString().split("T")[0],invoiceType:"INTERIM",notes:""}),t()},A=P=>{const M=new Set(o);M.has(P)?M.delete(P):M.add(P),c(M)},R=(P,M,k,_)=>{l({entityType:P,entityId:k,targetKey:M.key,hasDocument:M.hasDocument,label:_?`${_} → ${M.label}`:M.label})},w=(P,M,k,_)=>P.map(K=>{const Z=(i==null?void 0:i.entityType)===M&&(i==null?void 0:i.entityId)===k&&(i==null?void 0:i.targetKey)===K.key;return s.jsxs("div",{onClick:()=>R(M,K,k,_),className:` flex items-center gap-3 p-3 cursor-pointer transition-colors rounded-lg ml-4 ${Z?"bg-blue-100 ring-2 ring-blue-500":"hover:bg-gray-100"} `,children:[s.jsx("div",{className:"flex-1 min-w-0",children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-sm font-medium text-gray-900",children:K.label}),K.hasDocument&&s.jsxs("span",{className:"flex items-center gap-1 px-2 py-0.5 text-xs rounded-full bg-yellow-100 text-yellow-800",children:[s.jsx(hs,{className:"w-3 h-3"}),"Vorhanden"]})]})}),Z&&s.jsx(fr,{className:"w-5 h-5 text-blue-600"})]},K.key)}),S=(P,M)=>s.jsxs("div",{className:"mb-2",children:[s.jsx("div",{className:"text-sm font-medium text-gray-700 px-3 py-1 bg-gray-50 rounded",children:P.label}),w(P.slots,M,P.id,P.label)]},P.id),E=(P,M,k,_,K=!1)=>{const Z=o.has(M);return s.jsxs("div",{className:"border border-gray-200 rounded-lg overflow-hidden",children:[s.jsxs("button",{onClick:()=>A(M),className:"w-full flex items-center gap-2 p-3 bg-gray-50 hover:bg-gray-100 transition-colors",children:[Z?s.jsx(In,{className:"w-4 h-4 text-gray-500"}):s.jsx(Ft,{className:"w-4 h-4 text-gray-500"}),k,s.jsx("span",{className:"font-medium text-gray-900",children:P})]}),Z&&s.jsx("div",{className:"p-2",children:K?s.jsx("p",{className:"text-sm text-gray-500 text-center py-4",children:"Keine Einträge vorhanden"}):_})]})};return s.jsx(Ve,{isOpen:e,onClose:D,title:"Anhang speichern unter",size:"lg",children:s.jsxs("div",{className:"space-y-4",children:[s.jsx("div",{className:"p-3 bg-gray-50 rounded-lg",children:s.jsxs("p",{className:"text-sm text-gray-600",children:[s.jsx("span",{className:"font-medium",children:"Datei:"})," ",r]})}),x&&s.jsx("div",{className:"flex items-center justify-center py-8",children:s.jsx("div",{className:"animate-spin rounded-full h-6 w-6 border-b-2 border-blue-600"})}),b&&s.jsx("div",{className:"p-4 bg-red-50 text-red-700 rounded-lg",children:"Fehler beim Laden der Dokumentziele"}),y&&s.jsxs(s.Fragment,{children:[g&&s.jsxs("div",{className:"flex gap-2 p-1 bg-gray-100 rounded-lg",children:[s.jsxs("button",{onClick:()=>u("document"),className:`flex-1 flex items-center justify-center gap-2 px-4 py-2 rounded-md text-sm font-medium transition-colors ${d==="document"?"bg-white text-blue-600 shadow-sm":"text-gray-600 hover:text-gray-900"}`,children:[s.jsx(Ke,{className:"w-4 h-4"}),"Als Dokument"]}),s.jsxs("button",{onClick:()=>u("invoice"),className:`flex-1 flex items-center justify-center gap-2 px-4 py-2 rounded-md text-sm font-medium transition-colors ${d==="invoice"?"bg-white text-green-600 shadow-sm":"text-gray-600 hover:text-gray-900"}`,children:[s.jsx(uh,{className:"w-4 h-4"}),"Als Rechnung"]})]}),d==="document"&&s.jsxs("div",{className:"space-y-3 max-h-96 overflow-auto",children:[E(`Kunde: ${y.customer.name}`,"customer",s.jsx(Tl,{className:"w-4 h-4 text-blue-600"}),w(y.customer.slots,"customer"),y.customer.slots.length===0),E("Ausweisdokumente","identityDocuments",s.jsx(Dv,{className:"w-4 h-4 text-green-600"}),y.identityDocuments.map(P=>S(P,"identityDocument")),y.identityDocuments.length===0),E("Bankkarten","bankCards",s.jsx(oh,{className:"w-4 h-4 text-purple-600"}),y.bankCards.map(P=>S(P,"bankCard")),y.bankCards.length===0),y.contract&&E(`Vertrag: ${y.contract.contractNumber}`,"contract",s.jsx(Ke,{className:"w-4 h-4 text-orange-600"}),w(y.contract.slots,"contract"),y.contract.slots.length===0),!y.contract&&s.jsxs("div",{className:"p-3 bg-gray-50 rounded-lg text-sm text-gray-600",children:[s.jsx(Ke,{className:"w-4 h-4 inline-block mr-2 text-gray-400"}),"E-Mail ist keinem Vertrag zugeordnet. Ordnen Sie die E-Mail einem Vertrag zu, um Vertragsdokumente als Ziel auswählen zu können."]})]}),d==="invoice"&&g&&s.jsxs("div",{className:"space-y-4",children:[s.jsx("div",{className:"p-3 bg-green-50 rounded-lg",children:s.jsxs("p",{className:"text-sm text-green-700",children:["Der Anhang wird als Rechnung für den Vertrag ",s.jsx("strong",{children:(B=y.contract)==null?void 0:B.contractNumber})," gespeichert."]})}),s.jsx(V,{label:"Rechnungsdatum",type:"date",value:h.invoiceDate,onChange:P=>p({...h,invoiceDate:P.target.value}),required:!0}),s.jsx(Re,{label:"Rechnungstyp",value:h.invoiceType,onChange:P=>p({...h,invoiceType:P.target.value}),options:[{value:"INTERIM",label:"Zwischenrechnung"},{value:"FINAL",label:"Schlussrechnung"}]}),s.jsx(V,{label:"Notizen (optional)",value:h.notes,onChange:P=>p({...h,notes:P.target.value}),placeholder:"Optionale Anmerkungen..."})]})]}),d==="document"&&(i==null?void 0:i.hasDocument)&&s.jsxs("div",{className:"p-3 bg-yellow-50 border border-yellow-200 rounded-lg flex items-start gap-2",children:[s.jsx(hs,{className:"w-5 h-5 text-yellow-600 flex-shrink-0 mt-0.5"}),s.jsxs("div",{className:"text-sm text-yellow-800",children:[s.jsx("strong",{children:"Achtung:"})," An diesem Feld ist bereits ein Dokument hinterlegt. Das vorhandene Dokument wird durch den neuen Anhang ersetzt."]})]}),s.jsxs("div",{className:"flex justify-end gap-3 pt-4",children:[s.jsx(F,{variant:"secondary",onClick:D,children:"Abbrechen"}),d==="document"?s.jsx(F,{onClick:()=>v.mutate(),disabled:!i||v.isPending||N.isPending,children:v.isPending?"Wird gespeichert...":"Speichern"}):s.jsx(F,{onClick:()=>N.mutate(),disabled:!h.invoiceDate||v.isPending||N.isPending,children:N.isPending?"Wird gespeichert...":"Als Rechnung speichern"})]})]})})}function rk({isOpen:e,onClose:t,emailId:n,onSuccess:r}){var z,I,B;const[a,i]=j.useState(null),[l,o]=j.useState(new Set(["customer"])),[c,d]=j.useState("document"),[u,h]=j.useState({invoiceDate:new Date().toISOString().split("T")[0],invoiceType:"INTERIM",notes:""}),p=xe(),{data:m,isLoading:f,error:x}=me({queryKey:["attachment-targets",n],queryFn:()=>Ae.getAttachmentTargets(n),enabled:e}),b=m==null?void 0:m.data,y=((z=b==null?void 0:b.contract)==null?void 0:z.type)==="ELECTRICITY"||((I=b==null?void 0:b.contract)==null?void 0:I.type)==="GAS",g=W({mutationFn:()=>{if(!a)throw new Error("Kein Ziel ausgewählt");return Ae.saveEmailAsPdf(n,{entityType:a.entityType,entityId:a.entityId,targetKey:a.targetKey})},onSuccess:()=>{var P,M;Ie.success("E-Mail als PDF gespeichert"),p.invalidateQueries({queryKey:["attachment-targets",n]}),p.invalidateQueries({queryKey:["customers"]}),p.invalidateQueries({queryKey:["contracts"]}),(P=b==null?void 0:b.customer)!=null&&P.id&&p.invalidateQueries({queryKey:["customer",b.customer.id.toString()]}),(M=b==null?void 0:b.contract)!=null&&M.id&&p.invalidateQueries({queryKey:["contract",b.contract.id.toString()]}),r==null||r(),N()},onError:P=>{Ie.error(P.message||"Fehler beim Speichern")}}),v=W({mutationFn:()=>Ae.saveEmailAsInvoice(n,{invoiceDate:u.invoiceDate,invoiceType:u.invoiceType,notes:u.notes||void 0}),onSuccess:()=>{var P;Ie.success("E-Mail als Rechnung gespeichert"),p.invalidateQueries({queryKey:["attachment-targets",n]}),p.invalidateQueries({queryKey:["customers"]}),p.invalidateQueries({queryKey:["contracts"]}),(P=b==null?void 0:b.contract)!=null&&P.id&&p.invalidateQueries({queryKey:["contract",b.contract.id.toString()]}),r==null||r(),N()},onError:P=>{Ie.error(P.message||"Fehler beim Speichern der Rechnung")}}),N=()=>{i(null),d("document"),h({invoiceDate:new Date().toISOString().split("T")[0],invoiceType:"INTERIM",notes:""}),t()},D=P=>{const M=new Set(l);M.has(P)?M.delete(P):M.add(P),o(M)},A=(P,M,k,_)=>{i({entityType:P,entityId:k,targetKey:M.key,hasDocument:M.hasDocument,label:_?`${_} → ${M.label}`:M.label})},R=(P,M,k,_)=>P.map(K=>{const Z=(a==null?void 0:a.entityType)===M&&(a==null?void 0:a.entityId)===k&&(a==null?void 0:a.targetKey)===K.key;return s.jsxs("div",{onClick:()=>A(M,K,k,_),className:` flex items-center gap-3 p-3 cursor-pointer transition-colors rounded-lg ml-4 ${Z?"bg-blue-100 ring-2 ring-blue-500":"hover:bg-gray-100"} `,children:[s.jsx("div",{className:"flex-1 min-w-0",children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-sm font-medium text-gray-900",children:K.label}),K.hasDocument&&s.jsxs("span",{className:"flex items-center gap-1 px-2 py-0.5 text-xs rounded-full bg-yellow-100 text-yellow-800",children:[s.jsx(hs,{className:"w-3 h-3"}),"Vorhanden"]})]})}),Z&&s.jsx(fr,{className:"w-5 h-5 text-blue-600"})]},K.key)}),w=(P,M)=>s.jsxs("div",{className:"mb-2",children:[s.jsx("div",{className:"text-sm font-medium text-gray-700 px-3 py-1 bg-gray-50 rounded",children:P.label}),R(P.slots,M,P.id,P.label)]},P.id),S=(P,M,k,_,K=!1)=>{const Z=l.has(M);return s.jsxs("div",{className:"border border-gray-200 rounded-lg overflow-hidden",children:[s.jsxs("button",{onClick:()=>D(M),className:"w-full flex items-center gap-2 p-3 bg-gray-50 hover:bg-gray-100 transition-colors",children:[Z?s.jsx(In,{className:"w-4 h-4 text-gray-500"}):s.jsx(Ft,{className:"w-4 h-4 text-gray-500"}),k,s.jsx("span",{className:"font-medium text-gray-900",children:P})]}),Z&&s.jsx("div",{className:"p-2",children:K?s.jsx("p",{className:"text-sm text-gray-500 text-center py-4",children:"Keine Einträge vorhanden"}):_})]})},E=g.isPending||v.isPending;return s.jsx(Ve,{isOpen:e,onClose:N,title:"E-Mail als PDF speichern",size:"lg",children:s.jsxs("div",{className:"space-y-4",children:[s.jsx("div",{className:"p-3 bg-blue-50 rounded-lg",children:s.jsx("p",{className:"text-sm text-blue-700",children:"Die E-Mail wird als PDF exportiert (inkl. Absender, Empfänger, Datum und Inhalt) und im gewählten Dokumentenfeld gespeichert."})}),f&&s.jsx("div",{className:"flex items-center justify-center py-8",children:s.jsx("div",{className:"animate-spin rounded-full h-6 w-6 border-b-2 border-blue-600"})}),x&&s.jsx("div",{className:"p-4 bg-red-50 text-red-700 rounded-lg",children:"Fehler beim Laden der Dokumentziele"}),b&&s.jsxs(s.Fragment,{children:[y&&s.jsxs("div",{className:"flex gap-2 p-1 bg-gray-100 rounded-lg",children:[s.jsxs("button",{onClick:()=>d("document"),className:`flex-1 flex items-center justify-center gap-2 px-4 py-2 rounded-md text-sm font-medium transition-colors ${c==="document"?"bg-white text-blue-600 shadow-sm":"text-gray-600 hover:text-gray-900"}`,children:[s.jsx(Ke,{className:"w-4 h-4"}),"Als Dokument"]}),s.jsxs("button",{onClick:()=>d("invoice"),className:`flex-1 flex items-center justify-center gap-2 px-4 py-2 rounded-md text-sm font-medium transition-colors ${c==="invoice"?"bg-white text-green-600 shadow-sm":"text-gray-600 hover:text-gray-900"}`,children:[s.jsx(uh,{className:"w-4 h-4"}),"Als Rechnung"]})]}),c==="document"&&s.jsxs("div",{className:"space-y-3 max-h-96 overflow-auto",children:[S(`Kunde: ${b.customer.name}`,"customer",s.jsx(Tl,{className:"w-4 h-4 text-blue-600"}),R(b.customer.slots,"customer"),b.customer.slots.length===0),S("Ausweisdokumente","identityDocuments",s.jsx(Dv,{className:"w-4 h-4 text-green-600"}),b.identityDocuments.map(P=>w(P,"identityDocument")),b.identityDocuments.length===0),S("Bankkarten","bankCards",s.jsx(oh,{className:"w-4 h-4 text-purple-600"}),b.bankCards.map(P=>w(P,"bankCard")),b.bankCards.length===0),b.contract&&S(`Vertrag: ${b.contract.contractNumber}`,"contract",s.jsx(Ke,{className:"w-4 h-4 text-orange-600"}),R(b.contract.slots,"contract"),b.contract.slots.length===0),!b.contract&&s.jsxs("div",{className:"p-3 bg-gray-50 rounded-lg text-sm text-gray-600",children:[s.jsx(Ke,{className:"w-4 h-4 inline-block mr-2 text-gray-400"}),"E-Mail ist keinem Vertrag zugeordnet. Ordnen Sie die E-Mail einem Vertrag zu, um Vertragsdokumente als Ziel auswählen zu können."]})]}),c==="invoice"&&y&&s.jsxs("div",{className:"space-y-4",children:[s.jsx("div",{className:"p-3 bg-green-50 rounded-lg",children:s.jsxs("p",{className:"text-sm text-green-700",children:["Die E-Mail wird als Rechnung für den Vertrag ",s.jsx("strong",{children:(B=b.contract)==null?void 0:B.contractNumber})," gespeichert."]})}),s.jsx(V,{label:"Rechnungsdatum",type:"date",value:u.invoiceDate,onChange:P=>h({...u,invoiceDate:P.target.value}),required:!0}),s.jsx(Re,{label:"Rechnungstyp",value:u.invoiceType,onChange:P=>h({...u,invoiceType:P.target.value}),options:[{value:"INTERIM",label:"Zwischenrechnung"},{value:"FINAL",label:"Schlussrechnung"}]}),s.jsx(V,{label:"Notizen (optional)",value:u.notes,onChange:P=>h({...u,notes:P.target.value}),placeholder:"Optionale Anmerkungen..."})]})]}),c==="document"&&(a==null?void 0:a.hasDocument)&&s.jsxs("div",{className:"p-3 bg-yellow-50 border border-yellow-200 rounded-lg flex items-start gap-2",children:[s.jsx(hs,{className:"w-5 h-5 text-yellow-600 flex-shrink-0 mt-0.5"}),s.jsxs("div",{className:"text-sm text-yellow-800",children:[s.jsx("strong",{children:"Achtung:"})," An diesem Feld ist bereits ein Dokument hinterlegt. Das vorhandene Dokument wird durch die PDF ersetzt."]})]}),s.jsxs("div",{className:"flex justify-end gap-3 pt-4",children:[s.jsx(F,{variant:"secondary",onClick:N,children:"Abbrechen"}),c==="document"?s.jsx(F,{onClick:()=>g.mutate(),disabled:!a||E,children:E?"Wird erstellt...":"Als PDF speichern"}):s.jsx(F,{onClick:()=>v.mutate(),disabled:!u.invoiceDate||E,children:E?"Wird erstellt...":"Als Rechnung speichern"})]})]})})}function Iv({email:e,onReply:t,onAssignContract:n,onDeleted:r,isSentFolder:a=!1,isContractView:i=!1,isTrashView:l=!1,onRestored:o,accountId:c}){const[d,u]=j.useState(!0),[h,p]=j.useState(e.isStarred),[m,f]=j.useState(!1),[x,b]=j.useState(!1),[y,g]=j.useState(!1),[v,N]=j.useState(null),[D,A]=j.useState(!1),R=xe(),{hasPermission:w}=He();j.useEffect(()=>{p(e.isStarred)},[e.id,e.isStarred]);const S=W({mutationFn:()=>Ae.toggleStar(e.id),onMutate:()=>{p(H=>!H)},onSuccess:()=>{R.invalidateQueries({queryKey:["emails"]}),R.invalidateQueries({queryKey:["email",e.id]})},onError:()=>{p(e.isStarred)}}),E=W({mutationFn:()=>Ae.unassignFromContract(e.id),onSuccess:()=>{R.invalidateQueries({queryKey:["emails"]}),R.invalidateQueries({queryKey:["email",e.id]}),e.contractId&&R.invalidateQueries({queryKey:["contract-folder-counts",e.contractId]}),Ie.success("Vertragszuordnung aufgehoben")},onError:H=>{console.error("Unassign error:",H),Ie.error(H.message||"Fehler beim Aufheben der Zuordnung")}}),z=W({mutationFn:()=>Ae.delete(e.id),onSuccess:()=>{R.invalidateQueries({queryKey:["emails"]}),c&&R.invalidateQueries({queryKey:["folder-counts",c]}),e.contractId&&R.invalidateQueries({queryKey:["contract-folder-counts",e.contractId]}),Ie.success("E-Mail in Papierkorb verschoben"),f(!1),r==null||r()},onError:H=>{console.error("Delete error:",H),Ie.error(H.message||"Fehler beim Löschen der E-Mail"),f(!1)}}),I=W({mutationFn:()=>Ae.restore(e.id),onSuccess:()=>{R.invalidateQueries({queryKey:["emails"]}),c&&R.invalidateQueries({queryKey:["folder-counts",c]}),e.contractId&&R.invalidateQueries({queryKey:["contract-folder-counts",e.contractId]}),Ie.success("E-Mail wiederhergestellt"),b(!1),o==null||o()},onError:H=>{console.error("Restore error:",H),Ie.error(H.message||"Fehler beim Wiederherstellen der E-Mail"),b(!1)}}),B=W({mutationFn:()=>Ae.permanentDelete(e.id),onSuccess:()=>{R.invalidateQueries({queryKey:["emails"]}),c&&R.invalidateQueries({queryKey:["folder-counts",c]}),Ie.success("E-Mail endgültig gelöscht"),g(!1),r==null||r()},onError:H=>{console.error("Permanent delete error:",H),Ie.error(H.message||"Fehler beim endgültigen Löschen der E-Mail"),g(!1)}}),P=H=>new Date(H).toLocaleString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit"}),M=H=>{try{return JSON.parse(H)}catch{return[]}},k=H=>{if(!H)return[];try{return JSON.parse(H)}catch{return[]}},_=M(e.toAddresses),K=e.ccAddresses?M(e.ccAddresses):[],Z=k(e.attachmentNames);return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsxs("div",{className:"p-4 border-b border-gray-200 space-y-3",children:[s.jsxs("div",{className:"flex items-start justify-between gap-4",children:[s.jsx("h2",{className:"text-lg font-semibold text-gray-900",children:e.subject||"(Kein Betreff)"}),s.jsx("div",{className:"flex items-center gap-2 flex-shrink-0",children:l?s.jsxs(s.Fragment,{children:[s.jsxs(F,{variant:"secondary",size:"sm",onClick:()=>b(!0),title:"Wiederherstellen",children:[s.jsx(Fv,{className:"w-4 h-4 mr-1"}),"Wiederherstellen"]}),s.jsxs(F,{variant:"danger",size:"sm",onClick:()=>g(!0),title:"Endgültig löschen",children:[s.jsx(be,{className:"w-4 h-4 mr-1"}),"Endgültig löschen"]})]}):s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>S.mutate(),className:`p-2 rounded-lg hover:bg-gray-100 ${h?"text-yellow-500":"text-gray-400"}`,title:h?"Stern entfernen":"Als wichtig markieren",children:s.jsx(fh,{className:`w-5 h-5 ${h?"fill-current":""}`})}),s.jsxs(F,{variant:"secondary",size:"sm",onClick:t,children:[s.jsx(U2,{className:"w-4 h-4 mr-1"}),"Antworten"]}),s.jsx(F,{variant:"ghost",size:"sm",onClick:()=>A(!0),title:"E-Mail als PDF speichern",children:s.jsx(M2,{className:"w-4 h-4"})}),w("emails:delete")&&s.jsx(F,{variant:"danger",size:"sm",onClick:()=>f(!0),title:"E-Mail löschen",children:s.jsx(be,{className:"w-4 h-4"})})]})})]}),s.jsxs("div",{className:"text-sm space-y-1",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-gray-500 w-12",children:"Von:"}),s.jsxs("span",{className:"font-medium text-gray-900",children:[e.fromName&&`${e.fromName} `,s.jsxs("span",{className:"text-gray-600",children:["<",e.fromAddress,">"]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-gray-500 w-12",children:"An:"}),s.jsx("span",{className:"text-gray-700",children:_.join(", ")})]}),K.length>0&&s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-gray-500 w-12",children:"CC:"}),s.jsx("span",{className:"text-gray-700",children:K.join(", ")})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-gray-500 w-12",children:"Am:"}),s.jsx("span",{className:"text-gray-700",children:P(e.receivedAt)})]})]}),s.jsx("div",{className:"flex items-center gap-2 pt-2",children:e.contract?s.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 bg-green-50 border border-green-200 rounded-lg",children:[s.jsx(fx,{className:"w-4 h-4 text-green-600"}),s.jsxs("span",{className:"text-sm text-green-800",children:["Zugeordnet zu:"," ",s.jsx(ke,{to:`/contracts/${e.contract.id}`,className:"font-medium hover:underline",children:e.contract.contractNumber})]}),!e.isAutoAssigned&&s.jsx("button",{onClick:()=>E.mutate(),className:"ml-2 p-1 hover:bg-green-100 rounded",title:"Zuordnung aufheben",children:s.jsx(Vt,{className:"w-4 h-4 text-green-600"})})]}):!i&&s.jsxs(F,{variant:"secondary",size:"sm",onClick:n,children:[s.jsx(fx,{className:"w-4 h-4 mr-1"}),"Vertrag zuordnen"]})}),Z.length>0&&s.jsxs("div",{className:"pt-2",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[s.jsx(Fc,{className:"w-4 h-4 text-gray-400"}),s.jsxs("span",{className:"text-sm text-gray-500",children:[Z.length," Anhang",Z.length>1?"e":""]})]}),s.jsx("div",{className:"flex flex-wrap gap-2",children:Z.map((H,pe)=>s.jsxs("div",{className:"inline-flex items-center gap-1 px-3 py-2 bg-gray-100 rounded-lg text-sm text-gray-700",children:[s.jsx("span",{className:"max-w-[200px] truncate mr-1",children:H}),s.jsx("a",{href:Ae.getAttachmentUrl(e.id,H,!0),target:"_blank",rel:"noopener noreferrer",className:"p-1 hover:bg-gray-200 rounded transition-colors",title:`${H} öffnen`,children:s.jsx(ch,{className:"w-4 h-4 text-gray-500"})}),s.jsx("a",{href:Ae.getAttachmentUrl(e.id,H),download:H,className:"p-1 hover:bg-gray-200 rounded transition-colors",title:`${H} herunterladen`,children:s.jsx(As,{className:"w-4 h-4 text-gray-500"})}),!l&&s.jsx("button",{onClick:()=>N(H),className:"p-1 hover:bg-blue-100 rounded transition-colors",title:`${H} speichern unter...`,children:s.jsx(Av,{className:"w-4 h-4 text-blue-500"})})]},pe))})]})]}),e.htmlBody&&e.textBody&&s.jsxs("div",{className:"px-4 py-2 border-b border-gray-200 flex items-center gap-2",children:[s.jsx("button",{onClick:()=>u(!0),className:`px-3 py-1 text-sm rounded ${d?"bg-blue-100 text-blue-700":"text-gray-600 hover:bg-gray-100"}`,children:"HTML"}),s.jsx("button",{onClick:()=>u(!1),className:`px-3 py-1 text-sm rounded ${d?"text-gray-600 hover:bg-gray-100":"bg-blue-100 text-blue-700"}`,children:"Text"})]}),s.jsx("div",{className:"flex-1 overflow-auto p-4",children:d&&e.htmlBody?s.jsx("div",{className:"prose prose-sm max-w-none",dangerouslySetInnerHTML:{__html:e.htmlBody}}):s.jsx("pre",{className:"whitespace-pre-wrap text-sm text-gray-700 font-sans",children:e.textBody||"Kein Inhalt"})}),m&&s.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:s.jsxs("div",{className:"bg-white rounded-lg shadow-xl p-6 max-w-md mx-4",children:[s.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"E-Mail löschen?"}),s.jsx("p",{className:"text-gray-600 mb-4",children:"Die E-Mail wird in den Papierkorb verschoben."}),s.jsxs("div",{className:"flex justify-end gap-3",children:[s.jsx(F,{variant:"secondary",onClick:()=>f(!1),disabled:z.isPending,children:"Abbrechen"}),s.jsx(F,{variant:"danger",onClick:()=>z.mutate(),disabled:z.isPending,children:z.isPending?"Löschen...":"Löschen"})]})]})}),x&&s.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:s.jsxs("div",{className:"bg-white rounded-lg shadow-xl p-6 max-w-md mx-4",children:[s.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"E-Mail wiederherstellen?"}),s.jsxs("p",{className:"text-gray-600 mb-4",children:["Die E-Mail wird wieder in den ursprünglichen Ordner (",e.folder==="SENT"?"Gesendet":"Posteingang",") verschoben."]}),s.jsxs("div",{className:"flex justify-end gap-3",children:[s.jsx(F,{variant:"secondary",onClick:()=>b(!1),disabled:I.isPending,children:"Abbrechen"}),s.jsx(F,{variant:"primary",onClick:()=>I.mutate(),disabled:I.isPending,children:I.isPending?"Wird wiederhergestellt...":"Wiederherstellen"})]})]})}),y&&s.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:s.jsxs("div",{className:"bg-white rounded-lg shadow-xl p-6 max-w-md mx-4",children:[s.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"E-Mail endgültig löschen?"}),s.jsx("p",{className:"text-gray-600 mb-4",children:"Diese Aktion kann nicht rückgängig gemacht werden. Die E-Mail wird unwiderruflich gelöscht."}),s.jsxs("div",{className:"flex justify-end gap-3",children:[s.jsx(F,{variant:"secondary",onClick:()=>g(!1),disabled:B.isPending,children:"Abbrechen"}),s.jsx(F,{variant:"danger",onClick:()=>B.mutate(),disabled:B.isPending,children:B.isPending?"Wird gelöscht...":"Endgültig löschen"})]})]})}),v&&s.jsx(nk,{isOpen:!0,onClose:()=>N(null),emailId:e.id,attachmentFilename:v}),D&&s.jsx(rk,{isOpen:!0,onClose:()=>A(!1),emailId:e.id})]})}function Rv({isOpen:e,onClose:t,account:n,replyTo:r,onSuccess:a,contractId:i}){const[l,o]=j.useState(""),[c,d]=j.useState(""),[u,h]=j.useState(""),[p,m]=j.useState(""),[f,x]=j.useState([]),[b,y]=j.useState(null),g=j.useRef(null);j.useEffect(()=>{if(e){if(r){o(r.fromAddress||"");const I=r.subject||"",B=/^(Re|Aw|Fwd|Wg):\s*/i.test(I);h(B?I:`Re: ${I}`);const P=new Date(r.receivedAt).toLocaleString("de-DE"),M=r.textBody?` --- Ursprüngliche Nachricht --- Von: ${r.fromName||r.fromAddress} Am: ${P} ${r.textBody}`:"";m(M)}else o(""),h(""),m("");d(""),x([]),y(null)}},[e,r]);const v=10*1024*1024,N=25*1024*1024,D=I=>new Promise((B,P)=>{const M=new FileReader;M.readAsDataURL(I),M.onload=()=>{const _=M.result.split(",")[1];B(_)},M.onerror=P}),A=async I=>{const B=I.target.files;if(!B)return;const P=[];let M=f.reduce((k,_)=>k+_.content.length*.75,0);for(const k of Array.from(B)){if(k.size>v){y(`Datei "${k.name}" ist zu groß (max. 10 MB)`);continue}if(M+k.size>N){y("Maximale Gesamtgröße der Anhänge erreicht (25 MB)");break}try{const _=await D(k);P.push({filename:k.name,content:_,contentType:k.type||"application/octet-stream"}),M+=k.size}catch{y(`Fehler beim Lesen von "${k.name}"`)}}P.length>0&&x(k=>[...k,...P]),g.current&&(g.current.value="")},R=I=>{x(B=>B.filter((P,M)=>M!==I))},w=I=>{const B=I.length*.75;return B<1024?`${Math.round(B)} B`:B<1024*1024?`${(B/1024).toFixed(1)} KB`:`${(B/(1024*1024)).toFixed(1)} MB`},S=W({mutationFn:()=>xs.sendEmail(n.id,{to:l.split(",").map(I=>I.trim()).filter(Boolean),cc:c?c.split(",").map(I=>I.trim()).filter(Boolean):void 0,subject:u,text:p,inReplyTo:r==null?void 0:r.messageId,references:r!=null&&r.messageId?[r.messageId]:void 0,attachments:f.length>0?f:void 0,contractId:i}),onSuccess:()=>{a==null||a(),E()},onError:I=>{y(I instanceof Error?I.message:"Fehler beim Senden")}}),E=()=>{t()},z=()=>{if(!l.trim()){y("Bitte Empfänger angeben");return}if(!u.trim()){y("Bitte Betreff angeben");return}y(null),S.mutate()};return s.jsx(Ve,{isOpen:e,onClose:E,title:r?"Antworten":"Neue E-Mail",size:"lg",children:s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Von"}),s.jsx("div",{className:"px-3 py-2 bg-gray-100 rounded-lg text-sm text-gray-700",children:n.email})]}),s.jsxs("div",{children:[s.jsxs("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:["An ",s.jsx("span",{className:"text-red-500",children:"*"})]}),s.jsx("input",{type:"text",value:l,onChange:I=>o(I.target.value),placeholder:"empfaenger@example.com",className:"w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"}),s.jsx("p",{className:"mt-1 text-xs text-gray-500",children:"Mehrere Empfänger mit Komma trennen"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"CC"}),s.jsx("input",{type:"text",value:c,onChange:I=>d(I.target.value),placeholder:"cc@example.com",className:"w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"})]}),s.jsxs("div",{children:[s.jsxs("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:["Betreff ",s.jsx("span",{className:"text-red-500",children:"*"})]}),s.jsx("input",{type:"text",value:u,onChange:I=>h(I.target.value),placeholder:"Betreff eingeben",className:"w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Nachricht"}),s.jsx("textarea",{value:p,onChange:I=>m(I.target.value),rows:10,placeholder:"Ihre Nachricht...",className:"w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Anhänge"}),s.jsx("input",{type:"file",ref:g,onChange:A,multiple:!0,className:"hidden"}),s.jsxs("button",{type:"button",onClick:()=>{var I;return(I=g.current)==null?void 0:I.click()},className:"inline-flex items-center px-3 py-2 text-sm border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors",children:[s.jsx(Fc,{className:"w-4 h-4 mr-2"}),"Datei anhängen"]}),f.length>0&&s.jsx("div",{className:"mt-2 space-y-2",children:f.map((I,B)=>s.jsxs("div",{className:"flex items-center justify-between px-3 py-2 bg-gray-50 rounded-lg",children:[s.jsxs("div",{className:"flex items-center min-w-0",children:[s.jsx(Ke,{className:"w-4 h-4 text-gray-500 mr-2 flex-shrink-0"}),s.jsx("span",{className:"text-sm text-gray-700 truncate",children:I.filename}),s.jsxs("span",{className:"ml-2 text-xs text-gray-500 flex-shrink-0",children:["(",w(I.content),")"]})]}),s.jsx("button",{type:"button",onClick:()=>R(B),className:"ml-2 p-1 text-gray-400 hover:text-red-500 transition-colors",title:"Anhang entfernen",children:s.jsx(Vt,{className:"w-4 h-4"})})]},B))}),s.jsx("p",{className:"mt-1 text-xs text-gray-500",children:"Max. 10 MB pro Datei, 25 MB gesamt"})]}),b&&s.jsx("div",{className:"p-3 bg-red-50 border border-red-200 rounded-lg text-sm text-red-700",children:b}),s.jsxs("div",{className:"flex justify-end gap-3 pt-4",children:[s.jsx(F,{variant:"secondary",onClick:E,children:"Abbrechen"}),s.jsxs(F,{onClick:z,disabled:S.isPending,children:[s.jsx(Ml,{className:"w-4 h-4 mr-2"}),S.isPending?"Wird gesendet...":"Senden"]})]})]})})}function ak({isOpen:e,onClose:t,email:n,customerId:r,onSuccess:a}){const[i,l]=j.useState(""),[o,c]=j.useState(null),d=xe(),{data:u,isLoading:h}=me({queryKey:["contracts","customer",r],queryFn:()=>Le.getAll({customerId:r}),enabled:e}),m=((u==null?void 0:u.data)||[]).filter(g=>{var N,D,A,R;if(!i)return!0;const v=i.toLowerCase();return g.contractNumber.toLowerCase().includes(v)||((D=(N=g.contractCategory)==null?void 0:N.name)==null?void 0:D.toLowerCase().includes(v))||((R=(A=g.provider)==null?void 0:A.name)==null?void 0:R.toLowerCase().includes(v))}),f=W({mutationFn:g=>Ae.assignToContract(n.id,g),onSuccess:(g,v)=>{d.invalidateQueries({queryKey:["emails"]}),d.invalidateQueries({queryKey:["email",n.id]}),d.invalidateQueries({queryKey:["contract-folder-counts",v]}),a==null||a(),x()}}),x=()=>{l(""),c(null),t()},b=()=>{o&&f.mutate(o)},y=g=>g?new Date(g).toLocaleDateString("de-DE"):"-";return s.jsx(Ve,{isOpen:e,onClose:x,title:"E-Mail Vertrag zuordnen",size:"lg",children:s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"p-3 bg-gray-50 rounded-lg",children:[s.jsxs("p",{className:"text-sm text-gray-600",children:[s.jsx("span",{className:"font-medium",children:"Betreff:"})," ",n.subject||"(Kein Betreff)"]}),s.jsxs("p",{className:"text-sm text-gray-600",children:[s.jsx("span",{className:"font-medium",children:"Von:"})," ",n.fromAddress]})]}),s.jsxs("div",{className:"relative",children:[s.jsx(Al,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),s.jsx("input",{type:"text",value:i,onChange:g=>l(g.target.value),placeholder:"Vertrag suchen...",className:"w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"})]}),s.jsx("div",{className:"border border-gray-200 rounded-lg max-h-80 overflow-auto",children:h?s.jsx("div",{className:"flex items-center justify-center py-8",children:s.jsx("div",{className:"animate-spin rounded-full h-6 w-6 border-b-2 border-blue-600"})}):m.length===0?s.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-gray-500",children:[s.jsx(Ke,{className:"w-8 h-8 mb-2 opacity-50"}),s.jsx("p",{className:"text-sm",children:"Keine Verträge gefunden"})]}):s.jsx("div",{className:"divide-y divide-gray-200",children:m.map(g=>{var v;return s.jsx("div",{onClick:()=>c(g.id),className:` flex items-center gap-3 p-3 cursor-pointer transition-colors ${o===g.id?"bg-blue-50 border-l-2 border-l-blue-500":"hover:bg-gray-50"} `,children:s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"font-medium text-gray-900",children:g.contractNumber}),s.jsx("span",{className:` px-2 py-0.5 text-xs rounded-full ${g.status==="ACTIVE"?"bg-green-100 text-green-800":g.status==="PENDING"?"bg-yellow-100 text-yellow-800":g.status==="CANCELLED"?"bg-red-100 text-red-800":"bg-gray-100 text-gray-800"} `,children:g.status})]}),s.jsxs("div",{className:"text-sm text-gray-600 truncate",children:[(v=g.contractCategory)==null?void 0:v.name,g.provider&&` - ${g.provider.name}`]}),s.jsxs("div",{className:"text-xs text-gray-500",children:["Start: ",y(g.startDate)]})]})},g.id)})})}),s.jsxs("div",{className:"flex justify-end gap-3 pt-4",children:[s.jsx(F,{variant:"secondary",onClick:x,children:"Abbrechen"}),s.jsx(F,{onClick:b,disabled:!o||f.isPending,children:f.isPending?"Wird zugeordnet...":"Zuordnen"})]})]})})}function Lv({emails:e,selectedEmailId:t,onSelectEmail:n,onEmailRestored:r,onEmailDeleted:a,isLoading:i}){const[l,o]=j.useState(null),[c,d]=j.useState(null),u=xe(),h=A=>{if(A.folder==="SENT")try{const R=JSON.parse(A.toAddresses);if(R.length>0)return`An: ${R[0]}${R.length>1?` (+${R.length-1})`:""}`}catch{return"An: (Unbekannt)"}return A.fromName||A.fromAddress},p=W({mutationFn:A=>Ae.restore(A),onSuccess:(A,R)=>{u.invalidateQueries({queryKey:["emails"]}),Ie.success("E-Mail wiederhergestellt"),o(null),d(null),r==null||r(R)},onError:A=>{console.error("Restore error:",A),Ie.error(A.message||"Fehler beim Wiederherstellen"),o(null),d(null)}}),m=W({mutationFn:A=>Ae.permanentDelete(A),onSuccess:(A,R)=>{u.invalidateQueries({queryKey:["emails"]}),Ie.success("E-Mail endgültig gelöscht"),o(null),d(null),a==null||a(R)},onError:A=>{console.error("Permanent delete error:",A),Ie.error(A.message||"Fehler beim endgültigen Löschen"),o(null),d(null)}}),f=W({mutationFn:A=>Ae.unassignFromContract(A),onSuccess:()=>{u.invalidateQueries({queryKey:["emails"]}),Ie.success("Vertragszuordnung aufgehoben")},onError:A=>{console.error("Unassign error:",A),Ie.error(A.message||"Fehler beim Aufheben der Zuordnung")}}),x=(A,R)=>{A.stopPropagation(),f.mutate(R)},b=(A,R)=>{A.stopPropagation(),o(R),d("restore")},y=(A,R)=>{A.stopPropagation(),o(R),d("delete")},g=A=>{A.stopPropagation(),l&&c&&(c==="restore"?p.mutate(l):m.mutate(l))},v=A=>{A.stopPropagation(),o(null),d(null)},N=A=>new Date(A).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit"}),D=A=>{if(!A)return"";const R=new Date(A),w=new Date;return R.toDateString()===w.toDateString()?`Gelöscht um ${R.toLocaleTimeString("de-DE",{hour:"2-digit",minute:"2-digit"})}`:`Gelöscht am ${R.toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit"})}`};return i?s.jsx("div",{className:"flex items-center justify-center h-64",children:s.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-red-600"})}):e.length===0?s.jsxs("div",{className:"flex flex-col items-center justify-center h-64 text-gray-500",children:[s.jsx(be,{className:"w-12 h-12 mb-2 opacity-50"}),s.jsx("p",{children:"Papierkorb ist leer"})]}):s.jsxs("div",{className:"divide-y divide-gray-200",children:[e.map(A=>s.jsxs("div",{onClick:()=>n(A),className:["flex items-start gap-3 p-3 cursor-pointer transition-colors",t===A.id?"bg-red-100":"hover:bg-gray-100 bg-gray-50/50"].join(" "),style:{borderLeft:t===A.id?"4px solid #dc2626":"4px solid transparent"},children:[s.jsx("div",{className:"flex-shrink-0 mt-1 p-1 -ml-1 text-gray-400",title:A.folder==="SENT"?"Aus Gesendet":"Aus Posteingang",children:A.folder==="SENT"?s.jsx(Ml,{className:"w-4 h-4"}):s.jsx(Ur,{className:"w-4 h-4"})}),s.jsx("button",{onClick:R=>b(R,A.id),className:"flex-shrink-0 mt-1 p-1 -ml-1 rounded hover:bg-green-100 text-gray-400 hover:text-green-600",title:"Wiederherstellen",children:s.jsx(Fv,{className:"w-4 h-4"})}),s.jsx("button",{onClick:R=>y(R,A.id),className:"flex-shrink-0 mt-1 p-1 -ml-1 rounded hover:bg-red-100 text-gray-400 hover:text-red-600",title:"Endgültig löschen",children:s.jsx(be,{className:"w-4 h-4"})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2 mb-1",children:[s.jsx("span",{className:"text-sm truncate text-gray-700",children:h(A)}),s.jsx("span",{className:"text-xs text-gray-500 flex-shrink-0",children:N(A.receivedAt)})]}),s.jsx("div",{className:"text-sm truncate text-gray-600",children:A.subject||"(Kein Betreff)"}),s.jsx("div",{className:"text-xs text-red-500 mt-1",children:D(A.deletedAt)}),A.contract&&s.jsxs("div",{className:"mt-1 flex items-center gap-1",children:[s.jsx("span",{className:"inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-green-100 text-green-800",children:A.contract.contractNumber}),(A.folder==="INBOX"||A.folder==="SENT"&&!A.isAutoAssigned)&&s.jsx("button",{onClick:R=>x(R,A.id),className:"p-0.5 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded",title:"Zuordnung aufheben",disabled:f.isPending,children:s.jsx(Vt,{className:"w-3.5 h-3.5"})})]})]}),s.jsx(Ft,{className:"w-4 h-4 text-gray-400 flex-shrink-0 mt-2"})]},A.id)),l&&c&&s.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:s.jsxs("div",{className:"bg-white rounded-lg shadow-xl p-6 max-w-md mx-4",children:[s.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:c==="restore"?"E-Mail wiederherstellen?":"E-Mail endgültig löschen?"}),s.jsx("p",{className:"text-gray-600 mb-4",children:c==="restore"?"Die E-Mail wird wieder in den ursprünglichen Ordner verschoben.":"Die E-Mail wird unwiderruflich gelöscht. Diese Aktion kann nicht rückgängig gemacht werden."}),s.jsxs("div",{className:"flex justify-end gap-3",children:[s.jsx(F,{variant:"secondary",onClick:v,disabled:p.isPending||m.isPending,children:"Abbrechen"}),s.jsx(F,{variant:c==="restore"?"primary":"danger",onClick:g,disabled:p.isPending||m.isPending,children:p.isPending||m.isPending?"Wird ausgeführt...":c==="restore"?"Wiederherstellen":"Endgültig löschen"})]})]})})]})}function ik({customerId:e}){const[t,n]=j.useState(null),[r,a]=j.useState("INBOX"),[i,l]=j.useState(null),[o,c]=j.useState(!1),[d,u]=j.useState(!1),[h,p]=j.useState(null),m=xe(),{hasPermission:f}=He(),x=f("emails:delete"),{data:b,isLoading:y}=me({queryKey:["mailbox-accounts",e],queryFn:()=>Ae.getMailboxAccounts(e)}),g=(b==null?void 0:b.data)||[];j.useEffect(()=>{g.length>0&&!t&&n(g[0].id)},[g,t]);const v=g.find(oe=>oe.id===t),{data:N,isLoading:D,refetch:A}=me({queryKey:["emails","customer",e,t,r],queryFn:()=>Ae.getForCustomer(e,{accountId:t||void 0,folder:r}),enabled:!!t&&r!=="TRASH"}),R=(N==null?void 0:N.data)||[],{data:w,isLoading:S}=me({queryKey:["emails","trash",e],queryFn:()=>Ae.getTrash(e),enabled:r==="TRASH"&&x}),E=(w==null?void 0:w.data)||[],{data:z}=me({queryKey:["folder-counts",t],queryFn:()=>xs.getFolderCounts(t),enabled:!!t}),I=(z==null?void 0:z.data)||{inbox:0,inboxUnread:0,sent:0,sentUnread:0,trash:0,trashUnread:0},{data:B}=me({queryKey:["email",i==null?void 0:i.id],queryFn:()=>Ae.getById(i.id),enabled:!!(i!=null&&i.id)}),P=(B==null?void 0:B.data)||i,M=W({mutationFn:oe=>xs.syncEmails(oe),onSuccess:()=>{m.invalidateQueries({queryKey:["emails"]}),m.invalidateQueries({queryKey:["folder-counts",t]}),m.invalidateQueries({queryKey:["mailbox-accounts",e]})}}),k=()=>{t&&M.mutate(t)},_=oe=>{l(oe)},K=()=>{p(P||null),c(!0)},Z=()=>{p(null),c(!0)},H=()=>{u(!0)};if(!y&&g.length===0)return s.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-gray-500",children:[s.jsx(nn,{className:"w-16 h-16 mb-4 opacity-30"}),s.jsx("h3",{className:"text-lg font-medium text-gray-900 mb-2",children:"Keine E-Mail-Konten vorhanden"}),s.jsx("p",{className:"text-sm text-center max-w-md",children:"Erstellen Sie eine Stressfrei-Wechseln E-Mail-Adresse mit aktivierter Mailbox, um E-Mails hier empfangen und versenden zu können."})]});const pe=oe=>{a(oe),l(null)};return s.jsxs("div",{className:"flex flex-col h-full",style:{minHeight:"600px"},children:[s.jsxs("div",{className:"flex items-center justify-between gap-4 p-4 border-b border-gray-200 bg-gray-50",children:[g.length>1?s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(Ur,{className:"w-5 h-5 text-gray-500"}),s.jsx("select",{value:t||"",onChange:oe=>{n(Number(oe.target.value)),l(null)},className:"px-3 py-2 border border-gray-300 rounded-lg bg-white focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm",children:g.map(oe=>s.jsx("option",{value:oe.id,children:oe.email},oe.id))})]}):s.jsxs("div",{className:"flex items-center gap-3 text-sm text-gray-600",children:[s.jsx(Ur,{className:"w-5 h-5 text-gray-500"}),s.jsx("span",{children:v==null?void 0:v.email})]}),s.jsxs("div",{className:"flex items-center gap-1 bg-gray-200 rounded-lg p-1",children:[s.jsxs("button",{onClick:()=>pe("INBOX"),className:`flex items-center gap-1.5 px-3 py-1.5 text-sm rounded-md transition-colors ${r==="INBOX"?"bg-white text-blue-600 shadow-sm font-medium":"text-gray-600 hover:text-gray-900"}`,children:[s.jsx(Ur,{className:"w-4 h-4"}),"Posteingang",I.inbox>0&&s.jsx("span",{className:`ml-1 px-1.5 py-0.5 text-xs rounded-full cursor-help ${I.inboxUnread>0?"bg-blue-100 text-blue-600 font-medium":"bg-gray-100 text-gray-500"}`,title:`${I.inboxUnread} ungelesen / ${I.inbox} gesamt`,children:I.inboxUnread>0?`${I.inboxUnread}/${I.inbox}`:I.inbox})]}),s.jsxs("button",{onClick:()=>pe("SENT"),className:`flex items-center gap-1.5 px-3 py-1.5 text-sm rounded-md transition-colors ${r==="SENT"?"bg-white text-blue-600 shadow-sm font-medium":"text-gray-600 hover:text-gray-900"}`,children:[s.jsx(Ml,{className:"w-4 h-4"}),"Gesendet",I.sent>0&&s.jsx("span",{className:`ml-1 px-1.5 py-0.5 text-xs rounded-full cursor-help ${I.sentUnread>0?"bg-blue-100 text-blue-600 font-medium":"bg-gray-100 text-gray-500"}`,title:`${I.sentUnread} ungelesen / ${I.sent} gesamt`,children:I.sentUnread>0?`${I.sentUnread}/${I.sent}`:I.sent})]}),x&&s.jsxs("button",{onClick:()=>pe("TRASH"),className:`flex items-center gap-1.5 px-3 py-1.5 text-sm rounded-md transition-colors ${r==="TRASH"?"bg-white text-red-600 shadow-sm font-medium":"text-gray-600 hover:text-gray-900"}`,children:[s.jsx(be,{className:"w-4 h-4"}),"Papierkorb",I.trash>0&&s.jsx("span",{className:`ml-1 px-1.5 py-0.5 text-xs rounded-full cursor-help ${I.trashUnread>0?"bg-red-100 text-red-600 font-medium":"bg-gray-100 text-gray-500"}`,title:`${I.trashUnread} ungelesen / ${I.trash} gesamt`,children:I.trashUnread>0?`${I.trashUnread}/${I.trash}`:I.trash})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[r!=="TRASH"&&s.jsxs(F,{variant:"secondary",size:"sm",onClick:k,disabled:M.isPending||!t,children:[s.jsx(wr,{className:`w-4 h-4 mr-1 ${M.isPending?"animate-spin":""}`}),M.isPending?"Sync...":"Synchronisieren"]}),s.jsxs(F,{size:"sm",onClick:Z,disabled:!v,children:[s.jsx(Be,{className:"w-4 h-4 mr-1"}),"Neue E-Mail"]})]})]}),s.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[s.jsx("div",{className:"w-1/3 border-r border-gray-200 overflow-auto",children:r==="TRASH"?s.jsx(Lv,{emails:E,selectedEmailId:i==null?void 0:i.id,onSelectEmail:_,onEmailRestored:oe=>{(i==null?void 0:i.id)===oe&&l(null),m.invalidateQueries({queryKey:["emails"]}),m.invalidateQueries({queryKey:["folder-counts",t]})},onEmailDeleted:oe=>{(i==null?void 0:i.id)===oe&&l(null),m.invalidateQueries({queryKey:["emails","trash"]}),m.invalidateQueries({queryKey:["folder-counts",t]})},isLoading:S}):s.jsx(sk,{emails:R,selectedEmailId:i==null?void 0:i.id,onSelectEmail:_,onEmailDeleted:oe=>{(i==null?void 0:i.id)===oe&&l(null),m.invalidateQueries({queryKey:["folder-counts",t]})},isLoading:D,folder:r,accountId:t})}),s.jsx("div",{className:"flex-1 overflow-auto",children:P?s.jsx(Iv,{email:P,onReply:K,onAssignContract:H,onDeleted:()=>{l(null),m.invalidateQueries({queryKey:["emails"]}),m.invalidateQueries({queryKey:["folder-counts",t]})},isSentFolder:r==="SENT",isTrashView:r==="TRASH",onRestored:()=>{l(null),m.invalidateQueries({queryKey:["emails"]}),m.invalidateQueries({queryKey:["folder-counts",t]})},accountId:t||void 0}):s.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-gray-500",children:[s.jsx(nn,{className:"w-12 h-12 mb-2 opacity-30"}),s.jsx("p",{children:"Wählen Sie eine E-Mail aus"})]})})]}),v&&s.jsx(Rv,{isOpen:o,onClose:()=>{c(!1),p(null)},account:v,replyTo:h||void 0,onSuccess:()=>{m.invalidateQueries({queryKey:["emails","customer",e,t,"SENT"]}),m.invalidateQueries({queryKey:["folder-counts",t]}),r==="SENT"&&A()}}),P&&s.jsx(ak,{isOpen:d,onClose:()=>u(!1),email:P,customerId:e,onSuccess:()=>{A()}})]})}function lk({contractId:e,customerId:t}){const[n,r]=j.useState(null),[a,i]=j.useState("INBOX"),[l,o]=j.useState(null),[c,d]=j.useState(!1),[u,h]=j.useState(null),[p,m]=j.useState(null),f=xe(),{hasPermission:x}=He(),b=x("emails:delete"),{data:y,isLoading:g}=me({queryKey:["mailbox-accounts",t],queryFn:()=>Ae.getMailboxAccounts(t)}),v=(y==null?void 0:y.data)||[];j.useEffect(()=>{v.length>0&&!n&&r(v[0].id)},[v,n]);const N=v.find(ee=>ee.id===n),{data:D,isLoading:A,refetch:R}=me({queryKey:["emails","contract",e,a],queryFn:()=>Ae.getForContract(e,{folder:a}),enabled:a!=="TRASH"}),w=(D==null?void 0:D.data)||[],{data:S,isLoading:E}=me({queryKey:["emails","trash",t],queryFn:()=>Ae.getTrash(t),enabled:a==="TRASH"&&b}),z=(S==null?void 0:S.data)||[],{data:I}=me({queryKey:["contract-folder-counts",e],queryFn:()=>Ae.getContractFolderCounts(e)}),B=(I==null?void 0:I.data)||{inbox:0,inboxUnread:0,sent:0,sentUnread:0},{data:P}=me({queryKey:["folder-counts",n],queryFn:()=>xs.getFolderCounts(n),enabled:!!n&&b}),M=(P==null?void 0:P.data)||{trash:0,trashUnread:0},{data:k}=me({queryKey:["email",l==null?void 0:l.id],queryFn:()=>Ae.getById(l.id),enabled:!!(l!=null&&l.id)}),_=(k==null?void 0:k.data)||l,K=W({mutationFn:ee=>xs.syncEmails(ee),onSuccess:()=>{f.invalidateQueries({queryKey:["emails"]}),f.invalidateQueries({queryKey:["contract-folder-counts",e]}),n&&f.invalidateQueries({queryKey:["folder-counts",n]}),Ie.success("Synchronisation abgeschlossen")},onError:ee=>{Ie.error(ee.message||"Synchronisation fehlgeschlagen")}}),Z=W({mutationFn:ee=>Ae.toggleStar(ee),onSuccess:(ee,Ne)=>{f.invalidateQueries({queryKey:["emails","contract",e]}),f.invalidateQueries({queryKey:["email",Ne]})}}),H=W({mutationFn:({emailId:ee,isRead:Ne})=>Ae.markAsRead(ee,Ne),onSuccess:(ee,Ne)=>{f.invalidateQueries({queryKey:["emails","contract",e]}),f.invalidateQueries({queryKey:["email",Ne.emailId]}),f.invalidateQueries({queryKey:["contract-folder-counts",e]}),n&&f.invalidateQueries({queryKey:["folder-counts",n]})}}),pe=W({mutationFn:ee=>Ae.unassignFromContract(ee),onSuccess:()=>{f.invalidateQueries({queryKey:["emails","contract",e]}),f.invalidateQueries({queryKey:["contract-folder-counts",e]}),o(null),Ie.success("Zuordnung aufgehoben")},onError:ee=>{Ie.error(ee.message||"Fehler beim Aufheben der Zuordnung")}}),oe=W({mutationFn:ee=>Ae.delete(ee),onSuccess:(ee,Ne)=>{f.invalidateQueries({queryKey:["emails"]}),f.invalidateQueries({queryKey:["contract-folder-counts",e]}),n&&f.invalidateQueries({queryKey:["folder-counts",n]}),Ie.success("E-Mail in Papierkorb verschoben"),m(null),(l==null?void 0:l.id)===Ne&&o(null)},onError:ee=>{Ie.error(ee.message||"Fehler beim Löschen der E-Mail"),m(null)}}),Ze=()=>{n&&K.mutate(n)},Oe=ee=>{const Ne=new Date(ee),Is=new Date;return Ne.toDateString()===Is.toDateString()?Ne.toLocaleTimeString("de-DE",{hour:"2-digit",minute:"2-digit"}):Ne.toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit"})},it=(ee,Ne)=>{ee.stopPropagation(),Z.mutate(Ne)},C=(ee,Ne)=>{ee.stopPropagation(),H.mutate({emailId:Ne.id,isRead:!Ne.isRead})},et=ee=>{ee.isRead||H.mutate({emailId:ee.id,isRead:!0}),o(ee)},zt=()=>{h(_||null),d(!0)},Qt=()=>{h(null),d(!0)},J=(ee,Ne)=>{ee.stopPropagation(),(l==null?void 0:l.id)===Ne&&o(null),pe.mutate(Ne)},qe=(ee,Ne)=>{ee.stopPropagation(),m(Ne)},St=ee=>{ee.stopPropagation(),p&&oe.mutate(p)},G=ee=>{ee.stopPropagation(),m(null)},_e=ee=>{i(ee),o(null)},ht=ee=>{if(a==="SENT")try{const Ne=JSON.parse(ee.toAddresses);if(Ne.length>0)return`An: ${Ne[0]}${Ne.length>1?` (+${Ne.length-1})`:""}`}catch{return"An: (Unbekannt)"}return ee.fromName||ee.fromAddress};return!g&&v.length===0?s.jsx(Y,{title:"E-Mails",children:s.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-gray-500",children:[s.jsx(nn,{className:"w-10 h-10 mb-2 opacity-30"}),s.jsx("p",{className:"text-sm",children:"Keine E-Mail-Konten vorhanden"}),s.jsx("p",{className:"text-xs mt-1",children:"Erstellen Sie eine E-Mail-Adresse beim Kunden mit aktivierter Mailbox"})]})}):s.jsxs(Y,{title:s.jsx("div",{className:"flex items-center gap-4",children:s.jsx("span",{children:"E-Mails"})}),actions:s.jsxs("div",{className:"flex items-center gap-2",children:[a!=="TRASH"&&s.jsxs(F,{variant:"secondary",size:"sm",onClick:Ze,disabled:K.isPending||!n,children:[s.jsx(wr,{className:`w-4 h-4 mr-1 ${K.isPending?"animate-spin":""}`}),K.isPending?"Sync...":"Sync"]}),N&&s.jsxs(F,{size:"sm",onClick:Qt,children:[s.jsx(Be,{className:"w-4 h-4 mr-1"}),"Neue E-Mail"]})]}),children:[s.jsxs("div",{className:"flex items-center justify-between gap-4 pb-4 border-b border-gray-200 -mt-2",children:[v.length>1?s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Ur,{className:"w-4 h-4 text-gray-500"}),s.jsx("select",{value:n||"",onChange:ee=>{r(Number(ee.target.value)),o(null)},className:"px-2 py-1.5 border border-gray-300 rounded-lg bg-white focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm",children:v.map(ee=>s.jsx("option",{value:ee.id,children:ee.email},ee.id))})]}):s.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-600",children:[s.jsx(Ur,{className:"w-4 h-4 text-gray-500"}),s.jsx("span",{children:N==null?void 0:N.email})]}),s.jsxs("div",{className:"flex items-center gap-1 bg-gray-200 rounded-lg p-1",children:[s.jsxs("button",{onClick:()=>_e("INBOX"),className:`flex items-center gap-1.5 px-3 py-1.5 text-sm rounded-md transition-colors ${a==="INBOX"?"bg-white text-blue-600 shadow-sm font-medium":"text-gray-600 hover:text-gray-900"}`,children:[s.jsx(Ur,{className:"w-4 h-4"}),"Posteingang",B.inbox>0&&s.jsx("span",{className:`ml-1 px-1.5 py-0.5 text-xs rounded-full cursor-help ${B.inboxUnread>0?"bg-blue-100 text-blue-600 font-medium":"bg-gray-100 text-gray-500"}`,title:`${B.inboxUnread} ungelesen / ${B.inbox} gesamt`,children:B.inboxUnread>0?`${B.inboxUnread}/${B.inbox}`:B.inbox})]}),s.jsxs("button",{onClick:()=>_e("SENT"),className:`flex items-center gap-1.5 px-3 py-1.5 text-sm rounded-md transition-colors ${a==="SENT"?"bg-white text-blue-600 shadow-sm font-medium":"text-gray-600 hover:text-gray-900"}`,children:[s.jsx(Ml,{className:"w-4 h-4"}),"Gesendet",B.sent>0&&s.jsx("span",{className:`ml-1 px-1.5 py-0.5 text-xs rounded-full cursor-help ${B.sentUnread>0?"bg-blue-100 text-blue-600 font-medium":"bg-gray-100 text-gray-500"}`,title:`${B.sentUnread} ungelesen / ${B.sent} gesamt`,children:B.sentUnread>0?`${B.sentUnread}/${B.sent}`:B.sent})]}),b&&s.jsxs("button",{onClick:()=>_e("TRASH"),className:`flex items-center gap-1.5 px-3 py-1.5 text-sm rounded-md transition-colors ${a==="TRASH"?"bg-white text-red-600 shadow-sm font-medium":"text-gray-600 hover:text-gray-900"}`,children:[s.jsx(be,{className:"w-4 h-4"}),"Papierkorb",M.trash>0&&s.jsx("span",{className:`ml-1 px-1.5 py-0.5 text-xs rounded-full cursor-help ${M.trashUnread>0?"bg-red-100 text-red-600 font-medium":"bg-gray-100 text-gray-500"}`,title:`${M.trashUnread} ungelesen / ${M.trash} gesamt`,children:M.trashUnread>0?`${M.trashUnread}/${M.trash}`:M.trash})]})]})]}),(a==="TRASH"?E:A)?s.jsx("div",{className:"flex items-center justify-center py-8",children:s.jsx("div",{className:"animate-spin rounded-full h-6 w-6 border-b-2 border-blue-600"})}):(a==="TRASH"?z.length===0:w.length===0)?s.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-gray-500",children:[s.jsx(nn,{className:"w-10 h-10 mb-2 opacity-30"}),s.jsx("p",{className:"text-sm",children:a==="INBOX"?"Keine E-Mails zugeordnet":a==="SENT"?"Keine E-Mails über diesen Vertrag gesendet":"Papierkorb ist leer"}),a==="INBOX"&&s.jsx("p",{className:"text-xs mt-1",children:"E-Mails können im E-Mail-Tab des Kunden zugeordnet werden"})]}):s.jsxs("div",{className:"flex -mx-6 -mb-6",style:{minHeight:"400px"},children:[s.jsx("div",{className:"w-1/3 border-r border-gray-200 overflow-auto",children:a==="TRASH"?s.jsx(Lv,{emails:z,selectedEmailId:l==null?void 0:l.id,onSelectEmail:et,onEmailRestored:ee=>{(l==null?void 0:l.id)===ee&&o(null),f.invalidateQueries({queryKey:["emails"]}),f.invalidateQueries({queryKey:["folder-counts",n]}),f.invalidateQueries({queryKey:["contract-folder-counts",e]})},onEmailDeleted:ee=>{(l==null?void 0:l.id)===ee&&o(null),f.invalidateQueries({queryKey:["emails","trash"]}),f.invalidateQueries({queryKey:["folder-counts",n]})},isLoading:E}):s.jsx("div",{className:"divide-y divide-gray-200",children:w.map(ee=>s.jsxs("div",{onClick:()=>et(ee),className:["flex items-start gap-2 p-3 cursor-pointer transition-colors",(l==null?void 0:l.id)===ee.id?"bg-blue-100":["hover:bg-gray-100",ee.isRead?"bg-gray-50/50":"bg-white"].join(" ")].join(" "),style:{borderLeft:(l==null?void 0:l.id)===ee.id?"4px solid #2563eb":"4px solid transparent"},children:[s.jsx("button",{onClick:Ne=>C(Ne,ee),className:` flex-shrink-0 mt-1 p-1 -ml-1 rounded hover:bg-gray-200 ${ee.isRead?"text-gray-400":"text-blue-600"} `,title:ee.isRead?"Als ungelesen markieren":"Als gelesen markieren",children:ee.isRead?s.jsx(Pv,{className:"w-4 h-4"}):s.jsx(nn,{className:"w-4 h-4"})}),s.jsx("button",{onClick:Ne=>it(Ne,ee.id),className:` flex-shrink-0 mt-1 p-1 -ml-1 rounded hover:bg-gray-200 ${ee.isStarred?"text-yellow-500":"text-gray-400"} `,title:ee.isStarred?"Stern entfernen":"Als wichtig markieren",children:s.jsx(fh,{className:`w-4 h-4 ${ee.isStarred?"fill-current":""}`})}),x("emails:delete")&&s.jsx("button",{onClick:Ne=>qe(Ne,ee.id),className:"flex-shrink-0 mt-1 p-1 -ml-1 rounded hover:bg-red-100 text-gray-400 hover:text-red-600",title:"E-Mail löschen",children:s.jsx(be,{className:"w-4 h-4"})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2 mb-1",children:[s.jsx("span",{className:`text-sm truncate ${ee.isRead?"text-gray-700":"font-semibold text-gray-900"}`,children:ht(ee)}),s.jsx("span",{className:"text-xs text-gray-500 flex-shrink-0",children:Oe(ee.receivedAt)})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:`text-sm truncate ${ee.isRead?"text-gray-600":"font-medium text-gray-900"}`,children:ee.subject||"(Kein Betreff)"}),ee.hasAttachments&&s.jsx(Fc,{className:"w-3 h-3 text-gray-400 flex-shrink-0"})]}),ee.contract&&s.jsxs("div",{className:"mt-1 flex items-center gap-1",children:[s.jsx("span",{className:"inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-green-100 text-green-800",children:ee.contract.contractNumber}),(a==="INBOX"||a==="SENT"&&!ee.isAutoAssigned)&&s.jsx("button",{onClick:Ne=>J(Ne,ee.id),className:"p-0.5 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded",title:"Zuordnung aufheben",disabled:pe.isPending,children:s.jsx(Vt,{className:"w-3.5 h-3.5"})})]})]}),s.jsx(Ft,{className:"w-4 h-4 text-gray-400 flex-shrink-0 mt-2"})]},ee.id))})}),s.jsx("div",{className:"flex-1 overflow-auto",children:_&&l?s.jsx(Iv,{email:_,onReply:zt,onAssignContract:()=>{},onDeleted:()=>{o(null),f.invalidateQueries({queryKey:["emails"]}),f.invalidateQueries({queryKey:["contract-folder-counts",e]}),n&&f.invalidateQueries({queryKey:["folder-counts",n]})},isSentFolder:a==="SENT",isContractView:a!=="TRASH",isTrashView:a==="TRASH",onRestored:()=>{o(null),f.invalidateQueries({queryKey:["emails"]}),f.invalidateQueries({queryKey:["contract-folder-counts",e]}),n&&f.invalidateQueries({queryKey:["folder-counts",n]})},accountId:_==null?void 0:_.stressfreiEmailId}):s.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-gray-500",children:[s.jsx(nn,{className:"w-12 h-12 mb-2 opacity-30"}),s.jsx("p",{children:"Wählen Sie eine E-Mail aus"})]})})]}),p&&s.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:s.jsxs("div",{className:"bg-white rounded-lg shadow-xl p-6 max-w-md mx-4",children:[s.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"E-Mail löschen?"}),s.jsx("p",{className:"text-gray-600 mb-4",children:"Die E-Mail wird in den Papierkorb verschoben."}),s.jsxs("div",{className:"flex justify-end gap-3",children:[s.jsx(F,{variant:"secondary",onClick:G,disabled:oe.isPending,children:"Abbrechen"}),s.jsx(F,{variant:"danger",onClick:St,disabled:oe.isPending,children:oe.isPending?"Löschen...":"Löschen"})]})]})}),N&&s.jsx(Rv,{isOpen:c,onClose:()=>{d(!1),h(null)},account:N,replyTo:u||void 0,contractId:e,onSuccess:()=>{f.invalidateQueries({queryKey:["emails","contract",e,"SENT"]}),f.invalidateQueries({queryKey:["contract-folder-counts",e]}),a==="SENT"&&R()}})]})}function ok({tabs:e,defaultTab:t}){var a,i;const[n,r]=j.useState(t||((a=e[0])==null?void 0:a.id));return s.jsxs("div",{children:[s.jsx("div",{className:"border-b border-gray-200",children:s.jsx("nav",{className:"flex -mb-px space-x-8",children:e.map(l=>s.jsx("button",{onClick:()=>r(l.id),className:`py-4 px-1 border-b-2 font-medium text-sm whitespace-nowrap ${n===l.id?"border-blue-500 text-blue-600":"border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300"}`,children:l.label},l.id))})}),s.jsx("div",{className:"mt-4",children:(i=e.find(l=>l.id===n))==null?void 0:i.content})]})}function Et({onUpload:e,existingFile:t,accept:n=".pdf,.jpg,.jpeg,.png",label:r="Dokument hochladen",disabled:a=!1}){const i=j.useRef(null),[l,o]=j.useState(!1),[c,d]=j.useState(!1),u=async x=>{if(x){o(!0);try{await e(x)}catch(b){console.error("Upload failed:",b),alert("Upload fehlgeschlagen")}finally{o(!1)}}},h=x=>{var y;const b=(y=x.target.files)==null?void 0:y[0];b&&u(b)},p=x=>{var y;x.preventDefault(),d(!1);const b=(y=x.dataTransfer.files)==null?void 0:y[0];b&&u(b)},m=x=>{x.preventDefault(),d(!0)},f=()=>{d(!1)};return s.jsxs("div",{className:"space-y-2",children:[t?!a&&s.jsx(F,{variant:"secondary",size:"sm",onClick:()=>{var x;return(x=i.current)==null?void 0:x.click()},disabled:l,children:l?"Wird hochgeladen...":"Ersetzen"}):s.jsx("div",{className:`border-2 border-dashed rounded-lg p-4 text-center cursor-pointer transition-colors ${c?"border-blue-500 bg-blue-50":"border-gray-300 hover:border-gray-400"} ${a?"opacity-50 cursor-not-allowed":""}`,onClick:()=>{var x;return!a&&((x=i.current)==null?void 0:x.click())},onDrop:a?void 0:p,onDragOver:a?void 0:m,onDragLeave:a?void 0:f,children:l?s.jsxs("div",{className:"text-gray-500",children:[s.jsx("div",{className:"animate-spin w-6 h-6 border-2 border-blue-500 border-t-transparent rounded-full mx-auto mb-2"}),"Wird hochgeladen..."]}):s.jsxs(s.Fragment,{children:[s.jsx(Vu,{className:"w-6 h-6 text-gray-400 mx-auto mb-2"}),s.jsx("p",{className:"text-sm text-gray-600",children:r}),s.jsx("p",{className:"text-xs text-gray-400 mt-1",children:"PDF, JPG oder PNG (max. 10MB)"})]})}),s.jsx("input",{ref:i,type:"file",accept:n,onChange:h,className:"hidden",disabled:a||l})]})}function ce({value:e,className:t="",size:n="sm",title:r="In Zwischenablage kopieren"}){const[a,i]=j.useState(!1),l=async c=>{c.preventDefault(),c.stopPropagation();try{await navigator.clipboard.writeText(e),i(!0),setTimeout(()=>i(!1),1500)}catch(d){console.error("Failed to copy:",d)}},o=n==="sm"?"w-3.5 h-3.5":"w-4 h-4";return s.jsx("button",{type:"button",onClick:l,className:`inline-flex items-center justify-center p-1 rounded transition-colors ${a?"text-green-600 bg-green-50":"text-gray-400 hover:text-blue-600 hover:bg-blue-50"} ${t}`,title:a?"Kopiert!":r,children:a?s.jsx(fr,{className:o}):s.jsx(lh,{className:o})})}function Qu({values:e,separator:t=` `,children:n,className:r=""}){const a=e.filter(i=>i!=null&&i!=="").map(String).join(t);return a?s.jsxs("div",{className:`relative group ${r}`,children:[n,s.jsx(ce,{value:a,className:"absolute top-0 right-0 opacity-60 group-hover:opacity-100",title:"Alles kopieren"})]}):s.jsx(s.Fragment,{children:n})}function ck(){var K,Z;const{id:e}=bc(),t=ts(),n=xe(),{hasPermission:r}=He(),[a]=wc(),i=parseInt(e),l=a.get("tab")||"addresses",[o,c]=j.useState(!1),[d,u]=j.useState(!1),[h,p]=j.useState(!1),[m,f]=j.useState(!1),[x,b]=j.useState(!1),[y,g]=j.useState(!1),[v,N]=j.useState(null),[D,A]=j.useState(null),[R,w]=j.useState(null),[S,E]=j.useState(null),[z,I]=j.useState(null),{data:B,isLoading:P}=me({queryKey:["customer",e],queryFn:()=>Dt.getById(i)}),M=W({mutationFn:()=>Dt.delete(i),onSuccess:()=>{t("/customers")}});if(P)return s.jsx("div",{className:"text-center py-8",children:"Laden..."});if(!(B!=null&&B.data))return s.jsx("div",{className:"text-center py-8 text-red-600",children:"Kunde nicht gefunden"});const k=B.data,_=[{id:"addresses",label:"Adressen",content:s.jsx(mk,{customerId:i,addresses:k.addresses||[],canEdit:r("customers:update"),onAdd:()=>c(!0),onEdit:H=>w(H)})},{id:"bankcards",label:"Bankkarten",content:s.jsx(hk,{customerId:i,bankCards:k.bankCards||[],canEdit:r("customers:update"),showInactive:y,onToggleInactive:()=>g(!y),onAdd:()=>u(!0),onEdit:H=>N(H)})},{id:"documents",label:"Ausweise",content:s.jsx(fk,{customerId:i,documents:k.identityDocuments||[],canEdit:r("customers:update"),showInactive:y,onToggleInactive:()=>g(!y),onAdd:()=>p(!0),onEdit:H=>A(H)})},{id:"meters",label:"Zähler",content:s.jsx(pk,{customerId:i,meters:k.meters||[],canEdit:r("customers:update"),showInactive:y,onToggleInactive:()=>g(!y),onAdd:()=>f(!0),onEdit:H=>E(H)})},{id:"stressfrei",label:"Stressfrei-Wechseln",content:s.jsx(vk,{customerId:i,emails:k.stressfreiEmails||[],canEdit:r("customers:update"),showInactive:y,onToggleInactive:()=>g(!y),onAdd:()=>b(!0),onEdit:H=>I(H)})},{id:"emails",label:"E-Mail-Postfach",content:s.jsx(ik,{customerId:i})},{id:"contracts",label:"Verträge",content:s.jsx(xk,{customerId:i})},...r("customers:update")?[{id:"portal",label:"Portal",content:s.jsx(yk,{customerId:i,canEdit:r("customers:update")})}]:[]];return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center justify-between mb-6",children:[s.jsxs("div",{children:[s.jsx("h1",{className:"text-2xl font-bold",children:k.type==="BUSINESS"&&k.companyName?k.companyName:`${k.firstName} ${k.lastName}`}),s.jsxs("p",{className:"text-gray-500 font-mono flex items-center gap-1",children:[k.customerNumber,s.jsx(ce,{value:k.customerNumber})]})]}),s.jsxs("div",{className:"flex gap-2",children:[r("customers:update")&&s.jsx(ke,{to:`/customers/${e}/edit`,children:s.jsxs(F,{variant:"secondary",children:[s.jsx(Ye,{className:"w-4 h-4 mr-2"}),"Bearbeiten"]})}),r("customers:delete")&&s.jsxs(F,{variant:"danger",onClick:()=>{confirm("Kunde wirklich löschen?")&&M.mutate()},children:[s.jsx(be,{className:"w-4 h-4 mr-2"}),"Löschen"]})]})]}),s.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6 mb-6",children:[s.jsx(Y,{title:"Stammdaten",className:"lg:col-span-2",children:s.jsxs("dl",{className:"grid grid-cols-2 gap-4",children:[s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Typ"}),s.jsx("dd",{children:s.jsx(ye,{variant:k.type==="BUSINESS"?"info":"default",children:k.type==="BUSINESS"?"Geschäftskunde":"Privatkunde"})})]}),k.salutation&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Anrede"}),s.jsxs("dd",{className:"flex items-center gap-1",children:[k.salutation,s.jsx(ce,{value:k.salutation})]})]}),s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Vorname"}),s.jsxs("dd",{className:"flex items-center gap-1",children:[k.firstName,s.jsx(ce,{value:k.firstName})]})]}),s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Nachname"}),s.jsxs("dd",{className:"flex items-center gap-1",children:[k.lastName,s.jsx(ce,{value:k.lastName})]})]}),k.companyName&&s.jsxs("div",{className:"col-span-2",children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Firma"}),s.jsxs("dd",{className:"flex items-center gap-1",children:[k.companyName,s.jsx(ce,{value:k.companyName})]})]}),k.foundingDate&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Gründungsdatum"}),s.jsxs("dd",{className:"flex items-center gap-1",children:[new Date(k.foundingDate).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"}),s.jsx(ce,{value:new Date(k.foundingDate).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"})})]})]}),k.birthDate&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Geburtsdatum"}),s.jsxs("dd",{className:"flex items-center gap-1",children:[new Date(k.birthDate).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"}),s.jsx(ce,{value:new Date(k.birthDate).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"})})]})]}),k.birthPlace&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Geburtsort"}),s.jsxs("dd",{className:"flex items-center gap-1",children:[k.birthPlace,s.jsx(ce,{value:k.birthPlace})]})]})]})}),s.jsx(Y,{title:"Kontakt",children:s.jsxs("dl",{className:"space-y-3",children:[k.email&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"E-Mail"}),s.jsxs("dd",{className:"flex items-center gap-1",children:[s.jsx("a",{href:`mailto:${k.email}`,className:"text-blue-600 hover:underline",children:k.email}),s.jsx(ce,{value:k.email})]})]}),k.phone&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Telefon"}),s.jsxs("dd",{className:"flex items-center gap-1",children:[s.jsx("a",{href:`tel:${k.phone}`,className:"text-blue-600 hover:underline",children:k.phone}),s.jsx(ce,{value:k.phone})]})]}),k.mobile&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Mobil"}),s.jsxs("dd",{className:"flex items-center gap-1",children:[s.jsx("a",{href:`tel:${k.mobile}`,className:"text-blue-600 hover:underline",children:k.mobile}),s.jsx(ce,{value:k.mobile})]})]})]})})]}),k.type==="BUSINESS"&&s.jsx(dk,{customer:k,canEdit:r("customers:update"),onUpdate:()=>n.invalidateQueries({queryKey:["customer",e]})}),s.jsx(uk,{customer:k,canEdit:r("customers:update"),onUpdate:()=>n.invalidateQueries({queryKey:["customer",e]})}),k.notes&&s.jsx(Y,{title:"Notizen",className:"mb-6",children:s.jsx("p",{className:"whitespace-pre-wrap",children:k.notes})}),s.jsx(Y,{children:s.jsx(ok,{tabs:_,defaultTab:l})}),s.jsx(xx,{isOpen:o,onClose:()=>c(!1),customerId:i}),s.jsx(xx,{isOpen:!!R,onClose:()=>w(null),customerId:i,address:R}),s.jsx(gx,{isOpen:d,onClose:()=>u(!1),customerId:i}),s.jsx(gx,{isOpen:!!v,onClose:()=>N(null),customerId:i,bankCard:v}),s.jsx(yx,{isOpen:h,onClose:()=>p(!1),customerId:i}),s.jsx(yx,{isOpen:!!D,onClose:()=>A(null),customerId:i,document:D}),s.jsx(vx,{isOpen:m,onClose:()=>f(!1),customerId:i}),s.jsx(vx,{isOpen:!!S,onClose:()=>E(null),customerId:i,meter:S}),s.jsx(bx,{isOpen:x,onClose:()=>b(!1),customerId:i,customerEmail:(K=B==null?void 0:B.data)==null?void 0:K.email}),s.jsx(bx,{isOpen:!!z,onClose:()=>I(null),customerId:i,email:z,customerEmail:(Z=B==null?void 0:B.data)==null?void 0:Z.email})]})}function dk({customer:e,canEdit:t,onUpdate:n}){const r=async c=>{try{await ct.uploadBusinessRegistration(e.id,c),n()}catch(d){console.error("Upload fehlgeschlagen:",d),alert("Upload fehlgeschlagen")}},a=async()=>{if(confirm("Gewerbeanmeldung wirklich löschen?"))try{await ct.deleteBusinessRegistration(e.id),n()}catch(c){console.error("Löschen fehlgeschlagen:",c),alert("Löschen fehlgeschlagen")}},i=async c=>{try{await ct.uploadCommercialRegister(e.id,c),n()}catch(d){console.error("Upload fehlgeschlagen:",d),alert("Upload fehlgeschlagen")}},l=async()=>{if(confirm("Handelsregisterauszug wirklich löschen?"))try{await ct.deleteCommercialRegister(e.id),n()}catch(c){console.error("Löschen fehlgeschlagen:",c),alert("Löschen fehlgeschlagen")}};return!(e.taxNumber||e.commercialRegisterNumber||e.businessRegistrationPath||e.commercialRegisterPath)&&!t?null:s.jsxs(Y,{title:"Geschäftsdaten",className:"mb-6",children:[s.jsxs("dl",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.taxNumber&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Steuernummer"}),s.jsxs("dd",{className:"flex items-center gap-1",children:[e.taxNumber,s.jsx(ce,{value:e.taxNumber})]})]}),e.commercialRegisterNumber&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Handelsregisternummer"}),s.jsxs("dd",{className:"flex items-center gap-1",children:[e.commercialRegisterNumber,s.jsx(ce,{value:e.commercialRegisterNumber})]})]})]}),s.jsxs("div",{className:"mt-4 pt-4 border-t grid grid-cols-1 md:grid-cols-2 gap-6",children:[s.jsxs("div",{children:[s.jsx("h4",{className:"text-sm font-medium text-gray-700 mb-2",children:"Gewerbeanmeldung"}),e.businessRegistrationPath?s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsxs("a",{href:`/api${e.businessRegistrationPath}`,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:underline text-sm flex items-center gap-1",children:[s.jsx(Pe,{className:"w-4 h-4"}),"Anzeigen"]}),s.jsxs("a",{href:`/api${e.businessRegistrationPath}`,download:!0,className:"text-blue-600 hover:underline text-sm flex items-center gap-1",children:[s.jsx(As,{className:"w-4 h-4"}),"Download"]}),t&&s.jsxs(s.Fragment,{children:[s.jsx(Et,{onUpload:r,existingFile:e.businessRegistrationPath,accept:".pdf",label:"Ersetzen"}),s.jsxs("button",{onClick:a,className:"text-red-600 hover:underline text-sm flex items-center gap-1",children:[s.jsx(be,{className:"w-4 h-4"}),"Löschen"]})]})]}):t?s.jsx(Et,{onUpload:r,accept:".pdf",label:"PDF hochladen"}):s.jsx("p",{className:"text-sm text-gray-400",children:"Nicht vorhanden"})]}),s.jsxs("div",{children:[s.jsx("h4",{className:"text-sm font-medium text-gray-700 mb-2",children:"Handelsregisterauszug"}),e.commercialRegisterPath?s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsxs("a",{href:`/api${e.commercialRegisterPath}`,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:underline text-sm flex items-center gap-1",children:[s.jsx(Pe,{className:"w-4 h-4"}),"Anzeigen"]}),s.jsxs("a",{href:`/api${e.commercialRegisterPath}`,download:!0,className:"text-blue-600 hover:underline text-sm flex items-center gap-1",children:[s.jsx(As,{className:"w-4 h-4"}),"Download"]}),t&&s.jsxs(s.Fragment,{children:[s.jsx(Et,{onUpload:i,existingFile:e.commercialRegisterPath,accept:".pdf",label:"Ersetzen"}),s.jsxs("button",{onClick:l,className:"text-red-600 hover:underline text-sm flex items-center gap-1",children:[s.jsx(be,{className:"w-4 h-4"}),"Löschen"]})]})]}):t?s.jsx(Et,{onUpload:i,accept:".pdf",label:"PDF hochladen"}):s.jsx("p",{className:"text-sm text-gray-400",children:"Nicht vorhanden"})]})]})]})}function uk({customer:e,canEdit:t,onUpdate:n}){const r=async i=>{try{await ct.uploadPrivacyPolicy(e.id,i),n()}catch(l){console.error("Upload fehlgeschlagen:",l),alert("Upload fehlgeschlagen")}},a=async()=>{if(confirm("Datenschutzerklärung wirklich löschen?"))try{await ct.deletePrivacyPolicy(e.id),n()}catch(i){console.error("Löschen fehlgeschlagen:",i),alert("Löschen fehlgeschlagen")}};return!e.privacyPolicyPath&&!t?null:s.jsx(Y,{title:"Dokumente",className:"mb-6",children:s.jsxs("div",{children:[s.jsx("h4",{className:"text-sm font-medium text-gray-700 mb-2",children:"Datenschutzerklärung"}),e.privacyPolicyPath?s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsxs("a",{href:`/api${e.privacyPolicyPath}`,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:underline text-sm flex items-center gap-1",children:[s.jsx(Pe,{className:"w-4 h-4"}),"Anzeigen"]}),s.jsxs("a",{href:`/api${e.privacyPolicyPath}`,download:!0,className:"text-blue-600 hover:underline text-sm flex items-center gap-1",children:[s.jsx(As,{className:"w-4 h-4"}),"Download"]}),t&&s.jsxs(s.Fragment,{children:[s.jsx(Et,{onUpload:r,existingFile:e.privacyPolicyPath,accept:".pdf",label:"Ersetzen"}),s.jsxs("button",{onClick:a,className:"text-red-600 hover:underline text-sm flex items-center gap-1",children:[s.jsx(be,{className:"w-4 h-4"}),"Löschen"]})]})]}):t?s.jsx(Et,{onUpload:r,accept:".pdf",label:"PDF hochladen"}):s.jsx("p",{className:"text-sm text-gray-400",children:"Nicht vorhanden"})]})})}function mk({customerId:e,addresses:t,canEdit:n,onAdd:r,onEdit:a}){const i=xe(),l=W({mutationFn:qu.delete,onSuccess:()=>i.invalidateQueries({queryKey:["customer",e.toString()]})});return s.jsxs("div",{children:[n&&s.jsx("div",{className:"mb-4",children:s.jsxs(F,{size:"sm",onClick:r,children:[s.jsx(Be,{className:"w-4 h-4 mr-2"}),"Adresse hinzufügen"]})}),t.length>0?s.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:t.map(o=>s.jsxs("div",{className:"border rounded-lg p-4",children:[s.jsxs("div",{className:"flex items-start justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[s.jsx(z2,{className:"w-4 h-4 text-gray-400"}),s.jsx(ye,{variant:o.type==="BILLING"?"info":"default",children:o.type==="BILLING"?"Rechnung":"Liefer-/Meldeadresse"}),o.isDefault&&s.jsx(ye,{variant:"success",children:"Standard"})]}),n&&s.jsxs("div",{className:"flex gap-1",children:[s.jsx(F,{variant:"ghost",size:"sm",onClick:()=>a(o),title:"Bearbeiten",children:s.jsx(Ye,{className:"w-4 h-4"})}),s.jsx(F,{variant:"ghost",size:"sm",onClick:()=>{confirm("Adresse wirklich löschen?")&&l.mutate(o.id)},title:"Löschen",children:s.jsx(be,{className:"w-4 h-4 text-red-500"})})]})]}),s.jsxs(Qu,{values:[`${o.street} ${o.houseNumber}`,`${o.postalCode} ${o.city}`,o.country],children:[s.jsxs("p",{children:[o.street," ",o.houseNumber]}),s.jsxs("p",{children:[o.postalCode," ",o.city]}),s.jsx("p",{className:"text-gray-500",children:o.country})]})]},o.id))}):s.jsx("p",{className:"text-gray-500",children:"Keine Adressen vorhanden."})]})}function hk({customerId:e,bankCards:t,canEdit:n,showInactive:r,onToggleInactive:a,onAdd:i,onEdit:l}){const o=xe(),c=W({mutationFn:({id:m,data:f})=>Yo.update(m,f),onSuccess:()=>o.invalidateQueries({queryKey:["customer",e.toString()]})}),d=W({mutationFn:Yo.delete,onSuccess:()=>o.invalidateQueries({queryKey:["customer",e.toString()]})}),u=async(m,f)=>{try{await ct.uploadBankCardDocument(m,f),o.invalidateQueries({queryKey:["customer",e.toString()]})}catch(x){console.error("Upload fehlgeschlagen:",x),alert("Upload fehlgeschlagen")}},h=async m=>{if(confirm("Dokument wirklich löschen?"))try{await ct.deleteBankCardDocument(m),o.invalidateQueries({queryKey:["customer",e.toString()]})}catch(f){console.error("Löschen fehlgeschlagen:",f),alert("Löschen fehlgeschlagen")}},p=r?t:t.filter(m=>m.isActive);return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-4 mb-4",children:[n&&s.jsxs(F,{size:"sm",onClick:i,children:[s.jsx(Be,{className:"w-4 h-4 mr-2"}),"Bankkarte hinzufügen"]}),s.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[s.jsx("input",{type:"checkbox",checked:r,onChange:a,className:"rounded"}),"Inaktive anzeigen"]})]}),p.length>0?s.jsx("div",{className:"space-y-4",children:p.map(m=>s.jsxs("div",{className:`border rounded-lg p-4 ${m.isActive?"":"opacity-50 bg-gray-50"}`,children:[s.jsxs("div",{className:"flex items-start justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[s.jsx(oh,{className:"w-4 h-4 text-gray-400"}),!m.isActive&&s.jsx(ye,{variant:"danger",children:"Inaktiv"}),m.expiryDate&&new Date(m.expiryDate)l(m),title:"Bearbeiten",children:s.jsx(Ye,{className:"w-4 h-4"})}),m.isActive?s.jsx(F,{variant:"ghost",size:"sm",onClick:()=>{confirm("Bankkarte deaktivieren?")&&c.mutate({id:m.id,data:{isActive:!1}})},title:"Deaktivieren",children:s.jsx(It,{className:"w-4 h-4"})}):s.jsx(F,{variant:"ghost",size:"sm",onClick:()=>{confirm("Bankkarte wieder aktivieren?")&&c.mutate({id:m.id,data:{isActive:!0}})},title:"Aktivieren",children:s.jsx(Pe,{className:"w-4 h-4"})}),s.jsx(F,{variant:"ghost",size:"sm",onClick:()=>{confirm("Bankkarte wirklich löschen?")&&d.mutate(m.id)},title:"Löschen",children:s.jsx(be,{className:"w-4 h-4 text-red-500"})})]})]}),s.jsxs("p",{className:"font-medium flex items-center gap-1",children:[m.accountHolder,s.jsx(ce,{value:m.accountHolder})]}),s.jsxs("p",{className:"font-mono flex items-center gap-1",children:[m.iban,s.jsx(ce,{value:m.iban})]}),m.bic&&s.jsxs("p",{className:"text-sm text-gray-500 flex items-center gap-1",children:["BIC: ",m.bic,s.jsx(ce,{value:m.bic})]}),m.bankName&&s.jsxs("p",{className:"text-sm text-gray-500 flex items-center gap-1",children:[m.bankName,s.jsx(ce,{value:m.bankName})]}),m.expiryDate&&s.jsxs("p",{className:"text-sm text-gray-500",children:["Gültig bis: ",new Date(m.expiryDate).toLocaleDateString("de-DE")]}),s.jsx("div",{className:"mt-3 pt-3 border-t",children:m.documentPath?s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsxs("a",{href:`/api${m.documentPath}`,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:underline text-sm flex items-center gap-1",children:[s.jsx(Pe,{className:"w-4 h-4"}),"Anzeigen"]}),s.jsxs("a",{href:`/api${m.documentPath}`,download:!0,className:"text-blue-600 hover:underline text-sm flex items-center gap-1",children:[s.jsx(As,{className:"w-4 h-4"}),"Download"]}),n&&s.jsxs(s.Fragment,{children:[s.jsx(Et,{onUpload:f=>u(m.id,f),existingFile:m.documentPath,accept:".pdf",label:"Ersetzen",disabled:!m.isActive}),s.jsxs("button",{onClick:()=>h(m.id),className:"text-red-600 hover:underline text-sm flex items-center gap-1",title:"Dokument löschen",children:[s.jsx(be,{className:"w-4 h-4"}),"Löschen"]})]})]}):n&&m.isActive&&s.jsx(Et,{onUpload:f=>u(m.id,f),accept:".pdf",label:"PDF hochladen"})})]},m.id))}):s.jsx("p",{className:"text-gray-500",children:"Keine Bankkarten vorhanden."})]})}function fk({customerId:e,documents:t,canEdit:n,showInactive:r,onToggleInactive:a,onAdd:i,onEdit:l}){const o=xe(),c=W({mutationFn:({id:f,data:x})=>ec.update(f,x),onSuccess:()=>o.invalidateQueries({queryKey:["customer",e.toString()]})}),d=W({mutationFn:ec.delete,onSuccess:()=>o.invalidateQueries({queryKey:["customer",e.toString()]})}),u=async(f,x)=>{try{await ct.uploadIdentityDocument(f,x),o.invalidateQueries({queryKey:["customer",e.toString()]})}catch(b){console.error("Upload fehlgeschlagen:",b),alert("Upload fehlgeschlagen")}},h=async f=>{if(confirm("Dokument wirklich löschen?"))try{await ct.deleteIdentityDocument(f),o.invalidateQueries({queryKey:["customer",e.toString()]})}catch(x){console.error("Löschen fehlgeschlagen:",x),alert("Löschen fehlgeschlagen")}},p=r?t:t.filter(f=>f.isActive),m={ID_CARD:"Personalausweis",PASSPORT:"Reisepass",DRIVERS_LICENSE:"Führerschein",OTHER:"Sonstiges"};return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-4 mb-4",children:[n&&s.jsxs(F,{size:"sm",onClick:i,children:[s.jsx(Be,{className:"w-4 h-4 mr-2"}),"Ausweis hinzufügen"]}),s.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[s.jsx("input",{type:"checkbox",checked:r,onChange:a,className:"rounded"}),"Inaktive anzeigen"]})]}),p.length>0?s.jsx("div",{className:"space-y-4",children:p.map(f=>s.jsxs("div",{className:`border rounded-lg p-4 ${f.isActive?"":"opacity-50 bg-gray-50"}`,children:[s.jsxs("div",{className:"flex items-start justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[s.jsx(Ke,{className:"w-4 h-4 text-gray-400"}),s.jsx(ye,{children:m[f.type]}),!f.isActive&&s.jsx(ye,{variant:"danger",children:"Inaktiv"}),f.expiryDate&&new Date(f.expiryDate)l(f),title:"Bearbeiten",children:s.jsx(Ye,{className:"w-4 h-4"})}),f.isActive?s.jsx(F,{variant:"ghost",size:"sm",onClick:()=>{confirm("Ausweis deaktivieren?")&&c.mutate({id:f.id,data:{isActive:!1}})},title:"Deaktivieren",children:s.jsx(It,{className:"w-4 h-4"})}):s.jsx(F,{variant:"ghost",size:"sm",onClick:()=>{confirm("Ausweis wieder aktivieren?")&&c.mutate({id:f.id,data:{isActive:!0}})},title:"Aktivieren",children:s.jsx(Pe,{className:"w-4 h-4"})}),s.jsx(F,{variant:"ghost",size:"sm",onClick:()=>{confirm("Ausweis wirklich löschen?")&&d.mutate(f.id)},title:"Löschen",children:s.jsx(be,{className:"w-4 h-4 text-red-500"})})]})]}),s.jsxs("p",{className:"font-mono flex items-center gap-1",children:[f.documentNumber,s.jsx(ce,{value:f.documentNumber})]}),f.issuingAuthority&&s.jsxs("p",{className:"text-sm text-gray-500 flex items-center gap-1",children:["Ausgestellt von: ",f.issuingAuthority,s.jsx(ce,{value:f.issuingAuthority})]}),f.expiryDate&&s.jsxs("p",{className:"text-sm text-gray-500",children:["Gültig bis: ",new Date(f.expiryDate).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"})]}),f.type==="DRIVERS_LICENSE"&&f.licenseClasses&&s.jsxs("p",{className:"text-sm text-gray-500 flex items-center gap-1",children:["Klassen: ",f.licenseClasses,s.jsx(ce,{value:f.licenseClasses})]}),f.type==="DRIVERS_LICENSE"&&f.licenseIssueDate&&s.jsxs("p",{className:"text-sm text-gray-500",children:["Klasse B seit: ",new Date(f.licenseIssueDate).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"})]}),s.jsx("div",{className:"mt-3 pt-3 border-t",children:f.documentPath?s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsxs("a",{href:`/api${f.documentPath}`,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:underline text-sm flex items-center gap-1",children:[s.jsx(Pe,{className:"w-4 h-4"}),"Anzeigen"]}),s.jsxs("a",{href:`/api${f.documentPath}`,download:!0,className:"text-blue-600 hover:underline text-sm flex items-center gap-1",children:[s.jsx(As,{className:"w-4 h-4"}),"Download"]}),n&&s.jsxs(s.Fragment,{children:[s.jsx(Et,{onUpload:x=>u(f.id,x),existingFile:f.documentPath,accept:".pdf",label:"Ersetzen",disabled:!f.isActive}),s.jsxs("button",{onClick:()=>h(f.id),className:"text-red-600 hover:underline text-sm flex items-center gap-1",title:"Dokument löschen",children:[s.jsx(be,{className:"w-4 h-4"}),"Löschen"]})]})]}):n&&f.isActive&&s.jsx(Et,{onUpload:x=>u(f.id,x),accept:".pdf",label:"PDF hochladen"})})]},f.id))}):s.jsx("p",{className:"text-gray-500",children:"Keine Ausweise vorhanden."})]})}function pk({customerId:e,meters:t,canEdit:n,showInactive:r,onToggleInactive:a,onAdd:i,onEdit:l}){const[o,c]=j.useState(null),[d,u]=j.useState(null),[h,p]=j.useState(null),m=xe(),f=W({mutationFn:({id:v,data:N})=>ln.update(v,N),onSuccess:()=>m.invalidateQueries({queryKey:["customer",e.toString()]})}),x=W({mutationFn:ln.delete,onSuccess:()=>m.invalidateQueries({queryKey:["customer",e.toString()]})}),b=W({mutationFn:({meterId:v,readingId:N})=>ln.deleteReading(v,N),onSuccess:()=>m.invalidateQueries({queryKey:["customer",e.toString()]})}),y=r?t:t.filter(v=>v.isActive),g=v=>v?[...v].sort((N,D)=>new Date(D.readingDate).getTime()-new Date(N.readingDate).getTime()):[];return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-4 mb-4",children:[n&&s.jsxs(F,{size:"sm",onClick:i,children:[s.jsx(Be,{className:"w-4 h-4 mr-2"}),"Zähler hinzufügen"]}),s.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[s.jsx("input",{type:"checkbox",checked:r,onChange:a,className:"rounded"}),"Inaktive anzeigen"]})]}),y.length>0?s.jsx("div",{className:"space-y-4",children:y.map(v=>{const N=g(v.readings),D=d===v.id;return s.jsxs("div",{className:`border rounded-lg p-4 ${v.isActive?"":"opacity-50 bg-gray-50"}`,children:[s.jsxs("div",{className:"flex items-start justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[s.jsx(Ev,{className:"w-4 h-4 text-gray-400"}),s.jsx(ye,{variant:v.type==="ELECTRICITY"?"warning":"info",children:v.type==="ELECTRICITY"?"Strom":"Gas"}),!v.isActive&&s.jsx(ye,{variant:"danger",children:"Inaktiv"})]}),n&&s.jsxs("div",{className:"flex gap-1",children:[v.isActive&&s.jsx(F,{variant:"ghost",size:"sm",onClick:()=>c({meterId:v.id,meterType:v.type}),title:"Zählerstand hinzufügen",children:s.jsx(Be,{className:"w-4 h-4"})}),s.jsx(F,{variant:"ghost",size:"sm",onClick:()=>l(v),title:"Bearbeiten",children:s.jsx(Ye,{className:"w-4 h-4"})}),v.isActive?s.jsx(F,{variant:"ghost",size:"sm",onClick:()=>{confirm("Zähler deaktivieren?")&&f.mutate({id:v.id,data:{isActive:!1}})},title:"Deaktivieren",children:s.jsx(It,{className:"w-4 h-4"})}):s.jsx(F,{variant:"ghost",size:"sm",onClick:()=>{confirm("Zähler wieder aktivieren?")&&f.mutate({id:v.id,data:{isActive:!0}})},title:"Aktivieren",children:s.jsx(Pe,{className:"w-4 h-4"})}),s.jsx(F,{variant:"ghost",size:"sm",onClick:()=>{confirm("Zähler wirklich löschen? Alle Zählerstände werden ebenfalls gelöscht.")&&x.mutate(v.id)},title:"Löschen",children:s.jsx(be,{className:"w-4 h-4 text-red-500"})})]})]}),s.jsxs("p",{className:"font-mono text-lg flex items-center gap-1",children:[v.meterNumber,s.jsx(ce,{value:v.meterNumber})]}),v.location&&s.jsxs("p",{className:"text-sm text-gray-500 flex items-center gap-1",children:["Standort: ",v.location,s.jsx(ce,{value:v.location})]}),N.length>0&&s.jsxs("div",{className:"mt-3 pt-3 border-t",children:[s.jsxs("div",{className:"flex items-center justify-between mb-2",children:[s.jsx("p",{className:"text-sm font-medium",children:"Zählerstände:"}),N.length>3&&s.jsx(F,{variant:"ghost",size:"sm",onClick:()=>u(D?null:v.id),children:D?"Weniger anzeigen":`Alle ${N.length} anzeigen`})]}),s.jsx("div",{className:"space-y-1",children:(D?N:N.slice(0,3)).map(A=>s.jsxs("div",{className:"flex justify-between items-center text-sm group",children:[s.jsxs("span",{className:"text-gray-500 flex items-center gap-1",children:[new Date(A.readingDate).toLocaleDateString("de-DE"),s.jsx(ce,{value:new Date(A.readingDate).toLocaleDateString("de-DE")})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("span",{className:"font-mono flex items-center gap-1",children:[A.value.toLocaleString("de-DE")," ",A.unit,s.jsx(ce,{value:A.value.toString(),title:"Nur Wert kopieren"}),s.jsx(ce,{value:`${A.value.toLocaleString("de-DE")} ${A.unit}`,title:"Mit Einheit kopieren"})]}),n&&s.jsxs("div",{className:"opacity-0 group-hover:opacity-100 flex gap-1",children:[s.jsx("button",{onClick:()=>p({meterId:v.id,meterType:v.type,reading:A}),className:"text-gray-400 hover:text-blue-600",title:"Bearbeiten",children:s.jsx(Ye,{className:"w-3 h-3"})}),s.jsx("button",{onClick:()=>{confirm("Zählerstand wirklich löschen?")&&b.mutate({meterId:v.id,readingId:A.id})},className:"text-gray-400 hover:text-red-600",title:"Löschen",children:s.jsx(be,{className:"w-3 h-3"})})]})]})]},A.id))})]})]},v.id)})}):s.jsx("p",{className:"text-gray-500",children:"Keine Zähler vorhanden."}),o&&s.jsx(jx,{isOpen:!0,onClose:()=>c(null),meterId:o.meterId,meterType:o.meterType,customerId:e}),h&&s.jsx(jx,{isOpen:!0,onClose:()=>p(null),meterId:h.meterId,meterType:h.meterType,customerId:e,reading:h.reading})]})}function xk({customerId:e}){const{hasPermission:t}=He(),n=ts(),r=xe(),[a,i]=j.useState(new Set),[l,o]=j.useState(!1),{data:c,isLoading:d}=me({queryKey:["contract-tree",e],queryFn:()=>Le.getTreeForCustomer(e)}),u=(c==null?void 0:c.data)||[],h=W({mutationFn:Le.delete,onSuccess:()=>{r.invalidateQueries({queryKey:["customer",e.toString()]}),r.invalidateQueries({queryKey:["customers"]}),r.invalidateQueries({queryKey:["contracts"]}),r.invalidateQueries({queryKey:["contract-tree",e]})},onError:g=>{alert((g==null?void 0:g.message)||"Fehler beim Löschen des Vertrags")}}),p={ELECTRICITY:"Strom",GAS:"Gas",DSL:"DSL",FIBER:"Glasfaser",MOBILE:"Mobilfunk",TV:"TV",CAR_INSURANCE:"KFZ-Versicherung"},m={ACTIVE:"success",PENDING:"warning",CANCELLED:"danger",EXPIRED:"danger",DRAFT:"default",DEACTIVATED:"default"},f=[{status:"DRAFT",label:"Entwurf",description:"Vertrag wird noch vorbereitet",color:"text-gray-600"},{status:"PENDING",label:"Ausstehend",description:"Wartet auf Aktivierung",color:"text-yellow-600"},{status:"ACTIVE",label:"Aktiv",description:"Vertrag läuft normal",color:"text-green-600"},{status:"EXPIRED",label:"Abgelaufen",description:"Laufzeit vorbei, läuft aber ohne Kündigung weiter",color:"text-orange-600"},{status:"CANCELLED",label:"Gekündigt",description:"Aktive Kündigung eingereicht, Vertrag endet",color:"text-red-600"},{status:"DEACTIVATED",label:"Deaktiviert",description:"Manuell beendet/archiviert",color:"text-gray-500"}],x=g=>{i(v=>{const N=new Set(v);return N.has(g)?N.delete(g):N.add(g),N})},b=(g,v)=>g.map(N=>s.jsx("div",{children:y(N,v)},N.contract.id)),y=(g,v=0)=>{var S,E,z,I,B,P,M;const{contract:N,predecessors:D,hasHistory:A}=g,R=a.has(N.id),w=v>0;return s.jsxs("div",{children:[s.jsxs("div",{className:` border rounded-lg p-4 transition-colors ${w?"ml-6 border-l-4 border-l-gray-300 bg-gray-50":"hover:bg-gray-50"} `,children:[s.jsxs("div",{className:"flex items-center justify-between mb-2",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[!w&&A?s.jsx("button",{onClick:()=>x(N.id),className:"p-1 hover:bg-gray-200 rounded transition-colors",title:R?"Einklappen":"Vorgänger anzeigen",children:R?s.jsx(In,{className:"w-4 h-4 text-gray-500"}):s.jsx(Ft,{className:"w-4 h-4 text-gray-500"})}):w?null:s.jsx("div",{className:"w-6"}),s.jsxs("span",{className:"font-mono flex items-center gap-1",children:[N.contractNumber,s.jsx(ce,{value:N.contractNumber})]}),s.jsx(ye,{children:p[N.type]||N.type}),s.jsx(ye,{variant:m[N.status]||"default",children:N.status}),v===0&&!w&&s.jsx("button",{onClick:k=>{k.stopPropagation(),o(!0)},className:"text-gray-400 hover:text-blue-600 transition-colors",title:"Status-Erklärung",children:s.jsx(Pl,{className:"w-4 h-4"})}),w&&s.jsx("span",{className:"text-xs text-gray-500 ml-2",children:"(Vorgänger)"})]}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx(F,{variant:"ghost",size:"sm",onClick:()=>n(`/contracts/${N.id}`,{state:{from:"customer",customerId:e.toString()}}),title:"Ansehen",children:s.jsx(Pe,{className:"w-4 h-4"})}),t("contracts:update")&&s.jsx(F,{variant:"ghost",size:"sm",onClick:()=>n(`/contracts/${N.id}/edit`),title:"Bearbeiten",children:s.jsx(Ye,{className:"w-4 h-4"})}),t("contracts:delete")&&s.jsx(F,{variant:"ghost",size:"sm",onClick:()=>{confirm("Vertrag wirklich löschen?")&&h.mutate(N.id)},title:"Löschen",children:s.jsx(be,{className:"w-4 h-4 text-red-500"})})]})]}),(N.providerName||((S=N.provider)==null?void 0:S.name))&&s.jsxs("p",{className:`flex items-center gap-1 ${w?"ml-6":""}`,children:[N.providerName||((E=N.provider)==null?void 0:E.name),(N.tariffName||((z=N.tariff)==null?void 0:z.name))&&` - ${N.tariffName||((I=N.tariff)==null?void 0:I.name)}`,s.jsx(ce,{value:(N.providerName||((B=N.provider)==null?void 0:B.name)||"")+(N.tariffName||(P=N.tariff)!=null&&P.name?` - ${N.tariffName||((M=N.tariff)==null?void 0:M.name)}`:"")})]}),N.startDate&&s.jsxs("p",{className:`text-sm text-gray-500 ${w?"ml-6":""}`,children:["Beginn: ",new Date(N.startDate).toLocaleDateString("de-DE"),N.endDate&&` | Ende: ${new Date(N.endDate).toLocaleDateString("de-DE")}`]})]}),(v===0&&R||v>0)&&D.length>0&&s.jsx("div",{className:"mt-2",children:b(D,v+1)})]},N.id)};return d?s.jsx("div",{className:"flex items-center justify-center py-8",children:s.jsx("div",{className:"animate-spin rounded-full h-6 w-6 border-b-2 border-blue-600"})}):s.jsxs("div",{children:[t("contracts:create")&&s.jsx("div",{className:"mb-4",children:s.jsx(ke,{to:`/contracts/new?customerId=${e}`,children:s.jsxs(F,{size:"sm",children:[s.jsx(Be,{className:"w-4 h-4 mr-2"}),"Vertrag anlegen"]})})}),u.length>0?s.jsx("div",{className:"space-y-4",children:u.map(g=>y(g,0))}):s.jsx("p",{className:"text-gray-500",children:"Keine Verträge vorhanden."}),l&&s.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[s.jsx("div",{className:"fixed inset-0 bg-black/20",onClick:()=>o(!1)}),s.jsxs("div",{className:"relative bg-white rounded-lg shadow-xl p-4 max-w-sm w-full mx-4",children:[s.jsxs("div",{className:"flex items-center justify-between mb-3",children:[s.jsx("h3",{className:"text-sm font-semibold text-gray-900",children:"Vertragsstatus-Übersicht"}),s.jsx("button",{onClick:()=>o(!1),className:"text-gray-400 hover:text-gray-600",children:s.jsx(Vt,{className:"w-4 h-4"})})]}),s.jsx("div",{className:"space-y-2",children:f.map(({status:g,label:v,description:N,color:D})=>s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx("span",{className:`font-medium text-sm min-w-[90px] ${D}`,children:v}),s.jsx("span",{className:"text-sm text-gray-600",children:N})]},g))})]})]})]})}function gk({customerId:e}){const[t,n]=j.useState(!1),[r,a]=j.useState(null),[i,l]=j.useState(!1),o=async()=>{var c;if(t){n(!1);return}l(!0);try{const d=await Dt.getPortalPassword(e);a(((c=d.data)==null?void 0:c.password)||null),n(!0)}catch(d){console.error("Fehler beim Laden des Passworts:",d),alert("Fehler beim Laden des Passworts")}finally{l(!1)}};return s.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[s.jsx("p",{className:"text-xs text-green-600",children:"Passwort ist gesetzt"}),s.jsx("button",{type:"button",onClick:o,className:"text-xs text-blue-600 hover:underline flex items-center gap-1",disabled:i,children:i?"Laden...":t?s.jsxs(s.Fragment,{children:[s.jsx(It,{className:"w-3 h-3"}),"Verbergen"]}):s.jsxs(s.Fragment,{children:[s.jsx(Pe,{className:"w-3 h-3"}),"Anzeigen"]})}),t&&r&&s.jsxs("span",{className:"text-xs font-mono bg-gray-100 px-2 py-1 rounded flex items-center gap-1",children:[r,s.jsx(ce,{value:r})]}),t&&!r&&s.jsx("span",{className:"text-xs text-gray-500",children:"(Passwort nicht verfügbar)"})]})}function yk({customerId:e,canEdit:t}){const n=xe(),[r,a]=j.useState(!1),[i,l]=j.useState(""),[o,c]=j.useState(""),[d,u]=j.useState([]),[h,p]=j.useState(!1),{data:m,isLoading:f}=me({queryKey:["customer-portal",e],queryFn:()=>Dt.getPortalSettings(e)}),{data:x,isLoading:b}=me({queryKey:["customer-representatives",e],queryFn:()=>Dt.getRepresentatives(e)}),y=W({mutationFn:w=>Dt.updatePortalSettings(e,w),onSuccess:()=>{n.invalidateQueries({queryKey:["customer-portal",e]})}}),g=W({mutationFn:w=>Dt.setPortalPassword(e,w),onSuccess:()=>{l(""),n.invalidateQueries({queryKey:["customer-portal",e]}),alert("Passwort wurde gesetzt")},onError:w=>{alert(w.message)}}),v=W({mutationFn:w=>Dt.addRepresentative(e,w),onSuccess:()=>{n.invalidateQueries({queryKey:["customer-representatives",e]}),c(""),u([])},onError:w=>{alert(w.message)}}),N=W({mutationFn:w=>Dt.removeRepresentative(e,w),onSuccess:()=>{n.invalidateQueries({queryKey:["customer-representatives",e]})}}),D=async()=>{if(!(o.length<2)){p(!0);try{const w=await Dt.searchForRepresentative(e,o);u(w.data||[])}catch(w){console.error("Suche fehlgeschlagen:",w)}finally{p(!1)}}};if(f||b)return s.jsx("div",{className:"text-center py-4 text-gray-500",children:"Laden..."});const A=m==null?void 0:m.data,R=(x==null?void 0:x.data)||[];return s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{className:"border rounded-lg p-4",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[s.jsx(dh,{className:"w-5 h-5 text-gray-400"}),s.jsx("h3",{className:"font-medium",children:"Portal-Zugang"})]}),s.jsxs("div",{className:"space-y-4",children:[s.jsxs("label",{className:"flex items-center gap-3",children:[s.jsx("input",{type:"checkbox",checked:(A==null?void 0:A.portalEnabled)||!1,onChange:w=>y.mutate({portalEnabled:w.target.checked}),className:"rounded w-5 h-5",disabled:!t}),s.jsx("span",{children:"Portal aktiviert"}),(A==null?void 0:A.portalEnabled)&&s.jsx(ye,{variant:"success",children:"Aktiv"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Portal E-Mail"}),s.jsx("div",{className:"flex gap-2",children:s.jsx(V,{value:(A==null?void 0:A.portalEmail)||"",onChange:w=>y.mutate({portalEmail:w.target.value||null}),placeholder:"portal@example.com",disabled:!t||!(A!=null&&A.portalEnabled),className:"flex-1"})}),s.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Diese E-Mail wird für den Login ins Kundenportal verwendet."})]}),(A==null?void 0:A.portalEnabled)&&s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:A!=null&&A.hasPassword?"Neues Passwort setzen":"Passwort setzen"}),s.jsxs("div",{className:"flex gap-2",children:[s.jsxs("div",{className:"relative flex-1",children:[s.jsx(V,{type:r?"text":"password",value:i,onChange:w=>l(w.target.value),placeholder:"Mindestens 6 Zeichen",disabled:!t}),s.jsx("button",{type:"button",onClick:()=>a(!r),className:"absolute right-3 top-1/2 -translate-y-1/2 text-gray-400",children:r?s.jsx(It,{className:"w-4 h-4"}):s.jsx(Pe,{className:"w-4 h-4"})})]}),s.jsx(F,{onClick:()=>g.mutate(i),disabled:!t||i.length<6||g.isPending,children:g.isPending?"Speichern...":"Setzen"})]}),(A==null?void 0:A.hasPassword)&&s.jsx(gk,{customerId:e})]}),(A==null?void 0:A.portalLastLogin)&&s.jsxs("p",{className:"text-sm text-gray-500",children:["Letzte Anmeldung: ",new Date(A.portalLastLogin).toLocaleString("de-DE")]})]})]}),s.jsxs("div",{className:"border rounded-lg p-4",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[s.jsx(Q2,{className:"w-5 h-5 text-gray-400"}),s.jsx("h3",{className:"font-medium",children:"Vertreter (können Verträge einsehen)"})]}),s.jsx("p",{className:"text-sm text-gray-500 mb-4",children:"Hier können Sie anderen Kunden erlauben, die Verträge dieses Kunden einzusehen. Beispiel: Der Sohn kann die Verträge seiner Mutter einsehen."}),t&&s.jsxs("div",{className:"mb-4",children:[s.jsxs("div",{className:"flex gap-2",children:[s.jsx(V,{value:o,onChange:w=>c(w.target.value),placeholder:"Kunden suchen (Name, Kundennummer)...",onKeyDown:w=>w.key==="Enter"&&D(),className:"flex-1"}),s.jsx(F,{variant:"secondary",onClick:D,disabled:o.length<2||h,children:s.jsx(Al,{className:"w-4 h-4"})})]}),s.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Nur Kunden mit aktiviertem Portal können als Vertreter hinzugefügt werden."}),d.length>0&&s.jsx("div",{className:"mt-2 border rounded-lg divide-y",children:d.map(w=>s.jsxs("div",{className:"flex items-center justify-between p-3 hover:bg-gray-50",children:[s.jsxs("div",{children:[s.jsx("p",{className:"font-medium",children:w.companyName||`${w.firstName} ${w.lastName}`}),s.jsx("p",{className:"text-sm text-gray-500",children:w.customerNumber})]}),s.jsxs(F,{size:"sm",onClick:()=>v.mutate(w.id),disabled:v.isPending,children:[s.jsx(Be,{className:"w-4 h-4 mr-1"}),"Hinzufügen"]})]},w.id))})]}),R.length>0?s.jsx("div",{className:"space-y-2",children:R.map(w=>{var S,E,z,I;return s.jsxs("div",{className:"flex items-center justify-between p-3 bg-gray-50 rounded-lg",children:[s.jsxs("div",{children:[s.jsx("p",{className:"font-medium",children:((S=w.representative)==null?void 0:S.companyName)||`${(E=w.representative)==null?void 0:E.firstName} ${(z=w.representative)==null?void 0:z.lastName}`}),s.jsx("p",{className:"text-sm text-gray-500",children:(I=w.representative)==null?void 0:I.customerNumber})]}),t&&s.jsx(F,{variant:"ghost",size:"sm",onClick:()=>{confirm("Vertreter wirklich entfernen?")&&N.mutate(w.representativeId)},children:s.jsx(Vt,{className:"w-4 h-4 text-red-500"})})]},w.id)})}):s.jsx("p",{className:"text-gray-500 text-sm",children:"Keine Vertreter konfiguriert."})]})]})}function xx({isOpen:e,onClose:t,customerId:n,address:r}){const a=xe(),i=!!r,l=()=>({type:(r==null?void 0:r.type)||"DELIVERY_RESIDENCE",street:(r==null?void 0:r.street)||"",houseNumber:(r==null?void 0:r.houseNumber)||"",postalCode:(r==null?void 0:r.postalCode)||"",city:(r==null?void 0:r.city)||"",country:(r==null?void 0:r.country)||"Deutschland",isDefault:(r==null?void 0:r.isDefault)||!1}),[o,c]=j.useState(l),d=W({mutationFn:m=>qu.create(n,m),onSuccess:()=>{a.invalidateQueries({queryKey:["customer",n.toString()]}),t(),c({type:"DELIVERY_RESIDENCE",street:"",houseNumber:"",postalCode:"",city:"",country:"Deutschland",isDefault:!1})}}),u=W({mutationFn:m=>qu.update(r.id,m),onSuccess:()=>{a.invalidateQueries({queryKey:["customer",n.toString()]}),t()}}),h=m=>{m.preventDefault(),i?u.mutate(o):d.mutate(o)},p=d.isPending||u.isPending;return i&&o.street!==r.street&&c(l()),s.jsx(Ve,{isOpen:e,onClose:t,title:i?"Adresse bearbeiten":"Adresse hinzufügen",children:s.jsxs("form",{onSubmit:h,className:"space-y-4",children:[s.jsx(Re,{label:"Adresstyp",value:o.type,onChange:m=>c({...o,type:m.target.value}),options:[{value:"DELIVERY_RESIDENCE",label:"Liefer-/Meldeadresse"},{value:"BILLING",label:"Rechnungsadresse"}]}),s.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[s.jsx("div",{className:"col-span-2",children:s.jsx(V,{label:"Straße",value:o.street,onChange:m=>c({...o,street:m.target.value}),required:!0})}),s.jsx(V,{label:"Hausnr.",value:o.houseNumber,onChange:m=>c({...o,houseNumber:m.target.value}),required:!0})]}),s.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[s.jsx(V,{label:"PLZ",value:o.postalCode,onChange:m=>c({...o,postalCode:m.target.value}),required:!0}),s.jsx("div",{className:"col-span-2",children:s.jsx(V,{label:"Ort",value:o.city,onChange:m=>c({...o,city:m.target.value}),required:!0})})]}),s.jsx(V,{label:"Land",value:o.country,onChange:m=>c({...o,country:m.target.value})}),s.jsxs("label",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"checkbox",checked:o.isDefault,onChange:m=>c({...o,isDefault:m.target.checked}),className:"rounded"}),"Als Standard setzen"]}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx(F,{type:"button",variant:"secondary",onClick:t,children:"Abbrechen"}),s.jsx(F,{type:"submit",disabled:p,children:p?"Speichern...":"Speichern"})]})]})})}function gx({isOpen:e,onClose:t,customerId:n,bankCard:r}){const a=xe(),i=!!r,l=()=>({accountHolder:(r==null?void 0:r.accountHolder)||"",iban:(r==null?void 0:r.iban)||"",bic:(r==null?void 0:r.bic)||"",bankName:(r==null?void 0:r.bankName)||"",expiryDate:r!=null&&r.expiryDate?new Date(r.expiryDate).toISOString().split("T")[0]:"",isActive:(r==null?void 0:r.isActive)??!0}),[o,c]=j.useState(l);j.useState(()=>{c(l())});const d=W({mutationFn:m=>Yo.create(n,m),onSuccess:()=>{a.invalidateQueries({queryKey:["customer",n.toString()]}),t(),c({accountHolder:"",iban:"",bic:"",bankName:"",expiryDate:"",isActive:!0})}}),u=W({mutationFn:m=>Yo.update(r.id,m),onSuccess:()=>{a.invalidateQueries({queryKey:["customer",n.toString()]}),t()}}),h=m=>{m.preventDefault();const f={...o,expiryDate:o.expiryDate?new Date(o.expiryDate):void 0};i?u.mutate(f):d.mutate(f)},p=d.isPending||u.isPending;return i&&o.iban!==r.iban&&c(l()),s.jsx(Ve,{isOpen:e,onClose:t,title:i?"Bankkarte bearbeiten":"Bankkarte hinzufügen",children:s.jsxs("form",{onSubmit:h,className:"space-y-4",children:[s.jsx(V,{label:"Kontoinhaber",value:o.accountHolder,onChange:m=>c({...o,accountHolder:m.target.value}),required:!0}),s.jsx(V,{label:"IBAN",value:o.iban,onChange:m=>c({...o,iban:m.target.value}),required:!0}),s.jsx(V,{label:"BIC",value:o.bic,onChange:m=>c({...o,bic:m.target.value})}),s.jsx(V,{label:"Bank",value:o.bankName,onChange:m=>c({...o,bankName:m.target.value})}),s.jsx(V,{label:"Ablaufdatum",type:"date",value:o.expiryDate,onChange:m=>c({...o,expiryDate:m.target.value}),onClear:()=>c({...o,expiryDate:""})}),i&&s.jsxs("label",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"checkbox",checked:o.isActive,onChange:m=>c({...o,isActive:m.target.checked}),className:"rounded"}),"Aktiv"]}),!i&&s.jsx("p",{className:"text-sm text-gray-500 bg-gray-50 p-3 rounded",children:"Dokument-Upload ist nach dem Speichern in der Übersicht möglich."}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx(F,{type:"button",variant:"secondary",onClick:t,children:"Abbrechen"}),s.jsx(F,{type:"submit",disabled:p,children:p?"Speichern...":"Speichern"})]})]})})}function yx({isOpen:e,onClose:t,customerId:n,document:r}){const a=xe(),i=!!r,l=()=>({type:(r==null?void 0:r.type)||"ID_CARD",documentNumber:(r==null?void 0:r.documentNumber)||"",issuingAuthority:(r==null?void 0:r.issuingAuthority)||"",issueDate:r!=null&&r.issueDate?new Date(r.issueDate).toISOString().split("T")[0]:"",expiryDate:r!=null&&r.expiryDate?new Date(r.expiryDate).toISOString().split("T")[0]:"",isActive:(r==null?void 0:r.isActive)??!0,licenseClasses:(r==null?void 0:r.licenseClasses)||"",licenseIssueDate:r!=null&&r.licenseIssueDate?new Date(r.licenseIssueDate).toISOString().split("T")[0]:""}),[o,c]=j.useState(l),d=W({mutationFn:m=>ec.create(n,m),onSuccess:()=>{a.invalidateQueries({queryKey:["customer",n.toString()]}),t(),c({type:"ID_CARD",documentNumber:"",issuingAuthority:"",issueDate:"",expiryDate:"",isActive:!0,licenseClasses:"",licenseIssueDate:""})}}),u=W({mutationFn:m=>ec.update(r.id,m),onSuccess:()=>{a.invalidateQueries({queryKey:["customer",n.toString()]}),t()}}),h=m=>{m.preventDefault();const f={...o,issueDate:o.issueDate?new Date(o.issueDate):void 0,expiryDate:o.expiryDate?new Date(o.expiryDate):void 0};o.type==="DRIVERS_LICENSE"?(f.licenseClasses=o.licenseClasses||void 0,f.licenseIssueDate=o.licenseIssueDate?new Date(o.licenseIssueDate):void 0):(delete f.licenseClasses,delete f.licenseIssueDate),i?u.mutate(f):d.mutate(f)},p=d.isPending||u.isPending;return i&&o.documentNumber!==r.documentNumber&&c(l()),s.jsx(Ve,{isOpen:e,onClose:t,title:i?"Ausweis bearbeiten":"Ausweis hinzufügen",children:s.jsxs("form",{onSubmit:h,className:"space-y-4",children:[s.jsx(Re,{label:"Ausweistyp",value:o.type,onChange:m=>c({...o,type:m.target.value}),options:[{value:"ID_CARD",label:"Personalausweis"},{value:"PASSPORT",label:"Reisepass"},{value:"DRIVERS_LICENSE",label:"Führerschein"},{value:"OTHER",label:"Sonstiges"}]}),s.jsx(V,{label:"Ausweisnummer",value:o.documentNumber,onChange:m=>c({...o,documentNumber:m.target.value}),required:!0}),s.jsx(V,{label:"Ausstellende Behörde",value:o.issuingAuthority,onChange:m=>c({...o,issuingAuthority:m.target.value})}),s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[s.jsx(V,{label:"Ausstellungsdatum",type:"date",value:o.issueDate,onChange:m=>c({...o,issueDate:m.target.value}),onClear:()=>c({...o,issueDate:""})}),s.jsx(V,{label:"Ablaufdatum",type:"date",value:o.expiryDate,onChange:m=>c({...o,expiryDate:m.target.value}),onClear:()=>c({...o,expiryDate:""})})]}),o.type==="DRIVERS_LICENSE"&&s.jsxs(s.Fragment,{children:[s.jsx(V,{label:"Führerscheinklassen",value:o.licenseClasses,onChange:m=>c({...o,licenseClasses:m.target.value}),placeholder:"z.B. B, BE, AM, L"}),s.jsx(V,{label:"Erwerb Klasse B (Pkw)",type:"date",value:o.licenseIssueDate,onChange:m=>c({...o,licenseIssueDate:m.target.value}),onClear:()=>c({...o,licenseIssueDate:""})})]}),i&&s.jsxs("label",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"checkbox",checked:o.isActive,onChange:m=>c({...o,isActive:m.target.checked}),className:"rounded"}),"Aktiv"]}),!i&&s.jsx("p",{className:"text-sm text-gray-500 bg-gray-50 p-3 rounded",children:"Dokument-Upload ist nach dem Speichern in der Übersicht möglich."}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx(F,{type:"button",variant:"secondary",onClick:t,children:"Abbrechen"}),s.jsx(F,{type:"submit",disabled:p,children:p?"Speichern...":"Speichern"})]})]})})}function vx({isOpen:e,onClose:t,customerId:n,meter:r}){const a=xe(),i=!!r,l=()=>({meterNumber:(r==null?void 0:r.meterNumber)||"",type:(r==null?void 0:r.type)||"ELECTRICITY",location:(r==null?void 0:r.location)||"",isActive:(r==null?void 0:r.isActive)??!0}),[o,c]=j.useState(l),d=W({mutationFn:m=>ln.create(n,m),onSuccess:()=>{a.invalidateQueries({queryKey:["customer",n.toString()]}),t(),c({meterNumber:"",type:"ELECTRICITY",location:"",isActive:!0})}}),u=W({mutationFn:m=>ln.update(r.id,m),onSuccess:()=>{a.invalidateQueries({queryKey:["customer",n.toString()]}),t()}}),h=m=>{m.preventDefault(),i?u.mutate(o):d.mutate(o)},p=d.isPending||u.isPending;return i&&o.meterNumber!==r.meterNumber&&c(l()),s.jsx(Ve,{isOpen:e,onClose:t,title:i?"Zähler bearbeiten":"Zähler hinzufügen",children:s.jsxs("form",{onSubmit:h,className:"space-y-4",children:[s.jsx(V,{label:"Zählernummer",value:o.meterNumber,onChange:m=>c({...o,meterNumber:m.target.value}),required:!0}),s.jsx(Re,{label:"Zählertyp",value:o.type,onChange:m=>c({...o,type:m.target.value}),options:[{value:"ELECTRICITY",label:"Strom"},{value:"GAS",label:"Gas"}]}),s.jsx(V,{label:"Standort",value:o.location,onChange:m=>c({...o,location:m.target.value}),placeholder:"z.B. Keller, Wohnung"}),i&&s.jsxs("label",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"checkbox",checked:o.isActive,onChange:m=>c({...o,isActive:m.target.checked}),className:"rounded"}),"Aktiv"]}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx(F,{type:"button",variant:"secondary",onClick:t,children:"Abbrechen"}),s.jsx(F,{type:"submit",disabled:p,children:p?"Speichern...":"Speichern"})]})]})})}function jx({isOpen:e,onClose:t,meterId:n,meterType:r,customerId:a,reading:i}){const l=xe(),o=!!i,c=r==="ELECTRICITY"?"kWh":"m³",d=()=>{var b;return{readingDate:i!=null&&i.readingDate?new Date(i.readingDate).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],value:((b=i==null?void 0:i.value)==null?void 0:b.toString())||"",notes:(i==null?void 0:i.notes)||""}},[u,h]=j.useState(d),p=W({mutationFn:b=>ln.addReading(n,b),onSuccess:()=>{l.invalidateQueries({queryKey:["customer",a.toString()]}),t()}}),m=W({mutationFn:b=>ln.updateReading(n,i.id,b),onSuccess:()=>{l.invalidateQueries({queryKey:["customer",a.toString()]}),t()}}),f=b=>{b.preventDefault();const y={readingDate:new Date(u.readingDate),value:parseFloat(u.value),unit:c,notes:u.notes||void 0};o?m.mutate(y):p.mutate(y)},x=p.isPending||m.isPending;return o&&u.value!==i.value.toString()&&h(d()),s.jsx(Ve,{isOpen:e,onClose:t,title:o?"Zählerstand bearbeiten":"Zählerstand erfassen",children:s.jsxs("form",{onSubmit:f,className:"space-y-4",children:[s.jsx(V,{label:"Ablesedatum",type:"date",value:u.readingDate,onChange:b=>h({...u,readingDate:b.target.value}),required:!0}),s.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[s.jsx("div",{className:"col-span-2",children:s.jsx(V,{label:"Zählerstand",type:"number",step:"0.01",value:u.value,onChange:b=>h({...u,value:b.target.value}),required:!0})}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Einheit"}),s.jsx("div",{className:"h-10 flex items-center px-3 bg-gray-100 border border-gray-300 rounded-md text-gray-700",children:c})]})]}),s.jsx(V,{label:"Notizen",value:u.notes,onChange:b=>h({...u,notes:b.target.value}),placeholder:"Optionale Notizen..."}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx(F,{type:"button",variant:"secondary",onClick:t,children:"Abbrechen"}),s.jsx(F,{type:"submit",disabled:x,children:x?"Speichern...":"Speichern"})]})]})})}const pd="@stressfrei-wechseln.de";function vk({customerId:e,emails:t,canEdit:n,showInactive:r,onToggleInactive:a,onAdd:i,onEdit:l}){const o=xe(),c=W({mutationFn:({id:h,data:p})=>xs.update(h,p),onSuccess:()=>o.invalidateQueries({queryKey:["customer",e.toString()]})}),d=W({mutationFn:xs.delete,onSuccess:()=>o.invalidateQueries({queryKey:["customer",e.toString()]})}),u=r?t:t.filter(h=>h.isActive);return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-4 mb-4",children:[n&&s.jsxs(F,{size:"sm",onClick:i,children:[s.jsx(Be,{className:"w-4 h-4 mr-2"}),"Adresse hinzufügen"]}),s.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[s.jsx("input",{type:"checkbox",checked:r,onChange:a,className:"rounded"}),"Inaktive anzeigen"]})]}),s.jsxs("p",{className:"text-sm text-gray-500 mb-4 bg-blue-50 border border-blue-200 rounded-lg p-3",children:[s.jsx("strong",{children:"Hinweis:"})," Hier werden E-Mail-Weiterleitungsadressen verwaltet, die für die Registrierung bei Anbietern verwendet werden. E-Mails an diese Adressen werden sowohl an den Kunden als auch an Sie weitergeleitet."]}),u.length>0?s.jsx("div",{className:"space-y-3",children:u.map(h=>s.jsx("div",{className:`border rounded-lg p-4 ${h.isActive?"":"opacity-50 bg-gray-50"}`,children:s.jsxs("div",{className:"flex items-start justify-between",children:[s.jsxs("div",{className:"flex-1",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(nn,{className:"w-4 h-4 text-gray-400"}),s.jsx("span",{className:"font-mono text-sm",children:h.email}),s.jsx(ce,{value:h.email}),!h.isActive&&s.jsx(ye,{variant:"danger",children:"Inaktiv"})]}),h.notes&&s.jsxs("div",{className:"flex items-center gap-2 mt-1 text-sm text-gray-500",children:[s.jsx(Ke,{className:"w-4 h-4 flex-shrink-0"}),s.jsx("span",{children:h.notes})]})]}),n&&s.jsxs("div",{className:"flex gap-1",children:[s.jsx(F,{variant:"ghost",size:"sm",onClick:()=>l(h),title:"Bearbeiten",children:s.jsx(Ye,{className:"w-4 h-4"})}),h.isActive?s.jsx(F,{variant:"ghost",size:"sm",onClick:()=>{confirm("Adresse deaktivieren?")&&c.mutate({id:h.id,data:{isActive:!1}})},title:"Deaktivieren",children:s.jsx(It,{className:"w-4 h-4"})}):s.jsx(F,{variant:"ghost",size:"sm",onClick:()=>{confirm("Adresse wieder aktivieren?")&&c.mutate({id:h.id,data:{isActive:!0}})},title:"Aktivieren",children:s.jsx(Pe,{className:"w-4 h-4"})}),s.jsx(F,{variant:"ghost",size:"sm",onClick:()=>{confirm("Adresse wirklich löschen?")&&d.mutate(h.id)},title:"Löschen",children:s.jsx(be,{className:"w-4 h-4 text-red-500"})})]})]})},h.id))}):s.jsx("p",{className:"text-gray-500",children:"Keine Stressfrei-Wechseln Adressen vorhanden."})]})}function jk({credentials:e,onHide:t,onResetPassword:n,isResettingPassword:r}){const[a,i]=j.useState(null),l=async(u,h)=>{try{await navigator.clipboard.writeText(u),i(h),setTimeout(()=>i(null),2e3)}catch{const p=document.createElement("textarea");p.value=u,document.body.appendChild(p),p.select(),document.execCommand("copy"),document.body.removeChild(p),i(h),setTimeout(()=>i(null),2e3)}},o=({text:u,fieldName:h})=>s.jsx("button",{type:"button",onClick:()=>l(u,h),className:"p-1.5 text-gray-400 hover:text-blue-600 hover:bg-blue-50 rounded transition-colors",title:"In Zwischenablage kopieren",children:a===h?s.jsx(fr,{className:"w-4 h-4 text-green-600"}):s.jsx(lh,{className:"w-4 h-4"})}),c=e.imap?`${e.imap.server}:${e.imap.port}`:"",d=e.smtp?`${e.smtp.server}:${e.smtp.port}`:"";return s.jsxs("div",{className:"bg-gray-50 border border-gray-200 rounded-lg p-4 space-y-3",children:[s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsx("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wide",children:"Zugangsdaten"}),s.jsx("button",{type:"button",onClick:t,className:"text-gray-400 hover:text-gray-600 p-1 hover:bg-gray-200 rounded",title:"Zugangsdaten ausblenden",children:s.jsx(It,{className:"w-4 h-4"})})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("div",{className:"bg-white rounded-lg p-3 border border-gray-100",children:[s.jsx("label",{className:"text-xs text-gray-500 block mb-1",children:"Benutzername"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("code",{className:"text-sm text-gray-900 font-mono flex-1 break-all",children:e.email}),s.jsx(o,{text:e.email,fieldName:"email"})]})]}),s.jsxs("div",{className:"bg-white rounded-lg p-3 border border-gray-100",children:[s.jsx("label",{className:"text-xs text-gray-500 block mb-1",children:"Passwort"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("code",{className:"text-sm text-gray-900 font-mono flex-1 break-all",children:e.password}),s.jsx(o,{text:e.password,fieldName:"password"})]}),s.jsx("button",{type:"button",onClick:n,disabled:r,className:"mt-2 text-xs text-blue-600 hover:text-blue-800 disabled:opacity-50",children:r?"Generiere...":"Neu generieren"})]})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.imap&&s.jsxs("div",{className:"bg-white rounded-lg p-3 border border-gray-100",children:[s.jsx("label",{className:"text-xs text-gray-500 block mb-1",children:"IMAP (Empfang)"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("code",{className:"text-sm text-gray-900 font-mono flex-1",children:c}),s.jsx(o,{text:c,fieldName:"imap"})]}),s.jsx("span",{className:"text-xs text-gray-400 mt-1 block",children:e.imap.encryption})]}),e.smtp&&s.jsxs("div",{className:"bg-white rounded-lg p-3 border border-gray-100",children:[s.jsx("label",{className:"text-xs text-gray-500 block mb-1",children:"SMTP (Versand)"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("code",{className:"text-sm text-gray-900 font-mono flex-1",children:d}),s.jsx(o,{text:d,fieldName:"smtp"})]}),s.jsx("span",{className:"text-xs text-gray-400 mt-1 block",children:e.smtp.encryption})]})]})]})}function bx({isOpen:e,onClose:t,customerId:n,email:r,customerEmail:a}){const[i,l]=j.useState(""),[o,c]=j.useState(""),[d,u]=j.useState(!1),[h,p]=j.useState(!1),[m,f]=j.useState(null),[x,b]=j.useState("idle"),[y,g]=j.useState(!1),[v,N]=j.useState(!1),[D,A]=j.useState(!1),[R,w]=j.useState(!1),[S,E]=j.useState(null),[z,I]=j.useState(!1),[B,P]=j.useState(!1),M=xe(),k=!!r,{data:_}=me({queryKey:["email-provider-configs"],queryFn:()=>pn.getConfigs(),enabled:e}),K=((_==null?void 0:_.data)||[]).some(J=>J.isActive&&J.isDefault),Z=J=>{if(!J)return"";const qe=J.indexOf("@");return qe>0?J.substring(0,qe):J},H=async J=>{var qe;if(!(!K||!J)){b("checking");try{const St=await pn.checkEmailExists(J);b((qe=St.data)!=null&&qe.exists?"exists":"not_exists")}catch{b("error")}}},pe=async()=>{var J,qe;if(!(!a||!i)){g(!0),f(null);try{const St=await pn.provisionEmail(i,a);(J=St.data)!=null&&J.success?b("exists"):f(((qe=St.data)==null?void 0:qe.error)||"Provisionierung fehlgeschlagen")}catch(St){f(St instanceof Error?St.message:"Fehler bei der Provisionierung")}finally{g(!1)}}},oe=async()=>{if(r){N(!0),f(null);try{const J=await xs.enableMailbox(r.id);J.success?(A(!0),M.invalidateQueries({queryKey:["customer",n.toString()]}),M.invalidateQueries({queryKey:["mailbox-accounts",n]})):f(J.error||"Mailbox-Aktivierung fehlgeschlagen")}catch(J){f(J instanceof Error?J.message:"Fehler bei der Mailbox-Aktivierung")}finally{N(!1)}}},Ze=async()=>{if(r)try{const J=await xs.syncMailboxStatus(r.id);J.success&&J.data&&(A(J.data.hasMailbox),J.data.wasUpdated&&M.invalidateQueries({queryKey:["customer",n.toString()]}))}catch(J){console.error("Fehler beim Synchronisieren des Mailbox-Status:",J)}},Oe=async()=>{if(r){I(!0);try{const J=await xs.getMailboxCredentials(r.id);J.success&&J.data&&(E(J.data),w(!0))}catch(J){console.error("Fehler beim Laden der Zugangsdaten:",J)}finally{I(!1)}}},it=async()=>{if(r&&confirm("Neues Passwort generieren? Das alte Passwort wird ungültig.")){P(!0);try{const J=await xs.resetPassword(r.id);J.success&&J.data?(S&&E({...S,password:J.data.password}),alert("Passwort wurde erfolgreich zurückgesetzt.")):alert(J.error||"Fehler beim Zurücksetzen des Passworts")}catch(J){console.error("Fehler beim Zurücksetzen des Passworts:",J),alert(J instanceof Error?J.message:"Fehler beim Zurücksetzen des Passworts")}finally{P(!1)}}};j.useEffect(()=>{if(e){if(r){const J=Z(r.email);l(J),c(r.notes||""),b("idle"),A(r.hasMailbox||!1),K&&(H(J),Ze())}else l(""),c(""),u(!1),p(!1),b("idle"),A(!1);f(null),w(!1),E(null)}},[e,r,K]);const C=W({mutationFn:async J=>xs.create(n,{email:J.email,notes:J.notes,provisionAtProvider:J.provision,createMailbox:J.createMailbox}),onSuccess:()=>{M.invalidateQueries({queryKey:["customer",n.toString()]}),M.invalidateQueries({queryKey:["mailbox-accounts",n]}),l(""),c(""),u(!1),p(!1),t()},onError:J=>{f(J instanceof Error?J.message:"Fehler bei der Provisionierung")}}),et=W({mutationFn:J=>xs.update(r.id,J),onSuccess:()=>{M.invalidateQueries({queryKey:["customer",n.toString()]}),t()}}),zt=J=>{J.preventDefault(),f(null);const qe=i+pd;k?et.mutate({email:qe,notes:o||void 0}):C.mutate({email:qe,notes:o||void 0,provision:d,createMailbox:d&&h})},Qt=C.isPending||et.isPending;return s.jsx(Ve,{isOpen:e,onClose:t,title:k?"Adresse bearbeiten":"Adresse hinzufügen",children:s.jsxs("form",{onSubmit:zt,className:"space-y-4",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"E-Mail-Adresse"}),s.jsxs("div",{className:"flex",children:[s.jsx("input",{type:"text",value:i,onChange:J=>l(J.target.value.toLowerCase().replace(/[^a-z0-9._-]/g,"")),placeholder:"kunde-freenet",required:!0,className:"block w-full px-3 py-2 border border-gray-300 rounded-l-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"}),s.jsx("span",{className:"inline-flex items-center px-3 py-2 border border-l-0 border-gray-300 bg-gray-100 text-gray-600 rounded-r-lg text-sm",children:pd})]}),s.jsxs("p",{className:"text-xs text-gray-500 mt-1",children:["Vollständige Adresse: ",s.jsxs("span",{className:"font-mono",children:[i||"...",pd]})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Notizen (optional)"}),s.jsx("textarea",{value:o,onChange:J=>c(J.target.value),rows:3,className:"block w-full px-3 py-2 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500",placeholder:"z.B. für Freenet-Konten, für Klarmobil..."})]}),K&&a&&s.jsx("div",{className:"bg-blue-50 p-3 rounded-lg",children:k?s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"text-sm font-medium text-gray-700",children:"E-Mail-Provider Status"}),x==="checking"&&s.jsx("span",{className:"text-xs text-gray-500",children:"Prüfe..."}),x==="exists"&&s.jsxs("span",{className:"text-xs text-green-600 flex items-center gap-1",children:[s.jsx("svg",{className:"w-4 h-4",fill:"currentColor",viewBox:"0 0 20 20",children:s.jsx("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z",clipRule:"evenodd"})}),"Beim Provider vorhanden"]}),x==="not_exists"&&s.jsx("span",{className:"text-xs text-orange-600",children:"Nicht beim Provider angelegt"}),x==="error"&&s.jsx("span",{className:"text-xs text-red-600",children:"Status konnte nicht geprüft werden"})]}),x==="not_exists"&&s.jsxs("div",{className:"pt-2 border-t border-blue-100",children:[s.jsxs("p",{className:"text-xs text-gray-500 mb-2",children:["Die E-Mail-Weiterleitung ist noch nicht auf dem Server eingerichtet. Weiterleitungsziel: ",a]}),s.jsx(F,{type:"button",size:"sm",onClick:pe,disabled:y,children:y?"Wird angelegt...":"Jetzt beim Provider anlegen"})]}),x==="error"&&s.jsx(F,{type:"button",size:"sm",variant:"secondary",onClick:()=>H(i),children:"Erneut prüfen"}),x==="exists"&&s.jsxs("div",{className:"pt-3 mt-3 border-t border-blue-100",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"text-sm font-medium text-gray-700",children:"Mailbox (IMAP/SMTP)"}),D?s.jsxs("span",{className:"text-xs text-green-600 flex items-center gap-1",children:[s.jsx("svg",{className:"w-4 h-4",fill:"currentColor",viewBox:"0 0 20 20",children:s.jsx("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z",clipRule:"evenodd"})}),"Mailbox aktiv"]}):s.jsx("span",{className:"text-xs text-orange-600",children:"Keine Mailbox"})]}),!D&&s.jsxs("div",{className:"mt-2",children:[s.jsx("p",{className:"text-xs text-gray-500 mb-2",children:"Aktiviere eine echte Mailbox um E-Mails direkt im CRM zu empfangen und zu versenden."}),s.jsx(F,{type:"button",size:"sm",onClick:oe,disabled:v,children:v?"Wird aktiviert...":"Mailbox aktivieren"})]}),D&&s.jsx("div",{className:"mt-3",children:R?S&&s.jsx(jk,{credentials:S,onHide:()=>w(!1),onResetPassword:it,isResettingPassword:B}):s.jsx(F,{type:"button",size:"sm",variant:"secondary",onClick:Oe,disabled:z,children:z?"Laden...":s.jsxs(s.Fragment,{children:[s.jsx(Pe,{className:"w-4 h-4 mr-1"}),"Zugangsdaten anzeigen"]})})})]})]}):s.jsxs("div",{className:"space-y-3",children:[s.jsxs("label",{className:"flex items-start gap-2 cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:d,onChange:J=>{u(J.target.checked),J.target.checked||p(!1)},className:"mt-1 rounded border-gray-300"}),s.jsxs("div",{children:[s.jsx("span",{className:"text-sm font-medium text-gray-700",children:"Beim E-Mail-Provider anlegen"}),s.jsxs("p",{className:"text-xs text-gray-500 mt-1",children:["Die E-Mail-Weiterleitung wird automatisch auf dem konfigurierten Server erstellt. Weiterleitungsziel: ",a]})]})]}),d&&s.jsxs("label",{className:"flex items-start gap-2 cursor-pointer ml-6",children:[s.jsx("input",{type:"checkbox",checked:h,onChange:J=>p(J.target.checked),className:"mt-1 rounded border-gray-300"}),s.jsxs("div",{children:[s.jsx("span",{className:"text-sm font-medium text-gray-700",children:"Echte Mailbox erstellen (IMAP/SMTP-Zugang)"}),s.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Ermöglicht E-Mails direkt im CRM zu empfangen und zu versenden."})]})]})]})}),m&&s.jsx("div",{className:"bg-red-50 p-3 rounded-lg text-red-700 text-sm",children:m}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx(F,{type:"button",variant:"secondary",onClick:t,children:"Abbrechen"}),s.jsx(F,{type:"submit",disabled:Qt||!i,children:Qt?"Speichern...":"Speichern"})]})]})})}var Fl=e=>e.type==="checkbox",Pr=e=>e instanceof Date,as=e=>e==null;const Ov=e=>typeof e=="object";var vt=e=>!as(e)&&!Array.isArray(e)&&Ov(e)&&!Pr(e),bk=e=>vt(e)&&e.target?Fl(e.target)?e.target.checked:e.target.value:e,Nk=e=>e.substring(0,e.search(/\.\d+(\.|$)/))||e,wk=(e,t)=>e.has(Nk(t)),Sk=e=>{const t=e.constructor&&e.constructor.prototype;return vt(t)&&t.hasOwnProperty("isPrototypeOf")},xh=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function jt(e){if(e instanceof Date)return new Date(e);const t=typeof FileList<"u"&&e instanceof FileList;if(xh&&(e instanceof Blob||t))return e;const n=Array.isArray(e);if(!n&&!(vt(e)&&Sk(e)))return e;const r=n?[]:Object.create(Object.getPrototypeOf(e));for(const a in e)Object.prototype.hasOwnProperty.call(e,a)&&(r[a]=jt(e[a]));return r}var Ic=e=>/^\w*$/.test(e),tt=e=>e===void 0,gh=e=>Array.isArray(e)?e.filter(Boolean):[],yh=e=>gh(e.replace(/["|']|\]/g,"").split(/\.|\[/)),fe=(e,t,n)=>{if(!t||!vt(e))return n;const r=(Ic(t)?[t]:yh(t)).reduce((a,i)=>as(a)?a:a[i],e);return tt(r)||r===e?tt(e[t])?n:e[t]:r},Js=e=>typeof e=="boolean",Ks=e=>typeof e=="function",Je=(e,t,n)=>{let r=-1;const a=Ic(t)?[t]:yh(t),i=a.length,l=i-1;for(;++r{const a={defaultValues:t._defaultValues};for(const i in e)Object.defineProperty(a,i,{get:()=>{const l=i;return t._proxyFormState[l]!==Us.all&&(t._proxyFormState[l]=!r||Us.all),e[l]}});return a};const Ek=typeof window<"u"?Tt.useLayoutEffect:Tt.useEffect;var gs=e=>typeof e=="string",Dk=(e,t,n,r,a)=>gs(e)?(r&&t.watch.add(e),fe(n,e,a)):Array.isArray(e)?e.map(i=>(r&&t.watch.add(i),fe(n,i))):(r&&(t.watchAll=!0),n),Hu=e=>as(e)||!Ov(e);function Un(e,t,n=new WeakSet){if(Hu(e)||Hu(t))return Object.is(e,t);if(Pr(e)&&Pr(t))return Object.is(e.getTime(),t.getTime());const r=Object.keys(e),a=Object.keys(t);if(r.length!==a.length)return!1;if(n.has(e)||n.has(t))return!0;n.add(e),n.add(t);for(const i of r){const l=e[i];if(!a.includes(i))return!1;if(i!=="ref"){const o=t[i];if(Pr(l)&&Pr(o)||vt(l)&&vt(o)||Array.isArray(l)&&Array.isArray(o)?!Un(l,o,n):!Object.is(l,o))return!1}}return!0}const Pk=Tt.createContext(null);Pk.displayName="HookFormContext";var Ak=(e,t,n,r,a)=>t?{...n[e],types:{...n[e]&&n[e].types?n[e].types:{},[r]:a||!0}}:{},Ri=e=>Array.isArray(e)?e:[e],wx=()=>{let e=[];return{get observers(){return e},next:a=>{for(const i of e)i.next&&i.next(a)},subscribe:a=>(e.push(a),{unsubscribe:()=>{e=e.filter(i=>i!==a)}}),unsubscribe:()=>{e=[]}}};function zv(e,t){const n={};for(const r in e)if(e.hasOwnProperty(r)){const a=e[r],i=t[r];if(a&&vt(a)&&i){const l=zv(a,i);vt(l)&&(n[r]=l)}else e[r]&&(n[r]=i)}return n}var Zt=e=>vt(e)&&!Object.keys(e).length,vh=e=>e.type==="file",tc=e=>{if(!xh)return!1;const t=e?e.ownerDocument:0;return e instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},$v=e=>e.type==="select-multiple",jh=e=>e.type==="radio",Mk=e=>jh(e)||Fl(e),xd=e=>tc(e)&&e.isConnected;function Tk(e,t){const n=t.slice(0,-1).length;let r=0;for(;r{for(const t in e)if(Ks(e[t]))return!0;return!1};function _v(e){return Array.isArray(e)||vt(e)&&!Ik(e)}function Wu(e,t={}){for(const n in e){const r=e[n];_v(r)?(t[n]=Array.isArray(r)?[]:{},Wu(r,t[n])):tt(r)||(t[n]=!0)}return t}function aa(e,t,n){n||(n=Wu(t));for(const r in e){const a=e[r];if(_v(a))tt(t)||Hu(n[r])?n[r]=Wu(a,Array.isArray(a)?[]:{}):aa(a,as(t)?{}:t[r],n[r]);else{const i=t[r];n[r]=!Un(a,i)}}return n}const Sx={value:!1,isValid:!1},kx={value:!0,isValid:!0};var Kv=e=>{if(Array.isArray(e)){if(e.length>1){const t=e.filter(n=>n&&n.checked&&!n.disabled).map(n=>n.value);return{value:t,isValid:!!t.length}}return e[0].checked&&!e[0].disabled?e[0].attributes&&!tt(e[0].attributes.value)?tt(e[0].value)||e[0].value===""?kx:{value:e[0].value,isValid:!0}:kx:Sx}return Sx},Uv=(e,{valueAsNumber:t,valueAsDate:n,setValueAs:r})=>tt(e)?e:t?e===""?NaN:e&&+e:n&&gs(e)?new Date(e):r?r(e):e;const Cx={isValid:!1,value:null};var Bv=e=>Array.isArray(e)?e.reduce((t,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:t,Cx):Cx;function Ex(e){const t=e.ref;return vh(t)?t.files:jh(t)?Bv(e.refs).value:$v(t)?[...t.selectedOptions].map(({value:n})=>n):Fl(t)?Kv(e.refs).value:Uv(tt(t.value)?e.ref.value:t.value,e)}var Rk=(e,t,n,r)=>{const a={};for(const i of e){const l=fe(t,i);l&&Je(a,i,l._f)}return{criteriaMode:n,names:[...e],fields:a,shouldUseNativeValidation:r}},sc=e=>e instanceof RegExp,yi=e=>tt(e)?e:sc(e)?e.source:vt(e)?sc(e.value)?e.value.source:e.value:e,Dx=e=>({isOnSubmit:!e||e===Us.onSubmit,isOnBlur:e===Us.onBlur,isOnChange:e===Us.onChange,isOnAll:e===Us.all,isOnTouch:e===Us.onTouched});const Px="AsyncFunction";var Lk=e=>!!e&&!!e.validate&&!!(Ks(e.validate)&&e.validate.constructor.name===Px||vt(e.validate)&&Object.values(e.validate).find(t=>t.constructor.name===Px)),Ok=e=>e.mount&&(e.required||e.min||e.max||e.maxLength||e.minLength||e.pattern||e.validate),Ax=(e,t,n)=>!n&&(t.watchAll||t.watch.has(e)||[...t.watch].some(r=>e.startsWith(r)&&/^\.\w+/.test(e.slice(r.length))));const Li=(e,t,n,r)=>{for(const a of n||Object.keys(e)){const i=fe(e,a);if(i){const{_f:l,...o}=i;if(l){if(l.refs&&l.refs[0]&&t(l.refs[0],a)&&!r)return!0;if(l.ref&&t(l.ref,l.name)&&!r)return!0;if(Li(o,t))break}else if(vt(o)&&Li(o,t))break}}};function Mx(e,t,n){const r=fe(e,n);if(r||Ic(n))return{error:r,name:n};const a=n.split(".");for(;a.length;){const i=a.join("."),l=fe(t,i),o=fe(e,i);if(l&&!Array.isArray(l)&&n!==i)return{name:n};if(o&&o.type)return{name:i,error:o};if(o&&o.root&&o.root.type)return{name:`${i}.root`,error:o.root};a.pop()}return{name:n}}var zk=(e,t,n,r)=>{n(e);const{name:a,...i}=e;return Zt(i)||Object.keys(i).length>=Object.keys(t).length||Object.keys(i).find(l=>t[l]===(!r||Us.all))},$k=(e,t,n)=>!e||!t||e===t||Ri(e).some(r=>r&&(n?r===t:r.startsWith(t)||t.startsWith(r))),_k=(e,t,n,r,a)=>a.isOnAll?!1:!n&&a.isOnTouch?!(t||e):(n?r.isOnBlur:a.isOnBlur)?!e:(n?r.isOnChange:a.isOnChange)?e:!0,Kk=(e,t)=>!gh(fe(e,t)).length&>(e,t),Uk=(e,t,n)=>{const r=Ri(fe(e,n));return Je(r,"root",t[n]),Je(e,n,r),e};function Tx(e,t,n="validate"){if(gs(e)||Array.isArray(e)&&e.every(gs)||Js(e)&&!e)return{type:n,message:gs(e)?e:"",ref:t}}var na=e=>vt(e)&&!sc(e)?e:{value:e,message:""},Fx=async(e,t,n,r,a,i)=>{const{ref:l,refs:o,required:c,maxLength:d,minLength:u,min:h,max:p,pattern:m,validate:f,name:x,valueAsNumber:b,mount:y}=e._f,g=fe(n,x);if(!y||t.has(x))return{};const v=o?o[0]:l,N=I=>{a&&v.reportValidity&&(v.setCustomValidity(Js(I)?"":I||""),v.reportValidity())},D={},A=jh(l),R=Fl(l),w=A||R,S=(b||vh(l))&&tt(l.value)&&tt(g)||tc(l)&&l.value===""||g===""||Array.isArray(g)&&!g.length,E=Ak.bind(null,x,r,D),z=(I,B,P,M=un.maxLength,k=un.minLength)=>{const _=I?B:P;D[x]={type:I?M:k,message:_,ref:l,...E(I?M:k,_)}};if(i?!Array.isArray(g)||!g.length:c&&(!w&&(S||as(g))||Js(g)&&!g||R&&!Kv(o).isValid||A&&!Bv(o).isValid)){const{value:I,message:B}=gs(c)?{value:!!c,message:c}:na(c);if(I&&(D[x]={type:un.required,message:B,ref:v,...E(un.required,B)},!r))return N(B),D}if(!S&&(!as(h)||!as(p))){let I,B;const P=na(p),M=na(h);if(!as(g)&&!isNaN(g)){const k=l.valueAsNumber||g&&+g;as(P.value)||(I=k>P.value),as(M.value)||(B=knew Date(new Date().toDateString()+" "+H),K=l.type=="time",Z=l.type=="week";gs(P.value)&&g&&(I=K?_(g)>_(P.value):Z?g>P.value:k>new Date(P.value)),gs(M.value)&&g&&(B=K?_(g)<_(M.value):Z?g+I.value,M=!as(B.value)&&g.length<+B.value;if((P||M)&&(z(P,I.message,B.message),!r))return N(D[x].message),D}if(m&&!S&&gs(g)){const{value:I,message:B}=na(m);if(sc(I)&&!g.match(I)&&(D[x]={type:un.pattern,message:B,ref:l,...E(un.pattern,B)},!r))return N(B),D}if(f){if(Ks(f)){const I=await f(g,n),B=Tx(I,v);if(B&&(D[x]={...B,...E(un.validate,B.message)},!r))return N(B.message),D}else if(vt(f)){let I={};for(const B in f){if(!Zt(I)&&!r)break;const P=Tx(await f[B](g,n),v,B);P&&(I={...P,...E(B,P.message)},N(P.message),r&&(D[x]=I))}if(!Zt(I)&&(D[x]={ref:v,...I},!r))return D}}return N(!0),D};const Bk={mode:Us.onSubmit,reValidateMode:Us.onChange,shouldFocusError:!0};function qk(e={}){let t={...Bk,...e},n={submitCount:0,isDirty:!1,isReady:!1,isLoading:Ks(t.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{},errors:t.errors||{},disabled:t.disabled||!1},r={},a=vt(t.defaultValues)||vt(t.values)?jt(t.defaultValues||t.values)||{}:{},i=t.shouldUnregister?{}:jt(a),l={action:!1,mount:!1,watch:!1,keepIsValid:!1},o={mount:new Set,disabled:new Set,unMount:new Set,array:new Set,watch:new Set},c,d=0;const u={isDirty:!1,dirtyFields:!1,validatingFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},h={...u};let p={...h};const m={array:wx(),state:wx()},f=t.criteriaMode===Us.all,x=O=>U=>{clearTimeout(d),d=setTimeout(O,U)},b=async O=>{if(!l.keepIsValid&&!t.disabled&&(h.isValid||p.isValid||O)){let U;t.resolver?(U=Zt((await w()).errors),y()):U=await E(r,!0),U!==n.isValid&&m.state.next({isValid:U})}},y=(O,U)=>{!t.disabled&&(h.isValidating||h.validatingFields||p.isValidating||p.validatingFields)&&((O||Array.from(o.mount)).forEach(Q=>{Q&&(U?Je(n.validatingFields,Q,U):gt(n.validatingFields,Q))}),m.state.next({validatingFields:n.validatingFields,isValidating:!Zt(n.validatingFields)}))},g=(O,U=[],Q,le,ne=!0,te=!0)=>{if(le&&Q&&!t.disabled){if(l.action=!0,te&&Array.isArray(fe(r,O))){const ge=Q(fe(r,O),le.argA,le.argB);ne&&Je(r,O,ge)}if(te&&Array.isArray(fe(n.errors,O))){const ge=Q(fe(n.errors,O),le.argA,le.argB);ne&&Je(n.errors,O,ge),Kk(n.errors,O)}if((h.touchedFields||p.touchedFields)&&te&&Array.isArray(fe(n.touchedFields,O))){const ge=Q(fe(n.touchedFields,O),le.argA,le.argB);ne&&Je(n.touchedFields,O,ge)}(h.dirtyFields||p.dirtyFields)&&(n.dirtyFields=aa(a,i)),m.state.next({name:O,isDirty:I(O,U),dirtyFields:n.dirtyFields,errors:n.errors,isValid:n.isValid})}else Je(i,O,U)},v=(O,U)=>{Je(n.errors,O,U),m.state.next({errors:n.errors})},N=O=>{n.errors=O,m.state.next({errors:n.errors,isValid:!1})},D=(O,U,Q,le)=>{const ne=fe(r,O);if(ne){const te=fe(i,O,tt(Q)?fe(a,O):Q);tt(te)||le&&le.defaultChecked||U?Je(i,O,U?te:Ex(ne._f)):M(O,te),l.mount&&!l.action&&b()}},A=(O,U,Q,le,ne)=>{let te=!1,ge=!1;const Te={name:O};if(!t.disabled){if(!Q||le){(h.isDirty||p.isDirty)&&(ge=n.isDirty,n.isDirty=Te.isDirty=I(),te=ge!==Te.isDirty);const Fe=Un(fe(a,O),U);ge=!!fe(n.dirtyFields,O),Fe?gt(n.dirtyFields,O):Je(n.dirtyFields,O,!0),Te.dirtyFields=n.dirtyFields,te=te||(h.dirtyFields||p.dirtyFields)&&ge!==!Fe}if(Q){const Fe=fe(n.touchedFields,O);Fe||(Je(n.touchedFields,O,Q),Te.touchedFields=n.touchedFields,te=te||(h.touchedFields||p.touchedFields)&&Fe!==Q)}te&&ne&&m.state.next(Te)}return te?Te:{}},R=(O,U,Q,le)=>{const ne=fe(n.errors,O),te=(h.isValid||p.isValid)&&Js(U)&&n.isValid!==U;if(t.delayError&&Q?(c=x(()=>v(O,Q)),c(t.delayError)):(clearTimeout(d),c=null,Q?Je(n.errors,O,Q):gt(n.errors,O)),(Q?!Un(ne,Q):ne)||!Zt(le)||te){const ge={...le,...te&&Js(U)?{isValid:U}:{},errors:n.errors,name:O};n={...n,...ge},m.state.next(ge)}},w=async O=>(y(O,!0),await t.resolver(i,t.context,Rk(O||o.mount,r,t.criteriaMode,t.shouldUseNativeValidation))),S=async O=>{const{errors:U}=await w(O);if(y(O),O)for(const Q of O){const le=fe(U,Q);le?Je(n.errors,Q,le):gt(n.errors,Q)}else n.errors=U;return U},E=async(O,U,Q={valid:!0})=>{for(const le in O){const ne=O[le];if(ne){const{_f:te,...ge}=ne;if(te){const Te=o.array.has(te.name),Fe=ne._f&&Lk(ne._f);Fe&&h.validatingFields&&y([te.name],!0);const At=await Fx(ne,o.disabled,i,f,t.shouldUseNativeValidation&&!U,Te);if(Fe&&h.validatingFields&&y([te.name]),At[te.name]&&(Q.valid=!1,U||e.shouldUseNativeValidation))break;!U&&(fe(At,te.name)?Te?Uk(n.errors,At,te.name):Je(n.errors,te.name,At[te.name]):gt(n.errors,te.name))}!Zt(ge)&&await E(ge,U,Q)}}return Q.valid},z=()=>{for(const O of o.unMount){const U=fe(r,O);U&&(U._f.refs?U._f.refs.every(Q=>!xd(Q)):!xd(U._f.ref))&&zt(O)}o.unMount=new Set},I=(O,U)=>!t.disabled&&(O&&U&&Je(i,O,U),!Un(pe(),a)),B=(O,U,Q)=>Dk(O,o,{...l.mount?i:tt(U)?a:gs(O)?{[O]:U}:U},Q,U),P=O=>gh(fe(l.mount?i:a,O,t.shouldUnregister?fe(a,O,[]):[])),M=(O,U,Q={})=>{const le=fe(r,O);let ne=U;if(le){const te=le._f;te&&(!te.disabled&&Je(i,O,Uv(U,te)),ne=tc(te.ref)&&as(U)?"":U,$v(te.ref)?[...te.ref.options].forEach(ge=>ge.selected=ne.includes(ge.value)):te.refs?Fl(te.ref)?te.refs.forEach(ge=>{(!ge.defaultChecked||!ge.disabled)&&(Array.isArray(ne)?ge.checked=!!ne.find(Te=>Te===ge.value):ge.checked=ne===ge.value||!!ne)}):te.refs.forEach(ge=>ge.checked=ge.value===ne):vh(te.ref)?te.ref.value="":(te.ref.value=ne,te.ref.type||m.state.next({name:O,values:jt(i)})))}(Q.shouldDirty||Q.shouldTouch)&&A(O,ne,Q.shouldTouch,Q.shouldDirty,!0),Q.shouldValidate&&H(O)},k=(O,U,Q)=>{for(const le in U){if(!U.hasOwnProperty(le))return;const ne=U[le],te=O+"."+le,ge=fe(r,te);(o.array.has(O)||vt(ne)||ge&&!ge._f)&&!Pr(ne)?k(te,ne,Q):M(te,ne,Q)}},_=(O,U,Q={})=>{const le=fe(r,O),ne=o.array.has(O),te=jt(U);Je(i,O,te),ne?(m.array.next({name:O,values:jt(i)}),(h.isDirty||h.dirtyFields||p.isDirty||p.dirtyFields)&&Q.shouldDirty&&m.state.next({name:O,dirtyFields:aa(a,i),isDirty:I(O,te)})):le&&!le._f&&!as(te)?k(O,te,Q):M(O,te,Q),Ax(O,o)?m.state.next({...n,name:O,values:jt(i)}):m.state.next({name:l.mount?O:void 0,values:jt(i)})},K=async O=>{l.mount=!0;const U=O.target;let Q=U.name,le=!0;const ne=fe(r,Q),te=Fe=>{le=Number.isNaN(Fe)||Pr(Fe)&&isNaN(Fe.getTime())||Un(Fe,fe(i,Q,Fe))},ge=Dx(t.mode),Te=Dx(t.reValidateMode);if(ne){let Fe,At;const cn=U.type?Ex(ne._f):bk(O),Ht=O.type===Nx.BLUR||O.type===Nx.FOCUS_OUT,Rc=!Ok(ne._f)&&!t.resolver&&!fe(n.errors,Q)&&!ne._f.deps||_k(Ht,fe(n.touchedFields,Q),n.isSubmitted,Te,ge),ta=Ax(Q,o,Ht);Je(i,Q,cn),Ht?(!U||!U.readOnly)&&(ne._f.onBlur&&ne._f.onBlur(O),c&&c(0)):ne._f.onChange&&ne._f.onChange(O);const ai=A(Q,cn,Ht),Il=!Zt(ai)||ta;if(!Ht&&m.state.next({name:Q,type:O.type,values:jt(i)}),Rc)return(h.isValid||p.isValid)&&(t.mode==="onBlur"?Ht&&b():Ht||b()),Il&&m.state.next({name:Q,...ta?{}:ai});if(!Ht&&ta&&m.state.next({...n}),t.resolver){const{errors:ii}=await w([Q]);if(y([Q]),te(cn),le){const Rl=Mx(n.errors,r,Q),li=Mx(ii,r,Rl.name||Q);Fe=li.error,Q=li.name,At=Zt(ii)}}else y([Q],!0),Fe=(await Fx(ne,o.disabled,i,f,t.shouldUseNativeValidation))[Q],y([Q]),te(cn),le&&(Fe?At=!1:(h.isValid||p.isValid)&&(At=await E(r,!0)));le&&(ne._f.deps&&(!Array.isArray(ne._f.deps)||ne._f.deps.length>0)&&H(ne._f.deps),R(Q,At,Fe,ai))}},Z=(O,U)=>{if(fe(n.errors,U)&&O.focus)return O.focus(),1},H=async(O,U={})=>{let Q,le;const ne=Ri(O);if(t.resolver){const te=await S(tt(O)?O:ne);Q=Zt(te),le=O?!ne.some(ge=>fe(te,ge)):Q}else O?(le=(await Promise.all(ne.map(async te=>{const ge=fe(r,te);return await E(ge&&ge._f?{[te]:ge}:ge)}))).every(Boolean),!(!le&&!n.isValid)&&b()):le=Q=await E(r);return m.state.next({...!gs(O)||(h.isValid||p.isValid)&&Q!==n.isValid?{}:{name:O},...t.resolver||!O?{isValid:Q}:{},errors:n.errors}),U.shouldFocus&&!le&&Li(r,Z,O?ne:o.mount),le},pe=(O,U)=>{let Q={...l.mount?i:a};return U&&(Q=zv(U.dirtyFields?n.dirtyFields:n.touchedFields,Q)),tt(O)?Q:gs(O)?fe(Q,O):O.map(le=>fe(Q,le))},oe=(O,U)=>({invalid:!!fe((U||n).errors,O),isDirty:!!fe((U||n).dirtyFields,O),error:fe((U||n).errors,O),isValidating:!!fe(n.validatingFields,O),isTouched:!!fe((U||n).touchedFields,O)}),Ze=O=>{O&&Ri(O).forEach(U=>gt(n.errors,U)),m.state.next({errors:O?n.errors:{}})},Oe=(O,U,Q)=>{const le=(fe(r,O,{_f:{}})._f||{}).ref,ne=fe(n.errors,O)||{},{ref:te,message:ge,type:Te,...Fe}=ne;Je(n.errors,O,{...Fe,...U,ref:le}),m.state.next({name:O,errors:n.errors,isValid:!1}),Q&&Q.shouldFocus&&le&&le.focus&&le.focus()},it=(O,U)=>Ks(O)?m.state.subscribe({next:Q=>"values"in Q&&O(B(void 0,U),Q)}):B(O,U,!0),C=O=>m.state.subscribe({next:U=>{$k(O.name,U.name,O.exact)&&zk(U,O.formState||h,Is,O.reRenderRoot)&&O.callback({values:{...i},...n,...U,defaultValues:a})}}).unsubscribe,et=O=>(l.mount=!0,p={...p,...O.formState},C({...O,formState:{...u,...O.formState}})),zt=(O,U={})=>{for(const Q of O?Ri(O):o.mount)o.mount.delete(Q),o.array.delete(Q),U.keepValue||(gt(r,Q),gt(i,Q)),!U.keepError&>(n.errors,Q),!U.keepDirty&>(n.dirtyFields,Q),!U.keepTouched&>(n.touchedFields,Q),!U.keepIsValidating&>(n.validatingFields,Q),!t.shouldUnregister&&!U.keepDefaultValue&>(a,Q);m.state.next({values:jt(i)}),m.state.next({...n,...U.keepDirty?{isDirty:I()}:{}}),!U.keepIsValid&&b()},Qt=({disabled:O,name:U})=>{if(Js(O)&&l.mount||O||o.disabled.has(U)){const ne=o.disabled.has(U)!==!!O;O?o.disabled.add(U):o.disabled.delete(U),ne&&l.mount&&!l.action&&b()}},J=(O,U={})=>{let Q=fe(r,O);const le=Js(U.disabled)||Js(t.disabled);return Je(r,O,{...Q||{},_f:{...Q&&Q._f?Q._f:{ref:{name:O}},name:O,mount:!0,...U}}),o.mount.add(O),Q?Qt({disabled:Js(U.disabled)?U.disabled:t.disabled,name:O}):D(O,!0,U.value),{...le?{disabled:U.disabled||t.disabled}:{},...t.progressive?{required:!!U.required,min:yi(U.min),max:yi(U.max),minLength:yi(U.minLength),maxLength:yi(U.maxLength),pattern:yi(U.pattern)}:{},name:O,onChange:K,onBlur:K,ref:ne=>{if(ne){J(O,U),Q=fe(r,O);const te=tt(ne.value)&&ne.querySelectorAll&&ne.querySelectorAll("input,select,textarea")[0]||ne,ge=Mk(te),Te=Q._f.refs||[];if(ge?Te.find(Fe=>Fe===te):te===Q._f.ref)return;Je(r,O,{_f:{...Q._f,...ge?{refs:[...Te.filter(xd),te,...Array.isArray(fe(a,O))?[{}]:[]],ref:{type:te.type,name:O}}:{ref:te}}}),D(O,!1,void 0,te)}else Q=fe(r,O,{}),Q._f&&(Q._f.mount=!1),(t.shouldUnregister||U.shouldUnregister)&&!(wk(o.array,O)&&l.action)&&o.unMount.add(O)}}},qe=()=>t.shouldFocusError&&Li(r,Z,o.mount),St=O=>{Js(O)&&(m.state.next({disabled:O}),Li(r,(U,Q)=>{const le=fe(r,Q);le&&(U.disabled=le._f.disabled||O,Array.isArray(le._f.refs)&&le._f.refs.forEach(ne=>{ne.disabled=le._f.disabled||O}))},0,!1))},G=(O,U)=>async Q=>{let le;Q&&(Q.preventDefault&&Q.preventDefault(),Q.persist&&Q.persist());let ne=jt(i);if(m.state.next({isSubmitting:!0}),t.resolver){const{errors:te,values:ge}=await w();y(),n.errors=te,ne=jt(ge)}else await E(r);if(o.disabled.size)for(const te of o.disabled)gt(ne,te);if(gt(n.errors,"root"),Zt(n.errors)){m.state.next({errors:{}});try{await O(ne,Q)}catch(te){le=te}}else U&&await U({...n.errors},Q),qe(),setTimeout(qe);if(m.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:Zt(n.errors)&&!le,submitCount:n.submitCount+1,errors:n.errors}),le)throw le},_e=(O,U={})=>{fe(r,O)&&(tt(U.defaultValue)?_(O,jt(fe(a,O))):(_(O,U.defaultValue),Je(a,O,jt(U.defaultValue))),U.keepTouched||gt(n.touchedFields,O),U.keepDirty||(gt(n.dirtyFields,O),n.isDirty=U.defaultValue?I(O,jt(fe(a,O))):I()),U.keepError||(gt(n.errors,O),h.isValid&&b()),m.state.next({...n}))},ht=(O,U={})=>{const Q=O?jt(O):a,le=jt(Q),ne=Zt(O),te=ne?a:le;if(U.keepDefaultValues||(a=Q),!U.keepValues){if(U.keepDirtyValues){const ge=new Set([...o.mount,...Object.keys(aa(a,i))]);for(const Te of Array.from(ge)){const Fe=fe(n.dirtyFields,Te),At=fe(i,Te),cn=fe(te,Te);Fe&&!tt(At)?Je(te,Te,At):!Fe&&!tt(cn)&&_(Te,cn)}}else{if(xh&&tt(O))for(const ge of o.mount){const Te=fe(r,ge);if(Te&&Te._f){const Fe=Array.isArray(Te._f.refs)?Te._f.refs[0]:Te._f.ref;if(tc(Fe)){const At=Fe.closest("form");if(At){At.reset();break}}}}if(U.keepFieldsRef)for(const ge of o.mount)_(ge,fe(te,ge));else r={}}i=t.shouldUnregister?U.keepDefaultValues?jt(a):{}:jt(te),m.array.next({values:{...te}}),m.state.next({values:{...te}})}o={mount:U.keepDirtyValues?o.mount:new Set,unMount:new Set,array:new Set,disabled:new Set,watch:new Set,watchAll:!1,focus:""},l.mount=!h.isValid||!!U.keepIsValid||!!U.keepDirtyValues||!t.shouldUnregister&&!Zt(te),l.watch=!!t.shouldUnregister,l.keepIsValid=!!U.keepIsValid,l.action=!1,U.keepErrors||(n.errors={}),m.state.next({submitCount:U.keepSubmitCount?n.submitCount:0,isDirty:ne?!1:U.keepDirty?n.isDirty:!!(U.keepDefaultValues&&!Un(O,a)),isSubmitted:U.keepIsSubmitted?n.isSubmitted:!1,dirtyFields:ne?{}:U.keepDirtyValues?U.keepDefaultValues&&i?aa(a,i):n.dirtyFields:U.keepDefaultValues&&O?aa(a,O):U.keepDirty?n.dirtyFields:{},touchedFields:U.keepTouched?n.touchedFields:{},errors:U.keepErrors?n.errors:{},isSubmitSuccessful:U.keepIsSubmitSuccessful?n.isSubmitSuccessful:!1,isSubmitting:!1,defaultValues:a})},ee=(O,U)=>ht(Ks(O)?O(i):O,{...t.resetOptions,...U}),Ne=(O,U={})=>{const Q=fe(r,O),le=Q&&Q._f;if(le){const ne=le.refs?le.refs[0]:le.ref;ne.focus&&setTimeout(()=>{ne.focus(),U.shouldSelect&&Ks(ne.select)&&ne.select()})}},Is=O=>{n={...n,...O}},vr={control:{register:J,unregister:zt,getFieldState:oe,handleSubmit:G,setError:Oe,_subscribe:C,_runSchema:w,_updateIsValidating:y,_focusError:qe,_getWatch:B,_getDirty:I,_setValid:b,_setFieldArray:g,_setDisabledField:Qt,_setErrors:N,_getFieldArray:P,_reset:ht,_resetDefaultValues:()=>Ks(t.defaultValues)&&t.defaultValues().then(O=>{ee(O,t.resetOptions),m.state.next({isLoading:!1})}),_removeUnmounted:z,_disableForm:St,_subjects:m,_proxyFormState:h,get _fields(){return r},get _formValues(){return i},get _state(){return l},set _state(O){l=O},get _defaultValues(){return a},get _names(){return o},set _names(O){o=O},get _formState(){return n},get _options(){return t},set _options(O){t={...t,...O}}},subscribe:et,trigger:H,register:J,handleSubmit:G,watch:it,setValue:_,getValues:pe,reset:ee,resetField:_e,clearErrors:Ze,unregister:zt,setError:Oe,setFocus:Ne,getFieldState:oe};return{...vr,formControl:vr}}function qv(e={}){const t=Tt.useRef(void 0),n=Tt.useRef(void 0),[r,a]=Tt.useState({isDirty:!1,isValidating:!1,isLoading:Ks(e.defaultValues),isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,submitCount:0,dirtyFields:{},touchedFields:{},validatingFields:{},errors:e.errors||{},disabled:e.disabled||!1,isReady:!1,defaultValues:Ks(e.defaultValues)?void 0:e.defaultValues});if(!t.current)if(e.formControl)t.current={...e.formControl,formState:r},e.defaultValues&&!Ks(e.defaultValues)&&e.formControl.reset(e.defaultValues,e.resetOptions);else{const{formControl:l,...o}=qk(e);t.current={...o,formState:r}}const i=t.current.control;return i._options=e,Ek(()=>{const l=i._subscribe({formState:i._proxyFormState,callback:()=>a({...i._formState}),reRenderRoot:!0});return a(o=>({...o,isReady:!0})),i._formState.isReady=!0,l},[i]),Tt.useEffect(()=>i._disableForm(e.disabled),[i,e.disabled]),Tt.useEffect(()=>{e.mode&&(i._options.mode=e.mode),e.reValidateMode&&(i._options.reValidateMode=e.reValidateMode)},[i,e.mode,e.reValidateMode]),Tt.useEffect(()=>{e.errors&&(i._setErrors(e.errors),i._focusError())},[i,e.errors]),Tt.useEffect(()=>{e.shouldUnregister&&i._subjects.state.next({values:i._getWatch()})},[i,e.shouldUnregister]),Tt.useEffect(()=>{if(i._proxyFormState.isDirty){const l=i._getDirty();l!==r.isDirty&&i._subjects.state.next({isDirty:l})}},[i,r.isDirty]),Tt.useEffect(()=>{var l;e.values&&!Un(e.values,n.current)?(i._reset(e.values,{keepFieldsRef:!0,...i._options.resetOptions}),!((l=i._options.resetOptions)===null||l===void 0)&&l.keepIsValid||i._setValid(),n.current=e.values,a(o=>({...o}))):i._resetDefaultValues()},[i,e.values]),Tt.useEffect(()=>{i._state.mount||(i._setValid(),i._state.mount=!0),i._state.watch&&(i._state.watch=!1,i._subjects.state.next({...i._formState})),i._removeUnmounted()}),t.current.formState=Tt.useMemo(()=>Ck(r,i),[i,r]),t.current}function Ix(){var y,g;const{id:e}=bc(),t=ts(),n=xe(),r=!!e,{register:a,handleSubmit:i,reset:l,watch:o,setValue:c,formState:{errors:d}}=qv(),u=o("type"),{data:h}=me({queryKey:["customer",e],queryFn:()=>Dt.getById(parseInt(e)),enabled:r});j.useEffect(()=>{if(h!=null&&h.data){const v={...h.data};v.birthDate&&(v.birthDate=v.birthDate.split("T")[0]),v.foundingDate&&(v.foundingDate=v.foundingDate.split("T")[0]),l(v)}},[h,l]);const p=W({mutationFn:Dt.create,onSuccess:()=>{n.invalidateQueries({queryKey:["customers"]}),t("/customers")}}),m=W({mutationFn:v=>Dt.update(parseInt(e),v),onSuccess:()=>{n.invalidateQueries({queryKey:["customers"]}),n.invalidateQueries({queryKey:["customer",e]}),t(`/customers/${e}`)}}),f=v=>{const N={type:v.type,salutation:v.salutation||void 0,firstName:v.firstName,lastName:v.lastName,companyName:v.companyName||void 0,email:v.email||void 0,phone:v.phone||void 0,mobile:v.mobile||void 0,taxNumber:v.taxNumber||void 0,commercialRegisterNumber:v.commercialRegisterNumber||void 0,notes:v.notes||void 0,birthPlace:v.birthPlace||void 0};v.birthDate&&typeof v.birthDate=="string"&&v.birthDate.trim()!==""?N.birthDate=new Date(v.birthDate).toISOString():N.birthDate=null,v.foundingDate&&typeof v.foundingDate=="string"&&v.foundingDate.trim()!==""?N.foundingDate=new Date(v.foundingDate).toISOString():N.foundingDate=null,r?m.mutate(N):p.mutate(N)},x=p.isPending||m.isPending,b=p.error||m.error;return s.jsxs("div",{children:[s.jsx("h1",{className:"text-2xl font-bold mb-6",children:r?"Kunde bearbeiten":"Neuer Kunde"}),b&&s.jsx("div",{className:"mb-4 p-4 bg-red-50 border border-red-200 text-red-700 rounded-lg",children:b instanceof Error?b.message:"Ein Fehler ist aufgetreten"}),s.jsxs("form",{onSubmit:i(f),children:[s.jsx(Y,{className:"mb-6",title:"Stammdaten",children:s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[s.jsx(Re,{label:"Kundentyp",...a("type"),options:[{value:"PRIVATE",label:"Privatkunde"},{value:"BUSINESS",label:"Geschäftskunde"}]}),s.jsx(Re,{label:"Anrede",...a("salutation"),options:[{value:"Herr",label:"Herr"},{value:"Frau",label:"Frau"},{value:"Divers",label:"Divers"}]}),s.jsx(V,{label:"Vorname",...a("firstName",{required:"Vorname erforderlich"}),error:(y=d.firstName)==null?void 0:y.message}),s.jsx(V,{label:"Nachname",...a("lastName",{required:"Nachname erforderlich"}),error:(g=d.lastName)==null?void 0:g.message}),u==="BUSINESS"&&s.jsxs(s.Fragment,{children:[s.jsx(V,{label:"Firmenname",...a("companyName"),className:"md:col-span-2"}),s.jsx(V,{label:"Gründungsdatum",type:"date",...a("foundingDate"),value:o("foundingDate")||"",onClear:()=>c("foundingDate","")})]}),u!=="BUSINESS"&&s.jsxs(s.Fragment,{children:[s.jsx(V,{label:"Geburtsdatum",type:"date",...a("birthDate"),value:o("birthDate")||"",onClear:()=>c("birthDate","")}),s.jsx(V,{label:"Geburtsort",...a("birthPlace")})]})]})}),s.jsx(Y,{className:"mb-6",title:"Kontaktdaten",children:s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[s.jsx(V,{label:"E-Mail",type:"email",...a("email")}),s.jsx(V,{label:"Telefon",...a("phone")}),s.jsx(V,{label:"Mobil",...a("mobile")})]})}),u==="BUSINESS"&&s.jsxs(Y,{className:"mb-6",title:"Geschäftsdaten",children:[s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[s.jsx(V,{label:"Steuernummer",...a("taxNumber")}),s.jsx(V,{label:"Handelsregisternummer",...a("commercialRegisterNumber"),placeholder:"z.B. HRB 12345"})]}),r&&s.jsx("p",{className:"mt-4 text-sm text-gray-500",children:"Dokumente (Gewerbeanmeldung, Handelsregisterauszug) können nach dem Speichern in der Kundendetailansicht hochgeladen werden."})]}),s.jsx(Y,{className:"mb-6",title:"Notizen",children:s.jsx("textarea",{...a("notes"),rows:4,className:"block w-full px-3 py-2 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500",placeholder:"Interne Notizen..."})}),s.jsxs("div",{className:"flex justify-end gap-4",children:[s.jsx(F,{type:"button",variant:"secondary",onClick:()=>t(-1),children:"Abbrechen"}),s.jsx(F,{type:"submit",disabled:x,children:x?"Speichern...":"Speichern"})]})]})]})}const gd={ELECTRICITY:"Strom",GAS:"Gas",DSL:"DSL",CABLE:"Kabelinternet",FIBER:"Glasfaser",MOBILE:"Mobilfunk",TV:"TV",CAR_INSURANCE:"KFZ-Versicherung"},yd={DRAFT:"Entwurf",PENDING:"Ausstehend",ACTIVE:"Aktiv",CANCELLED:"Gekündigt",EXPIRED:"Abgelaufen",DEACTIVATED:"Deaktiviert"},Rx={ACTIVE:"success",PENDING:"warning",CANCELLED:"danger",EXPIRED:"danger",DRAFT:"default",DEACTIVATED:"default"},Vk=[{status:"DRAFT",label:"Entwurf",description:"Vertrag wird noch vorbereitet",color:"text-gray-600"},{status:"PENDING",label:"Ausstehend",description:"Wartet auf Aktivierung",color:"text-yellow-600"},{status:"ACTIVE",label:"Aktiv",description:"Vertrag läuft normal",color:"text-green-600"},{status:"EXPIRED",label:"Abgelaufen",description:"Laufzeit vorbei, läuft aber ohne Kündigung weiter",color:"text-orange-600"},{status:"CANCELLED",label:"Gekündigt",description:"Aktive Kündigung eingereicht, Vertrag endet",color:"text-red-600"},{status:"DEACTIVATED",label:"Deaktiviert",description:"Manuell beendet/archiviert",color:"text-gray-500"}];function Qk({isOpen:e,onClose:t}){return e?s.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[s.jsx("div",{className:"fixed inset-0 bg-black/20",onClick:t}),s.jsxs("div",{className:"relative bg-white rounded-lg shadow-xl p-4 max-w-sm w-full mx-4",children:[s.jsxs("div",{className:"flex items-center justify-between mb-3",children:[s.jsx("h3",{className:"text-sm font-semibold text-gray-900",children:"Vertragsstatus-Übersicht"}),s.jsx("button",{onClick:t,className:"text-gray-400 hover:text-gray-600",children:s.jsx(Vt,{className:"w-4 h-4"})})]}),s.jsx("div",{className:"space-y-2",children:Vk.map(({status:n,label:r,description:a,color:i})=>s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx("span",{className:`font-medium text-sm min-w-[90px] ${i}`,children:r}),s.jsx("span",{className:"text-sm text-gray-600",children:a})]},n))})]})]}):null}function Hk(){const[e,t]=wc(),n=ts(),[r,a]=j.useState(e.get("search")||""),[i,l]=j.useState(e.get("type")||""),[o,c]=j.useState(e.get("status")||""),[d,u]=j.useState(parseInt(e.get("page")||"1",10)),[h,p]=j.useState(new Set),[m,f]=j.useState(!1),{hasPermission:x,isCustomer:b,isCustomerPortal:y,user:g}=He(),v=xe();j.useEffect(()=>{const P=new URLSearchParams;r&&P.set("search",r),i&&P.set("type",i),o&&P.set("status",o),d>1&&P.set("page",d.toString()),t(P,{replace:!0})},[r,i,o,d,t]);const N=W({mutationFn:Le.delete,onSuccess:()=>{v.invalidateQueries({queryKey:["contracts"]})}}),{data:D,isLoading:A}=me({queryKey:["contracts",r,i,o,d,b?g==null?void 0:g.customerId:null],queryFn:()=>Le.getAll({search:r||void 0,type:i||void 0,status:o||void 0,page:d,limit:20,customerId:b?g==null?void 0:g.customerId:void 0})}),R=j.useMemo(()=>{if(!y||!(D!=null&&D.data))return[];const P=new Set;return g!=null&&g.customerId&&P.add(g.customerId),D.data.forEach(M=>P.add(M.customerId)),[...P]},[D==null?void 0:D.data,y,g==null?void 0:g.customerId]),w=t1({queries:R.map(P=>({queryKey:["contract-tree",P],queryFn:()=>Le.getTreeForCustomer(P),enabled:y}))}),S=j.useMemo(()=>{const P=new Map;return R.forEach((M,k)=>{var K;const _=w[k];(K=_==null?void 0:_.data)!=null&&K.data&&P.set(M,_.data.data)}),P},[R,w]),E=j.useMemo(()=>{if(!y||!(D!=null&&D.data))return null;const P={};for(const M of D.data){const k=M.customerId;if(!P[k]){const _=M.customer?M.customer.companyName||`${M.customer.firstName} ${M.customer.lastName}`:`Kunde ${k}`;P[k]={customerId:k,customerName:_,isOwn:k===(g==null?void 0:g.customerId),contracts:[],tree:S.get(k)||[]}}P[k].contracts.push(M)}return Object.values(P).sort((M,k)=>M.isOwn&&!k.isOwn?-1:!M.isOwn&&k.isOwn?1:M.customerName.localeCompare(k.customerName))},[D==null?void 0:D.data,y,g==null?void 0:g.customerId,S]),z=P=>{p(M=>{const k=new Set(M);return k.has(P)?k.delete(P):k.add(P),k})},I=(P,M)=>P.map(k=>s.jsx("div",{children:B(k,M)},k.contract.id)),B=(P,M=0)=>{var pe,oe,Ze,Oe,it,C,et;const{contract:k,predecessors:_,hasHistory:K}=P,Z=h.has(k.id),H=M>0;return s.jsxs("div",{children:[s.jsxs("div",{className:` border rounded-lg p-4 transition-colors ${H?"ml-6 border-l-4 border-l-gray-300 bg-gray-50":"hover:bg-gray-50"} `,children:[s.jsxs("div",{className:"flex items-center justify-between mb-2",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[!H&&K?s.jsx("button",{onClick:()=>z(k.id),className:"p-1 hover:bg-gray-200 rounded transition-colors",title:Z?"Einklappen":"Vorgänger anzeigen",children:Z?s.jsx(In,{className:"w-4 h-4 text-gray-500"}):s.jsx(Ft,{className:"w-4 h-4 text-gray-500"})}):H?null:s.jsx("div",{className:"w-6"}),s.jsxs("span",{className:"font-mono flex items-center gap-1",children:[k.contractNumber,s.jsx(ce,{value:k.contractNumber})]}),s.jsx(ye,{children:gd[k.type]||k.type}),s.jsx(ye,{variant:Rx[k.status]||"default",children:yd[k.status]||k.status}),H&&s.jsx("span",{className:"text-xs text-gray-500 ml-2",children:"(Vorgänger)"})]}),s.jsx("div",{className:"flex gap-2",children:s.jsx(F,{variant:"ghost",size:"sm",onClick:()=>n(`/contracts/${k.id}`,{state:{from:"contracts"}}),title:"Ansehen",children:s.jsx(Pe,{className:"w-4 h-4"})})})]}),(k.providerName||((pe=k.provider)==null?void 0:pe.name))&&s.jsxs("p",{className:`flex items-center gap-1 ${H?"ml-6":""}`,children:[k.providerName||((oe=k.provider)==null?void 0:oe.name),(k.tariffName||((Ze=k.tariff)==null?void 0:Ze.name))&&` - ${k.tariffName||((Oe=k.tariff)==null?void 0:Oe.name)}`,s.jsx(ce,{value:(k.providerName||((it=k.provider)==null?void 0:it.name)||"")+(k.tariffName||(C=k.tariff)!=null&&C.name?` - ${k.tariffName||((et=k.tariff)==null?void 0:et.name)}`:"")})]}),k.startDate&&s.jsxs("p",{className:`text-sm text-gray-500 ${H?"ml-6":""}`,children:["Beginn: ",new Date(k.startDate).toLocaleDateString("de-DE"),k.endDate&&` | Ende: ${new Date(k.endDate).toLocaleDateString("de-DE")}`]})]}),(M===0&&Z||M>0)&&_.length>0&&s.jsx("div",{className:"mt-2",children:I(_,M+1)})]},k.id)};return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center justify-between mb-6",children:[s.jsx("h1",{className:"text-2xl font-bold",children:"Verträge"}),x("contracts:create")&&!b&&s.jsx(ke,{to:"/contracts/new",children:s.jsxs(F,{children:[s.jsx(Be,{className:"w-4 h-4 mr-2"}),"Neuer Vertrag"]})})]}),s.jsx(Y,{className:"mb-6",children:s.jsxs("div",{className:"flex gap-4 flex-wrap",children:[s.jsx("div",{className:"flex-1 min-w-[200px]",children:s.jsx(V,{placeholder:"Suchen...",value:r,onChange:P=>a(P.target.value)})}),s.jsx(Re,{value:i,onChange:P=>l(P.target.value),options:Object.entries(gd).map(([P,M])=>({value:P,label:M})),className:"w-48"}),s.jsx(Re,{value:o,onChange:P=>c(P.target.value),options:Object.entries(yd).map(([P,M])=>({value:P,label:M})),className:"w-48"}),s.jsx(F,{variant:"secondary",children:s.jsx(Al,{className:"w-4 h-4"})})]})}),A?s.jsx(Y,{children:s.jsx("div",{className:"text-center py-8 text-gray-500",children:"Laden..."})}):D!=null&&D.data&&D.data.length>0?s.jsx(s.Fragment,{children:y&&E?s.jsx("div",{className:"space-y-6",children:E.map(P=>s.jsxs(Y,{children:[s.jsx("div",{className:"flex items-center gap-3 mb-4 pb-3 border-b",children:P.isOwn?s.jsxs(s.Fragment,{children:[s.jsx(Tl,{className:"w-5 h-5 text-blue-600"}),s.jsx("h2",{className:"text-lg font-semibold text-gray-900",children:"Meine Verträge"}),s.jsx(ye,{variant:"default",children:P.contracts.length})]}):s.jsxs(s.Fragment,{children:[s.jsx(ka,{className:"w-5 h-5 text-purple-600"}),s.jsxs("h2",{className:"text-lg font-semibold text-gray-900",children:["Verträge von ",P.customerName]}),s.jsx(ye,{variant:"default",children:P.contracts.length})]})}),P.tree.length>0?s.jsx("div",{className:"space-y-4",children:P.tree.map(M=>B(M,0))}):s.jsx("p",{className:"text-gray-500",children:"Keine Verträge vorhanden."})]},P.isOwn?"own":P.customerName))}):s.jsxs(Y,{children:[s.jsx("div",{className:"overflow-x-auto",children:s.jsxs("table",{className:"w-full",children:[s.jsx("thead",{children:s.jsxs("tr",{className:"border-b",children:[s.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"Vertragsnr."}),!b&&s.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"Kunde"}),s.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"Typ"}),s.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"Anbieter / Tarif"}),s.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:s.jsxs("span",{className:"flex items-center gap-1",children:["Status",s.jsx("button",{onClick:()=>f(!0),className:"text-gray-400 hover:text-blue-600 transition-colors",title:"Status-Erklärung",children:s.jsx(Pl,{className:"w-4 h-4"})})]})}),s.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"Beginn"}),s.jsx("th",{className:"text-right py-3 px-4 font-medium text-gray-600",children:"Aktionen"})]})}),s.jsx("tbody",{children:D.data.map(P=>s.jsxs("tr",{className:"border-b hover:bg-gray-50",children:[s.jsx("td",{className:"py-3 px-4 font-mono text-sm",children:P.contractNumber}),!b&&s.jsx("td",{className:"py-3 px-4",children:P.customer&&s.jsx(ke,{to:`/customers/${P.customer.id}`,className:"text-blue-600 hover:underline",children:P.customer.companyName||`${P.customer.firstName} ${P.customer.lastName}`})}),s.jsx("td",{className:"py-3 px-4",children:s.jsx(ye,{children:gd[P.type]})}),s.jsxs("td",{className:"py-3 px-4",children:[P.providerName||"-",P.tariffName&&s.jsxs("span",{className:"text-gray-500",children:[" / ",P.tariffName]})]}),s.jsx("td",{className:"py-3 px-4",children:s.jsx(ye,{variant:Rx[P.status],children:yd[P.status]})}),s.jsx("td",{className:"py-3 px-4",children:P.startDate?new Date(P.startDate).toLocaleDateString("de-DE"):"-"}),s.jsx("td",{className:"py-3 px-4 text-right",children:s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx(F,{variant:"ghost",size:"sm",onClick:()=>n(`/contracts/${P.id}`,{state:{from:"contracts"}}),children:s.jsx(Pe,{className:"w-4 h-4"})}),x("contracts:update")&&!b&&s.jsx(ke,{to:`/contracts/${P.id}/edit`,children:s.jsx(F,{variant:"ghost",size:"sm",children:s.jsx(Ye,{className:"w-4 h-4"})})}),x("contracts:delete")&&!b&&s.jsx(F,{variant:"ghost",size:"sm",onClick:()=>{confirm("Vertrag wirklich löschen?")&&N.mutate(P.id)},children:s.jsx(be,{className:"w-4 h-4 text-red-500"})})]})})]},P.id))})]})}),D.pagination&&D.pagination.totalPages>1&&s.jsxs("div",{className:"mt-4 flex items-center justify-between",children:[s.jsxs("p",{className:"text-sm text-gray-500",children:["Seite ",D.pagination.page," von ",D.pagination.totalPages," (",D.pagination.total," Einträge)"]}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx(F,{variant:"secondary",size:"sm",onClick:()=>u(P=>Math.max(1,P-1)),disabled:d===1,children:"Zurück"}),s.jsx(F,{variant:"secondary",size:"sm",onClick:()=>u(P=>P+1),disabled:d>=D.pagination.totalPages,children:"Weiter"})]})]})]})}):s.jsx(Y,{children:s.jsx("div",{className:"text-center py-8 text-gray-500",children:"Keine Verträge gefunden."})}),s.jsx(Qk,{isOpen:m,onClose:()=>f(!1)})]})}const Wk={ELECTRICITY:"Strom",GAS:"Gas",DSL:"DSL",CABLE:"Kabelinternet",FIBER:"Glasfaser",MOBILE:"Mobilfunk",TV:"TV",CAR_INSURANCE:"KFZ-Versicherung"},Gk={DRAFT:"Entwurf",PENDING:"Ausstehend",ACTIVE:"Aktiv",CANCELLED:"Gekündigt",EXPIRED:"Abgelaufen",DEACTIVATED:"Deaktiviert"},Zk={ACTIVE:"success",PENDING:"warning",CANCELLED:"danger",EXPIRED:"danger",DRAFT:"default",DEACTIVATED:"default"};function Jk({contractId:e,isOpen:t,onClose:n}){var o,c,d,u,h,p,m,f,x,b;const{data:r,isLoading:a,error:i}=me({queryKey:["contract",e],queryFn:()=>Le.getById(e),enabled:t}),l=r==null?void 0:r.data;return s.jsxs(Ve,{isOpen:t,onClose:n,title:"Vertragsdetails",size:"xl",children:[a&&s.jsx("div",{className:"text-center py-8 text-gray-500",children:"Laden..."}),i&&s.jsx("div",{className:"text-center py-8 text-red-600",children:"Fehler beim Laden des Vertrags"}),l&&s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"flex items-center gap-3 pb-4 border-b",children:[s.jsxs("span",{className:"text-xl font-bold font-mono flex items-center gap-2",children:[l.contractNumber,s.jsx(ce,{value:l.contractNumber})]}),s.jsx(ye,{children:Wk[l.type]||l.type}),s.jsx(ye,{variant:Zk[l.status]||"default",children:Gk[l.status]||l.status})]}),(l.providerName||((o=l.provider)==null?void 0:o.name)||l.tariffName||((c=l.tariff)==null?void 0:c.name))&&s.jsx(Y,{title:"Anbieter & Tarif",children:s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[(l.providerName||((d=l.provider)==null?void 0:d.name))&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Anbieter"}),s.jsxs("dd",{className:"flex items-center gap-1",children:[l.providerName||((u=l.provider)==null?void 0:u.name),s.jsx(ce,{value:l.providerName||((h=l.provider)==null?void 0:h.name)||""})]})]}),(l.tariffName||((p=l.tariff)==null?void 0:p.name))&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Tarif"}),s.jsxs("dd",{className:"flex items-center gap-1",children:[l.tariffName||((m=l.tariff)==null?void 0:m.name),s.jsx(ce,{value:l.tariffName||((f=l.tariff)==null?void 0:f.name)||""})]})]}),l.customerNumberAtProvider&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Kundennummer beim Anbieter"}),s.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[l.customerNumberAtProvider,s.jsx(ce,{value:l.customerNumberAtProvider})]})]})]})}),s.jsx(Y,{title:"Laufzeit",children:s.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[l.startDate&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Vertragsbeginn"}),s.jsx("dd",{children:new Date(l.startDate).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"})})]}),l.endDate&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Vertragsende"}),s.jsx("dd",{children:new Date(l.endDate).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"})})]}),l.contractDuration&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Laufzeit"}),s.jsx("dd",{children:l.contractDuration.description})]}),l.cancellationPeriod&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Kündigungsfrist"}),s.jsx("dd",{children:l.cancellationPeriod.description})]})]})}),(l.portalUsername||((x=l.provider)==null?void 0:x.portalUrl))&&s.jsx(Y,{title:"Portal-Zugangsdaten",children:s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[((b=l.provider)==null?void 0:b.portalUrl)&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Portal-URL"}),s.jsx("dd",{children:s.jsx("a",{href:l.provider.portalUrl,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:underline",children:l.provider.portalUrl})})]}),l.portalUsername&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Benutzername"}),s.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[l.portalUsername,s.jsx(ce,{value:l.portalUsername})]})]})]})}),l.address&&s.jsxs(Y,{title:"Lieferadresse",children:[s.jsxs("p",{children:[l.address.street," ",l.address.houseNumber]}),s.jsxs("p",{children:[l.address.postalCode," ",l.address.city]})]}),l.notes&&s.jsx(Y,{title:"Notizen",children:s.jsx("p",{className:"whitespace-pre-wrap text-gray-700",children:l.notes})})]})]})}const Lx={INTERIM:"Zwischenrechnung",FINAL:"Schlussrechnung",NOT_AVAILABLE:"Nicht verfügbar"};function Xk({ecdId:e,invoices:t,contractId:n,canEdit:r}){const[a,i]=j.useState(!1),[l,o]=j.useState(!1),[c,d]=j.useState(null),u=xe(),h=W({mutationFn:x=>ra.deleteInvoice(e,x),onSuccess:()=>{u.invalidateQueries({queryKey:["contract",n.toString()]})}}),p=[...t].sort((x,b)=>new Date(b.invoiceDate).getTime()-new Date(x.invoiceDate).getTime()),m=t.some(x=>x.invoiceType==="FINAL"),f=t.some(x=>x.invoiceType==="NOT_AVAILABLE");return s.jsxs("div",{className:"mt-4 pt-4 border-t",children:[s.jsxs("div",{className:"flex items-center justify-between mb-3",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Ke,{className:"w-4 h-4 text-gray-500"}),s.jsx("h4",{className:"text-sm font-medium text-gray-700",children:"Rechnungen"}),s.jsx(ye,{variant:"default",children:t.length}),m?s.jsxs("span",{className:"flex items-center gap-1 px-2 py-0.5 text-xs rounded-full bg-green-100 text-green-800",children:[s.jsx(fr,{className:"w-3 h-3"}),"Schlussrechnung"]}):f?s.jsxs("span",{className:"flex items-center gap-1 px-2 py-0.5 text-xs rounded-full bg-yellow-100 text-yellow-800",children:[s.jsx(hs,{className:"w-3 h-3"}),"Nicht verfügbar"]}):t.length>0?s.jsxs("span",{className:"flex items-center gap-1 px-2 py-0.5 text-xs rounded-full bg-orange-100 text-orange-800",children:[s.jsx(hs,{className:"w-3 h-3"}),"Schlussrechnung fehlt"]}):null]}),s.jsxs("div",{className:"flex items-center gap-2",children:[r&&s.jsx(F,{variant:"ghost",size:"sm",onClick:()=>o(!0),children:s.jsx(Be,{className:"w-4 h-4"})}),t.length>0&&s.jsx("button",{onClick:()=>i(!a),className:"text-gray-500 hover:text-gray-700",children:a?s.jsx(ih,{className:"w-4 h-4"}):s.jsx(In,{className:"w-4 h-4"})})]})]}),!a&&p.length>0&&s.jsxs("div",{className:"text-sm text-gray-600",children:["Letzte: ",new Date(p[0].invoiceDate).toLocaleDateString("de-DE")," - ",Lx[p[0].invoiceType]]}),a&&p.length>0&&s.jsx("div",{className:"space-y-2",children:p.map(x=>s.jsxs("div",{className:"flex items-center justify-between p-3 bg-gray-50 rounded-lg group",children:[s.jsxs("div",{className:"flex items-center gap-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium",children:new Date(x.invoiceDate).toLocaleDateString("de-DE")}),s.jsx("div",{className:"text-xs text-gray-500",children:Lx[x.invoiceType]})]}),x.documentPath&&s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("a",{href:`/api${x.documentPath}`,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1 text-blue-600 hover:text-blue-800 text-sm",title:"Anzeigen",children:s.jsx(Pe,{className:"w-4 h-4"})}),s.jsx("a",{href:`/api${x.documentPath}`,download:!0,className:"flex items-center gap-1 text-blue-600 hover:text-blue-800 text-sm",title:"Download",children:s.jsx(As,{className:"w-4 h-4"})})]}),x.notes&&s.jsx("span",{className:"text-xs text-gray-400 italic",children:x.notes})]}),r&&s.jsxs("div",{className:"flex items-center gap-2 opacity-0 group-hover:opacity-100",children:[s.jsx("button",{onClick:()=>d(x),className:"text-gray-500 hover:text-blue-600",title:"Bearbeiten",children:s.jsx(Ye,{className:"w-4 h-4"})}),s.jsx("button",{onClick:()=>{confirm("Rechnung wirklich löschen?")&&h.mutate(x.id)},className:"text-gray-500 hover:text-red-600",title:"Löschen",children:s.jsx(be,{className:"w-4 h-4"})})]})]},x.id))}),a&&p.length===0&&s.jsx("p",{className:"text-sm text-gray-500 italic",children:"Keine Rechnungen vorhanden."}),(l||c)&&s.jsx(Yk,{isOpen:!0,onClose:()=>{o(!1),d(null)},ecdId:e,contractId:n,invoice:c})]})}function Yk({isOpen:e,onClose:t,ecdId:n,contractId:r,invoice:a}){const i=xe(),l=!!a,o=j.useRef(null),[c,d]=j.useState({invoiceDate:a!=null&&a.invoiceDate?new Date(a.invoiceDate).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],invoiceType:(a==null?void 0:a.invoiceType)||"INTERIM",notes:(a==null?void 0:a.notes)||""}),[u,h]=j.useState(null),[p,m]=j.useState(null),f=W({mutationFn:async N=>{var A;const D=await ra.addInvoice(n,{invoiceDate:c.invoiceDate,invoiceType:c.invoiceType,notes:c.notes||void 0});return(A=D.data)!=null&&A.id&&await ra.uploadDocument(D.data.id,N),D},onSuccess:()=>{i.invalidateQueries({queryKey:["contract",r.toString()]}),t()},onError:N=>{m(N.message)}}),x=W({mutationFn:async()=>await ra.addInvoice(n,{invoiceDate:c.invoiceDate,invoiceType:c.invoiceType,notes:c.notes||void 0}),onSuccess:()=>{i.invalidateQueries({queryKey:["contract",r.toString()]}),t()},onError:N=>{m(N.message)}}),b=W({mutationFn:async N=>{const D=await ra.updateInvoice(n,a.id,{invoiceDate:c.invoiceDate,invoiceType:c.invoiceType,notes:c.notes||void 0});return N&&await ra.uploadDocument(a.id,N),D},onSuccess:()=>{i.invalidateQueries({queryKey:["contract",r.toString()]}),t()},onError:N=>{m(N.message)}}),y=N=>{if(N.preventDefault(),m(null),l){if(c.invoiceType!=="NOT_AVAILABLE"&&!(a!=null&&a.documentPath)&&!u){m("Bitte laden Sie ein Dokument hoch");return}b.mutate(u)}else if(c.invoiceType==="NOT_AVAILABLE")x.mutate();else if(u)f.mutate(u);else{m("Bitte laden Sie ein Dokument hoch");return}},g=N=>{var A;const D=(A=N.target.files)==null?void 0:A[0];if(D){if(D.type!=="application/pdf"){m("Nur PDF-Dateien sind erlaubt");return}if(D.size>10*1024*1024){m("Datei ist zu groß (max. 10 MB)");return}h(D),m(null)}},v=f.isPending||x.isPending||b.isPending;return s.jsx(Ve,{isOpen:e,onClose:t,title:l?"Rechnung bearbeiten":"Rechnung hinzufügen",children:s.jsxs("form",{onSubmit:y,className:"space-y-4",children:[p&&s.jsx("div",{className:"p-3 bg-red-50 border border-red-200 rounded-lg text-red-700 text-sm",children:p}),s.jsx(V,{label:"Rechnungsdatum",type:"date",value:c.invoiceDate,onChange:N=>d({...c,invoiceDate:N.target.value}),required:!0}),s.jsx(Re,{label:"Rechnungstyp",value:c.invoiceType,onChange:N=>d({...c,invoiceType:N.target.value}),options:[{value:"INTERIM",label:"Zwischenrechnung"},{value:"FINAL",label:"Schlussrechnung"},{value:"NOT_AVAILABLE",label:"Nicht verfügbar"}]}),c.invoiceType!=="NOT_AVAILABLE"&&s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Dokument (PDF) *"}),(a==null?void 0:a.documentPath)&&!u&&s.jsxs("div",{className:"mb-2 text-sm text-green-600 flex items-center gap-1",children:[s.jsx(fr,{className:"w-4 h-4"}),"Dokument vorhanden"]}),u&&s.jsxs("div",{className:"mb-2 text-sm text-blue-600 flex items-center gap-1",children:[s.jsx(Ke,{className:"w-4 h-4"}),u.name]}),s.jsx("input",{type:"file",ref:o,accept:".pdf",onChange:g,className:"hidden"}),s.jsx(F,{type:"button",variant:"secondary",onClick:()=>{var N;return(N=o.current)==null?void 0:N.click()},children:a!=null&&a.documentPath||u?"Ersetzen":"PDF hochladen"})]}),c.invoiceType==="NOT_AVAILABLE"&&s.jsx("div",{className:"p-3 bg-yellow-50 border border-yellow-200 rounded-lg text-yellow-800 text-sm",children:'Bei diesem Typ wird kein Dokument benötigt. Die Rechnung wird als "nicht mehr zu bekommen" markiert.'}),s.jsx(V,{label:"Notizen (optional)",value:c.notes,onChange:N=>d({...c,notes:N.target.value}),placeholder:"Optionale Anmerkungen..."}),s.jsxs("div",{className:"flex justify-end gap-3 pt-4",children:[s.jsx(F,{type:"button",variant:"secondary",onClick:t,children:"Abbrechen"}),s.jsx(F,{type:"submit",disabled:v,children:v?"Wird gespeichert...":l?"Speichern":"Hinzufügen"})]})]})})}const eC=10.5;function Ox(e,t){const n=new Date(e),r=new Date(t);n.setHours(0,0,0,0),r.setHours(0,0,0,0);const a=r.getTime()-n.getTime();return Math.ceil(a/(1e3*60*60*24))}function tC(e,t,n){const r=new Date(t),a=new Date(n);return r.setHours(0,0,0,0),a.setHours(0,0,0,0),e.filter(i=>{const l=new Date(i.readingDate);return l.setHours(0,0,0,0),l>=r&&l<=a})}function sC(e,t,n,r){const a=tC(e,t,n);if(a.length===0)return{type:"none",consumptionKwh:0};if(a.length===1)return{type:"insufficient",consumptionKwh:0,message:"Berechnung auf Grund fehlender Stände nicht möglich"};const i=[...a].sort((f,x)=>new Date(f.readingDate).getTime()-new Date(x.readingDate).getTime()),l=i[0],o=i[i.length-1],c=new Date(o.readingDate),d=new Date(n);if(c.setHours(0,0,0,0),d.setHours(0,0,0,0),c>=d){const f=o.value-l.value;return zx("exact",f,r,l,o)}const u=Ox(l.readingDate,o.readingDate);if(u<1)return{type:"insufficient",consumptionKwh:0,message:"Zeitraum zwischen Zählerständen zu kurz für Berechnung"};const h=Ox(t,n),m=(o.value-l.value)/u*h;return zx("projected",m,r,l,o,n)}function zx(e,t,n,r,a,i){return n==="GAS"?{type:e,consumptionM3:t,consumptionKwh:t*eC,startReading:r,endReading:a,projectedEndDate:i}:{type:e,consumptionKwh:t,startReading:r,endReading:a,projectedEndDate:i}}function nC(e,t,n,r){if(t==null&&n==null)return null;const a=(t??0)*12,i=e*(n??0),l=a+i,o=l-(r??0),c=o/12;return{annualBaseCost:a,annualConsumptionCost:i,annualTotalCost:l,monthlyPayment:c,bonus:r??void 0,effectiveAnnualCost:o}}const rC={ELECTRICITY:"Strom",GAS:"Gas",DSL:"DSL",CABLE:"Kabelinternet",FIBER:"Glasfaser",MOBILE:"Mobilfunk",TV:"TV",CAR_INSURANCE:"KFZ-Versicherung"},aC={DRAFT:"Entwurf",PENDING:"Ausstehend",ACTIVE:"Aktiv",CANCELLED:"Gekündigt",EXPIRED:"Abgelaufen",DEACTIVATED:"Deaktiviert"},iC={ACTIVE:"success",PENDING:"warning",CANCELLED:"danger",EXPIRED:"danger",DRAFT:"default",DEACTIVATED:"default"},lC=[{status:"DRAFT",label:"Entwurf",description:"Vertrag wird noch vorbereitet",color:"text-gray-600"},{status:"PENDING",label:"Ausstehend",description:"Wartet auf Aktivierung",color:"text-yellow-600"},{status:"ACTIVE",label:"Aktiv",description:"Vertrag läuft normal",color:"text-green-600"},{status:"EXPIRED",label:"Abgelaufen",description:"Laufzeit vorbei, läuft aber ohne Kündigung weiter",color:"text-orange-600"},{status:"CANCELLED",label:"Gekündigt",description:"Aktive Kündigung eingereicht, Vertrag endet",color:"text-red-600"},{status:"DEACTIVATED",label:"Deaktiviert",description:"Manuell beendet/archiviert",color:"text-gray-500"}];function oC({isOpen:e,onClose:t}){return e?s.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[s.jsx("div",{className:"fixed inset-0 bg-black/20",onClick:t}),s.jsxs("div",{className:"relative bg-white rounded-lg shadow-xl p-4 max-w-sm w-full mx-4",children:[s.jsxs("div",{className:"flex items-center justify-between mb-3",children:[s.jsx("h3",{className:"text-sm font-semibold text-gray-900",children:"Vertragsstatus-Übersicht"}),s.jsx("button",{onClick:t,className:"text-gray-400 hover:text-gray-600",children:s.jsx(Vt,{className:"w-4 h-4"})})]}),s.jsx("div",{className:"space-y-2",children:lC.map(({status:n,label:r,description:a,color:i})=>s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx("span",{className:`font-medium text-sm min-w-[90px] ${i}`,children:r}),s.jsx("span",{className:"text-sm text-gray-600",children:a})]},n))})]})]}):null}function cC(e){const t=e.match(/^(\d+)([TMWJ])$/);if(!t)return!1;const n=parseInt(t[1]),r=t[2];let a=0;return r==="T"?a=n:r==="W"?a=n*7:r==="M"?a=n*30:r==="J"&&(a=n*365),a<=30}function dC({simCard:e}){const[t,n]=j.useState(!1),[r,a]=j.useState(null),[i,l]=j.useState(!1),o=async()=>{if(t)n(!1),a(null);else{l(!0);try{const c=await Le.getSimCardCredentials(e.id);c.data&&(a(c.data),n(!0))}catch{alert("PIN/PUK konnte nicht geladen werden")}finally{l(!1)}}};return s.jsxs("div",{className:"p-3 bg-gray-50 rounded-lg border",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.isMain&&s.jsx(ye,{variant:"success",children:"Hauptkarte"}),e.isMultisim&&s.jsx(ye,{variant:"warning",children:"Multisim"})]}),s.jsxs("dl",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 text-sm",children:[e.phoneNumber&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-gray-500",children:"Rufnummer"}),s.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[e.phoneNumber,s.jsx(ce,{value:e.phoneNumber})]})]}),e.simCardNumber&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-gray-500",children:"SIM-Nr."}),s.jsxs("dd",{className:"font-mono text-xs flex items-center gap-1",children:[e.simCardNumber,s.jsx(ce,{value:e.simCardNumber})]})]}),s.jsxs("div",{children:[s.jsx("dt",{className:"text-gray-500",children:"PIN"}),s.jsx("dd",{className:"font-mono flex items-center gap-1",children:t&&(r!=null&&r.pin)?s.jsxs(s.Fragment,{children:[r.pin,s.jsx(ce,{value:r.pin})]}):"••••"})]}),s.jsxs("div",{children:[s.jsx("dt",{className:"text-gray-500",children:"PUK"}),s.jsx("dd",{className:"font-mono flex items-center gap-1",children:t&&(r!=null&&r.puk)?s.jsxs(s.Fragment,{children:[r.puk,s.jsx(ce,{value:r.puk})]}):"••••••••"})]})]}),s.jsx("div",{className:"mt-2",children:s.jsx(F,{variant:"ghost",size:"sm",onClick:o,disabled:i,children:i?"Laden...":t?s.jsxs(s.Fragment,{children:[s.jsx(It,{className:"w-4 h-4 mr-1"})," PIN/PUK verbergen"]}):s.jsxs(s.Fragment,{children:[s.jsx(Pe,{className:"w-4 h-4 mr-1"})," PIN/PUK anzeigen"]})})})]})}function uC({meterId:e,meterType:t,readings:n,contractId:r,canEdit:a}){const[i,l]=j.useState(!1),[o,c]=j.useState(!1),[d,u]=j.useState(null),h=xe(),p=W({mutationFn:x=>ln.deleteReading(e,x),onSuccess:()=>{h.invalidateQueries({queryKey:["contract",r.toString()]})}}),m=[...n].sort((x,b)=>new Date(b.readingDate).getTime()-new Date(x.readingDate).getTime()),f=t==="ELECTRICITY"?"kWh":"m³";return s.jsxs("div",{className:"mt-4 pt-4 border-t",children:[s.jsxs("div",{className:"flex items-center justify-between mb-3",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Ev,{className:"w-4 h-4 text-gray-500"}),s.jsx("h4",{className:"text-sm font-medium text-gray-700",children:"Zählerstände"}),s.jsx(ye,{variant:"default",children:n.length})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[a&&s.jsx(F,{variant:"ghost",size:"sm",onClick:()=>c(!0),title:"Zählerstand erfassen",children:s.jsx(Be,{className:"w-4 h-4"})}),n.length>0&&s.jsx(F,{variant:"ghost",size:"sm",onClick:()=>l(!i),children:i?s.jsx(ih,{className:"w-4 h-4"}):s.jsx(In,{className:"w-4 h-4"})})]})]}),i&&n.length>0&&s.jsx("div",{className:"space-y-2 bg-gray-50 rounded-lg p-3",children:m.map(x=>s.jsxs("div",{className:"flex justify-between items-center text-sm group py-1 border-b border-gray-200 last:border-0",children:[s.jsxs("span",{className:"text-gray-500 flex items-center gap-1",children:[new Date(x.readingDate).toLocaleDateString("de-DE"),s.jsx(ce,{value:new Date(x.readingDate).toLocaleDateString("de-DE")})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("span",{className:"font-mono flex items-center gap-1",children:[x.value.toLocaleString("de-DE")," ",x.unit,s.jsx(ce,{value:x.value.toString(),title:"Nur Wert kopieren"})]}),a&&s.jsxs("div",{className:"opacity-0 group-hover:opacity-100 flex gap-1",children:[s.jsx("button",{onClick:()=>u(x),className:"text-gray-400 hover:text-blue-600",title:"Bearbeiten",children:s.jsx(Ye,{className:"w-3 h-3"})}),s.jsx("button",{onClick:()=>{confirm("Zählerstand wirklich löschen?")&&p.mutate(x.id)},className:"text-gray-400 hover:text-red-600",title:"Löschen",children:s.jsx(be,{className:"w-3 h-3"})})]})]})]},x.id))}),!i&&n.length>0&&s.jsxs("p",{className:"text-sm text-gray-500",children:["Letzter Stand: ",m[0].value.toLocaleString("de-DE")," ",m[0].unit," (",new Date(m[0].readingDate).toLocaleDateString("de-DE"),")"]}),n.length===0&&s.jsx("p",{className:"text-sm text-gray-500",children:"Keine Zählerstände vorhanden."}),(o||d)&&s.jsx(mC,{isOpen:!0,onClose:()=>{c(!1),u(null)},meterId:e,contractId:r,reading:d,defaultUnit:f})]})}function mC({isOpen:e,onClose:t,meterId:n,contractId:r,reading:a,defaultUnit:i}){var f;const l=xe(),o=!!a,[c,d]=j.useState({readingDate:a!=null&&a.readingDate?new Date(a.readingDate).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],value:((f=a==null?void 0:a.value)==null?void 0:f.toString())||"",notes:(a==null?void 0:a.notes)||""}),u=W({mutationFn:x=>ln.addReading(n,x),onSuccess:()=>{l.invalidateQueries({queryKey:["contract",r.toString()]}),t()}}),h=W({mutationFn:x=>ln.updateReading(n,a.id,x),onSuccess:()=>{l.invalidateQueries({queryKey:["contract",r.toString()]}),t()}}),p=x=>{x.preventDefault();const b={readingDate:new Date(c.readingDate),value:parseFloat(c.value),unit:i,notes:c.notes||void 0};o?h.mutate(b):u.mutate(b)},m=u.isPending||h.isPending;return s.jsx(Ve,{isOpen:e,onClose:t,title:o?"Zählerstand bearbeiten":"Zählerstand erfassen",children:s.jsxs("form",{onSubmit:p,className:"space-y-4",children:[s.jsx(V,{label:"Ablesedatum",type:"date",value:c.readingDate,onChange:x=>d({...c,readingDate:x.target.value}),required:!0}),s.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[s.jsx("div",{className:"col-span-2",children:s.jsx(V,{label:"Zählerstand",type:"number",step:"0.01",value:c.value,onChange:x=>d({...c,value:x.target.value}),required:!0})}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Einheit"}),s.jsx("div",{className:"h-10 flex items-center px-3 bg-gray-100 border border-gray-300 rounded-md text-gray-700",children:i})]})]}),s.jsx(V,{label:"Notizen (optional)",value:c.notes,onChange:x=>d({...c,notes:x.target.value})}),s.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[s.jsx(F,{type:"button",variant:"secondary",onClick:t,children:"Abbrechen"}),s.jsx(F,{type:"submit",disabled:m||!c.value,children:m?"Speichern...":o?"Speichern":"Erfassen"})]})]})})}function hC({contractType:e,readings:t,startDate:n,endDate:r,basePrice:a,unitPrice:i,bonus:l}){const o=sC(t,n,r,e),c=o.consumptionKwh>0?nC(o.consumptionKwh,a,i,l):null;if(o.type==="none")return null;const d=(h,p=2)=>h.toLocaleString("de-DE",{minimumFractionDigits:p,maximumFractionDigits:p}),u=h=>new Date(h).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"});return s.jsxs("div",{className:"mt-4 pt-4 border-t",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[s.jsx(P2,{className:"w-4 h-4 text-gray-500"}),s.jsx("h4",{className:"text-sm font-medium text-gray-700",children:"Verbrauch & Kosten"}),o.type==="exact"&&s.jsx(ye,{variant:"success",children:"Exakt"}),o.type==="projected"&&s.jsx(ye,{variant:"warning",children:"Hochrechnung"})]}),o.type==="insufficient"?s.jsx("p",{className:"text-sm text-gray-500 italic",children:o.message}):s.jsxs("div",{className:"bg-gray-50 rounded-lg p-4 space-y-4",children:[s.jsxs("div",{children:[s.jsxs("h5",{className:"text-sm font-medium text-gray-600 mb-2",children:["Berechneter Verbrauch",o.type==="projected"&&" (hochgerechnet)"]}),s.jsx("div",{className:"text-lg font-semibold text-gray-900",children:e==="GAS"?s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"font-mono",children:[d(o.consumptionM3||0)," m³"]}),s.jsxs("span",{className:"text-gray-500 text-sm ml-2",children:["= ",d(o.consumptionKwh)," kWh"]})]}):s.jsxs("span",{className:"font-mono",children:[d(o.consumptionKwh)," kWh"]})}),o.startReading&&o.endReading&&s.jsxs("p",{className:"text-xs text-gray-400 mt-1",children:["Basierend auf Zählerständen vom ",u(o.startReading.readingDate)," bis ",u(o.endReading.readingDate)]})]}),c&&s.jsxs("div",{className:"border-t border-gray-200 pt-4",children:[s.jsx("h5",{className:"text-sm font-medium text-gray-600 mb-3",children:"Kostenvorschau"}),s.jsxs("div",{className:"space-y-2 text-sm",children:[a!=null&&a>0&&s.jsxs("div",{className:"flex justify-between",children:[s.jsxs("span",{className:"text-gray-600",children:["Grundpreis: ",d(a)," €/Mon × 12"]}),s.jsxs("span",{className:"font-mono",children:[d(c.annualBaseCost)," €"]})]}),i!=null&&i>0&&s.jsxs("div",{className:"flex justify-between",children:[s.jsxs("span",{className:"text-gray-600",children:["Arbeitspreis: ",d(o.consumptionKwh)," kWh × ",d(i,4)," €"]}),s.jsxs("span",{className:"font-mono",children:[d(c.annualConsumptionCost)," €"]})]}),s.jsx("div",{className:"border-t border-gray-300 pt-2",children:s.jsxs("div",{className:"flex justify-between font-medium",children:[s.jsx("span",{className:"text-gray-700",children:"Jahreskosten"}),s.jsxs("span",{className:"font-mono",children:[d(c.annualTotalCost)," €"]})]})}),c.bonus!=null&&c.bonus>0&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex justify-between text-green-600",children:[s.jsx("span",{children:"Bonus"}),s.jsxs("span",{className:"font-mono",children:["- ",d(c.bonus)," €"]})]}),s.jsx("div",{className:"border-t border-gray-300 pt-2",children:s.jsxs("div",{className:"flex justify-between font-semibold",children:[s.jsx("span",{className:"text-gray-800",children:"Effektive Jahreskosten"}),s.jsxs("span",{className:"font-mono",children:[d(c.effectiveAnnualCost)," €"]})]})})]}),s.jsx("div",{className:"border-t border-gray-300 pt-2 mt-2",children:s.jsxs("div",{className:"flex justify-between text-blue-700 font-semibold",children:[s.jsx("span",{children:"Monatlicher Abschlag"}),s.jsxs("span",{className:"font-mono",children:[d(c.monthlyPayment)," €"]})]})})]})]})]})]})}function $x({task:e,contractId:t,canEdit:n,isCustomerPortal:r,isCompleted:a,onEdit:i}){const[l,o]=j.useState(""),[c,d]=j.useState(!1),[u,h]=j.useState(null),[p,m]=j.useState(""),f=xe(),x=W({mutationFn:_=>ut.complete(_),onSuccess:async()=>{await f.refetchQueries({queryKey:["contract-tasks",t]})}}),b=W({mutationFn:_=>ut.reopen(_),onSuccess:async()=>{await f.refetchQueries({queryKey:["contract-tasks",t]})}}),y=W({mutationFn:_=>ut.delete(_),onSuccess:async()=>{await f.refetchQueries({queryKey:["contract-tasks",t]})}}),g=W({mutationFn:_=>ut.createSubtask(e.id,_),onSuccess:async()=>{await f.refetchQueries({queryKey:["contract-tasks",t]}),o(""),d(!1)},onError:_=>{console.error("Fehler beim Erstellen der Unteraufgabe:",_),alert("Fehler beim Erstellen der Unteraufgabe. Bitte versuchen Sie es erneut.")}}),v=W({mutationFn:_=>ut.createReply(e.id,_),onSuccess:async()=>{await f.refetchQueries({queryKey:["contract-tasks",t]}),o(""),d(!1)},onError:_=>{console.error("Fehler beim Erstellen der Antwort:",_),alert("Fehler beim Erstellen der Antwort. Bitte versuchen Sie es erneut.")}}),N=W({mutationFn:({id:_,title:K})=>ut.updateSubtask(_,K),onSuccess:async()=>{await f.refetchQueries({queryKey:["contract-tasks",t]}),h(null),m("")}}),D=W({mutationFn:_=>ut.completeSubtask(_),onSuccess:async()=>{await f.refetchQueries({queryKey:["contract-tasks",t]})}}),A=W({mutationFn:_=>ut.reopenSubtask(_),onSuccess:async()=>{await f.refetchQueries({queryKey:["contract-tasks",t]})}}),R=W({mutationFn:_=>ut.deleteSubtask(_),onSuccess:async()=>{await f.refetchQueries({queryKey:["contract-tasks",t]})}}),w=_=>{_.preventDefault(),l.trim()&&(r?v.mutate(l.trim()):g.mutate(l.trim()))},S=_=>{_.preventDefault(),p.trim()&&u&&N.mutate({id:u,title:p.trim()})},E=(_,K)=>{h(_),m(K)},z=()=>{h(null),m("")},I=e.subtasks||[],B=I.filter(_=>_.status==="OPEN"),P=I.filter(_=>_.status==="COMPLETED"),M=r?{singular:"Antwort",placeholder:"Antwort...",deleteConfirm:"Antwort löschen?"}:{singular:"Unteraufgabe",placeholder:"Unteraufgabe...",deleteConfirm:"Unteraufgabe löschen?"},k=(_,K)=>u===_.id?s.jsx("div",{className:"py-1",children:s.jsxs("form",{onSubmit:S,className:"flex items-center gap-2",children:[s.jsx(No,{className:"w-4 h-4 text-gray-300 flex-shrink-0"}),s.jsx("input",{type:"text",value:p,onChange:H=>m(H.target.value),className:"flex-1 text-sm px-2 py-1 border rounded focus:outline-none focus:ring-1 focus:ring-blue-500",autoFocus:!0}),s.jsx(F,{type:"submit",size:"sm",disabled:!p.trim()||N.isPending,children:"✓"}),s.jsx(F,{type:"button",variant:"ghost",size:"sm",onClick:z,children:"×"})]})},_.id):s.jsx("div",{className:`py-1 group/subtask ${K?"opacity-60":""}`,children:s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx("button",{onClick:()=>K?A.mutate(_.id):D.mutate(_.id),disabled:D.isPending||A.isPending||r,className:`flex-shrink-0 mt-0.5 ${r?"cursor-default":K?"hover:text-yellow-600":"hover:text-green-600"}`,children:K?s.jsx(Ps,{className:"w-4 h-4 text-green-500"}):s.jsx(No,{className:"w-4 h-4 text-gray-400"})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsx("span",{className:`text-sm ${K?"line-through text-gray-500":""}`,children:_.title}),n&&!r&&!K&&s.jsxs("div",{className:"flex items-center gap-0.5 opacity-0 group-hover/subtask:opacity-100",children:[s.jsx("button",{onClick:()=>E(_.id,_.title),className:"text-gray-400 hover:text-blue-600 p-0.5",title:"Bearbeiten",children:s.jsx(Ye,{className:"w-3 h-3"})}),s.jsx("button",{onClick:()=>{confirm(M.deleteConfirm)&&R.mutate(_.id)},className:"text-gray-400 hover:text-red-600 p-0.5",title:"Löschen",children:s.jsx(be,{className:"w-3 h-3"})})]}),n&&!r&&K&&s.jsx("button",{onClick:()=>{confirm(M.deleteConfirm)&&R.mutate(_.id)},className:"text-gray-400 hover:text-red-600 p-0.5 opacity-0 group-hover/subtask:opacity-100",title:"Löschen",children:s.jsx(be,{className:"w-3 h-3"})})]}),s.jsxs("p",{className:"text-xs text-gray-400",children:[_.createdBy&&`${_.createdBy} • `,K?`Erledigt am ${_.completedAt?new Date(_.completedAt).toLocaleDateString("de-DE"):new Date(_.updatedAt).toLocaleDateString("de-DE")}`:new Date(_.createdAt).toLocaleDateString("de-DE")]})]})]})},_.id);return s.jsx("div",{className:`p-3 bg-gray-50 rounded-lg group ${a?"bg-gray-50/50 opacity-70":""}`,children:s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx("button",{onClick:()=>a?b.mutate(e.id):x.mutate(e.id),disabled:x.isPending||b.isPending||r,className:`mt-0.5 flex-shrink-0 ${r?"cursor-default":a?"hover:text-yellow-600":"hover:text-green-600"}`,title:r?void 0:a?"Wieder öffnen":"Als erledigt markieren",children:a?s.jsx(Ps,{className:"w-5 h-5 text-green-500"}):s.jsx(No,{className:"w-5 h-5 text-gray-400"})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:`font-medium ${a?"line-through text-gray-500":""}`,children:e.title}),e.visibleInPortal&&s.jsx(ye,{variant:"default",className:"text-xs",children:"Portal"}),I.length>0&&s.jsxs("span",{className:"text-xs text-gray-400",children:["(",P.length,"/",I.length,")"]})]}),e.description&&s.jsx("p",{className:`text-sm mt-1 whitespace-pre-wrap ${a?"text-gray-500":"text-gray-600"}`,children:e.description}),s.jsxs("p",{className:"text-xs text-gray-400 mt-1",children:[e.createdBy&&`${e.createdBy} • `,a?`Erledigt am ${e.completedAt?new Date(e.completedAt).toLocaleDateString("de-DE"):"-"}`:new Date(e.createdAt).toLocaleDateString("de-DE")]}),I.length>0&&s.jsxs("div",{className:"mt-3 ml-2 space-y-0 border-l-2 border-gray-200 pl-3",children:[B.map(_=>k(_,!1)),P.map(_=>k(_,!0))]}),!a&&(n&&!r||r)&&s.jsx("div",{className:"mt-2 ml-2",children:c?s.jsxs("form",{onSubmit:w,className:"flex items-center gap-2",children:[s.jsx("input",{type:"text",value:l,onChange:_=>o(_.target.value),placeholder:M.placeholder,className:"flex-1 text-sm px-2 py-1 border rounded focus:outline-none focus:ring-1 focus:ring-blue-500",autoFocus:!0}),s.jsx(F,{type:"submit",size:"sm",disabled:!l.trim()||g.isPending||v.isPending,children:s.jsx(Be,{className:"w-3 h-3"})}),s.jsx(F,{type:"button",variant:"ghost",size:"sm",onClick:()=>{d(!1),o("")},children:"×"})]}):s.jsxs("button",{onClick:()=>d(!0),className:"text-xs text-gray-400 hover:text-blue-600 flex items-center gap-1",children:[s.jsx(Be,{className:"w-3 h-3"}),M.singular]})})]}),n&&!r&&s.jsxs("div",{className:"flex gap-1 opacity-0 group-hover:opacity-100",children:[!a&&s.jsx("button",{onClick:i,className:"text-gray-400 hover:text-blue-600 p-1",title:"Bearbeiten",children:s.jsx(Ye,{className:"w-4 h-4"})}),s.jsx("button",{onClick:()=>{confirm("Aufgabe wirklich löschen?")&&y.mutate(e.id)},className:"text-gray-400 hover:text-red-600 p-1",title:"Löschen",children:s.jsx(be,{className:"w-4 h-4"})})]})]})})}function fC({contractId:e,canEdit:t,isCustomerPortal:n}){var v;const[r,a]=j.useState(!1),[i,l]=j.useState(null),{data:o,isLoading:c}=me({queryKey:["contract-tasks",e],queryFn:()=>ut.getByContract(e),staleTime:0,gcTime:0,refetchOnMount:"always"}),{data:d,isLoading:u}=me({queryKey:["app-settings-public"],queryFn:()=>Jr.getPublic(),enabled:n,staleTime:0}),h=!u&&((v=d==null?void 0:d.data)==null?void 0:v.customerSupportTicketsEnabled)==="true",p=(o==null?void 0:o.data)||[],m=p.filter(N=>N.status==="OPEN"),f=p.filter(N=>N.status==="COMPLETED"),x=n?{title:"Support-Anfragen",button:"Anfrage erstellen",empty:"Keine Support-Anfragen vorhanden."}:{title:"Aufgaben",button:"Aufgabe",empty:"Keine Aufgaben vorhanden."},b=n?cl:ol;if(c||n&&u)return s.jsx(Y,{className:"mb-6",title:x.title,children:s.jsx("div",{className:"text-center py-4 text-gray-500",children:"Laden..."})});const g=t&&!n||n&&h;return s.jsxs(Y,{className:"mb-6",title:x.title,children:[s.jsxs("div",{className:"flex items-center justify-between mb-4",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(b,{className:"w-5 h-5 text-gray-500"}),s.jsxs("span",{className:"text-sm text-gray-600",children:[m.length," offen, ",f.length," erledigt"]})]}),g&&s.jsxs(F,{size:"sm",onClick:()=>a(!0),children:[s.jsx(Be,{className:"w-4 h-4 mr-1"}),x.button]})]}),p.length===0?s.jsx("p",{className:"text-center py-4 text-gray-500",children:x.empty}):s.jsxs("div",{className:"space-y-2",children:[m.map(N=>s.jsx($x,{task:N,contractId:e,canEdit:t,isCustomerPortal:n,isCompleted:!1,onEdit:()=>l(N)},N.id)),f.length>0&&m.length>0&&s.jsx("div",{className:"border-t my-3"}),f.map(N=>s.jsx($x,{task:N,contractId:e,canEdit:t,isCustomerPortal:n,isCompleted:!0,onEdit:()=>{}},N.id))]}),(r||i)&&s.jsx(pC,{isOpen:!0,onClose:()=>{a(!1),l(null)},contractId:e,task:i,isCustomerPortal:n})]})}function pC({isOpen:e,onClose:t,contractId:n,task:r,isCustomerPortal:a=!1}){const i=xe(),l=!!r,[o,c]=j.useState({title:(r==null?void 0:r.title)||"",description:(r==null?void 0:r.description)||"",visibleInPortal:(r==null?void 0:r.visibleInPortal)||!1});j.useEffect(()=>{e&&c({title:(r==null?void 0:r.title)||"",description:(r==null?void 0:r.description)||"",visibleInPortal:(r==null?void 0:r.visibleInPortal)||!1})},[e,r]);const d=W({mutationFn:x=>ut.create(n,x),onSuccess:async()=>{await i.refetchQueries({queryKey:["contract-tasks",n]}),t()}}),u=W({mutationFn:x=>ut.createSupportTicket(n,x),onSuccess:async()=>{await i.refetchQueries({queryKey:["contract-tasks",n]}),t()}}),h=W({mutationFn:x=>ut.update(r.id,x),onSuccess:async()=>{await i.refetchQueries({queryKey:["contract-tasks",n]}),t()}}),p=x=>{x.preventDefault(),l?h.mutate({title:o.title,description:o.description||void 0,visibleInPortal:o.visibleInPortal}):a?u.mutate({title:o.title,description:o.description||void 0}):d.mutate({title:o.title,description:o.description||void 0,visibleInPortal:o.visibleInPortal})},m=d.isPending||u.isPending||h.isPending,f=a?{modalTitle:l?"Anfrage bearbeiten":"Neue Support-Anfrage",titleLabel:"Betreff",titlePlaceholder:"Kurze Beschreibung Ihrer Anfrage",descLabel:"Ihre Nachricht",descPlaceholder:"Beschreiben Sie Ihr Anliegen...",submitBtn:l?"Speichern":"Anfrage senden"}:{modalTitle:l?"Aufgabe bearbeiten":"Neue Aufgabe",titleLabel:"Titel",titlePlaceholder:"Kurze Beschreibung der Aufgabe",descLabel:"Beschreibung (optional)",descPlaceholder:"Details zur Aufgabe...",submitBtn:l?"Speichern":"Erstellen"};return s.jsx(Ve,{isOpen:e,onClose:t,title:f.modalTitle,children:s.jsxs("form",{onSubmit:p,className:"space-y-4",children:[s.jsx(V,{label:f.titleLabel,value:o.title,onChange:x=>c({...o,title:x.target.value}),required:!0,placeholder:f.titlePlaceholder}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:f.descLabel}),s.jsx("textarea",{value:o.description,onChange:x=>c({...o,description:x.target.value}),className:"w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500",rows:a?5:3,placeholder:f.descPlaceholder})]}),!a&&s.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:o.visibleInPortal,onChange:x=>c({...o,visibleInPortal:x.target.checked}),className:"w-4 h-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"}),s.jsx("span",{className:"text-sm text-gray-700",children:"Im Kundenportal sichtbar"})]}),s.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[s.jsx(F,{type:"button",variant:"secondary",onClick:t,children:"Abbrechen"}),s.jsx(F,{type:"submit",disabled:m||!o.title.trim(),children:m?"Speichern...":f.submitBtn})]})]})})}function xC(){var et,zt,Qt,J,qe,St;const{id:e}=bc(),t=ts(),r=Fn().state,a=xe(),{hasPermission:i,isCustomer:l,isCustomerPortal:o}=He(),c=parseInt(e),[d,u]=j.useState(!1),[h,p]=j.useState(null),[m,f]=j.useState(!1),[x,b]=j.useState(!1),[y,g]=j.useState(null),[v,N]=j.useState({}),[D,A]=j.useState({}),[R,w]=j.useState(!1),[S,E]=j.useState(!1),[z,I]=j.useState(!1),[B,P]=j.useState(!1),{data:M,isLoading:k}=me({queryKey:["contract",e],queryFn:()=>Le.getById(c)}),_=W({mutationFn:()=>Le.delete(c),onSuccess:()=>{t("/contracts")}}),K=W({mutationFn:()=>Le.createFollowUp(c),onSuccess:G=>{G.data?t(`/contracts/${G.data.id}/edit`):alert("Folgevertrag wurde erstellt, aber keine ID zurückgegeben")},onError:G=>{console.error("Folgevertrag Fehler:",G),alert(`Fehler beim Erstellen des Folgevertrags: ${G instanceof Error?G.message:"Unbekannter Fehler"}`)}}),Z=W({mutationFn:()=>Le.snooze(c,{}),onSuccess:()=>{a.invalidateQueries({queryKey:["contract",e]}),a.invalidateQueries({queryKey:["contract-cockpit"]}),P(!1)},onError:G=>{console.error("Un-Snooze Fehler:",G),alert(`Fehler beim Aufheben der Zurückstellung: ${G instanceof Error?G.message:"Unbekannter Fehler"}`)}}),H=W({mutationFn:G=>{const ht={cancellationConfirmationDate:G?new Date(G).toISOString():null};return Le.update(c,ht)},onSuccess:()=>{a.invalidateQueries({queryKey:["contract",e]}),a.invalidateQueries({queryKey:["contract-cockpit"]})},onError:G=>{console.error("Fehler beim Speichern des Datums:",G),alert("Fehler beim Speichern des Datums")}}),pe=W({mutationFn:G=>{const ht={cancellationConfirmationOptionsDate:G?new Date(G).toISOString():null};return Le.update(c,ht)},onSuccess:()=>{a.invalidateQueries({queryKey:["contract",e]}),a.invalidateQueries({queryKey:["contract-cockpit"]})},onError:G=>{console.error("Fehler beim Speichern des Datums:",G),alert("Fehler beim Speichern des Datums")}}),oe=async()=>{var G;if(d)u(!1),p(null);else try{const _e=await Le.getPassword(c);(G=_e.data)!=null&&G.password&&(p(_e.data.password),u(!0))}catch{alert("Passwort konnte nicht entschlüsselt werden")}},Ze=async()=>{var G;if(x)b(!1),g(null);else try{const _e=await Le.getInternetCredentials(c);(G=_e.data)!=null&&G.password&&(g(_e.data.password),b(!0))}catch{alert("Internet-Passwort konnte nicht entschlüsselt werden")}},Oe=async G=>{var _e;if(v[G])N(ht=>({...ht,[G]:!1})),A(ht=>({...ht,[G]:null}));else try{const ee=(_e=(await Le.getSipCredentials(G)).data)==null?void 0:_e.password;ee&&(A(Ne=>({...Ne,[G]:ee})),N(Ne=>({...Ne,[G]:!0})))}catch{alert("SIP-Passwort konnte nicht entschlüsselt werden")}},it=async()=>{var ht,ee,Ne;const G=M==null?void 0:M.data,_e=((ht=G==null?void 0:G.stressfreiEmail)==null?void 0:ht.email)||(G==null?void 0:G.portalUsername);if(!((ee=G==null?void 0:G.provider)!=null&&ee.portalUrl)||!_e){alert("Portal-URL oder Benutzername fehlt");return}f(!0);try{const Is=await Le.getPassword(c);if(!((Ne=Is.data)!=null&&Ne.password)){alert("Passwort konnte nicht entschlüsselt werden");return}const ft=G.provider,vr=ft.portalUrl,O=ft.usernameFieldName||"username",U=ft.passwordFieldName||"password",Q=new URL(vr);Q.searchParams.set(O,_e),Q.searchParams.set(U,Is.data.password),window.open(Q.toString(),"_blank")}catch{alert("Fehler beim Auto-Login")}finally{f(!1)}};if(k)return s.jsx("div",{className:"text-center py-8",children:"Laden..."});if(!(M!=null&&M.data))return s.jsx("div",{className:"text-center py-8 text-red-600",children:"Vertrag nicht gefunden"});const C=M.data;return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center justify-between mb-6",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-4 mb-2",children:[s.jsx(F,{variant:"ghost",size:"sm",onClick:()=>{if((r==null?void 0:r.from)==="customer"&&(r!=null&&r.customerId))t(`/customers/${r.customerId}?tab=contracts`);else if((r==null?void 0:r.from)==="cockpit"){const G=r.filter?`?filter=${r.filter}`:"";t(`/contracts/cockpit${G}`)}else(r==null?void 0:r.from)==="contracts"?t("/contracts"):C.customer?t(`/customers/${C.customer.id}?tab=contracts`):t("/contracts")},children:s.jsx(Qs,{className:"w-4 h-4"})}),s.jsx("h1",{className:"text-2xl font-bold",children:C.contractNumber}),s.jsx(ye,{children:rC[C.type]}),s.jsx(ye,{variant:iC[C.status],children:aC[C.status]}),s.jsx("button",{onClick:()=>I(!0),className:"text-gray-400 hover:text-blue-600 transition-colors",title:"Status-Erklärung",children:s.jsx(Pl,{className:"w-4 h-4"})}),C.nextReviewDate&&new Date(C.nextReviewDate)>new Date&&s.jsxs("div",{className:"flex items-center gap-1 px-2 py-1 bg-amber-100 text-amber-800 rounded-full text-xs",children:[s.jsx(wv,{className:"w-3 h-3"}),s.jsxs("span",{children:["Zurückgestellt bis ",new Date(C.nextReviewDate).toLocaleDateString("de-DE")]}),i("contracts:update")&&s.jsx("button",{onClick:()=>P(!0),className:"ml-1 p-0.5 hover:bg-amber-200 rounded",title:"Zurückstellung aufheben",children:s.jsx(Vt,{className:"w-3 h-3"})})]})]}),C.customer&&s.jsxs("p",{className:"text-gray-500 ml-10",children:["Kunde:"," ",s.jsx(ke,{to:`/customers/${C.customer.id}`,className:"text-blue-600 hover:underline",children:C.customer.companyName||`${C.customer.firstName} ${C.customer.lastName}`})]})]}),!l&&s.jsxs("div",{className:"flex gap-2",children:[C.previousContract&&s.jsx(ke,{to:`/contracts/${C.previousContract.id}`,children:s.jsxs(F,{variant:"secondary",children:[s.jsx(Qs,{className:"w-4 h-4 mr-2"}),"Vorgängervertrag"]})}),i("contracts:create")&&!C.followUpContract&&s.jsxs(F,{variant:"secondary",onClick:()=>E(!0),disabled:K.isPending,children:[s.jsx(lh,{className:"w-4 h-4 mr-2"}),K.isPending?"Erstelle...":"Folgevertrag anlegen"]}),C.followUpContract&&s.jsx(ke,{to:`/contracts/${C.followUpContract.id}`,children:s.jsxs(F,{variant:"secondary",children:[s.jsx(Nv,{className:"w-4 h-4 mr-2"}),"Folgevertrag anzeigen"]})}),i("contracts:update")&&s.jsx(ke,{to:`/contracts/${e}/edit`,children:s.jsxs(F,{variant:"secondary",children:[s.jsx(Ye,{className:"w-4 h-4 mr-2"}),"Bearbeiten"]})}),i("contracts:delete")&&s.jsxs(F,{variant:"danger",onClick:()=>{confirm("Vertrag wirklich löschen?")&&_.mutate()},children:[s.jsx(be,{className:"w-4 h-4 mr-2"}),"Löschen"]})]})]}),C.previousContract&&s.jsx(Y,{className:"mb-6 border-l-4 border-l-blue-500",title:"Vorgängervertrag",children:s.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Vertragsnummer"}),s.jsx("dd",{children:s.jsx("button",{onClick:()=>w(!0),className:"text-blue-600 hover:underline",children:C.previousContract.contractNumber})})]}),C.previousContract.providerName&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Anbieter"}),s.jsx("dd",{children:C.previousContract.providerName})]}),C.previousContract.customerNumberAtProvider&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Kundennummer"}),s.jsx("dd",{className:"font-mono",children:C.previousContract.customerNumberAtProvider})]}),C.previousContract.portalUsername&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Zugangsdaten"}),s.jsx("dd",{children:C.previousContract.portalUsername})]})]})}),C.cancellationConfirmationDate&&s.jsxs("div",{className:"mb-6 p-4 bg-red-50 border-2 border-red-400 rounded-lg flex items-start gap-3",children:[s.jsx("span",{className:"text-red-600 text-xl font-bold",children:"!"}),s.jsxs("div",{children:[s.jsx("p",{className:"font-semibold text-red-800",children:"Kündigungsbestätigung vorhanden"}),s.jsxs("p",{className:"text-sm text-red-700 mt-1",children:["Dieser Vertrag hat eine Kündigungsbestätigung vom"," ",s.jsx("strong",{children:new Date(C.cancellationConfirmationDate).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"})}),".",C.cancellationConfirmationOptionsDate&&s.jsxs(s.Fragment,{children:[" Optionen-Bestätigung: ",s.jsx("strong",{children:new Date(C.cancellationConfirmationOptionsDate).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"})}),"."]})]})]})]}),C.type==="MOBILE"&&((et=C.mobileDetails)==null?void 0:et.requiresMultisim)&&s.jsxs("div",{className:"mb-6 p-4 bg-amber-50 border border-amber-300 rounded-lg flex items-start gap-3",children:[s.jsx("span",{className:"text-amber-600 text-xl font-bold",children:"!"}),s.jsxs("div",{children:[s.jsx("p",{className:"font-semibold text-amber-800",children:"Multisim erforderlich"}),s.jsx("p",{className:"text-sm text-amber-700 mt-1",children:"Dieser Kunde benötigt eine Multisim-Karte. Multisim ist bei Klarmobil, Congstar und Otelo nicht buchbar. Bitte einen Anbieter wie Freenet oder vergleichbar wählen."})]})]}),s.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6",children:[s.jsx(Y,{title:"Anbieter & Tarif",children:s.jsxs("dl",{className:"space-y-3",children:[(C.provider||C.providerName)&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Anbieter"}),s.jsx("dd",{className:"font-medium",children:((zt=C.provider)==null?void 0:zt.name)||C.providerName})]}),(C.tariff||C.tariffName)&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Tarif"}),s.jsx("dd",{children:((Qt=C.tariff)==null?void 0:Qt.name)||C.tariffName})]}),C.customerNumberAtProvider&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Kundennummer"}),s.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[C.customerNumberAtProvider,s.jsx(ce,{value:C.customerNumberAtProvider})]})]}),C.salesPlatform&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Vertriebsplattform"}),s.jsx("dd",{children:C.salesPlatform.name})]}),C.commission!==null&&C.commission!==void 0&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Provision"}),s.jsx("dd",{children:C.commission.toLocaleString("de-DE",{style:"currency",currency:"EUR"})})]}),C.priceFirst12Months&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Preis erste 12 Monate"}),s.jsx("dd",{children:C.priceFirst12Months})]}),C.priceFrom13Months&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Preis ab 13. Monat"}),s.jsx("dd",{children:C.priceFrom13Months})]}),C.priceAfter24Months&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Preis nach 24 Monaten"}),s.jsx("dd",{children:C.priceAfter24Months})]})]})}),s.jsxs(Y,{title:"Laufzeit und Kündigung",className:C.cancellationConfirmationDate?"border-2 border-red-400":"",children:[C.contractDuration&&cC(C.contractDuration.code)&&s.jsxs("p",{className:"text-sm text-gray-500 mb-4 bg-blue-50 border border-blue-200 rounded-lg p-3",children:[s.jsx("strong",{children:"Hinweis:"})," Dieser Vertrag gilt als unbefristet mit der jeweiligen Kündigungsfrist."]}),s.jsxs("dl",{className:"space-y-3",children:[C.startDate&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Vertragsbeginn"}),s.jsx("dd",{children:new Date(C.startDate).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"})})]}),C.endDate&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Vertragsende"}),s.jsx("dd",{children:new Date(C.endDate).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"})})]}),C.contractDuration&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Vertragslaufzeit"}),s.jsx("dd",{children:C.contractDuration.description})]}),C.cancellationPeriod&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Kündigungsfrist"}),s.jsx("dd",{children:C.cancellationPeriod.description})]}),C.cancellationConfirmationDate&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Kündigungsbestätigungsdatum"}),s.jsx("dd",{children:new Date(C.cancellationConfirmationDate).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"})})]}),C.cancellationConfirmationOptionsDate&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Kündigungsbestätigungsoptionendatum"}),s.jsx("dd",{children:new Date(C.cancellationConfirmationOptionsDate).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"})})]}),C.wasSpecialCancellation&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Sonderkündigung"}),s.jsx("dd",{children:s.jsx(ye,{variant:"warning",children:"Ja"})})]})]}),i("contracts:update")&&s.jsxs("div",{className:"mt-6 pt-6 border-t",children:[s.jsx("h4",{className:"font-medium mb-4",children:"Kündigungsdokumente"}),s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500 mb-1",children:"Kündigungsschreiben"}),C.cancellationLetterPath?s.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[s.jsxs("a",{href:`/api${C.cancellationLetterPath}`,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:underline text-sm flex items-center gap-1",children:[s.jsx(Pe,{className:"w-4 h-4"}),"Anzeigen"]}),s.jsxs("a",{href:`/api${C.cancellationLetterPath}`,download:!0,className:"text-blue-600 hover:underline text-sm flex items-center gap-1",children:[s.jsx(As,{className:"w-4 h-4"}),"Download"]}),s.jsx(Et,{onUpload:async G=>{await ct.uploadCancellationLetter(c,G),a.invalidateQueries({queryKey:["contract",e]})},existingFile:C.cancellationLetterPath,accept:".pdf",label:"Ersetzen"}),s.jsxs("button",{onClick:async()=>{confirm("Dokument wirklich löschen?")&&(await ct.deleteCancellationLetter(c),a.invalidateQueries({queryKey:["contract",e]}))},className:"text-red-600 hover:underline text-sm flex items-center gap-1",children:[s.jsx(be,{className:"w-4 h-4"}),"Löschen"]})]}):s.jsx(Et,{onUpload:async G=>{await ct.uploadCancellationLetter(c,G),a.invalidateQueries({queryKey:["contract",e]})},accept:".pdf",label:"PDF hochladen"})]}),s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500 mb-1",children:"Kündigungsbestätigung"}),C.cancellationConfirmationPath?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[s.jsxs("a",{href:`/api${C.cancellationConfirmationPath}`,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:underline text-sm flex items-center gap-1",children:[s.jsx(Pe,{className:"w-4 h-4"}),"Anzeigen"]}),s.jsxs("a",{href:`/api${C.cancellationConfirmationPath}`,download:!0,className:"text-blue-600 hover:underline text-sm flex items-center gap-1",children:[s.jsx(As,{className:"w-4 h-4"}),"Download"]}),s.jsx(Et,{onUpload:async G=>{await ct.uploadCancellationConfirmation(c,G),a.invalidateQueries({queryKey:["contract",e]})},existingFile:C.cancellationConfirmationPath,accept:".pdf",label:"Ersetzen"}),s.jsxs("button",{onClick:async()=>{confirm("Dokument wirklich löschen?")&&(await ct.deleteCancellationConfirmation(c),a.invalidateQueries({queryKey:["contract",e]}))},className:"text-red-600 hover:underline text-sm flex items-center gap-1",children:[s.jsx(be,{className:"w-4 h-4"}),"Löschen"]})]}),s.jsxs("div",{className:"mt-2",children:[s.jsx("label",{className:"text-xs text-gray-500 block mb-1",children:"Bestätigung erhalten am"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"date",value:C.cancellationConfirmationDate?C.cancellationConfirmationDate.split("T")[0]:"",onChange:G=>{const _e=G.target.value||null;H.mutate(_e)},className:"block w-full max-w-[180px] px-2 py-1 text-sm border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-blue-500"}),C.cancellationConfirmationDate&&s.jsx("button",{onClick:()=>H.mutate(null),className:"p-1 text-red-500 hover:text-red-700 hover:bg-red-50 rounded",title:"Datum löschen",children:s.jsx(be,{className:"w-4 h-4"})})]})]})]}):s.jsx(Et,{onUpload:async G=>{await ct.uploadCancellationConfirmation(c,G),a.invalidateQueries({queryKey:["contract",e]})},accept:".pdf",label:"PDF hochladen"})]}),s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500 mb-1",children:"Kündigungsschreiben Optionen"}),C.cancellationLetterOptionsPath?s.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[s.jsxs("a",{href:`/api${C.cancellationLetterOptionsPath}`,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:underline text-sm flex items-center gap-1",children:[s.jsx(Pe,{className:"w-4 h-4"}),"Anzeigen"]}),s.jsxs("a",{href:`/api${C.cancellationLetterOptionsPath}`,download:!0,className:"text-blue-600 hover:underline text-sm flex items-center gap-1",children:[s.jsx(As,{className:"w-4 h-4"}),"Download"]}),s.jsx(Et,{onUpload:async G=>{await ct.uploadCancellationLetterOptions(c,G),a.invalidateQueries({queryKey:["contract",e]})},existingFile:C.cancellationLetterOptionsPath,accept:".pdf",label:"Ersetzen"}),s.jsxs("button",{onClick:async()=>{confirm("Dokument wirklich löschen?")&&(await ct.deleteCancellationLetterOptions(c),a.invalidateQueries({queryKey:["contract",e]}))},className:"text-red-600 hover:underline text-sm flex items-center gap-1",children:[s.jsx(be,{className:"w-4 h-4"}),"Löschen"]})]}):s.jsx(Et,{onUpload:async G=>{await ct.uploadCancellationLetterOptions(c,G),a.invalidateQueries({queryKey:["contract",e]})},accept:".pdf",label:"PDF hochladen"})]}),s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500 mb-1",children:"Kündigungsbestätigung Optionen"}),C.cancellationConfirmationOptionsPath?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[s.jsxs("a",{href:`/api${C.cancellationConfirmationOptionsPath}`,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:underline text-sm flex items-center gap-1",children:[s.jsx(Pe,{className:"w-4 h-4"}),"Anzeigen"]}),s.jsxs("a",{href:`/api${C.cancellationConfirmationOptionsPath}`,download:!0,className:"text-blue-600 hover:underline text-sm flex items-center gap-1",children:[s.jsx(As,{className:"w-4 h-4"}),"Download"]}),s.jsx(Et,{onUpload:async G=>{await ct.uploadCancellationConfirmationOptions(c,G),a.invalidateQueries({queryKey:["contract",e]})},existingFile:C.cancellationConfirmationOptionsPath,accept:".pdf",label:"Ersetzen"}),s.jsxs("button",{onClick:async()=>{confirm("Dokument wirklich löschen?")&&(await ct.deleteCancellationConfirmationOptions(c),a.invalidateQueries({queryKey:["contract",e]}))},className:"text-red-600 hover:underline text-sm flex items-center gap-1",children:[s.jsx(be,{className:"w-4 h-4"}),"Löschen"]})]}),s.jsxs("div",{className:"mt-2",children:[s.jsx("label",{className:"text-xs text-gray-500 block mb-1",children:"Bestätigung erhalten am"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"date",value:C.cancellationConfirmationOptionsDate?C.cancellationConfirmationOptionsDate.split("T")[0]:"",onChange:G=>{const _e=G.target.value||null;pe.mutate(_e)},className:"block w-full max-w-[180px] px-2 py-1 text-sm border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-blue-500"}),C.cancellationConfirmationOptionsDate&&s.jsx("button",{onClick:()=>pe.mutate(null),className:"p-1 text-red-500 hover:text-red-700 hover:bg-red-50 rounded",title:"Datum löschen",children:s.jsx(be,{className:"w-4 h-4"})})]})]})]}):s.jsx(Et,{onUpload:async G=>{await ct.uploadCancellationConfirmationOptions(c,G),a.invalidateQueries({queryKey:["contract",e]})},accept:".pdf",label:"PDF hochladen"})]})]})]})]})]}),(C.portalUsername||C.stressfreiEmail||C.portalPasswordEncrypted)&&s.jsxs(Y,{className:"mb-6",title:"Zugangsdaten",children:[s.jsxs("dl",{className:"grid grid-cols-2 gap-4",children:[(C.portalUsername||C.stressfreiEmail)&&s.jsxs("div",{children:[s.jsxs("dt",{className:"text-sm text-gray-500",children:["Benutzername",C.stressfreiEmail&&s.jsx("span",{className:"ml-2 text-xs text-blue-600",children:"(Stressfrei-Wechseln)"})]}),s.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[((J=C.stressfreiEmail)==null?void 0:J.email)||C.portalUsername,s.jsx(ce,{value:((qe=C.stressfreiEmail)==null?void 0:qe.email)||C.portalUsername||""})]})]}),C.portalPasswordEncrypted&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Passwort"}),s.jsxs("dd",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"font-mono",children:d&&h?h:"••••••••"}),d&&h&&s.jsx(ce,{value:h}),s.jsx(F,{variant:"ghost",size:"sm",onClick:oe,children:d?s.jsx(It,{className:"w-4 h-4"}):s.jsx(Pe,{className:"w-4 h-4"})})]})]})]}),((St=C.provider)==null?void 0:St.portalUrl)&&(C.portalUsername||C.stressfreiEmail)&&C.portalPasswordEncrypted&&s.jsxs("div",{className:"mt-4 pt-4 border-t",children:[s.jsxs(F,{onClick:it,disabled:m,className:"w-full sm:w-auto",children:[s.jsx(ch,{className:"w-4 h-4 mr-2"}),m?"Wird geöffnet...":"Zum Kundenportal (Auto-Login)"]}),s.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"Öffnet das Portal mit vorausgefüllten Zugangsdaten"})]})]}),s.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-4 gap-6 mb-6",children:[C.address&&s.jsx(Y,{title:"Lieferadresse",children:s.jsxs(Qu,{values:[`${C.address.street} ${C.address.houseNumber}`,`${C.address.postalCode} ${C.address.city}`,C.address.country],children:[s.jsxs("p",{children:[C.address.street," ",C.address.houseNumber]}),s.jsxs("p",{children:[C.address.postalCode," ",C.address.city]}),s.jsx("p",{className:"text-gray-500",children:C.address.country})]})}),(C.billingAddress||C.address)&&s.jsx(Y,{title:"Rechnungsadresse",children:(()=>{const G=C.billingAddress||C.address;return G?s.jsxs(Qu,{values:[`${G.street} ${G.houseNumber}`,`${G.postalCode} ${G.city}`,G.country],children:[s.jsxs("p",{children:[G.street," ",G.houseNumber]}),s.jsxs("p",{children:[G.postalCode," ",G.city]}),s.jsx("p",{className:"text-gray-500",children:G.country}),!C.billingAddress&&C.address&&s.jsx("p",{className:"text-xs text-gray-400 mt-1",children:"(wie Lieferadresse)"})]}):null})()}),C.bankCard&&s.jsxs(Y,{title:"Bankkarte",children:[s.jsx("p",{className:"font-medium",children:C.bankCard.accountHolder}),s.jsxs("p",{className:"font-mono flex items-center gap-1",children:[C.bankCard.iban,s.jsx(ce,{value:C.bankCard.iban})]}),C.bankCard.bankName&&s.jsx("p",{className:"text-gray-500",children:C.bankCard.bankName})]}),C.identityDocument&&s.jsxs(Y,{title:"Ausweis",children:[s.jsxs("p",{className:"font-mono flex items-center gap-1",children:[C.identityDocument.documentNumber,s.jsx(ce,{value:C.identityDocument.documentNumber})]}),s.jsx("p",{className:"text-gray-500",children:C.identityDocument.type})]})]}),C.energyDetails&&s.jsxs(Y,{className:"mb-6",title:C.type==="ELECTRICITY"?"Strom-Details":"Gas-Details",children:[s.jsxs("dl",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[C.energyDetails.meter&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Zählernummer"}),s.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[C.energyDetails.meter.meterNumber,s.jsx(ce,{value:C.energyDetails.meter.meterNumber})]})]}),C.energyDetails.maloId&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"MaLo-ID"}),s.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[C.energyDetails.maloId,s.jsx(ce,{value:C.energyDetails.maloId})]})]}),C.energyDetails.annualConsumption&&s.jsxs("div",{children:[s.jsxs("dt",{className:"text-sm text-gray-500",children:["Jahresverbrauch ",C.type==="ELECTRICITY"?"":"(m³)"]}),s.jsxs("dd",{children:[C.energyDetails.annualConsumption.toLocaleString("de-DE")," ",C.type==="ELECTRICITY"?"kWh":"m³"]})]}),C.type==="GAS"&&C.energyDetails.annualConsumptionKwh&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Jahresverbrauch (kWh)"}),s.jsxs("dd",{children:[C.energyDetails.annualConsumptionKwh.toLocaleString("de-DE")," kWh"]})]}),C.energyDetails.basePrice!=null&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Grundpreis"}),s.jsxs("dd",{children:[C.energyDetails.basePrice.toLocaleString("de-DE",{minimumFractionDigits:2,maximumFractionDigits:10})," €/Monat"]})]}),C.energyDetails.unitPrice!=null&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Arbeitspreis"}),s.jsxs("dd",{children:[C.energyDetails.unitPrice.toLocaleString("de-DE",{minimumFractionDigits:2,maximumFractionDigits:10})," €/kWh"]})]}),C.energyDetails.bonus&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Bonus"}),s.jsxs("dd",{children:[C.energyDetails.bonus.toLocaleString("de-DE")," €"]})]}),C.energyDetails.previousProviderName&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Vorversorger"}),s.jsx("dd",{children:C.energyDetails.previousProviderName})]}),C.energyDetails.previousCustomerNumber&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Vorherige Kundennr."}),s.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[C.energyDetails.previousCustomerNumber,s.jsx(ce,{value:C.energyDetails.previousCustomerNumber})]})]})]}),C.energyDetails.meter&&s.jsx(uC,{meterId:C.energyDetails.meter.id,meterType:C.energyDetails.meter.type,readings:C.energyDetails.meter.readings||[],contractId:c,canEdit:i("contracts:update")&&!l}),C.energyDetails.meter&&C.startDate&&C.endDate&&s.jsx(hC,{contractType:C.type,readings:C.energyDetails.meter.readings||[],startDate:C.startDate,endDate:C.endDate,basePrice:C.energyDetails.basePrice,unitPrice:C.energyDetails.unitPrice,bonus:C.energyDetails.bonus}),s.jsx(Xk,{ecdId:C.energyDetails.id,invoices:C.energyDetails.invoices||[],contractId:c,canEdit:i("contracts:update")&&!l})]}),C.internetDetails&&s.jsxs(Y,{className:"mb-6",title:C.type==="DSL"?"DSL-Details":C.type==="CABLE"?"Kabelinternet-Details":"Glasfaser-Details",children:[s.jsxs("dl",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[C.internetDetails.downloadSpeed&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Download"}),s.jsxs("dd",{children:[C.internetDetails.downloadSpeed," Mbit/s"]})]}),C.internetDetails.uploadSpeed&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Upload"}),s.jsxs("dd",{children:[C.internetDetails.uploadSpeed," Mbit/s"]})]}),C.internetDetails.routerModel&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Router"}),s.jsx("dd",{children:C.internetDetails.routerModel})]}),C.internetDetails.routerSerialNumber&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Router S/N"}),s.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[C.internetDetails.routerSerialNumber,s.jsx(ce,{value:C.internetDetails.routerSerialNumber})]})]}),C.internetDetails.installationDate&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Installation"}),s.jsx("dd",{children:new Date(C.internetDetails.installationDate).toLocaleDateString("de-DE")})]}),C.internetDetails.homeId&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Home-ID"}),s.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[C.internetDetails.homeId,s.jsx(ce,{value:C.internetDetails.homeId})]})]}),C.internetDetails.activationCode&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Aktivierungscode"}),s.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[C.internetDetails.activationCode,s.jsx(ce,{value:C.internetDetails.activationCode})]})]})]}),(C.internetDetails.internetUsername||C.internetDetails.internetPasswordEncrypted)&&s.jsxs("div",{className:"mt-4 pt-4 border-t",children:[s.jsx("h4",{className:"text-sm font-medium text-gray-700 mb-3",children:"Internet-Zugangsdaten"}),s.jsxs("dl",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[C.internetDetails.internetUsername&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Benutzername"}),s.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[C.internetDetails.internetUsername,s.jsx(ce,{value:C.internetDetails.internetUsername})]})]}),C.internetDetails.internetPasswordEncrypted&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Passwort"}),s.jsxs("dd",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"font-mono",children:x&&y?y:"••••••••"}),x&&y&&s.jsx(ce,{value:y}),s.jsx(F,{variant:"ghost",size:"sm",onClick:Ze,children:x?s.jsx(It,{className:"w-4 h-4"}):s.jsx(Pe,{className:"w-4 h-4"})})]})]})]})]}),C.internetDetails.phoneNumbers&&C.internetDetails.phoneNumbers.length>0&&s.jsxs("div",{className:"mt-4 pt-4 border-t",children:[s.jsx("h4",{className:"text-sm font-medium text-gray-700 mb-3",children:"Rufnummern & SIP-Zugangsdaten"}),s.jsx("div",{className:"space-y-3",children:C.internetDetails.phoneNumbers.map(G=>s.jsxs("div",{className:"p-3 bg-gray-50 rounded-lg",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[s.jsxs("span",{className:"font-mono font-medium flex items-center gap-1",children:[G.phoneNumber,s.jsx(ce,{value:G.phoneNumber})]}),G.isMain&&s.jsx(ye,{variant:"success",children:"Hauptnummer"})]}),(G.sipUsername||G.sipPasswordEncrypted||G.sipServer)&&s.jsxs("dl",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 text-sm",children:[G.sipUsername&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-gray-500",children:"SIP-Benutzer"}),s.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[G.sipUsername,s.jsx(ce,{value:G.sipUsername})]})]}),G.sipPasswordEncrypted&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-gray-500",children:"SIP-Passwort"}),s.jsxs("dd",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"font-mono",children:v[G.id]&&D[G.id]?D[G.id]:"••••••••"}),v[G.id]&&D[G.id]&&s.jsx(ce,{value:D[G.id]}),s.jsx(F,{variant:"ghost",size:"sm",onClick:()=>Oe(G.id),children:v[G.id]?s.jsx(It,{className:"w-3 h-3"}):s.jsx(Pe,{className:"w-3 h-3"})})]})]}),G.sipServer&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-gray-500",children:"SIP-Server"}),s.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[G.sipServer,s.jsx(ce,{value:G.sipServer})]})]})]})]},G.id))})]})]}),C.mobileDetails&&s.jsxs(Y,{className:"mb-6",title:"Mobilfunk-Details",children:[s.jsxs("dl",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[C.mobileDetails.dataVolume&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Datenvolumen"}),s.jsxs("dd",{children:[C.mobileDetails.dataVolume," GB"]})]}),C.mobileDetails.includedMinutes&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Inklusiv-Minuten"}),s.jsx("dd",{children:C.mobileDetails.includedMinutes})]}),C.mobileDetails.includedSMS&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Inklusiv-SMS"}),s.jsx("dd",{children:C.mobileDetails.includedSMS})]}),C.mobileDetails.deviceModel&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Gerät"}),s.jsx("dd",{children:C.mobileDetails.deviceModel})]}),C.mobileDetails.deviceImei&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"IMEI"}),s.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[C.mobileDetails.deviceImei,s.jsx(ce,{value:C.mobileDetails.deviceImei})]})]}),C.mobileDetails.requiresMultisim&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Multisim"}),s.jsx("dd",{children:s.jsx(ye,{variant:"warning",children:"Erforderlich"})})]})]}),C.mobileDetails.simCards&&C.mobileDetails.simCards.length>0&&s.jsxs("div",{className:"mt-6 pt-6 border-t",children:[s.jsx("h4",{className:"font-medium mb-4",children:"SIM-Karten"}),s.jsx("div",{className:"space-y-3",children:C.mobileDetails.simCards.map(G=>s.jsx(dC,{simCard:G},G.id))})]}),(!C.mobileDetails.simCards||C.mobileDetails.simCards.length===0)&&(C.mobileDetails.phoneNumber||C.mobileDetails.simCardNumber)&&s.jsxs("div",{className:"mt-6 pt-6 border-t",children:[s.jsx("h4",{className:"font-medium mb-4",children:"SIM-Karte (Legacy)"}),s.jsxs("dl",{className:"grid grid-cols-2 gap-4",children:[C.mobileDetails.phoneNumber&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Rufnummer"}),s.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[C.mobileDetails.phoneNumber,s.jsx(ce,{value:C.mobileDetails.phoneNumber})]})]}),C.mobileDetails.simCardNumber&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"SIM-Kartennummer"}),s.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[C.mobileDetails.simCardNumber,s.jsx(ce,{value:C.mobileDetails.simCardNumber})]})]})]})]})]}),C.tvDetails&&s.jsx(Y,{className:"mb-6",title:"TV-Details",children:s.jsxs("dl",{className:"grid grid-cols-2 md:grid-cols-3 gap-4",children:[C.tvDetails.receiverModel&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Receiver"}),s.jsx("dd",{children:C.tvDetails.receiverModel})]}),C.tvDetails.smartcardNumber&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Smartcard"}),s.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[C.tvDetails.smartcardNumber,s.jsx(ce,{value:C.tvDetails.smartcardNumber})]})]}),C.tvDetails.package&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Paket"}),s.jsx("dd",{children:C.tvDetails.package})]})]})}),C.carInsuranceDetails&&s.jsx(Y,{className:"mb-6",title:"KFZ-Versicherung Details",children:s.jsxs("dl",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[C.carInsuranceDetails.licensePlate&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Kennzeichen"}),s.jsxs("dd",{className:"font-mono font-bold flex items-center gap-1",children:[C.carInsuranceDetails.licensePlate,s.jsx(ce,{value:C.carInsuranceDetails.licensePlate})]})]}),C.carInsuranceDetails.vehicleType&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Fahrzeug"}),s.jsx("dd",{children:C.carInsuranceDetails.vehicleType})]}),C.carInsuranceDetails.hsn&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"HSN/TSN"}),s.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[C.carInsuranceDetails.hsn,"/",C.carInsuranceDetails.tsn,s.jsx(ce,{value:`${C.carInsuranceDetails.hsn}/${C.carInsuranceDetails.tsn}`})]})]}),C.carInsuranceDetails.vin&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"FIN"}),s.jsxs("dd",{className:"font-mono text-sm flex items-center gap-1",children:[C.carInsuranceDetails.vin,s.jsx(ce,{value:C.carInsuranceDetails.vin})]})]}),C.carInsuranceDetails.firstRegistration&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Erstzulassung"}),s.jsx("dd",{children:new Date(C.carInsuranceDetails.firstRegistration).toLocaleDateString("de-DE")})]}),C.carInsuranceDetails.noClaimsClass&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"SF-Klasse"}),s.jsx("dd",{children:C.carInsuranceDetails.noClaimsClass})]}),s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Versicherungsart"}),s.jsx("dd",{children:s.jsx(ye,{variant:C.carInsuranceDetails.insuranceType==="FULL"?"success":C.carInsuranceDetails.insuranceType==="PARTIAL"?"warning":"default",children:C.carInsuranceDetails.insuranceType==="FULL"?"Vollkasko":C.carInsuranceDetails.insuranceType==="PARTIAL"?"Teilkasko":"Haftpflicht"})})]}),C.carInsuranceDetails.deductiblePartial&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"SB Teilkasko"}),s.jsxs("dd",{children:[C.carInsuranceDetails.deductiblePartial," €"]})]}),C.carInsuranceDetails.deductibleFull&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"SB Vollkasko"}),s.jsxs("dd",{children:[C.carInsuranceDetails.deductibleFull," €"]})]}),C.carInsuranceDetails.policyNumber&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Versicherungsschein-Nr."}),s.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[C.carInsuranceDetails.policyNumber,s.jsx(ce,{value:C.carInsuranceDetails.policyNumber})]})]}),C.carInsuranceDetails.previousInsurer&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Vorversicherer"}),s.jsx("dd",{children:C.carInsuranceDetails.previousInsurer})]})]})}),s.jsx(fC,{contractId:c,canEdit:i("contracts:update"),isCustomerPortal:o}),!o&&i("contracts:read")&&C.customerId&&s.jsx(lk,{contractId:c,customerId:C.customerId}),C.notes&&s.jsx(Y,{title:"Notizen",children:s.jsx("p",{className:"whitespace-pre-wrap",children:C.notes})}),R&&C.previousContract&&s.jsx(Jk,{contractId:C.previousContract.id,isOpen:!0,onClose:()=>w(!1)}),s.jsx(Ve,{isOpen:S,onClose:()=>E(!1),title:"Folgevertrag anlegen",size:"sm",children:s.jsxs("div",{className:"space-y-4",children:[s.jsx("p",{className:"text-gray-700",children:"Möchten Sie wirklich einen Folgevertrag für diesen Vertrag anlegen?"}),s.jsx("p",{className:"text-sm text-gray-500",children:"Die Daten des aktuellen Vertrags werden als Vorlage übernommen."}),s.jsxs("div",{className:"flex justify-end gap-3 pt-2",children:[s.jsx(F,{variant:"secondary",onClick:()=>E(!1),children:"Nein"}),s.jsx(F,{onClick:()=>{E(!1),K.mutate()},children:"Ja, anlegen"})]})]})}),s.jsx(oC,{isOpen:z,onClose:()=>I(!1)}),s.jsx(Ve,{isOpen:B,onClose:()=>P(!1),title:"Zurückstellung aufheben?",children:s.jsxs("div",{className:"space-y-4",children:[s.jsx("p",{className:"text-gray-700",children:"Möchten Sie die Zurückstellung für diesen Vertrag wirklich aufheben?"}),s.jsx("p",{className:"text-sm text-gray-500",children:"Der Vertrag wird danach wieder im Cockpit angezeigt, wenn Fristen anstehen oder abgelaufen sind."}),s.jsxs("div",{className:"flex justify-end gap-3 pt-4",children:[s.jsx(F,{variant:"secondary",onClick:()=>P(!1),children:"Abbrechen"}),s.jsx(F,{variant:"danger",onClick:()=>Z.mutate(),disabled:Z.isPending,children:Z.isPending?"Wird aufgehoben...":"Ja, aufheben"})]})]})})]})}const gC=[{value:"DRAFT",label:"Entwurf"},{value:"PENDING",label:"Ausstehend"},{value:"ACTIVE",label:"Aktiv"},{value:"CANCELLED",label:"Gekündigt"},{value:"EXPIRED",label:"Abgelaufen"},{value:"DEACTIVATED",label:"Deaktiviert"}],yC=[{status:"DRAFT",label:"Entwurf",description:"Vertrag wird noch vorbereitet",color:"text-gray-600"},{status:"PENDING",label:"Ausstehend",description:"Wartet auf Aktivierung",color:"text-yellow-600"},{status:"ACTIVE",label:"Aktiv",description:"Vertrag läuft normal",color:"text-green-600"},{status:"EXPIRED",label:"Abgelaufen",description:"Laufzeit vorbei, läuft aber ohne Kündigung weiter",color:"text-orange-600"},{status:"CANCELLED",label:"Gekündigt",description:"Aktive Kündigung eingereicht, Vertrag endet",color:"text-red-600"},{status:"DEACTIVATED",label:"Deaktiviert",description:"Manuell beendet/archiviert",color:"text-gray-500"}];function vC({isOpen:e,onClose:t}){return e?s.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[s.jsx("div",{className:"fixed inset-0 bg-black/20",onClick:t}),s.jsxs("div",{className:"relative bg-white rounded-lg shadow-xl p-4 max-w-sm w-full mx-4",children:[s.jsxs("div",{className:"flex items-center justify-between mb-3",children:[s.jsx("h3",{className:"text-sm font-semibold text-gray-900",children:"Vertragsstatus-Übersicht"}),s.jsx("button",{onClick:t,className:"text-gray-400 hover:text-gray-600",children:s.jsx(Vt,{className:"w-4 h-4"})})]}),s.jsx("div",{className:"space-y-2",children:yC.map(({status:n,label:r,description:a,color:i})=>s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx("span",{className:`font-medium text-sm min-w-[90px] ${i}`,children:r}),s.jsx("span",{className:"text-sm text-gray-600",children:a})]},n))})]})]}):null}function _x(){var Il,ii,Rl,li,bh,Nh,wh,Sh,kh;const{id:e}=bc(),[t]=wc(),n=ts(),r=xe(),a=!!e,i=t.get("customerId"),{register:l,handleSubmit:o,reset:c,watch:d,setValue:u,formState:{errors:h}}=qv({defaultValues:{customerId:i||"",type:"ELECTRICITY",status:"DRAFT",previousContractId:""}}),p=d("type"),m=d("customerId"),{data:f}=me({queryKey:["contract",e],queryFn:()=>Le.getById(parseInt(e)),enabled:a}),{data:x}=me({queryKey:["customers-all"],queryFn:()=>Dt.getAll({limit:1e3})}),{data:b}=me({queryKey:["customer",m],queryFn:()=>Dt.getById(parseInt(m)),enabled:!!m}),{data:y}=me({queryKey:["customer-contracts-for-predecessor",m],queryFn:()=>Le.getAll({customerId:parseInt(m),limit:1e3}),enabled:!!m}),{data:g}=me({queryKey:["platforms"],queryFn:()=>rl.getAll()}),{data:v}=me({queryKey:["cancellation-periods"],queryFn:()=>al.getAll()}),{data:N}=me({queryKey:["contract-durations"],queryFn:()=>il.getAll()}),{data:D}=me({queryKey:["providers"],queryFn:()=>Ja.getAll()}),{data:A}=me({queryKey:["contract-categories"],queryFn:()=>ll.getAll()}),R=d("providerId"),[w,S]=j.useState(null),[E,z]=j.useState([]),[I,B]=j.useState([]),[P,M]=j.useState(!1),[k,_]=j.useState("manual"),[K,Z]=j.useState(""),[H,pe]=j.useState(!1),[oe,Ze]=j.useState(!1),[Oe,it]=j.useState({}),[C,et]=j.useState({}),[zt,Qt]=j.useState({}),[J,qe]=j.useState(!1);j.useEffect(()=>{a||M(!0)},[a]),j.useEffect(()=>{!a&&i&&(x!=null&&x.data)&&x.data.some(ie=>ie.id.toString()===i)&&u("customerId",i)},[a,i,x,u]),j.useEffect(()=>{P&&w&&R!==w&&u("tariffId",""),S(R)},[R,w,u,P]),j.useEffect(()=>{if(!a&&(A!=null&&A.data)&&A.data.length>0){const L=d("type"),ie=A.data.filter(he=>he.isActive),we=ie.some(he=>he.code===L);if(!L||!we){const he=ie.sort((je,lt)=>je.sortOrder-lt.sortOrder)[0];he&&u("type",he.code)}}},[A,a,u,d]),j.useEffect(()=>{a&&(f!=null&&f.data)&&!m&&u("customerId",f.data.customerId.toString())},[a,f,m,u]),j.useEffect(()=>{var L,ie,we,he,je,lt,Ce,oi,Ch,Eh,Dh,Ph,Ah,Mh,Th,Fh,Ih,Rh,Lh,Oh,zh,$h,_h,Kh,Uh,Bh,qh,Vh,Qh,Hh,Wh,Gh,Zh,Jh,Xh,Yh,ef,tf,sf,nf,rf,af,lf,of,cf,df,uf,mf,hf,ff,pf,xf,gf;if(f!=null&&f.data&&(g!=null&&g.data)&&(A!=null&&A.data)&&(D!=null&&D.data)&&(b!=null&&b.data)){const ae=f.data;c({customerId:ae.customerId.toString(),type:ae.type,status:ae.status,addressId:((L=ae.addressId)==null?void 0:L.toString())||"",billingAddressId:((ie=ae.billingAddressId)==null?void 0:ie.toString())||"",bankCardId:((we=ae.bankCardId)==null?void 0:we.toString())||"",identityDocumentId:((he=ae.identityDocumentId)==null?void 0:he.toString())||"",salesPlatformId:((je=ae.salesPlatformId)==null?void 0:je.toString())||"",providerId:((lt=ae.providerId)==null?void 0:lt.toString())||"",tariffId:((Ce=ae.tariffId)==null?void 0:Ce.toString())||"",providerName:ae.providerName||"",tariffName:ae.tariffName||"",customerNumberAtProvider:ae.customerNumberAtProvider||"",priceFirst12Months:ae.priceFirst12Months||"",priceFrom13Months:ae.priceFrom13Months||"",priceAfter24Months:ae.priceAfter24Months||"",startDate:ae.startDate?ae.startDate.split("T")[0]:"",endDate:ae.endDate?ae.endDate.split("T")[0]:"",cancellationPeriodId:((oi=ae.cancellationPeriodId)==null?void 0:oi.toString())||"",contractDurationId:((Ch=ae.contractDurationId)==null?void 0:Ch.toString())||"",commission:ae.commission||"",portalUsername:ae.portalUsername||"",notes:ae.notes||"",meterId:((Dh=(Eh=ae.energyDetails)==null?void 0:Eh.meterId)==null?void 0:Dh.toString())||"",maloId:((Ph=ae.energyDetails)==null?void 0:Ph.maloId)||"",annualConsumption:((Ah=ae.energyDetails)==null?void 0:Ah.annualConsumption)||"",annualConsumptionKwh:((Mh=ae.energyDetails)==null?void 0:Mh.annualConsumptionKwh)||"",basePrice:((Th=ae.energyDetails)==null?void 0:Th.basePrice)||"",unitPrice:((Fh=ae.energyDetails)==null?void 0:Fh.unitPrice)||"",bonus:((Ih=ae.energyDetails)==null?void 0:Ih.bonus)||"",previousProviderName:((Rh=ae.energyDetails)==null?void 0:Rh.previousProviderName)||"",previousCustomerNumber:((Lh=ae.energyDetails)==null?void 0:Lh.previousCustomerNumber)||"",downloadSpeed:((Oh=ae.internetDetails)==null?void 0:Oh.downloadSpeed)||"",uploadSpeed:((zh=ae.internetDetails)==null?void 0:zh.uploadSpeed)||"",routerModel:(($h=ae.internetDetails)==null?void 0:$h.routerModel)||"",routerSerialNumber:((_h=ae.internetDetails)==null?void 0:_h.routerSerialNumber)||"",installationDate:(Kh=ae.internetDetails)!=null&&Kh.installationDate?ae.internetDetails.installationDate.split("T")[0]:"",internetUsername:((Uh=ae.internetDetails)==null?void 0:Uh.internetUsername)||"",homeId:((Bh=ae.internetDetails)==null?void 0:Bh.homeId)||"",activationCode:((qh=ae.internetDetails)==null?void 0:qh.activationCode)||"",requiresMultisim:((Vh=ae.mobileDetails)==null?void 0:Vh.requiresMultisim)||!1,dataVolume:((Qh=ae.mobileDetails)==null?void 0:Qh.dataVolume)||"",includedMinutes:((Hh=ae.mobileDetails)==null?void 0:Hh.includedMinutes)||"",includedSMS:((Wh=ae.mobileDetails)==null?void 0:Wh.includedSMS)||"",deviceModel:((Gh=ae.mobileDetails)==null?void 0:Gh.deviceModel)||"",deviceImei:((Zh=ae.mobileDetails)==null?void 0:Zh.deviceImei)||"",phoneNumber:((Jh=ae.mobileDetails)==null?void 0:Jh.phoneNumber)||"",simCardNumber:((Xh=ae.mobileDetails)==null?void 0:Xh.simCardNumber)||"",receiverModel:((Yh=ae.tvDetails)==null?void 0:Yh.receiverModel)||"",smartcardNumber:((ef=ae.tvDetails)==null?void 0:ef.smartcardNumber)||"",tvPackage:((tf=ae.tvDetails)==null?void 0:tf.package)||"",licensePlate:((sf=ae.carInsuranceDetails)==null?void 0:sf.licensePlate)||"",hsn:((nf=ae.carInsuranceDetails)==null?void 0:nf.hsn)||"",tsn:((rf=ae.carInsuranceDetails)==null?void 0:rf.tsn)||"",vin:((af=ae.carInsuranceDetails)==null?void 0:af.vin)||"",vehicleType:((lf=ae.carInsuranceDetails)==null?void 0:lf.vehicleType)||"",firstRegistration:(of=ae.carInsuranceDetails)!=null&&of.firstRegistration?ae.carInsuranceDetails.firstRegistration.split("T")[0]:"",noClaimsClass:((cf=ae.carInsuranceDetails)==null?void 0:cf.noClaimsClass)||"",insuranceType:((df=ae.carInsuranceDetails)==null?void 0:df.insuranceType)||"LIABILITY",deductiblePartial:((uf=ae.carInsuranceDetails)==null?void 0:uf.deductiblePartial)||"",deductibleFull:((mf=ae.carInsuranceDetails)==null?void 0:mf.deductibleFull)||"",policyNumber:((hf=ae.carInsuranceDetails)==null?void 0:hf.policyNumber)||"",previousInsurer:((ff=ae.carInsuranceDetails)==null?void 0:ff.previousInsurer)||"",cancellationConfirmationDate:ae.cancellationConfirmationDate?ae.cancellationConfirmationDate.split("T")[0]:"",cancellationConfirmationOptionsDate:ae.cancellationConfirmationOptionsDate?ae.cancellationConfirmationOptionsDate.split("T")[0]:"",wasSpecialCancellation:ae.wasSpecialCancellation||!1,previousContractId:((pf=ae.previousContractId)==null?void 0:pf.toString())||""}),(xf=ae.mobileDetails)!=null&&xf.simCards&&ae.mobileDetails.simCards.length>0?z(ae.mobileDetails.simCards.map(ss=>({id:ss.id,phoneNumber:ss.phoneNumber||"",simCardNumber:ss.simCardNumber||"",pin:"",puk:"",hasExistingPin:!!ss.pin,hasExistingPuk:!!ss.puk,isMultisim:ss.isMultisim,isMain:ss.isMain}))):z([]),(gf=ae.internetDetails)!=null&&gf.phoneNumbers&&ae.internetDetails.phoneNumbers.length>0?B(ae.internetDetails.phoneNumbers.map(ss=>({id:ss.id,phoneNumber:ss.phoneNumber||"",sipUsername:ss.sipUsername||"",sipPassword:"",hasExistingSipPassword:!!ss.sipPasswordEncrypted,sipServer:ss.sipServer||"",isMain:ss.isMain}))):B([]),ae.stressfreiEmailId?(_("stressfrei"),Z(ae.stressfreiEmailId.toString())):(_("manual"),Z("")),M(!0)}},[f,c,g,A,D,b]);const St=d("startDate"),G=d("contractDurationId");j.useEffect(()=>{if(St&&G&&(N!=null&&N.data)){const L=N.data.find(ie=>ie.id===parseInt(G));if(L){const ie=new Date(St),he=L.code.match(/^(\d+)([MTJ])$/);if(he){const je=parseInt(he[1]),lt=he[2];let Ce=new Date(ie);lt==="T"?Ce.setDate(Ce.getDate()+je):lt==="M"?Ce.setMonth(Ce.getMonth()+je):lt==="J"&&Ce.setFullYear(Ce.getFullYear()+je),u("endDate",Ce.toISOString().split("T")[0])}}}},[St,G,N,u]);const _e=W({mutationFn:Le.create,onSuccess:(L,ie)=>{r.invalidateQueries({queryKey:["contracts"]}),ie.customerId&&r.invalidateQueries({queryKey:["customer",ie.customerId.toString()]}),r.invalidateQueries({queryKey:["customers"]}),n(i?`/customers/${i}?tab=contracts`:"/contracts")}}),ht=W({mutationFn:L=>Le.update(parseInt(e),L),onSuccess:(L,ie)=>{r.invalidateQueries({queryKey:["contracts"]}),r.invalidateQueries({queryKey:["contract",e]}),ie.customerId&&r.invalidateQueries({queryKey:["customer",ie.customerId.toString()]}),r.invalidateQueries({queryKey:["customers"]}),n(`/contracts/${e}`)}}),ee=L=>{const ie=Ce=>{if(Ce==null||Ce==="")return;const oi=parseInt(String(Ce));return isNaN(oi)?void 0:oi},we=Fe.find(Ce=>Ce.code===L.type),he=ie(L.customerId);if(!he){alert("Bitte wählen Sie einen Kunden aus");return}if(!L.type||!we){alert("Bitte wählen Sie einen Vertragstyp aus");return}const je=Ce=>Ce==null||Ce===""?null:Ce,lt={customerId:he,type:L.type,contractCategoryId:we.id,status:L.status,addressId:ie(L.addressId)??null,billingAddressId:ie(L.billingAddressId)??null,bankCardId:ie(L.bankCardId)??null,identityDocumentId:ie(L.identityDocumentId)??null,salesPlatformId:ie(L.salesPlatformId)??null,providerId:ie(L.providerId)??null,tariffId:ie(L.tariffId)??null,providerName:je(L.providerName),tariffName:je(L.tariffName),customerNumberAtProvider:je(L.customerNumberAtProvider),priceFirst12Months:je(L.priceFirst12Months),priceFrom13Months:je(L.priceFrom13Months),priceAfter24Months:je(L.priceAfter24Months),startDate:L.startDate?new Date(L.startDate):null,endDate:L.endDate?new Date(L.endDate):null,cancellationPeriodId:ie(L.cancellationPeriodId)??null,contractDurationId:ie(L.contractDurationId)??null,commission:L.commission?parseFloat(L.commission):null,portalUsername:k==="manual"?je(L.portalUsername):null,stressfreiEmailId:k==="stressfrei"&&K?parseInt(K):null,portalPassword:L.portalPassword||void 0,notes:je(L.notes),cancellationConfirmationDate:L.cancellationConfirmationDate?new Date(L.cancellationConfirmationDate):null,cancellationConfirmationOptionsDate:L.cancellationConfirmationOptionsDate?new Date(L.cancellationConfirmationOptionsDate):null,wasSpecialCancellation:L.wasSpecialCancellation||!1,previousContractId:ie(L.previousContractId)??null};["ELECTRICITY","GAS"].includes(L.type)&&(lt.energyDetails={meterId:ie(L.meterId)??null,maloId:je(L.maloId),annualConsumption:L.annualConsumption?parseFloat(L.annualConsumption):null,annualConsumptionKwh:L.annualConsumptionKwh?parseFloat(L.annualConsumptionKwh):null,basePrice:L.basePrice?parseFloat(L.basePrice):null,unitPrice:L.unitPrice?parseFloat(L.unitPrice):null,bonus:L.bonus?parseFloat(L.bonus):null,previousProviderName:je(L.previousProviderName),previousCustomerNumber:je(L.previousCustomerNumber)}),["DSL","CABLE","FIBER"].includes(L.type)&&(lt.internetDetails={downloadSpeed:ie(L.downloadSpeed)??null,uploadSpeed:ie(L.uploadSpeed)??null,routerModel:je(L.routerModel),routerSerialNumber:je(L.routerSerialNumber),installationDate:L.installationDate?new Date(L.installationDate):null,internetUsername:je(L.internetUsername),internetPassword:L.internetPassword||void 0,homeId:je(L.homeId),activationCode:je(L.activationCode),phoneNumbers:I.length>0?I.map(Ce=>({id:Ce.id,phoneNumber:Ce.phoneNumber||"",isMain:Ce.isMain??!1,sipUsername:je(Ce.sipUsername),sipPassword:Ce.sipPassword||void 0,sipServer:je(Ce.sipServer)})):void 0}),L.type==="MOBILE"&&(lt.mobileDetails={requiresMultisim:L.requiresMultisim||!1,dataVolume:L.dataVolume?parseFloat(L.dataVolume):null,includedMinutes:ie(L.includedMinutes)??null,includedSMS:ie(L.includedSMS)??null,deviceModel:je(L.deviceModel),deviceImei:je(L.deviceImei),phoneNumber:je(L.phoneNumber),simCardNumber:je(L.simCardNumber),simCards:E.length>0?E.map(Ce=>({id:Ce.id,phoneNumber:je(Ce.phoneNumber),simCardNumber:je(Ce.simCardNumber),pin:Ce.pin||void 0,puk:Ce.puk||void 0,isMultisim:Ce.isMultisim,isMain:Ce.isMain})):void 0}),L.type==="TV"&&(lt.tvDetails={receiverModel:je(L.receiverModel),smartcardNumber:je(L.smartcardNumber),package:je(L.tvPackage)}),L.type==="CAR_INSURANCE"&&(lt.carInsuranceDetails={licensePlate:je(L.licensePlate),hsn:je(L.hsn),tsn:je(L.tsn),vin:je(L.vin),vehicleType:je(L.vehicleType),firstRegistration:L.firstRegistration?new Date(L.firstRegistration):null,noClaimsClass:je(L.noClaimsClass),insuranceType:L.insuranceType,deductiblePartial:L.deductiblePartial?parseFloat(L.deductiblePartial):null,deductibleFull:L.deductibleFull?parseFloat(L.deductibleFull):null,policyNumber:je(L.policyNumber),previousInsurer:je(L.previousInsurer)}),a?ht.mutate(lt):_e.mutate(lt)},Ne=_e.isPending||ht.isPending,Is=_e.error||ht.error,ft=b==null?void 0:b.data,vr=(ft==null?void 0:ft.addresses)||[],O=((Il=ft==null?void 0:ft.bankCards)==null?void 0:Il.filter(L=>L.isActive))||[],U=((ii=ft==null?void 0:ft.identityDocuments)==null?void 0:ii.filter(L=>L.isActive))||[],Q=((Rl=ft==null?void 0:ft.meters)==null?void 0:Rl.filter(L=>L.isActive))||[],le=((li=ft==null?void 0:ft.stressfreiEmails)==null?void 0:li.filter(L=>L.isActive))||[],ne=(g==null?void 0:g.data)||[],te=(v==null?void 0:v.data)||[],ge=(N==null?void 0:N.data)||[],Te=((bh=D==null?void 0:D.data)==null?void 0:bh.filter(L=>L.isActive))||[],Fe=((Nh=A==null?void 0:A.data)==null?void 0:Nh.filter(L=>L.isActive).sort((L,ie)=>L.sortOrder-ie.sortOrder))||[],At=Fe.map(L=>({value:L.code,label:L.name})),cn=((y==null?void 0:y.data)||[]).filter(L=>!a||L.id!==parseInt(e)).sort((L,ie)=>new Date(ie.startDate||0).getTime()-new Date(L.startDate||0).getTime()),Ht=Te.find(L=>L.id===parseInt(R||"0")),Rc=((wh=Ht==null?void 0:Ht.tariffs)==null?void 0:wh.filter(L=>L.isActive))||[],ta=L=>{const ie=L.companyName||`${L.firstName} ${L.lastName}`,we=L.birthDate?` (geb. ${new Date(L.birthDate).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"})})`:"";return`${L.customerNumber} - ${ie}${we}`},ai=(()=>{var we;const ie=((x==null?void 0:x.data)||[]).map(he=>({value:he.id.toString(),label:ta(he)}));if(a&&((we=f==null?void 0:f.data)!=null&&we.customer)){const he=f.data.customer;ie.some(lt=>lt.value===he.id.toString())||ie.unshift({value:he.id.toString(),label:ta(he)})}return ie})();return s.jsxs("div",{children:[s.jsx("h1",{className:"text-2xl font-bold mb-6",children:a?"Vertrag bearbeiten":"Neuer Vertrag"}),Is&&s.jsx("div",{className:"mb-4 p-4 bg-red-50 border border-red-200 text-red-700 rounded-lg",children:Is instanceof Error?Is.message:"Ein Fehler ist aufgetreten"}),s.jsxs("form",{onSubmit:o(ee),children:[s.jsx(Y,{className:"mb-6",title:"Vertragsdaten",children:s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[s.jsx(Re,{label:"Kunde *",...l("customerId",{required:"Kunde erforderlich"}),options:ai,error:(Sh=h.customerId)==null?void 0:Sh.message}),s.jsx(Re,{label:"Vertragstyp *",...l("type",{required:"Typ erforderlich"}),options:At}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-1 mb-1",children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700",children:"Status"}),s.jsx("button",{type:"button",onClick:()=>qe(!0),className:"text-gray-400 hover:text-blue-600 transition-colors",title:"Status-Erklärung",children:s.jsx(Pl,{className:"w-4 h-4"})})]}),s.jsx(Re,{...l("status"),options:gC})]}),s.jsx(Re,{label:"Vertriebsplattform",...l("salesPlatformId"),options:ne.map(L=>({value:L.id,label:L.name}))}),m&&s.jsx(Re,{label:"Vorgänger-Vertrag",...l("previousContractId"),options:cn.map(L=>({value:L.id,label:`${L.contractNumber} (${L.type}${L.startDate?` - ${new Date(L.startDate).toLocaleDateString("de-DE")}`:""})`})),placeholder:"Keinen Vorgänger auswählen"})]})}),m&&s.jsxs(Y,{className:"mb-6",title:"Kundendaten verknüpfen",children:[s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 mb-4",children:[s.jsx(Re,{label:"Lieferadresse",...l("addressId"),options:vr.filter(L=>L.type==="DELIVERY_RESIDENCE").map(L=>({value:L.id,label:`${L.street} ${L.houseNumber}, ${L.postalCode} ${L.city}`}))}),s.jsx(Re,{label:"Rechnungsadresse",...l("billingAddressId"),options:vr.filter(L=>L.type==="BILLING").map(L=>({value:L.id,label:`${L.street} ${L.houseNumber}, ${L.postalCode} ${L.city}`})),placeholder:"Wie Lieferadresse"})]}),s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[s.jsx(Re,{label:"Bankkarte",...l("bankCardId"),options:O.map(L=>({value:L.id,label:`${L.iban} (${L.accountHolder})`}))}),s.jsx(Re,{label:"Ausweis",...l("identityDocumentId"),options:U.map(L=>({value:L.id,label:`${L.documentNumber} (${L.type})`}))})]})]}),s.jsx(Y,{className:"mb-6",title:"Anbieter & Tarif",children:s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[s.jsx(Re,{label:"Anbieter",...l("providerId"),options:Te.map(L=>({value:L.id,label:L.name}))}),s.jsx(Re,{label:"Tarif",...l("tariffId"),options:Rc.map(L=>({value:L.id,label:L.name})),disabled:!R}),s.jsx(V,{label:"Kundennummer beim Anbieter",...l("customerNumberAtProvider")}),s.jsx(V,{label:"Provision (€)",type:"number",step:"0.01",...l("commission")}),s.jsx(V,{label:"Preis erste 12 Monate",...l("priceFirst12Months"),placeholder:"z.B. 29,99 €/Monat"}),s.jsx(V,{label:"Preis ab 13. Monat",...l("priceFrom13Months"),placeholder:"z.B. 39,99 €/Monat"}),s.jsx(V,{label:"Preis nach 24 Monaten",...l("priceAfter24Months"),placeholder:"z.B. 49,99 €/Monat"})]})}),s.jsxs(Y,{className:"mb-6",title:"Laufzeit und Kündigung",children:[s.jsxs("p",{className:"text-sm text-gray-500 mb-4 bg-blue-50 border border-blue-200 rounded-lg p-3",children:[s.jsx("strong",{children:"Hinweis:"})," Ist die Laufzeit ≤ 4 Wochen, 1 Monat oder 30 Tage, gilt der Vertrag als unbefristet mit der jeweiligen Kündigungsfrist."]}),s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[s.jsx(V,{label:"Vertragsbeginn",type:"date",...l("startDate"),value:d("startDate")||"",onClear:()=>u("startDate","")}),s.jsx(V,{label:"Vertragsende (berechnet)",type:"date",...l("endDate"),disabled:!0,className:"bg-gray-50"}),s.jsx(Re,{label:"Vertragslaufzeit",...l("contractDurationId"),options:ge.map(L=>({value:L.id,label:L.description}))}),s.jsx(Re,{label:"Kündigungsfrist",...l("cancellationPeriodId"),options:te.map(L=>({value:L.id,label:L.description}))}),s.jsx(V,{label:"Kündigungsbestätigungsdatum",type:"date",...l("cancellationConfirmationDate"),value:d("cancellationConfirmationDate")||"",onClear:()=>u("cancellationConfirmationDate","")}),s.jsx(V,{label:"Kündigungsbestätigungsoptionendatum",type:"date",...l("cancellationConfirmationOptionsDate"),value:d("cancellationConfirmationOptionsDate")||"",onClear:()=>u("cancellationConfirmationOptionsDate","")}),s.jsx("div",{className:"col-span-2",children:s.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[s.jsx("input",{type:"checkbox",...l("wasSpecialCancellation"),className:"rounded border-gray-300"}),s.jsx("span",{children:"Wurde sondergekündigt?"})]})})]})]}),s.jsx(Y,{className:"mb-6",title:"Zugangsdaten (verschlüsselt gespeichert)",children:s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"Portal Benutzername"}),s.jsxs("div",{className:"space-y-2",children:[s.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[s.jsx("input",{type:"radio",name:"usernameType",checked:k==="manual",onChange:()=>{_("manual"),Z("")},className:"text-blue-600"}),s.jsx("span",{className:"text-sm",children:"Manuell eingeben"})]}),k==="manual"&&s.jsx(V,{...l("portalUsername"),placeholder:"Benutzername eingeben..."}),s.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[s.jsx("input",{type:"radio",name:"usernameType",checked:k==="stressfrei",onChange:()=>{_("stressfrei"),u("portalUsername","")},className:"text-blue-600"}),s.jsx("span",{className:"text-sm",children:"Stressfrei-Wechseln Adresse"})]}),k==="stressfrei"&&s.jsx(Re,{value:K,onChange:L=>Z(L.target.value),options:le.map(L=>({value:L.id,label:L.email+(L.notes?` (${L.notes})`:"")})),placeholder:le.length===0?"Keine Stressfrei-Adressen vorhanden":"Adresse auswählen..."}),k==="stressfrei"&&le.length===0&&s.jsx("p",{className:"text-xs text-amber-600",children:"Keine Stressfrei-Wechseln Adressen für diesen Kunden vorhanden. Bitte zuerst beim Kunden anlegen."})]})]}),s.jsxs("div",{className:"mt-8",children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:a?"Neues Passwort (leer lassen = unverändert)":"Portal Passwort"}),s.jsxs("div",{className:"relative",children:[s.jsx("input",{type:H?"text":"password",...l("portalPassword"),className:"block w-full px-3 py-2 pr-10 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"}),s.jsx("button",{type:"button",onClick:()=>pe(!H),className:"absolute inset-y-0 right-0 flex items-center pr-3 text-gray-400 hover:text-gray-600",children:H?s.jsx(It,{className:"w-4 h-4"}):s.jsx(Pe,{className:"w-4 h-4"})})]})]})]})}),["ELECTRICITY","GAS"].includes(p)&&s.jsxs(Y,{className:"mb-6",title:p==="ELECTRICITY"?"Strom-Details":"Gas-Details",children:[s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[s.jsx(Re,{label:"Zähler",...l("meterId"),options:Q.filter(L=>L.type===p).map(L=>({value:L.id,label:`${L.meterNumber}${L.location?` (${L.location})`:""}`}))}),s.jsx(V,{label:"MaLo-ID (Marktlokations-ID)",...l("maloId")}),s.jsx(V,{label:`Jahresverbrauch (${p==="ELECTRICITY"?"kWh":"m³"})`,type:"number",...l("annualConsumption")}),p==="GAS"&&s.jsx(V,{label:"Jahresverbrauch (kWh)",type:"number",...l("annualConsumptionKwh")}),s.jsx(V,{label:"Grundpreis (€/Monat)",type:"number",step:"any",...l("basePrice")}),s.jsx(V,{label:"Arbeitspreis (€/kWh)",type:"number",step:"any",...l("unitPrice")}),s.jsx(V,{label:"Bonus (€)",type:"number",step:"0.01",...l("bonus")}),s.jsx(V,{label:"Vorversorger",...l("previousProviderName")}),s.jsx(V,{label:"Kundennr. beim Vorversorger",...l("previousCustomerNumber")})]}),a&&s.jsxs("div",{className:"mt-4 p-3 bg-blue-50 border border-blue-200 rounded-lg text-sm text-blue-700",children:[s.jsx("strong",{children:"Hinweis:"})," Zählerstände und Rechnungen werden in der"," ",s.jsx("span",{className:"font-medium",children:"Vertragsdetailansicht"})," verwaltet, nicht hier im Bearbeitungsformular."]})]}),["DSL","CABLE","FIBER"].includes(p)&&s.jsxs(s.Fragment,{children:[s.jsx(Y,{className:"mb-6",title:p==="DSL"?"DSL-Details":p==="CABLE"?"Kabelinternet-Details":"Glasfaser-Details",children:s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[s.jsx(V,{label:"Download (Mbit/s)",type:"number",...l("downloadSpeed")}),s.jsx(V,{label:"Upload (Mbit/s)",type:"number",...l("uploadSpeed")}),s.jsx(V,{label:"Router Modell",...l("routerModel")}),s.jsx(V,{label:"Router Seriennummer",...l("routerSerialNumber")}),s.jsx(V,{label:"Installationsdatum",type:"date",...l("installationDate"),value:d("installationDate")||"",onClear:()=>u("installationDate","")}),p==="FIBER"&&s.jsx(V,{label:"Home-ID",...l("homeId")}),((kh=Ht==null?void 0:Ht.name)==null?void 0:kh.toLowerCase().includes("vodafone"))&&["DSL","CABLE"].includes(p)&&s.jsx(V,{label:"Aktivierungscode",...l("activationCode")})]})}),s.jsx(Y,{className:"mb-6",title:"Internet-Zugangsdaten (verschlüsselt)",children:s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[s.jsx(V,{label:"Benutzername",...l("internetUsername")}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:a?"Neues Passwort (leer = beibehalten)":"Passwort"}),s.jsxs("div",{className:"relative",children:[s.jsx("input",{type:oe?"text":"password",...l("internetPassword"),className:"block w-full px-3 py-2 pr-10 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"}),s.jsx("button",{type:"button",onClick:()=>Ze(!oe),className:"absolute inset-y-0 right-0 flex items-center pr-3 text-gray-400 hover:text-gray-600",children:oe?s.jsx(It,{className:"w-4 h-4"}):s.jsx(Pe,{className:"w-4 h-4"})})]})]})]})}),s.jsxs(Y,{className:"mb-6",title:"Rufnummern & SIP-Zugangsdaten",children:[s.jsx("p",{className:"text-sm text-gray-500 mb-4",children:"Hier können Sie Festnetz-Rufnummern mit SIP-Zugangsdaten erfassen."}),I.length>0&&s.jsx("div",{className:"space-y-4 mb-4",children:I.map((L,ie)=>s.jsxs("div",{className:"p-4 border rounded-lg bg-gray-50",children:[s.jsxs("div",{className:"flex justify-between items-center mb-3",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsxs("span",{className:"font-medium",children:["Rufnummer ",ie+1]}),s.jsxs("label",{className:"flex items-center gap-1 text-sm",children:[s.jsx("input",{type:"checkbox",checked:L.isMain,onChange:we=>{const he=[...I];we.target.checked?he.forEach((je,lt)=>je.isMain=lt===ie):he[ie].isMain=!1,B(he)},className:"rounded border-gray-300"}),"Hauptnummer"]})]}),s.jsx(F,{type:"button",variant:"ghost",size:"sm",onClick:()=>{B(I.filter((we,he)=>he!==ie))},children:s.jsx(be,{className:"w-4 h-4 text-red-500"})})]}),s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-3",children:[s.jsx(V,{label:"Rufnummer",value:L.phoneNumber,onChange:we=>{const he=[...I];he[ie].phoneNumber=we.target.value,B(he)},placeholder:"z.B. 030 123456"}),s.jsx(V,{label:"SIP-Benutzername",value:L.sipUsername,onChange:we=>{const he=[...I];he[ie].sipUsername=we.target.value,B(he)}}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:L.hasExistingSipPassword?"SIP-Passwort (bereits hinterlegt)":"SIP-Passwort"}),s.jsxs("div",{className:"relative",children:[s.jsx("input",{type:Oe[ie]?"text":"password",value:L.sipPassword,onChange:we=>{const he=[...I];he[ie].sipPassword=we.target.value,B(he)},placeholder:L.hasExistingSipPassword?"Leer = beibehalten":"",className:"block w-full px-3 py-2 pr-10 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"}),s.jsx("button",{type:"button",onClick:()=>it(we=>({...we,[ie]:!we[ie]})),className:"absolute inset-y-0 right-0 flex items-center pr-3 text-gray-400 hover:text-gray-600",children:Oe[ie]?s.jsx(It,{className:"w-4 h-4"}):s.jsx(Pe,{className:"w-4 h-4"})})]})]}),s.jsx(V,{label:"SIP-Server",value:L.sipServer,onChange:we=>{const he=[...I];he[ie].sipServer=we.target.value,B(he)},placeholder:"z.B. sip.provider.de"})]})]},ie))}),s.jsxs(F,{type:"button",variant:"secondary",onClick:()=>{B([...I,{phoneNumber:"",sipUsername:"",sipPassword:"",sipServer:"",isMain:I.length===0}])},children:[s.jsx(Be,{className:"w-4 h-4 mr-2"}),"Rufnummer hinzufügen"]})]})]}),p==="MOBILE"&&s.jsxs(s.Fragment,{children:[s.jsxs(Y,{className:"mb-6",title:"Mobilfunk-Details",children:[s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[s.jsx(V,{label:"Datenvolumen (GB)",type:"number",...l("dataVolume")}),s.jsx(V,{label:"Inklusiv-Minuten",type:"number",...l("includedMinutes")}),s.jsx(V,{label:"Inklusiv-SMS",type:"number",...l("includedSMS")}),s.jsx(V,{label:"Gerät (Modell)",...l("deviceModel")}),s.jsx(V,{label:"Gerät (IMEI)",...l("deviceImei")})]}),s.jsx("div",{className:"mt-4 pt-4 border-t",children:s.jsxs("label",{className:"flex items-start gap-3 cursor-pointer",children:[s.jsx("input",{type:"checkbox",...l("requiresMultisim"),className:"mt-1 rounded border-gray-300"}),s.jsxs("div",{children:[s.jsx("span",{className:"font-medium",children:"Multisim erforderlich"}),s.jsx("p",{className:"text-sm text-amber-600 mt-1",children:"Hinweis: Multisim ist bei Klarmobil, Congstar und Otelo nicht buchbar. Muss Freenet oder vergleichbar sein."})]})]})})]}),s.jsxs(Y,{className:"mb-6",title:"SIM-Karten",children:[s.jsx("p",{className:"text-sm text-gray-500 mb-4",children:"Hier können Sie alle SIM-Karten zum Vertrag erfassen (Hauptkarte und Multisim-Karten)."}),E.length>0&&s.jsx("div",{className:"space-y-4 mb-4",children:E.map((L,ie)=>s.jsxs("div",{className:"p-4 border rounded-lg bg-gray-50",children:[s.jsxs("div",{className:"flex justify-between items-center mb-3",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsxs("span",{className:"font-medium",children:["SIM-Karte ",ie+1]}),s.jsxs("label",{className:"flex items-center gap-1 text-sm",children:[s.jsx("input",{type:"checkbox",checked:L.isMain,onChange:we=>{const he=[...E];we.target.checked?he.forEach((je,lt)=>je.isMain=lt===ie):he[ie].isMain=!1,z(he)},className:"rounded border-gray-300"}),"Hauptkarte"]}),s.jsxs("label",{className:"flex items-center gap-1 text-sm",children:[s.jsx("input",{type:"checkbox",checked:L.isMultisim,onChange:we=>{const he=[...E];he[ie].isMultisim=we.target.checked,z(he)},className:"rounded border-gray-300"}),"Multisim"]})]}),s.jsx(F,{type:"button",variant:"ghost",size:"sm",onClick:()=>{z(E.filter((we,he)=>he!==ie))},children:s.jsx(be,{className:"w-4 h-4 text-red-500"})})]}),s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-3",children:[s.jsx(V,{label:"Rufnummer",value:L.phoneNumber,onChange:we=>{const he=[...E];he[ie].phoneNumber=we.target.value,z(he)},placeholder:"z.B. 0171 1234567"}),s.jsx(V,{label:"SIM-Kartennummer",value:L.simCardNumber,onChange:we=>{const he=[...E];he[ie].simCardNumber=we.target.value,z(he)},placeholder:"ICCID"}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:L.hasExistingPin?"PIN (bereits hinterlegt)":"PIN"}),s.jsxs("div",{className:"relative",children:[s.jsx("input",{type:C[ie]?"text":"password",value:L.pin,onChange:we=>{const he=[...E];he[ie].pin=we.target.value,z(he)},placeholder:L.hasExistingPin?"Leer = beibehalten":"4-stellig",className:"block w-full px-3 py-2 pr-10 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"}),s.jsx("button",{type:"button",onClick:()=>et(we=>({...we,[ie]:!we[ie]})),className:"absolute inset-y-0 right-0 flex items-center pr-3 text-gray-400 hover:text-gray-600",children:C[ie]?s.jsx(It,{className:"w-4 h-4"}):s.jsx(Pe,{className:"w-4 h-4"})})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:L.hasExistingPuk?"PUK (bereits hinterlegt)":"PUK"}),s.jsxs("div",{className:"relative",children:[s.jsx("input",{type:zt[ie]?"text":"password",value:L.puk,onChange:we=>{const he=[...E];he[ie].puk=we.target.value,z(he)},placeholder:L.hasExistingPuk?"Leer = beibehalten":"8-stellig",className:"block w-full px-3 py-2 pr-10 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"}),s.jsx("button",{type:"button",onClick:()=>Qt(we=>({...we,[ie]:!we[ie]})),className:"absolute inset-y-0 right-0 flex items-center pr-3 text-gray-400 hover:text-gray-600",children:zt[ie]?s.jsx(It,{className:"w-4 h-4"}):s.jsx(Pe,{className:"w-4 h-4"})})]})]})]})]},ie))}),s.jsxs(F,{type:"button",variant:"secondary",onClick:()=>{z([...E,{phoneNumber:"",simCardNumber:"",pin:"",puk:"",isMultisim:!1,isMain:E.length===0}])},children:[s.jsx(Be,{className:"w-4 h-4 mr-2"}),"SIM-Karte hinzufügen"]})]})]}),p==="TV"&&s.jsx(Y,{className:"mb-6",title:"TV-Details",children:s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[s.jsx(V,{label:"Receiver Modell",...l("receiverModel")}),s.jsx(V,{label:"Smartcard-Nummer",...l("smartcardNumber")}),s.jsx(V,{label:"Paket",...l("tvPackage"),placeholder:"z.B. Basis, Premium, Sport"})]})}),p==="CAR_INSURANCE"&&s.jsx(Y,{className:"mb-6",title:"KFZ-Versicherung Details",children:s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[s.jsx(V,{label:"Kennzeichen",...l("licensePlate")}),s.jsx(V,{label:"HSN",...l("hsn")}),s.jsx(V,{label:"TSN",...l("tsn")}),s.jsx(V,{label:"FIN (VIN)",...l("vin")}),s.jsx(V,{label:"Fahrzeugtyp",...l("vehicleType")}),s.jsx(V,{label:"Erstzulassung",type:"date",...l("firstRegistration"),value:d("firstRegistration")||"",onClear:()=>u("firstRegistration","")}),s.jsx(V,{label:"SF-Klasse",...l("noClaimsClass")}),s.jsx(Re,{label:"Versicherungsart",...l("insuranceType"),options:[{value:"LIABILITY",label:"Haftpflicht"},{value:"PARTIAL",label:"Teilkasko"},{value:"FULL",label:"Vollkasko"}]}),s.jsx(V,{label:"SB Teilkasko (€)",type:"number",...l("deductiblePartial")}),s.jsx(V,{label:"SB Vollkasko (€)",type:"number",...l("deductibleFull")}),s.jsx(V,{label:"Versicherungsscheinnummer",...l("policyNumber")}),s.jsx(V,{label:"Vorversicherer",...l("previousInsurer")})]})}),s.jsx(Y,{className:"mb-6",title:"Notizen",children:s.jsx("textarea",{...l("notes"),rows:4,className:"block w-full px-3 py-2 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500",placeholder:"Interne Notizen..."})}),s.jsxs("div",{className:"flex justify-end gap-4",children:[s.jsx(F,{type:"button",variant:"secondary",onClick:()=>n(-1),children:"Abbrechen"}),s.jsx(F,{type:"submit",disabled:Ne,children:Ne?"Speichern...":"Speichern"})]})]}),s.jsx(vC,{isOpen:J,onClose:()=>qe(!1)})]})}const jC={ELECTRICITY:ph,GAS:Cv,DSL:Ca,CABLE:Ca,FIBER:Ca,MOBILE:hh,TV:Tv,CAR_INSURANCE:kv},bC={ELECTRICITY:"Strom",GAS:"Gas",DSL:"DSL",CABLE:"Kabel",FIBER:"Glasfaser",MOBILE:"Mobilfunk",TV:"TV",CAR_INSURANCE:"KFZ"},NC={critical:"bg-red-100 border-red-300 text-red-800",warning:"bg-yellow-100 border-yellow-300 text-yellow-800",ok:"bg-green-100 border-green-300 text-green-800",none:"bg-gray-100 border-gray-300 text-gray-800"},wC={critical:"danger",warning:"warning",ok:"success",none:"default"},SC={cancellation_deadline:Sv,contract_ending:An,missing_cancellation_letter:Ke,missing_cancellation_confirmation:Ke,missing_portal_credentials:R2,missing_customer_number:Ke,missing_provider:Ke,missing_address:Ke,missing_bank:Ke,missing_meter:ph,missing_sim:hh,open_tasks:ol,pending_status:An,draft_status:Ke,review_due:mh,missing_invoice:uh},kC={cancellationDeadlines:"Kündigungsfristen",contractEnding:"Vertragsenden",missingCredentials:"Fehlende Zugangsdaten",missingData:"Fehlende Daten",openTasks:"Offene Aufgaben",pendingContracts:"Wartende Verträge",missingInvoices:"Fehlende Rechnungen",reviewDue:"Erneute Prüfung fällig"};function CC(){var w;const[e,t]=wc(),[n,r]=j.useState(new Set),a=e.get("filter"),[i,l]=j.useState(a||"all");j.useEffect(()=>{i==="all"?e.delete("filter"):e.set("filter",i),t(e,{replace:!0})},[i,e,t]);const{data:o,isLoading:c,error:d}=me({queryKey:["contract-cockpit"],queryFn:()=>Le.getCockpit(),staleTime:0}),u=xe(),[h,p]=j.useState(null),[m,f]=j.useState(""),x=j.useRef(null);j.useEffect(()=>{const S=E=>{x.current&&!x.current.contains(E.target)&&(p(null),f(""))};return document.addEventListener("mousedown",S),()=>document.removeEventListener("mousedown",S)},[]);const b=W({mutationFn:({contractId:S,data:E})=>Le.snooze(S,E),onSuccess:()=>{u.invalidateQueries({queryKey:["contract-cockpit"]}),p(null),f("")}}),y=(S,E)=>{E?b.mutate({contractId:S,data:{months:E}}):m&&b.mutate({contractId:S,data:{nextReviewDate:m}})},g=S=>{b.mutate({contractId:S,data:{}})},v=S=>{r(E=>{const z=new Set(E);return z.has(S)?z.delete(S):z.add(S),z})},N=j.useMemo(()=>{var E;if(!((E=o==null?void 0:o.data)!=null&&E.contracts))return[];const S=o.data.contracts;switch(i){case"critical":return S.filter(z=>z.highestUrgency==="critical");case"warning":return S.filter(z=>z.highestUrgency==="warning");case"ok":return S.filter(z=>z.highestUrgency==="ok");case"deadlines":return S.filter(z=>z.issues.some(I=>["cancellation_deadline","contract_ending"].includes(I.type)));case"credentials":return S.filter(z=>z.issues.some(I=>I.type.includes("credentials")));case"data":return S.filter(z=>z.issues.some(I=>I.type.startsWith("missing_")&&!I.type.includes("credentials")));case"tasks":return S.filter(z=>z.issues.some(I=>["open_tasks","pending_status","draft_status"].includes(I.type)));case"review":return S.filter(z=>z.issues.some(I=>I.type==="review_due"));case"invoices":return S.filter(z=>z.issues.some(I=>I.type.includes("invoice")));default:return S}},[(w=o==null?void 0:o.data)==null?void 0:w.contracts,i]);if(c)return s.jsx("div",{className:"flex items-center justify-center py-12",children:s.jsx("div",{className:"text-gray-500",children:"Laden..."})});if(d||!(o!=null&&o.data))return s.jsx("div",{className:"text-center py-12",children:s.jsx("p",{className:"text-red-500",children:"Fehler beim Laden des Cockpits"})});const{summary:D,thresholds:A}=o.data,R=S=>{var I,B,P,M;const E=n.has(S.id),z=jC[S.type]||Ke;return s.jsxs("div",{className:`border rounded-lg mb-2 ${NC[S.highestUrgency]}`,children:[s.jsxs("div",{className:"flex items-center p-4 cursor-pointer hover:bg-opacity-50",onClick:()=>v(S.id),children:[s.jsx("div",{className:"w-6 mr-2",children:E?s.jsx(In,{className:"w-5 h-5"}):s.jsx(Ft,{className:"w-5 h-5"})}),s.jsx(z,{className:"w-5 h-5 mr-3"}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx(ke,{to:`/contracts/${S.id}`,state:{from:"cockpit",filter:i!=="all"?i:void 0},className:"font-medium hover:underline",onClick:k=>k.stopPropagation(),children:S.contractNumber}),s.jsxs(ye,{variant:wC[S.highestUrgency],children:[S.issues.length," ",S.highestUrgency==="ok"?S.issues.length===1?"Hinweis":"Hinweise":S.issues.length===1?"Problem":"Probleme"]}),s.jsx("span",{className:"text-sm",children:bC[S.type]})]}),s.jsxs("div",{className:"text-sm mt-1",children:[s.jsxs(ke,{to:`/customers/${S.customer.id}`,className:"hover:underline",onClick:k=>k.stopPropagation(),children:[S.customer.customerNumber," - ",S.customer.name]}),(((I=S.provider)==null?void 0:I.name)||S.providerName)&&s.jsxs("span",{className:"ml-2",children:["| ",((B=S.provider)==null?void 0:B.name)||S.providerName,(((P=S.tariff)==null?void 0:P.name)||S.tariffName)&&` - ${((M=S.tariff)==null?void 0:M.name)||S.tariffName}`]})]})]}),s.jsxs("div",{className:"flex items-center gap-1 ml-4",children:[s.jsxs("div",{className:"relative",ref:h===S.id?x:void 0,children:[s.jsx("button",{onClick:k=>{k.stopPropagation(),p(h===S.id?null:S.id),f("")},className:"p-2 hover:bg-white hover:bg-opacity-50 rounded",title:"Zurückstellen",children:s.jsx(wv,{className:"w-4 h-4"})}),h===S.id&&s.jsxs("div",{className:"absolute right-0 top-full mt-1 w-56 bg-white border rounded-lg shadow-lg z-50 p-3",onClick:k=>k.stopPropagation(),children:[s.jsx("div",{className:"text-sm font-medium mb-2",children:"Zurückstellen"}),s.jsxs("div",{className:"space-y-1",children:[s.jsx("button",{onClick:()=>y(S.id,3),className:"w-full text-left px-3 py-2 text-sm hover:bg-gray-100 rounded",disabled:b.isPending,children:"+3 Monate"}),s.jsxs("button",{onClick:()=>y(S.id,6),className:"w-full text-left px-3 py-2 text-sm hover:bg-gray-100 rounded bg-blue-50 border-blue-200",disabled:b.isPending,children:["+6 Monate ",s.jsx("span",{className:"text-xs text-gray-500",children:"(Empfohlen)"})]}),s.jsx("button",{onClick:()=>y(S.id,12),className:"w-full text-left px-3 py-2 text-sm hover:bg-gray-100 rounded",disabled:b.isPending,children:"+12 Monate"})]}),s.jsxs("div",{className:"border-t mt-2 pt-2",children:[s.jsx("label",{className:"text-xs text-gray-500 block mb-1",children:"Eigenes Datum:"}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx(V,{type:"date",value:m,onChange:k=>f(k.target.value),className:"flex-1 text-sm",min:new Date().toISOString().split("T")[0]}),s.jsx(F,{size:"sm",onClick:()=>y(S.id),disabled:!m||b.isPending,children:"OK"})]})]}),S.issues.some(k=>k.type==="review_due")&&s.jsx("div",{className:"border-t mt-2 pt-2",children:s.jsxs("button",{onClick:()=>g(S.id),className:"w-full text-left px-3 py-2 text-sm hover:bg-red-50 text-red-600 rounded flex items-center gap-2",disabled:b.isPending,children:[s.jsx(mh,{className:"w-4 h-4"}),"Snooze aufheben"]})})]})]}),s.jsx(ke,{to:`/contracts/${S.id}`,state:{from:"cockpit",filter:i!=="all"?i:void 0},className:"p-2 hover:bg-white hover:bg-opacity-50 rounded",onClick:k=>k.stopPropagation(),title:"Zum Vertrag",children:s.jsx(Pe,{className:"w-4 h-4"})})]})]}),E&&s.jsx("div",{className:"border-t px-4 py-3 bg-white bg-opacity-50",children:s.jsx("div",{className:"space-y-2",children:S.issues.map((k,_)=>{const K=SC[k.type]||Nn,Z=k.urgency==="critical"?Nn:k.urgency==="warning"?hs:k.urgency==="ok"?Ps:An;return s.jsxs("div",{className:"flex items-start gap-3 text-sm",children:[s.jsx(Z,{className:`w-4 h-4 mt-0.5 flex-shrink-0 ${k.urgency==="critical"?"text-red-500":k.urgency==="warning"?"text-yellow-500":k.urgency==="ok"?"text-green-500":"text-gray-500"}`}),s.jsx(K,{className:"w-4 h-4 mt-0.5 flex-shrink-0 text-gray-500"}),s.jsxs("div",{children:[s.jsx("span",{className:"font-medium",children:k.label}),k.details&&s.jsx("span",{className:"text-gray-600 ml-2",children:k.details})]})]},_)})})})]},S.id)};return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center justify-between mb-6",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(Nn,{className:"w-6 h-6 text-red-500"}),s.jsx("h1",{className:"text-2xl font-bold",children:"Vertrags-Cockpit"})]}),s.jsx(ke,{to:"/settings/deadlines",className:"text-sm text-blue-600 hover:underline",children:"Fristenschwellen anpassen"})]}),s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4 mb-6",children:[s.jsx(Y,{className:"!p-4",children:s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("div",{className:"p-2 bg-red-100 rounded-lg",children:s.jsx(Nn,{className:"w-6 h-6 text-red-500"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-2xl font-bold text-red-600",children:D.criticalCount}),s.jsxs("p",{className:"text-sm text-gray-500",children:["Kritisch (<",A.criticalDays," Tage)"]})]})]})}),s.jsx(Y,{className:"!p-4",children:s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("div",{className:"p-2 bg-yellow-100 rounded-lg",children:s.jsx(hs,{className:"w-6 h-6 text-yellow-500"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-2xl font-bold text-yellow-600",children:D.warningCount}),s.jsxs("p",{className:"text-sm text-gray-500",children:["Warnung (<",A.warningDays," Tage)"]})]})]})}),s.jsx(Y,{className:"!p-4",children:s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("div",{className:"p-2 bg-green-100 rounded-lg",children:s.jsx(Ps,{className:"w-6 h-6 text-green-500"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-2xl font-bold text-green-600",children:D.okCount}),s.jsxs("p",{className:"text-sm text-gray-500",children:["OK (<",A.okDays," Tage)"]})]})]})}),s.jsx(Y,{className:"!p-4",children:s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("div",{className:"p-2 bg-gray-100 rounded-lg",children:s.jsx(Ke,{className:"w-6 h-6 text-gray-500"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-2xl font-bold text-gray-600",children:D.totalContracts}),s.jsx("p",{className:"text-sm text-gray-500",children:"Verträge mit Handlungsbedarf"})]})]})})]}),s.jsx(Y,{className:"mb-6",children:s.jsx("div",{className:"flex flex-wrap gap-4",children:Object.entries(D.byCategory).map(([S,E])=>E>0&&s.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[s.jsxs("span",{className:"font-medium",children:[kC[S]||S,":"]}),s.jsx(ye,{variant:"default",children:E})]},S))})}),s.jsx(Y,{className:"mb-6",children:s.jsxs("div",{className:"flex items-center gap-4",children:[s.jsx("span",{className:"text-sm text-gray-600",children:"Filter:"}),s.jsx(Re,{value:i,onChange:S=>l(S.target.value),options:[{value:"all",label:`Alle (${o.data.contracts.length})`},{value:"critical",label:`Kritisch (${D.criticalCount})`},{value:"warning",label:`Warnung (${D.warningCount})`},{value:"ok",label:`OK (${D.okCount})`},{value:"deadlines",label:`Fristen (${D.byCategory.cancellationDeadlines+D.byCategory.contractEnding})`},{value:"credentials",label:`Zugangsdaten (${D.byCategory.missingCredentials})`},{value:"data",label:`Fehlende Daten (${D.byCategory.missingData})`},{value:"tasks",label:`Aufgaben/Status (${D.byCategory.openTasks+D.byCategory.pendingContracts})`},{value:"review",label:`Erneute Prüfung (${D.byCategory.reviewDue||0})`},{value:"invoices",label:`Fehlende Rechnungen (${D.byCategory.missingInvoices||0})`}],className:"w-64"}),s.jsxs("span",{className:"text-sm text-gray-500",children:[N.length," Verträge angezeigt"]})]})}),N.length===0?s.jsx(Y,{children:s.jsx("div",{className:"text-center py-8 text-gray-500",children:i==="all"?s.jsxs(s.Fragment,{children:[s.jsx(Ps,{className:"w-12 h-12 mx-auto mb-4 text-green-500"}),s.jsx("p",{className:"text-lg font-medium",children:"Alles in Ordnung!"}),s.jsx("p",{children:"Keine Verträge mit Handlungsbedarf gefunden."})]}):s.jsx("p",{children:"Keine Verträge für diesen Filter gefunden."})})}):s.jsx("div",{children:N.map(R)})]})}const Kx={OPEN:"Offen",COMPLETED:"Erledigt"},EC={OPEN:"warning",COMPLETED:"success"};function DC(){var P;const e=ts(),t=xe(),{isCustomerPortal:n,user:r,hasPermission:a}=He(),[i,l]=j.useState("OPEN"),[o,c]=j.useState(new Set),[d,u]=j.useState(!1),[h,p]=j.useState({}),m=n?"Support-Anfragen":"Aufgaben",f=n?"Anfrage":"Aufgabe",{data:x,isLoading:b}=me({queryKey:["app-settings-public"],queryFn:()=>Jr.getPublic(),enabled:n,staleTime:0}),y=!b&&((P=x==null?void 0:x.data)==null?void 0:P.customerSupportTicketsEnabled)==="true",{data:g,isLoading:v}=me({queryKey:["all-tasks",i],queryFn:()=>ut.getAll({status:i||void 0}),staleTime:0}),N=W({mutationFn:M=>ut.completeSubtask(M),onSuccess:()=>{t.invalidateQueries({queryKey:["all-tasks"]}),t.invalidateQueries({queryKey:["task-stats"]})}}),D=W({mutationFn:M=>ut.reopenSubtask(M),onSuccess:()=>{t.invalidateQueries({queryKey:["all-tasks"]}),t.invalidateQueries({queryKey:["task-stats"]})}}),A=W({mutationFn:({taskId:M,title:k})=>n?ut.createReply(M,k):ut.createSubtask(M,k),onSuccess:(M,{taskId:k})=>{t.invalidateQueries({queryKey:["all-tasks"]}),p(_=>({..._,[k]:""}))}}),R=j.useMemo(()=>{var K;if(!(g!=null&&g.data))return{ownTasks:[],representedTasks:[],allTasks:[]};const M=g.data;if(!n)return{allTasks:M,ownTasks:[],representedTasks:[]};const k=[],_=[];for(const Z of M)((K=Z.contract)==null?void 0:K.customerId)===(r==null?void 0:r.customerId)?k.push(Z):_.push(Z);return{ownTasks:k,representedTasks:_,allTasks:[]}},[g==null?void 0:g.data,n,r==null?void 0:r.customerId]),w=M=>{c(k=>{const _=new Set(k);return _.has(M)?_.delete(M):_.add(M),_})},S=M=>{N.isPending||D.isPending||(M.status==="COMPLETED"?D.mutate(M.id):N.mutate(M.id))},E=M=>{var _;const k=(_=h[M])==null?void 0:_.trim();k&&A.mutate({taskId:M,title:k})},z=!n&&a("contracts:update"),I=(M,k=!1)=>{var Oe,it,C,et,zt,Qt;const _=o.has(M.id),K=M.subtasks&&M.subtasks.length>0,Z=((Oe=M.subtasks)==null?void 0:Oe.filter(J=>J.status==="COMPLETED").length)||0,H=((it=M.subtasks)==null?void 0:it.length)||0,pe=M.status==="COMPLETED",oe=M.contract?`${M.contract.contractNumber} - ${((C=M.contract.provider)==null?void 0:C.name)||M.contract.providerName||"Kein Anbieter"}`:`Vertrag #${M.contractId}`,Ze=(et=M.contract)!=null&&et.customer?M.contract.customer.companyName||`${M.contract.customer.firstName} ${M.contract.customer.lastName}`:"";return s.jsxs("div",{className:"border rounded-lg mb-2",children:[s.jsxs("div",{className:"flex items-center p-4 hover:bg-gray-50 cursor-pointer",onClick:()=>w(M.id),children:[s.jsx("div",{className:"w-6 mr-2",children:_?s.jsx(In,{className:"w-5 h-5 text-gray-400"}):s.jsx(Ft,{className:"w-5 h-5 text-gray-400"})}),s.jsx("div",{className:"mr-3",children:M.status==="COMPLETED"?s.jsx(Ps,{className:"w-5 h-5 text-green-500"}):s.jsx(An,{className:"w-5 h-5 text-yellow-500"})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("span",{className:"font-medium",children:M.title}),s.jsx(ye,{variant:EC[M.status],children:Kx[M.status]}),K&&s.jsxs("span",{className:"text-xs text-gray-500",children:["(",Z,"/",H," erledigt)"]})]}),s.jsxs("div",{className:"text-sm text-gray-500 mt-1 flex items-center gap-2",children:[s.jsx(Ke,{className:"w-4 h-4"}),s.jsx(ke,{to:`/contracts/${M.contractId}`,className:"text-blue-600 hover:underline",onClick:J=>J.stopPropagation(),children:oe}),k&&Ze&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-gray-400",children:"|"}),s.jsx("span",{children:Ze})]})]}),M.description&&s.jsx("p",{className:"text-sm text-gray-600 mt-1 line-clamp-2",children:M.description})]}),s.jsx("div",{className:"ml-4 flex gap-2",children:s.jsx(F,{variant:"ghost",size:"sm",onClick:J=>{J.stopPropagation(),e(`/contracts/${M.contractId}`)},title:"Zum Vertrag",children:s.jsx(Pe,{className:"w-4 h-4"})})})]}),_&&s.jsxs("div",{className:"border-t bg-gray-50 px-4 py-3",children:[K&&s.jsx("div",{className:"space-y-2 mb-4",children:(zt=M.subtasks)==null?void 0:zt.map(J=>{const qe=new Date(J.createdAt).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"});return s.jsxs("div",{className:`flex items-start gap-2 text-sm ml-6 ${z?"cursor-pointer hover:bg-gray-100 rounded px-2 py-1 -mx-2":""}`,onClick:z?()=>S(J):void 0,children:[s.jsx("span",{className:"flex-shrink-0 mt-0.5",children:J.status==="COMPLETED"?s.jsx(Ps,{className:"w-4 h-4 text-green-500"}):s.jsx(No,{className:"w-4 h-4 text-gray-400"})}),s.jsxs("span",{className:J.status==="COMPLETED"?"text-gray-500 line-through":"",children:[J.title,s.jsxs("span",{className:"text-xs text-gray-400 ml-2",children:[J.createdBy," • ",qe]})]})]},J.id)})}),!pe&&(z||n)&&s.jsxs("div",{className:"flex gap-2 ml-6",children:[s.jsx(V,{placeholder:n?"Antwort schreiben...":"Neue Unteraufgabe...",value:h[M.id]||"",onChange:J=>p(qe=>({...qe,[M.id]:J.target.value})),onKeyDown:J=>{J.key==="Enter"&&!J.shiftKey&&(J.preventDefault(),E(M.id))},className:"flex-1"}),s.jsx(F,{size:"sm",onClick:()=>E(M.id),disabled:!((Qt=h[M.id])!=null&&Qt.trim())||A.isPending,children:s.jsx(Ml,{className:"w-4 h-4"})})]}),!K&&pe&&s.jsx("p",{className:"text-gray-500 text-sm text-center py-2",children:"Keine Unteraufgaben vorhanden."})]})]},M.id)},B=n?y:a("contracts:update");return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center justify-between mb-6",children:[s.jsx("h1",{className:"text-2xl font-bold",children:m}),B&&s.jsxs(F,{onClick:()=>u(!0),children:[s.jsx(Be,{className:"w-4 h-4 mr-2"}),"Neue ",f]})]}),s.jsx(Y,{className:"mb-6",children:s.jsx("div",{className:"flex gap-4 flex-wrap items-center",children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-sm text-gray-600",children:"Status:"}),s.jsx(Re,{value:i,onChange:M=>l(M.target.value),options:[{value:"",label:"Alle"},...Object.entries(Kx).map(([M,k])=>({value:M,label:k}))],className:"w-40"})]})})}),v?s.jsx(Y,{children:s.jsx("div",{className:"text-center py-8 text-gray-500",children:"Laden..."})}):s.jsx(s.Fragment,{children:n?s.jsxs("div",{className:"space-y-6",children:[s.jsxs(Y,{children:[s.jsxs("div",{className:"flex items-center gap-3 mb-4 pb-3 border-b",children:[s.jsx(Tl,{className:"w-5 h-5 text-blue-600"}),s.jsxs("h2",{className:"text-lg font-semibold text-gray-900",children:["Meine ",m]}),s.jsx(ye,{variant:"default",children:R.ownTasks.length})]}),R.ownTasks.length>0?s.jsx("div",{children:R.ownTasks.map(M=>I(M,!1))}):s.jsxs("p",{className:"text-gray-500 text-center py-4",children:["Keine eigenen ",m.toLowerCase()," vorhanden."]})]}),R.representedTasks.length>0&&s.jsxs(Y,{children:[s.jsxs("div",{className:"flex items-center gap-3 mb-4 pb-3 border-b",children:[s.jsx(ka,{className:"w-5 h-5 text-purple-600"}),s.jsxs("h2",{className:"text-lg font-semibold text-gray-900",children:[m," freigegebener Kunden"]}),s.jsx(ye,{variant:"default",children:R.representedTasks.length})]}),s.jsx("div",{children:R.representedTasks.map(M=>I(M,!0))})]})]}):s.jsx(Y,{children:R.allTasks&&R.allTasks.length>0?s.jsx("div",{children:R.allTasks.map(M=>I(M,!0))}):s.jsxs("div",{className:"text-center py-8 text-gray-500",children:["Keine ",m.toLowerCase()," gefunden."]})})}),n?s.jsx(PC,{isOpen:d,onClose:()=>u(!1)}):s.jsx(AC,{isOpen:d,onClose:()=>u(!1)})]})}function PC({isOpen:e,onClose:t}){const{user:n}=He(),r=ts(),a=xe(),[i,l]=j.useState("own"),[o,c]=j.useState(null),[d,u]=j.useState(""),[h,p]=j.useState(""),[m,f]=j.useState(!1),[x,b]=j.useState(""),{data:y}=me({queryKey:["contracts",n==null?void 0:n.customerId],queryFn:()=>Le.getAll({customerId:n==null?void 0:n.customerId}),enabled:e}),g=j.useMemo(()=>{if(!(y!=null&&y.data))return{own:[],represented:{}};const w=[],S={};for(const E of y.data)if(E.customerId===(n==null?void 0:n.customerId))w.push(E);else{if(!S[E.customerId]){const z=E.customer?E.customer.companyName||`${E.customer.firstName} ${E.customer.lastName}`:`Kunde ${E.customerId}`;S[E.customerId]={name:z,contracts:[]}}S[E.customerId].contracts.push(E)}return{own:w,represented:S}},[y==null?void 0:y.data,n==null?void 0:n.customerId]),v=Object.keys(g.represented).length>0,N=j.useMemo(()=>{var w;return i==="own"?g.own:((w=g.represented[i])==null?void 0:w.contracts)||[]},[i,g]),D=j.useMemo(()=>{if(!x)return N;const w=x.toLowerCase();return N.filter(S=>S.contractNumber.toLowerCase().includes(w)||(S.providerName||"").toLowerCase().includes(w)||(S.tariffName||"").toLowerCase().includes(w))},[N,x]),A=async()=>{if(!(!o||!d.trim())){f(!0);try{await ut.createSupportTicket(o,{title:d.trim(),description:h.trim()||void 0}),a.invalidateQueries({queryKey:["all-tasks"]}),a.invalidateQueries({queryKey:["task-stats"]}),t(),u(""),p(""),c(null),l("own"),r(`/contracts/${o}`)}catch(w){console.error("Fehler beim Erstellen der Support-Anfrage:",w),alert("Fehler beim Erstellen der Support-Anfrage. Bitte versuchen Sie es erneut.")}finally{f(!1)}}},R=()=>{u(""),p(""),c(null),l("own"),b(""),t()};return s.jsx(Ve,{isOpen:e,onClose:R,title:"Neue Support-Anfrage",children:s.jsxs("div",{className:"space-y-4",children:[v&&s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Kunde"}),s.jsxs("select",{value:i,onChange:w=>{const S=w.target.value;l(S==="own"?"own":parseInt(S)),c(null),b("")},className:"w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500",children:[s.jsx("option",{value:"own",children:"Eigene Verträge"}),Object.entries(g.represented).map(([w,{name:S}])=>s.jsx("option",{value:w,children:S},w))]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Vertrag *"}),s.jsx(V,{placeholder:"Vertrag suchen...",value:x,onChange:w=>b(w.target.value),className:"mb-2"}),s.jsx("div",{className:"max-h-48 overflow-y-auto border rounded-lg",children:D.length>0?D.map(w=>s.jsxs("div",{onClick:()=>c(w.id),className:`p-3 cursor-pointer border-b last:border-b-0 hover:bg-gray-50 ${o===w.id?"bg-blue-50 border-blue-200":""}`,children:[s.jsx("div",{className:"font-medium",children:w.contractNumber}),s.jsxs("div",{className:"text-sm text-gray-500",children:[w.providerName||"Kein Anbieter",w.tariffName&&` - ${w.tariffName}`]})]},w.id)):s.jsx("div",{className:"p-3 text-gray-500 text-center",children:"Keine Verträge gefunden."})})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Titel *"}),s.jsx(V,{value:d,onChange:w=>u(w.target.value),placeholder:"Kurze Beschreibung Ihres Anliegens"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Beschreibung"}),s.jsx("textarea",{value:h,onChange:w=>p(w.target.value),placeholder:"Detaillierte Beschreibung (optional)",rows:4,className:"w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"})]}),s.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[s.jsx(F,{variant:"secondary",onClick:R,children:"Abbrechen"}),s.jsx(F,{onClick:A,disabled:!o||!d.trim()||m,children:m?"Wird erstellt...":"Anfrage erstellen"})]})]})})}function AC({isOpen:e,onClose:t}){const n=ts(),r=xe(),[a,i]=j.useState(null),[l,o]=j.useState(null),[c,d]=j.useState(""),[u,h]=j.useState(""),[p,m]=j.useState(!1),[f,x]=j.useState(!1),[b,y]=j.useState(""),[g,v]=j.useState(""),{data:N}=me({queryKey:["customers-for-task"],queryFn:()=>Dt.getAll({limit:100}),enabled:e}),{data:D}=me({queryKey:["contracts-for-task",a],queryFn:()=>Le.getAll({customerId:a}),enabled:e&&a!==null}),A=j.useMemo(()=>{if(!(N!=null&&N.data))return[];if(!b)return N.data;const z=b.toLowerCase();return N.data.filter(I=>I.customerNumber.toLowerCase().includes(z)||I.firstName.toLowerCase().includes(z)||I.lastName.toLowerCase().includes(z)||(I.companyName||"").toLowerCase().includes(z))},[N==null?void 0:N.data,b]),R=j.useMemo(()=>{if(!(D!=null&&D.data))return[];if(!g)return D.data;const z=g.toLowerCase();return D.data.filter(I=>I.contractNumber.toLowerCase().includes(z)||(I.providerName||"").toLowerCase().includes(z)||(I.tariffName||"").toLowerCase().includes(z))},[D==null?void 0:D.data,g]),w=async()=>{if(!(!l||!c.trim())){x(!0);try{await ut.create(l,{title:c.trim(),description:u.trim()||void 0,visibleInPortal:p}),r.invalidateQueries({queryKey:["all-tasks"]}),r.invalidateQueries({queryKey:["task-stats"]}),t(),d(""),h(""),m(!1),o(null),i(null),n(`/contracts/${l}`)}catch(z){console.error("Fehler beim Erstellen der Aufgabe:",z),alert("Fehler beim Erstellen der Aufgabe. Bitte versuchen Sie es erneut.")}finally{x(!1)}}},S=()=>{d(""),h(""),m(!1),o(null),i(null),y(""),v(""),t()},E=z=>{const I=z.companyName||`${z.firstName} ${z.lastName}`;return`${z.customerNumber} - ${I}`};return s.jsx(Ve,{isOpen:e,onClose:S,title:"Neue Aufgabe",children:s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Kunde *"}),s.jsx(V,{placeholder:"Kunde suchen...",value:b,onChange:z=>y(z.target.value),className:"mb-2"}),s.jsx("div",{className:"max-h-40 overflow-y-auto border rounded-lg",children:A.length>0?A.map(z=>s.jsx("div",{onClick:()=>{i(z.id),o(null),v("")},className:`p-3 cursor-pointer border-b last:border-b-0 hover:bg-gray-50 ${a===z.id?"bg-blue-50 border-blue-200":""}`,children:s.jsx("div",{className:"font-medium",children:E(z)})},z.id)):s.jsx("div",{className:"p-3 text-gray-500 text-center",children:"Keine Kunden gefunden."})})]}),a&&s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Vertrag *"}),s.jsx(V,{placeholder:"Vertrag suchen...",value:g,onChange:z=>v(z.target.value),className:"mb-2"}),s.jsx("div",{className:"max-h-40 overflow-y-auto border rounded-lg",children:R.length>0?R.map(z=>s.jsxs("div",{onClick:()=>o(z.id),className:`p-3 cursor-pointer border-b last:border-b-0 hover:bg-gray-50 ${l===z.id?"bg-blue-50 border-blue-200":""}`,children:[s.jsx("div",{className:"font-medium",children:z.contractNumber}),s.jsxs("div",{className:"text-sm text-gray-500",children:[z.providerName||"Kein Anbieter",z.tariffName&&` - ${z.tariffName}`]})]},z.id)):s.jsx("div",{className:"p-3 text-gray-500 text-center",children:D?"Keine Verträge gefunden.":"Laden..."})})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Titel *"}),s.jsx(V,{value:c,onChange:z=>d(z.target.value),placeholder:"Aufgabentitel"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Beschreibung"}),s.jsx("textarea",{value:u,onChange:z=>h(z.target.value),placeholder:"Detaillierte Beschreibung (optional)",rows:3,className:"w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"})]}),s.jsx("div",{children:s.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:p,onChange:z=>m(z.target.checked),className:"rounded border-gray-300 text-blue-600 focus:ring-blue-500"}),s.jsx("span",{className:"text-sm text-gray-700",children:"Im Kundenportal sichtbar"})]})}),s.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[s.jsx(F,{variant:"secondary",onClick:S,children:"Abbrechen"}),s.jsx(F,{onClick:w,disabled:!l||!c.trim()||f,children:f?"Wird erstellt...":"Aufgabe erstellen"})]})]})})}function MC(){const[e,t]=j.useState(!1),[n,r]=j.useState(null),[a,i]=j.useState(!1),{hasPermission:l}=He(),o=xe(),{data:c,isLoading:d}=me({queryKey:["platforms",a],queryFn:()=>rl.getAll(a)}),u=W({mutationFn:rl.delete,onSuccess:()=>{o.invalidateQueries({queryKey:["platforms"]})}}),h=m=>{r(m),t(!0)},p=()=>{t(!1),r(null)};return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center justify-between mb-6",children:[s.jsx("h1",{className:"text-2xl font-bold",children:"Vertriebsplattformen"}),l("platforms:create")&&s.jsxs(F,{onClick:()=>t(!0),children:[s.jsx(Be,{className:"w-4 h-4 mr-2"}),"Neue Plattform"]})]}),s.jsxs(Y,{children:[s.jsx("div",{className:"mb-4",children:s.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[s.jsx("input",{type:"checkbox",checked:a,onChange:m=>i(m.target.checked),className:"rounded"}),"Inaktive anzeigen"]})}),d?s.jsx("div",{className:"text-center py-8 text-gray-500",children:"Laden..."}):c!=null&&c.data&&c.data.length>0?s.jsx("div",{className:"overflow-x-auto",children:s.jsxs("table",{className:"w-full",children:[s.jsx("thead",{children:s.jsxs("tr",{className:"border-b",children:[s.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"Name"}),s.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"Kontakt"}),s.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"Status"}),s.jsx("th",{className:"text-right py-3 px-4 font-medium text-gray-600",children:"Aktionen"})]})}),s.jsx("tbody",{children:c.data.map(m=>s.jsxs("tr",{className:"border-b hover:bg-gray-50",children:[s.jsx("td",{className:"py-3 px-4 font-medium",children:m.name}),s.jsx("td",{className:"py-3 px-4 text-gray-500",children:m.contactInfo||"-"}),s.jsx("td",{className:"py-3 px-4",children:s.jsx(ye,{variant:m.isActive?"success":"danger",children:m.isActive?"Aktiv":"Inaktiv"})}),s.jsx("td",{className:"py-3 px-4 text-right",children:s.jsxs("div",{className:"flex justify-end gap-2",children:[l("platforms:update")&&s.jsx(F,{variant:"ghost",size:"sm",onClick:()=>h(m),children:s.jsx(Ye,{className:"w-4 h-4"})}),l("platforms:delete")&&s.jsx(F,{variant:"ghost",size:"sm",onClick:()=>{confirm("Plattform wirklich löschen?")&&u.mutate(m.id)},children:s.jsx(be,{className:"w-4 h-4 text-red-500"})})]})})]},m.id))})]})}):s.jsx("div",{className:"text-center py-8 text-gray-500",children:"Keine Plattformen vorhanden."})]}),s.jsx(TC,{isOpen:e,onClose:p,platform:n})]})}function TC({isOpen:e,onClose:t,platform:n}){const r=xe(),[a,i]=j.useState({name:"",contactInfo:"",isActive:!0});j.useState(()=>{i(n?{name:n.name,contactInfo:n.contactInfo||"",isActive:n.isActive}:{name:"",contactInfo:"",isActive:!0})}),n&&a.name!==n.name?i({name:n.name,contactInfo:n.contactInfo||"",isActive:n.isActive}):!n&&a.name;const l=W({mutationFn:rl.create,onSuccess:()=>{r.invalidateQueries({queryKey:["platforms"]}),t(),i({name:"",contactInfo:"",isActive:!0})}}),o=W({mutationFn:u=>rl.update(n.id,u),onSuccess:()=>{r.invalidateQueries({queryKey:["platforms"]}),t()}}),c=u=>{u.preventDefault(),n?o.mutate(a):l.mutate(a)},d=l.isPending||o.isPending;return s.jsx(Ve,{isOpen:e,onClose:t,title:n?"Plattform bearbeiten":"Neue Plattform",children:s.jsxs("form",{onSubmit:c,className:"space-y-4",children:[s.jsx(V,{label:"Name *",value:a.name,onChange:u=>i({...a,name:u.target.value}),required:!0}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Kontaktinformationen"}),s.jsx("textarea",{value:a.contactInfo,onChange:u=>i({...a,contactInfo:u.target.value}),rows:3,className:"block w-full px-3 py-2 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500",placeholder:"E-Mail, Telefon, Ansprechpartner..."})]}),n&&s.jsxs("label",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"checkbox",checked:a.isActive,onChange:u=>i({...a,isActive:u.target.checked}),className:"rounded"}),"Aktiv"]}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx(F,{type:"button",variant:"secondary",onClick:t,children:"Abbrechen"}),s.jsx(F,{type:"submit",disabled:d,children:d?"Speichern...":"Speichern"})]})]})})}function FC(){const[e,t]=j.useState(!1),[n,r]=j.useState(null),[a,i]=j.useState(!1),{hasPermission:l}=He(),o=xe(),{data:c,isLoading:d}=me({queryKey:["cancellation-periods",a],queryFn:()=>al.getAll(a)}),u=W({mutationFn:al.delete,onSuccess:()=>{o.invalidateQueries({queryKey:["cancellation-periods"]})}}),h=m=>{r(m),t(!0)},p=()=>{t(!1),r(null)};return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-4 mb-6",children:[s.jsx(ke,{to:"/settings",children:s.jsx(F,{variant:"ghost",size:"sm",children:s.jsx(Qs,{className:"w-4 h-4"})})}),s.jsx("h1",{className:"text-2xl font-bold flex-1",children:"Kündigungsfristen"}),l("platforms:create")&&s.jsxs(F,{onClick:()=>t(!0),children:[s.jsx(Be,{className:"w-4 h-4 mr-2"}),"Neue Frist"]})]}),s.jsxs(Y,{children:[s.jsx("div",{className:"mb-4",children:s.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[s.jsx("input",{type:"checkbox",checked:a,onChange:m=>i(m.target.checked),className:"rounded"}),"Inaktive anzeigen"]})}),s.jsxs("div",{className:"mb-4 p-4 bg-blue-50 border border-blue-200 rounded-lg text-sm",children:[s.jsx("strong",{children:"Code-Format:"})," Zahl + Buchstabe (T=Tage, M=Monate, J=Jahre)",s.jsx("br",{}),s.jsx("strong",{children:"Beispiele:"})," 14T = 14 Tage, 3M = 3 Monate, 1J = 1 Jahr"]}),d?s.jsx("div",{className:"text-center py-8 text-gray-500",children:"Laden..."}):c!=null&&c.data&&c.data.length>0?s.jsx("div",{className:"overflow-x-auto",children:s.jsxs("table",{className:"w-full",children:[s.jsx("thead",{children:s.jsxs("tr",{className:"border-b",children:[s.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"Code"}),s.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"Beschreibung"}),s.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"Status"}),s.jsx("th",{className:"text-right py-3 px-4 font-medium text-gray-600",children:"Aktionen"})]})}),s.jsx("tbody",{children:c.data.map(m=>s.jsxs("tr",{className:"border-b hover:bg-gray-50",children:[s.jsx("td",{className:"py-3 px-4 font-mono font-medium",children:m.code}),s.jsx("td",{className:"py-3 px-4",children:m.description}),s.jsx("td",{className:"py-3 px-4",children:s.jsx(ye,{variant:m.isActive?"success":"danger",children:m.isActive?"Aktiv":"Inaktiv"})}),s.jsx("td",{className:"py-3 px-4 text-right",children:s.jsxs("div",{className:"flex justify-end gap-2",children:[l("platforms:update")&&s.jsx(F,{variant:"ghost",size:"sm",onClick:()=>h(m),children:s.jsx(Ye,{className:"w-4 h-4"})}),l("platforms:delete")&&s.jsx(F,{variant:"ghost",size:"sm",onClick:()=>{confirm("Kündigungsfrist wirklich löschen?")&&u.mutate(m.id)},children:s.jsx(be,{className:"w-4 h-4 text-red-500"})})]})})]},m.id))})]})}):s.jsx("div",{className:"text-center py-8 text-gray-500",children:"Keine Kündigungsfristen vorhanden."})]}),s.jsx(IC,{isOpen:e,onClose:p,period:n})]})}function IC({isOpen:e,onClose:t,period:n}){const r=xe(),[a,i]=j.useState({code:"",description:"",isActive:!0});j.useEffect(()=>{e&&i(n?{code:n.code,description:n.description,isActive:n.isActive}:{code:"",description:"",isActive:!0})},[e,n]);const l=W({mutationFn:al.create,onSuccess:()=>{r.invalidateQueries({queryKey:["cancellation-periods"]}),t(),i({code:"",description:"",isActive:!0})}}),o=W({mutationFn:u=>al.update(n.id,u),onSuccess:()=>{r.invalidateQueries({queryKey:["cancellation-periods"]}),t()}}),c=u=>{u.preventDefault(),n?o.mutate(a):l.mutate(a)},d=l.isPending||o.isPending;return s.jsx(Ve,{isOpen:e,onClose:t,title:n?"Kündigungsfrist bearbeiten":"Neue Kündigungsfrist",children:s.jsxs("form",{onSubmit:c,className:"space-y-4",children:[s.jsx(V,{label:"Code *",value:a.code,onChange:u=>i({...a,code:u.target.value.toUpperCase()}),required:!0,placeholder:"z.B. 14T, 3M, 1J"}),s.jsx(V,{label:"Beschreibung *",value:a.description,onChange:u=>i({...a,description:u.target.value}),required:!0,placeholder:"z.B. 14 Tage, 3 Monate, 1 Jahr"}),n&&s.jsxs("label",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"checkbox",checked:a.isActive,onChange:u=>i({...a,isActive:u.target.checked}),className:"rounded"}),"Aktiv"]}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx(F,{type:"button",variant:"secondary",onClick:t,children:"Abbrechen"}),s.jsx(F,{type:"submit",disabled:d,children:d?"Speichern...":"Speichern"})]})]})})}function RC(){const[e,t]=j.useState(!1),[n,r]=j.useState(null),[a,i]=j.useState(!1),{hasPermission:l}=He(),o=xe(),{data:c,isLoading:d}=me({queryKey:["contract-durations",a],queryFn:()=>il.getAll(a)}),u=W({mutationFn:il.delete,onSuccess:()=>{o.invalidateQueries({queryKey:["contract-durations"]})}}),h=m=>{r(m),t(!0)},p=()=>{t(!1),r(null)};return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-4 mb-6",children:[s.jsx(ke,{to:"/settings",children:s.jsx(F,{variant:"ghost",size:"sm",children:s.jsx(Qs,{className:"w-4 h-4"})})}),s.jsx("h1",{className:"text-2xl font-bold flex-1",children:"Vertragslaufzeiten"}),l("platforms:create")&&s.jsxs(F,{onClick:()=>t(!0),children:[s.jsx(Be,{className:"w-4 h-4 mr-2"}),"Neue Laufzeit"]})]}),s.jsxs(Y,{children:[s.jsx("div",{className:"mb-4",children:s.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[s.jsx("input",{type:"checkbox",checked:a,onChange:m=>i(m.target.checked),className:"rounded"}),"Inaktive anzeigen"]})}),s.jsxs("div",{className:"mb-4 p-4 bg-blue-50 border border-blue-200 rounded-lg text-sm",children:[s.jsx("strong",{children:"Code-Format:"})," Zahl + Buchstabe (T=Tage, M=Monate, J=Jahre)",s.jsx("br",{}),s.jsx("strong",{children:"Beispiele:"})," 12M = 12 Monate, 24M = 24 Monate, 2J = 2 Jahre"]}),d?s.jsx("div",{className:"text-center py-8 text-gray-500",children:"Laden..."}):c!=null&&c.data&&c.data.length>0?s.jsx("div",{className:"overflow-x-auto",children:s.jsxs("table",{className:"w-full",children:[s.jsx("thead",{children:s.jsxs("tr",{className:"border-b",children:[s.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"Code"}),s.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"Beschreibung"}),s.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"Status"}),s.jsx("th",{className:"text-right py-3 px-4 font-medium text-gray-600",children:"Aktionen"})]})}),s.jsx("tbody",{children:c.data.map(m=>s.jsxs("tr",{className:"border-b hover:bg-gray-50",children:[s.jsx("td",{className:"py-3 px-4 font-mono font-medium",children:m.code}),s.jsx("td",{className:"py-3 px-4",children:m.description}),s.jsx("td",{className:"py-3 px-4",children:s.jsx(ye,{variant:m.isActive?"success":"danger",children:m.isActive?"Aktiv":"Inaktiv"})}),s.jsx("td",{className:"py-3 px-4 text-right",children:s.jsxs("div",{className:"flex justify-end gap-2",children:[l("platforms:update")&&s.jsx(F,{variant:"ghost",size:"sm",onClick:()=>h(m),children:s.jsx(Ye,{className:"w-4 h-4"})}),l("platforms:delete")&&s.jsx(F,{variant:"ghost",size:"sm",onClick:()=>{confirm("Laufzeit wirklich löschen?")&&u.mutate(m.id)},children:s.jsx(be,{className:"w-4 h-4 text-red-500"})})]})})]},m.id))})]})}):s.jsx("div",{className:"text-center py-8 text-gray-500",children:"Keine Laufzeiten vorhanden."})]}),s.jsx(LC,{isOpen:e,onClose:p,duration:n})]})}function LC({isOpen:e,onClose:t,duration:n}){const r=xe(),[a,i]=j.useState({code:"",description:"",isActive:!0});j.useEffect(()=>{e&&i(n?{code:n.code,description:n.description,isActive:n.isActive}:{code:"",description:"",isActive:!0})},[e,n]);const l=W({mutationFn:il.create,onSuccess:()=>{r.invalidateQueries({queryKey:["contract-durations"]}),t(),i({code:"",description:"",isActive:!0})}}),o=W({mutationFn:u=>il.update(n.id,u),onSuccess:()=>{r.invalidateQueries({queryKey:["contract-durations"]}),t()}}),c=u=>{u.preventDefault(),n?o.mutate(a):l.mutate(a)},d=l.isPending||o.isPending;return s.jsx(Ve,{isOpen:e,onClose:t,title:n?"Laufzeit bearbeiten":"Neue Laufzeit",children:s.jsxs("form",{onSubmit:c,className:"space-y-4",children:[s.jsx(V,{label:"Code *",value:a.code,onChange:u=>i({...a,code:u.target.value.toUpperCase()}),required:!0,placeholder:"z.B. 12M, 24M, 2J"}),s.jsx(V,{label:"Beschreibung *",value:a.description,onChange:u=>i({...a,description:u.target.value}),required:!0,placeholder:"z.B. 12 Monate, 24 Monate, 2 Jahre"}),n&&s.jsxs("label",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"checkbox",checked:a.isActive,onChange:u=>i({...a,isActive:u.target.checked}),className:"rounded"}),"Aktiv"]}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx(F,{type:"button",variant:"secondary",onClick:t,children:"Abbrechen"}),s.jsx(F,{type:"submit",disabled:d,children:d?"Speichern...":"Speichern"})]})]})})}function OC(){const[e,t]=j.useState(!1),[n,r]=j.useState(null),[a,i]=j.useState(!1),[l,o]=j.useState(new Set),{hasPermission:c}=He(),d=xe(),{data:u,isLoading:h}=me({queryKey:["providers",a],queryFn:()=>Ja.getAll(a)}),p=W({mutationFn:Ja.delete,onSuccess:()=>{d.invalidateQueries({queryKey:["providers"]})},onError:b=>{alert(b.message)}}),m=b=>{o(y=>{const g=new Set(y);return g.has(b)?g.delete(b):g.add(b),g})},f=b=>{r(b),t(!0)},x=()=>{t(!1),r(null)};return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-4 mb-6",children:[s.jsx(ke,{to:"/settings",children:s.jsx(F,{variant:"ghost",size:"sm",children:s.jsx(Qs,{className:"w-4 h-4"})})}),s.jsx("h1",{className:"text-2xl font-bold flex-1",children:"Anbieter & Tarife"}),c("providers:create")&&s.jsxs(F,{onClick:()=>t(!0),children:[s.jsx(Be,{className:"w-4 h-4 mr-2"}),"Neuer Anbieter"]})]}),s.jsxs(Y,{children:[s.jsx("div",{className:"mb-4",children:s.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[s.jsx("input",{type:"checkbox",checked:a,onChange:b=>i(b.target.checked),className:"rounded"}),"Inaktive anzeigen"]})}),h?s.jsx("div",{className:"text-center py-8 text-gray-500",children:"Laden..."}):u!=null&&u.data&&u.data.length>0?s.jsx("div",{className:"space-y-2",children:u.data.map(b=>s.jsx(zC,{provider:b,isExpanded:l.has(b.id),onToggle:()=>m(b.id),onEdit:()=>f(b),onDelete:()=>{confirm("Anbieter wirklich löschen?")&&p.mutate(b.id)},hasPermission:c,showInactive:a},b.id))}):s.jsx("div",{className:"text-center py-8 text-gray-500",children:"Keine Anbieter vorhanden."})]}),s.jsx($C,{isOpen:e,onClose:x,provider:n})]})}function zC({provider:e,isExpanded:t,onToggle:n,onEdit:r,onDelete:a,hasPermission:i,showInactive:l}){var f,x;const[o,c]=j.useState(!1),[d,u]=j.useState(null),h=xe(),p=W({mutationFn:gv.delete,onSuccess:()=>{h.invalidateQueries({queryKey:["providers"]})},onError:b=>{alert(b.message)}}),m=((f=e.tariffs)==null?void 0:f.filter(b=>l||b.isActive))||[];return s.jsxs("div",{className:"border rounded-lg",children:[s.jsxs("div",{className:"flex items-center p-4 hover:bg-gray-50",children:[s.jsx("button",{onClick:n,className:"mr-3 p-1 hover:bg-gray-200 rounded",children:t?s.jsx(In,{className:"w-5 h-5 text-gray-400"}):s.jsx(Ft,{className:"w-5 h-5 text-gray-400"})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("span",{className:"font-medium",children:e.name}),s.jsx(ye,{variant:e.isActive?"success":"danger",children:e.isActive?"Aktiv":"Inaktiv"}),s.jsxs("span",{className:"text-sm text-gray-500",children:["(",m.length," Tarife, ",((x=e._count)==null?void 0:x.contracts)||0," Verträge)"]})]}),e.portalUrl&&s.jsxs("a",{href:e.portalUrl,target:"_blank",rel:"noopener noreferrer",className:"text-sm text-blue-600 hover:underline flex items-center gap-1 mt-1",children:[s.jsx(ch,{className:"w-3 h-3"}),e.portalUrl]})]}),s.jsxs("div",{className:"flex gap-2 ml-4",children:[i("providers:update")&&s.jsx(F,{variant:"ghost",size:"sm",onClick:r,title:"Bearbeiten",children:s.jsx(Ye,{className:"w-4 h-4"})}),i("providers:delete")&&s.jsx(F,{variant:"ghost",size:"sm",onClick:a,title:"Löschen",children:s.jsx(be,{className:"w-4 h-4 text-red-500"})})]})]}),t&&s.jsxs("div",{className:"border-t bg-gray-50 p-4",children:[s.jsxs("div",{className:"flex justify-between items-center mb-3",children:[s.jsx("h4",{className:"font-medium text-gray-700",children:"Tarife"}),i("providers:create")&&s.jsxs(F,{size:"sm",onClick:()=>c(!0),children:[s.jsx(Be,{className:"w-4 h-4 mr-1"}),"Tarif hinzufügen"]})]}),m.length>0?s.jsx("div",{className:"space-y-2",children:m.map(b=>{var y;return s.jsxs("div",{className:"flex items-center justify-between bg-white p-3 rounded border",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{children:b.name}),s.jsx(ye,{variant:b.isActive?"success":"danger",className:"text-xs",children:b.isActive?"Aktiv":"Inaktiv"}),((y=b._count)==null?void 0:y.contracts)!==void 0&&s.jsxs("span",{className:"text-xs text-gray-500",children:["(",b._count.contracts," Verträge)"]})]}),s.jsxs("div",{className:"flex gap-1",children:[i("providers:update")&&s.jsx(F,{variant:"ghost",size:"sm",onClick:()=>{u(b),c(!0)},title:"Bearbeiten",children:s.jsx(Ye,{className:"w-3 h-3"})}),i("providers:delete")&&s.jsx(F,{variant:"ghost",size:"sm",onClick:()=>{confirm("Tarif wirklich löschen?")&&p.mutate(b.id)},title:"Löschen",children:s.jsx(be,{className:"w-3 h-3 text-red-500"})})]})]},b.id)})}):s.jsx("p",{className:"text-sm text-gray-500",children:"Keine Tarife vorhanden."})]}),s.jsx(_C,{isOpen:o,onClose:()=>{c(!1),u(null)},providerId:e.id,tariff:d})]})}function $C({isOpen:e,onClose:t,provider:n}){const r=xe(),[a,i]=j.useState({name:"",portalUrl:"",usernameFieldName:"",passwordFieldName:"",isActive:!0});j.useEffect(()=>{e&&i(n?{name:n.name,portalUrl:n.portalUrl||"",usernameFieldName:n.usernameFieldName||"",passwordFieldName:n.passwordFieldName||"",isActive:n.isActive}:{name:"",portalUrl:"",usernameFieldName:"",passwordFieldName:"",isActive:!0})},[e,n]);const l=W({mutationFn:Ja.create,onSuccess:()=>{r.invalidateQueries({queryKey:["providers"]}),t()},onError:u=>{alert(u.message)}}),o=W({mutationFn:u=>Ja.update(n.id,u),onSuccess:()=>{r.invalidateQueries({queryKey:["providers"]}),t()},onError:u=>{alert(u.message)}}),c=u=>{u.preventDefault(),n?o.mutate(a):l.mutate(a)},d=l.isPending||o.isPending;return s.jsx(Ve,{isOpen:e,onClose:t,title:n?"Anbieter bearbeiten":"Neuer Anbieter",children:s.jsxs("form",{onSubmit:c,className:"space-y-4",children:[s.jsx(V,{label:"Anbietername *",value:a.name,onChange:u=>i({...a,name:u.target.value}),required:!0,placeholder:"z.B. Vodafone, E.ON, Allianz"}),s.jsx(V,{label:"Portal-URL (Login-Seite)",value:a.portalUrl,onChange:u=>i({...a,portalUrl:u.target.value}),placeholder:"https://kundenportal.anbieter.de/login"}),s.jsxs("div",{className:"p-3 bg-gray-50 rounded-lg space-y-3",children:[s.jsxs("p",{className:"text-sm text-gray-600",children:[s.jsx("strong",{children:"Auto-Login Felder"})," (optional)",s.jsx("br",{}),"Feldnamen für URL-Parameter beim Auto-Login:"]}),s.jsx(V,{label:"Benutzername-Feldname",value:a.usernameFieldName,onChange:u=>i({...a,usernameFieldName:u.target.value}),placeholder:"z.B. username, email, login"}),s.jsx(V,{label:"Passwort-Feldname",value:a.passwordFieldName,onChange:u=>i({...a,passwordFieldName:u.target.value}),placeholder:"z.B. password, pwd, kennwort"})]}),n&&s.jsxs("label",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"checkbox",checked:a.isActive,onChange:u=>i({...a,isActive:u.target.checked}),className:"rounded"}),"Aktiv"]}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx(F,{type:"button",variant:"secondary",onClick:t,children:"Abbrechen"}),s.jsx(F,{type:"submit",disabled:d,children:d?"Speichern...":"Speichern"})]})]})})}function _C({isOpen:e,onClose:t,providerId:n,tariff:r}){const a=xe(),[i,l]=j.useState({name:"",isActive:!0});j.useEffect(()=>{e&&l(r?{name:r.name,isActive:r.isActive}:{name:"",isActive:!0})},[e,r]);const o=W({mutationFn:h=>Ja.createTariff(n,h),onSuccess:()=>{a.invalidateQueries({queryKey:["providers"]}),t()},onError:h=>{alert(h.message)}}),c=W({mutationFn:h=>gv.update(r.id,h),onSuccess:()=>{a.invalidateQueries({queryKey:["providers"]}),t()},onError:h=>{alert(h.message)}}),d=h=>{h.preventDefault(),r?c.mutate(i):o.mutate(i)},u=o.isPending||c.isPending;return s.jsx(Ve,{isOpen:e,onClose:t,title:r?"Tarif bearbeiten":"Neuer Tarif",children:s.jsxs("form",{onSubmit:d,className:"space-y-4",children:[s.jsx(V,{label:"Tarifname *",value:i.name,onChange:h=>l({...i,name:h.target.value}),required:!0,placeholder:"z.B. Comfort Plus, Basic 100"}),r&&s.jsxs("label",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"checkbox",checked:i.isActive,onChange:h=>l({...i,isActive:h.target.checked}),className:"rounded"}),"Aktiv"]}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx(F,{type:"button",variant:"secondary",onClick:t,children:"Abbrechen"}),s.jsx(F,{type:"submit",disabled:u,children:u?"Speichern...":"Speichern"})]})]})})}const Gu={Zap:s.jsx(ph,{className:"w-5 h-5"}),Flame:s.jsx(Cv,{className:"w-5 h-5"}),Wifi:s.jsx(Ca,{className:"w-5 h-5"}),Cable:s.jsx(D2,{className:"w-5 h-5"}),Network:s.jsx(K2,{className:"w-5 h-5"}),Smartphone:s.jsx(hh,{className:"w-5 h-5"}),Tv:s.jsx(Tv,{className:"w-5 h-5"}),Car:s.jsx(kv,{className:"w-5 h-5"}),FileText:s.jsx(Ke,{className:"w-5 h-5"})},KC=[{value:"Zap",label:"Blitz (Strom)"},{value:"Flame",label:"Flamme (Gas)"},{value:"Wifi",label:"WLAN (DSL)"},{value:"Cable",label:"Kabel"},{value:"Network",label:"Netzwerk (Glasfaser)"},{value:"Smartphone",label:"Smartphone (Mobilfunk)"},{value:"Tv",label:"TV"},{value:"Car",label:"Auto (KFZ)"},{value:"FileText",label:"Dokument (Sonstige)"}],UC=[{value:"#FFC107",label:"Gelb"},{value:"#FF5722",label:"Orange"},{value:"#2196F3",label:"Blau"},{value:"#9C27B0",label:"Lila"},{value:"#4CAF50",label:"Grün"},{value:"#E91E63",label:"Pink"},{value:"#607D8B",label:"Grau"},{value:"#795548",label:"Braun"},{value:"#00BCD4",label:"Cyan"},{value:"#F44336",label:"Rot"}];function BC(){const[e,t]=j.useState(!1),[n,r]=j.useState(null),[a,i]=j.useState(!1),{hasPermission:l}=He(),o=xe(),{data:c,isLoading:d}=me({queryKey:["contract-categories",a],queryFn:()=>ll.getAll(a)}),u=W({mutationFn:ll.delete,onSuccess:()=>{o.invalidateQueries({queryKey:["contract-categories"]})},onError:m=>{alert(m.message)}}),h=m=>{r(m),t(!0)},p=()=>{t(!1),r(null)};return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-4 mb-6",children:[s.jsx(ke,{to:"/settings",children:s.jsx(F,{variant:"ghost",size:"sm",children:s.jsx(Qs,{className:"w-4 h-4"})})}),s.jsx("h1",{className:"text-2xl font-bold flex-1",children:"Vertragstypen"}),l("developer:access")&&s.jsxs(F,{onClick:()=>t(!0),children:[s.jsx(Be,{className:"w-4 h-4 mr-2"}),"Neuer Vertragstyp"]})]}),s.jsxs(Y,{children:[s.jsx("div",{className:"mb-4",children:s.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[s.jsx("input",{type:"checkbox",checked:a,onChange:m=>i(m.target.checked),className:"rounded"}),"Inaktive anzeigen"]})}),d?s.jsx("div",{className:"text-center py-8 text-gray-500",children:"Laden..."}):c!=null&&c.data&&c.data.length>0?s.jsx("div",{className:"space-y-2",children:c.data.map(m=>{var f;return s.jsxs("div",{className:"flex items-center p-4 border rounded-lg hover:bg-gray-50",children:[s.jsx("div",{className:"mr-3 text-gray-400",children:s.jsx(I2,{className:"w-5 h-5"})}),s.jsx("div",{className:"w-10 h-10 rounded-lg flex items-center justify-center mr-4",style:{backgroundColor:m.color||"#E5E7EB",color:"#fff"},children:m.icon&&Gu[m.icon]?Gu[m.icon]:s.jsx(Ke,{className:"w-5 h-5"})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("span",{className:"font-medium",children:m.name}),s.jsx(ye,{variant:m.isActive?"success":"danger",children:m.isActive?"Aktiv":"Inaktiv"}),s.jsxs("span",{className:"text-sm text-gray-500",children:["(",((f=m._count)==null?void 0:f.contracts)||0," Verträge)"]})]}),s.jsxs("div",{className:"text-sm text-gray-500",children:["Code: ",s.jsx("span",{className:"font-mono",children:m.code})]})]}),s.jsxs("div",{className:"flex gap-2 ml-4",children:[l("developer:access")&&s.jsx(F,{variant:"ghost",size:"sm",onClick:()=>h(m),title:"Bearbeiten",children:s.jsx(Ye,{className:"w-4 h-4"})}),l("developer:access")&&s.jsx(F,{variant:"ghost",size:"sm",onClick:()=>{confirm("Vertragstyp wirklich löschen?")&&u.mutate(m.id)},title:"Löschen",children:s.jsx(be,{className:"w-4 h-4 text-red-500"})})]})]},m.id)})}):s.jsx("div",{className:"text-center py-8 text-gray-500",children:"Keine Vertragstypen vorhanden."})]}),s.jsx(qC,{isOpen:e,onClose:p,category:n})]})}function qC({isOpen:e,onClose:t,category:n}){const r=xe(),[a,i]=j.useState({code:"",name:"",icon:"FileText",color:"#607D8B",sortOrder:0,isActive:!0});j.useEffect(()=>{e&&i(n?{code:n.code,name:n.name,icon:n.icon||"FileText",color:n.color||"#607D8B",sortOrder:n.sortOrder,isActive:n.isActive}:{code:"",name:"",icon:"FileText",color:"#607D8B",sortOrder:0,isActive:!0})},[e,n]);const l=W({mutationFn:ll.create,onSuccess:()=>{r.invalidateQueries({queryKey:["contract-categories"]}),t()},onError:u=>{alert(u.message)}}),o=W({mutationFn:u=>ll.update(n.id,u),onSuccess:()=>{r.invalidateQueries({queryKey:["contract-categories"]}),t()},onError:u=>{alert(u.message)}}),c=u=>{u.preventDefault(),n?o.mutate(a):l.mutate(a)},d=l.isPending||o.isPending;return s.jsx(Ve,{isOpen:e,onClose:t,title:n?"Vertragstyp bearbeiten":"Neuer Vertragstyp",children:s.jsxs("form",{onSubmit:c,className:"space-y-4",children:[s.jsx(V,{label:"Code (technisch) *",value:a.code,onChange:u=>i({...a,code:u.target.value.toUpperCase().replace(/[^A-Z0-9_]/g,"")}),required:!0,placeholder:"z.B. ELECTRICITY, MOBILE_BUSINESS",disabled:!!n}),s.jsx(V,{label:"Anzeigename *",value:a.name,onChange:u=>i({...a,name:u.target.value}),required:!0,placeholder:"z.B. Strom, Mobilfunk Business"}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Icon"}),s.jsx("div",{className:"grid grid-cols-4 gap-2",children:KC.map(u=>s.jsxs("button",{type:"button",onClick:()=>i({...a,icon:u.value}),className:`p-3 border rounded-lg flex flex-col items-center gap-1 text-xs ${a.icon===u.value?"border-blue-500 bg-blue-50":"border-gray-200 hover:bg-gray-50"}`,children:[Gu[u.value],s.jsx("span",{className:"truncate w-full text-center",children:u.label.split(" ")[0]})]},u.value))})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Farbe"}),s.jsx("div",{className:"flex flex-wrap gap-2",children:UC.map(u=>s.jsx("button",{type:"button",onClick:()=>i({...a,color:u.value}),className:`w-8 h-8 rounded-full border-2 ${a.color===u.value?"border-gray-800 ring-2 ring-offset-2 ring-gray-400":"border-transparent"}`,style:{backgroundColor:u.value},title:u.label},u.value))})]}),s.jsx(V,{label:"Sortierung",type:"number",value:a.sortOrder,onChange:u=>i({...a,sortOrder:parseInt(u.target.value)||0}),placeholder:"0"}),n&&s.jsxs("label",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"checkbox",checked:a.isActive,onChange:u=>i({...a,isActive:u.target.checked}),className:"rounded"}),"Aktiv"]}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx(F,{type:"button",variant:"secondary",onClick:t,children:"Abbrechen"}),s.jsx(F,{type:"submit",disabled:d,children:d?"Speichern...":"Speichern"})]})]})})}const VC=[{value:"0.1",label:"10%"},{value:"0.2",label:"20%"},{value:"0.3",label:"30%"},{value:"0.4",label:"40%"},{value:"0.5",label:"50%"},{value:"0.6",label:"60%"},{value:"0.7",label:"70% (Standard)"},{value:"0.8",label:"80%"},{value:"0.9",label:"90%"},{value:"999",label:"Deaktiviert"}];function QC(){const{settings:e,updateSettings:t}=jv();return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-4 mb-6",children:[s.jsx(ke,{to:"/settings",className:"p-2 hover:bg-gray-100 rounded-lg transition-colors",children:s.jsx(Qs,{className:"w-5 h-5"})}),s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(Pe,{className:"w-6 h-6"}),s.jsx("h1",{className:"text-2xl font-bold",children:"Ansicht"})]})]}),s.jsx(Y,{title:"Scroll-Verhalten",children:s.jsx("div",{className:"space-y-6",children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"font-medium",children:"Nach-oben-Button"}),s.jsx("p",{className:"text-sm text-gray-500",children:"Ab welcher Scroll-Position der Button unten rechts erscheinen soll"})]}),s.jsx("div",{className:"w-48",children:s.jsx(Re,{options:VC,value:e.scrollToTopThreshold.toString(),onChange:n=>t({scrollToTopThreshold:parseFloat(n.target.value)})})})]})})})]})}function HC(){const e=xe(),{data:t,isLoading:n}=me({queryKey:["app-settings"],queryFn:()=>Jr.getAll()}),[r,a]=j.useState(!1);j.useEffect(()=>{t!=null&&t.data&&a(t.data.customerSupportTicketsEnabled==="true")},[t]);const i=W({mutationFn:o=>Jr.update(o),onSuccess:()=>{e.invalidateQueries({queryKey:["app-settings"]}),e.invalidateQueries({queryKey:["app-settings-public"]})}}),l=o=>{a(o),i.mutate({customerSupportTicketsEnabled:o?"true":"false"})};return n?s.jsx("div",{className:"flex items-center justify-center py-12",children:s.jsx("div",{className:"text-gray-500",children:"Laden..."})}):s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-4 mb-6",children:[s.jsx(ke,{to:"/settings",className:"text-gray-500 hover:text-gray-700",children:s.jsx(Qs,{className:"w-5 h-5"})}),s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(dh,{className:"w-6 h-6"}),s.jsx("h1",{className:"text-2xl font-bold",children:"Kundenportal"})]})]}),s.jsxs(Y,{title:"Support-Anfragen",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(cl,{className:"w-5 h-5 text-gray-500"}),s.jsxs("div",{children:[s.jsx("p",{className:"font-medium",children:"Kunden können Support-Anfragen erstellen"}),s.jsx("p",{className:"text-sm text-gray-500",children:"Wenn aktiviert, können Kunden im Portal Support-Anfragen zu ihren Verträgen erstellen. Diese erscheinen als Aufgaben in der Vertragsdetailansicht."})]})]}),s.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:r,onChange:o=>l(o.target.checked),disabled:i.isPending,className:"sr-only peer"}),s.jsx("div",{className:"w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"})]})]}),r&&s.jsx("div",{className:"mt-4 p-3 bg-blue-50 border border-blue-200 rounded-lg",children:s.jsxs("p",{className:"text-sm text-blue-800",children:[s.jsx("strong",{children:"Hinweis:"}),' Kunden sehen diese Anfragen als "Support-Anfragen" in ihrem Portal. Sie können die Anfrage mit einem Titel und einer Beschreibung erstellen. Ihre Mitarbeiter können dann mit Antworten (Unteraufgaben) reagieren.']})})]})]})}function WC(){const e=xe(),{data:t,isLoading:n}=me({queryKey:["app-settings"],queryFn:()=>Jr.getAll()}),[r,a]=j.useState("14"),[i,l]=j.useState("42"),[o,c]=j.useState("90"),[d,u]=j.useState(!1);j.useEffect(()=>{t!=null&&t.data&&(a(t.data.deadlineCriticalDays||"14"),l(t.data.deadlineWarningDays||"42"),c(t.data.deadlineOkDays||"90"),u(!1))},[t]);const h=W({mutationFn:f=>Jr.update(f),onSuccess:()=>{e.invalidateQueries({queryKey:["app-settings"]}),e.invalidateQueries({queryKey:["contract-cockpit"]}),u(!1)}}),p=()=>{const f=parseInt(r),x=parseInt(i),b=parseInt(o);if(isNaN(f)||isNaN(x)||isNaN(b)){alert("Bitte gültige Zahlen eingeben");return}if(f>=x||x>=b){alert("Die Werte müssen aufsteigend sein: Kritisch < Warnung < OK");return}h.mutate({deadlineCriticalDays:r,deadlineWarningDays:i,deadlineOkDays:o})},m=(f,x)=>{f(x),u(!0)};return n?s.jsx("div",{className:"flex items-center justify-center py-12",children:s.jsx("div",{className:"text-gray-500",children:"Laden..."})}):s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-4 mb-6",children:[s.jsx(ke,{to:"/settings",className:"text-gray-500 hover:text-gray-700",children:s.jsx(Qs,{className:"w-5 h-5"})}),s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(An,{className:"w-6 h-6"}),s.jsx("h1",{className:"text-2xl font-bold",children:"Fristenschwellen"})]})]}),s.jsxs(Y,{title:"Farbkodierung für Fristen",children:[s.jsx("p",{className:"text-gray-600 mb-6",children:"Definiere, ab wann Vertragsfristen als kritisch (rot), Warnung (gelb) oder OK (grün) angezeigt werden sollen. Die Werte geben die Anzahl der Tage bis zur Frist an."}),s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{className:"flex items-center gap-4 p-4 bg-red-50 border border-red-200 rounded-lg",children:[s.jsx(Nn,{className:"w-8 h-8 text-red-500 flex-shrink-0"}),s.jsxs("div",{className:"flex-1",children:[s.jsx("label",{className:"block font-medium text-red-800 mb-1",children:"Kritisch (Rot)"}),s.jsx("p",{className:"text-sm text-red-600 mb-2",children:"Fristen mit weniger als X Tagen werden rot markiert"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(V,{type:"number",min:"1",value:r,onChange:f=>m(a,f.target.value),className:"w-24"}),s.jsx("span",{className:"text-red-700",children:"Tage"})]})]})]}),s.jsxs("div",{className:"flex items-center gap-4 p-4 bg-yellow-50 border border-yellow-200 rounded-lg",children:[s.jsx(hs,{className:"w-8 h-8 text-yellow-500 flex-shrink-0"}),s.jsxs("div",{className:"flex-1",children:[s.jsx("label",{className:"block font-medium text-yellow-800 mb-1",children:"Warnung (Gelb)"}),s.jsx("p",{className:"text-sm text-yellow-600 mb-2",children:"Fristen mit weniger als X Tagen werden gelb markiert"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(V,{type:"number",min:"1",value:i,onChange:f=>m(l,f.target.value),className:"w-24"}),s.jsx("span",{className:"text-yellow-700",children:"Tage"})]})]})]}),s.jsxs("div",{className:"flex items-center gap-4 p-4 bg-green-50 border border-green-200 rounded-lg",children:[s.jsx(Ps,{className:"w-8 h-8 text-green-500 flex-shrink-0"}),s.jsxs("div",{className:"flex-1",children:[s.jsx("label",{className:"block font-medium text-green-800 mb-1",children:"OK (Grün)"}),s.jsx("p",{className:"text-sm text-green-600 mb-2",children:"Fristen mit weniger als X Tagen werden grün markiert (darüber nicht angezeigt)"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(V,{type:"number",min:"1",value:o,onChange:f=>m(c,f.target.value),className:"w-24"}),s.jsx("span",{className:"text-green-700",children:"Tage"})]})]})]})]}),s.jsxs("div",{className:"mt-6 pt-4 border-t flex justify-between items-center",children:[s.jsx("p",{className:"text-sm text-gray-500",children:"Beispiel: Bei 14/42/90 Tagen wird eine Frist die in 10 Tagen abläuft rot, eine in 30 Tagen gelb, und eine in 60 Tagen grün markiert."}),s.jsx(F,{onClick:p,disabled:!d||h.isPending,children:h.isPending?"Speichere...":"Speichern"})]})]})]})}const GC=[{value:"PLESK",label:"Plesk"},{value:"CPANEL",label:"cPanel"},{value:"DIRECTADMIN",label:"DirectAdmin"}],Ux=[{value:"SSL",label:"SSL/TLS",description:"Verschlüsselung von Anfang an"},{value:"STARTTLS",label:"STARTTLS",description:"Startet unverschlüsselt, dann Upgrade"},{value:"NONE",label:"Keine",description:"Keine Verschlüsselung"}],vd={name:"",type:"PLESK",apiUrl:"",apiKey:"",username:"",password:"",domain:"stressfrei-wechseln.de",defaultForwardEmail:"",imapEncryption:"SSL",smtpEncryption:"SSL",allowSelfSignedCerts:!1,isActive:!0,isDefault:!1};function ZC(){const e=ts(),t=xe(),[n,r]=j.useState(!1),[a,i]=j.useState(null),[l,o]=j.useState(vd),[c,d]=j.useState(!1),[u,h]=j.useState(null),[p,m]=j.useState(!1),[f,x]=j.useState({}),[b,y]=j.useState(null),{data:g,isLoading:v}=me({queryKey:["email-provider-configs"],queryFn:()=>pn.getConfigs()}),N=W({mutationFn:k=>pn.createConfig(k),onSuccess:()=>{t.invalidateQueries({queryKey:["email-provider-configs"]}),E()}}),D=W({mutationFn:({id:k,data:_})=>pn.updateConfig(k,_),onSuccess:()=>{t.invalidateQueries({queryKey:["email-provider-configs"]}),E()}}),A=W({mutationFn:k=>pn.deleteConfig(k),onSuccess:()=>{t.invalidateQueries({queryKey:["email-provider-configs"]})}}),R=(g==null?void 0:g.data)||[],w=()=>{o(vd),i(null),d(!1),h(null),r(!0)},S=k=>{o({name:k.name,type:k.type,apiUrl:k.apiUrl,apiKey:k.apiKey||"",username:k.username||"",password:"",domain:k.domain,defaultForwardEmail:k.defaultForwardEmail||"",imapEncryption:k.imapEncryption??"SSL",smtpEncryption:k.smtpEncryption??"SSL",allowSelfSignedCerts:k.allowSelfSignedCerts??!1,isActive:k.isActive,isDefault:k.isDefault}),i(k.id),d(!1),h(null),r(!0)},E=()=>{r(!1),i(null),o(vd),d(!1),h(null)},z=async k=>{var _,K,Z;y(k.id),x(H=>({...H,[k.id]:null}));try{const H=await pn.testConnection({id:k.id}),pe={success:((_=H.data)==null?void 0:_.success)||!1,message:(K=H.data)==null?void 0:K.message,error:(Z=H.data)==null?void 0:Z.error};x(oe=>({...oe,[k.id]:pe}))}catch(H){x(pe=>({...pe,[k.id]:{success:!1,error:H instanceof Error?H.message:"Unbekannter Fehler beim Testen"}}))}finally{y(null)}},I=async()=>{var k,_,K;if(!l.apiUrl||!l.domain){h({success:!1,error:"Bitte geben Sie API-URL und Domain ein."});return}m(!0),h(null);try{const Z=await pn.testConnection({testData:{type:l.type,apiUrl:l.apiUrl,apiKey:l.apiKey||void 0,username:l.username||void 0,password:l.password||void 0,domain:l.domain}});h({success:((k=Z.data)==null?void 0:k.success)||!1,message:(_=Z.data)==null?void 0:_.message,error:(K=Z.data)==null?void 0:K.error})}catch(Z){h({success:!1,error:Z instanceof Error?Z.message:"Unbekannter Fehler beim Verbindungstest"})}finally{m(!1)}},B=k=>{k.preventDefault();const _={name:l.name,type:l.type,apiUrl:l.apiUrl,apiKey:l.apiKey,username:l.username,domain:l.domain,defaultForwardEmail:l.defaultForwardEmail,imapEncryption:l.imapEncryption,smtpEncryption:l.smtpEncryption,allowSelfSignedCerts:l.allowSelfSignedCerts,isActive:l.isActive,isDefault:l.isDefault};l.password&&(_.password=l.password),a?D.mutate({id:a,data:_}):N.mutate(_)},P=(k,_)=>{confirm(`Möchten Sie den Provider "${_}" wirklich löschen?`)&&A.mutate(k)},M=k=>k.error?k.error:k.message?k.message:"Verbindung fehlgeschlagen";return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-4 mb-6",children:[s.jsxs(F,{variant:"ghost",onClick:()=>e("/settings"),children:[s.jsx(Qs,{className:"w-4 h-4 mr-2"}),"Zurück"]}),s.jsx("h1",{className:"text-2xl font-bold",children:"Email-Provisionierung"})]}),s.jsxs(Y,{className:"mb-6",children:[s.jsx("p",{className:"text-gray-600 mb-4",children:'Hier konfigurieren Sie die automatische Erstellung von Stressfrei-Wechseln E-Mail-Adressen. Wenn beim Anlegen einer Stressfrei-Adresse die Option "Bei Provider anlegen" aktiviert ist, wird die E-Mail-Weiterleitung automatisch erstellt.'}),s.jsxs(F,{onClick:w,children:[s.jsx(Be,{className:"w-4 h-4 mr-2"}),"Provider hinzufügen"]})]}),v?s.jsx("div",{className:"text-center py-8",children:"Laden..."}):R.length===0?s.jsx(Y,{children:s.jsx("div",{className:"text-center py-8 text-gray-500",children:"Noch keine Email-Provider konfiguriert."})}):s.jsx("div",{className:"space-y-4",children:R.map(k=>{const _=f[k.id],K=b===k.id;return s.jsx(Y,{children:s.jsxs("div",{className:"flex items-start justify-between",children:[s.jsxs("div",{className:"flex-1",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("h3",{className:"font-semibold text-lg",children:k.name}),s.jsx("span",{className:"px-2 py-1 text-xs rounded bg-blue-100 text-blue-800",children:k.type}),k.isDefault&&s.jsx("span",{className:"px-2 py-1 text-xs rounded bg-green-100 text-green-800",children:"Standard"}),!k.isActive&&s.jsx("span",{className:"px-2 py-1 text-xs rounded bg-gray-100 text-gray-600",children:"Inaktiv"})]}),s.jsxs("dl",{className:"mt-3 grid grid-cols-2 md:grid-cols-4 gap-4 text-sm",children:[s.jsxs("div",{children:[s.jsx("dt",{className:"text-gray-500",children:"API-URL"}),s.jsx("dd",{className:"font-mono text-xs truncate",children:k.apiUrl})]}),s.jsxs("div",{children:[s.jsx("dt",{className:"text-gray-500",children:"Domain"}),s.jsx("dd",{children:k.domain})]}),s.jsxs("div",{children:[s.jsx("dt",{className:"text-gray-500",children:"Benutzer"}),s.jsx("dd",{children:k.username||"-"})]}),s.jsxs("div",{children:[s.jsx("dt",{className:"text-gray-500",children:"Standard-Weiterleitung"}),s.jsx("dd",{className:"truncate",children:k.defaultForwardEmail||"-"})]})]}),_&&s.jsx("div",{className:`mt-3 p-3 rounded-lg text-sm ${_.success?"bg-green-50 text-green-800":"bg-red-50 text-red-800"}`,children:_.success?s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(fr,{className:"w-4 h-4 flex-shrink-0"}),s.jsx("span",{children:"Verbindung erfolgreich!"})]}):s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx(px,{className:"w-4 h-4 flex-shrink-0 mt-0.5"}),s.jsx("span",{children:M(_)})]})})]}),s.jsxs("div",{className:"flex gap-2 ml-4",children:[s.jsx(F,{variant:"ghost",size:"sm",onClick:()=>z(k),disabled:K,title:"Verbindung testen",children:K?s.jsx("span",{className:"w-4 h-4 border-2 border-gray-400 border-t-transparent rounded-full animate-spin"}):s.jsx(Ca,{className:"w-4 h-4 text-blue-500"})}),s.jsx(F,{variant:"ghost",size:"sm",onClick:()=>S(k),children:s.jsx(Ye,{className:"w-4 h-4"})}),s.jsx(F,{variant:"ghost",size:"sm",onClick:()=>P(k.id,k.name),children:s.jsx(be,{className:"w-4 h-4 text-red-500"})})]})]})},k.id)})}),n&&s.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:s.jsx("div",{className:"bg-white rounded-lg shadow-xl w-full max-w-lg mx-4 max-h-[90vh] overflow-y-auto",children:s.jsxs("div",{className:"p-6",children:[s.jsxs("div",{className:"flex items-center justify-between mb-4",children:[s.jsx("h2",{className:"text-xl font-semibold",children:a?"Provider bearbeiten":"Neuer Provider"}),s.jsx("button",{onClick:E,className:"text-gray-400 hover:text-gray-600",children:s.jsx(Vt,{className:"w-5 h-5"})})]}),(N.error||D.error)&&s.jsx("div",{className:"mb-4 p-3 rounded-lg bg-red-50 text-red-800 text-sm",children:s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx(Vt,{className:"w-4 h-4 flex-shrink-0 mt-0.5"}),s.jsx("span",{children:N.error instanceof Error?N.error.message:D.error instanceof Error?D.error.message:"Fehler beim Speichern"})]})}),s.jsxs("form",{onSubmit:B,className:"space-y-4",children:[s.jsx(V,{label:"Name *",value:l.name,onChange:k=>o({...l,name:k.target.value}),placeholder:"z.B. Plesk Hauptserver",required:!0}),s.jsx(Re,{label:"Provider-Typ *",value:l.type,onChange:k=>o({...l,type:k.target.value}),options:GC}),s.jsx(V,{label:"API-URL *",value:l.apiUrl,onChange:k=>o({...l,apiUrl:k.target.value}),placeholder:"https://server.de:8443",required:!0}),s.jsx(V,{label:"API-Key",value:l.apiKey,onChange:k=>o({...l,apiKey:k.target.value}),placeholder:"Optional - alternativ zu Benutzername/Passwort"}),s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[s.jsx(V,{label:"Benutzername",value:l.username,onChange:k=>o({...l,username:k.target.value}),placeholder:"admin"}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:a?"Neues Passwort (leer = beibehalten)":"Passwort"}),s.jsxs("div",{className:"relative",children:[s.jsx("input",{type:c?"text":"password",value:l.password,onChange:k=>o({...l,password:k.target.value}),className:"block w-full px-3 py-2 pr-10 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"}),s.jsx("button",{type:"button",onClick:()=>d(!c),className:"absolute inset-y-0 right-0 flex items-center pr-3 text-gray-400 hover:text-gray-600",children:c?s.jsx(It,{className:"w-4 h-4"}):s.jsx(Pe,{className:"w-4 h-4"})})]})]})]}),s.jsx(V,{label:"Domain *",value:l.domain,onChange:k=>o({...l,domain:k.target.value}),placeholder:"stressfrei-wechseln.de",required:!0}),s.jsx(V,{label:"Standard-Weiterleitungsadresse",value:l.defaultForwardEmail,onChange:k=>o({...l,defaultForwardEmail:k.target.value}),placeholder:"info@meinefirma.de",type:"email"}),s.jsx("p",{className:"text-xs text-gray-500 -mt-2",children:"Diese E-Mail-Adresse wird zusätzlich zur Kunden-E-Mail als Weiterleitungsziel hinzugefügt."}),s.jsxs("div",{className:"pt-4 border-t",children:[s.jsx("h4",{className:"text-sm font-medium text-gray-700 mb-3",children:"E-Mail-Verbindungseinstellungen"}),s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[s.jsxs("div",{children:[s.jsxs("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:["IMAP Verschlüsselung",s.jsxs("span",{className:"text-gray-400 font-normal ml-1",children:["(Port ",l.imapEncryption==="SSL"?"993":"143",")"]})]}),s.jsx("select",{value:l.imapEncryption,onChange:k=>o({...l,imapEncryption:k.target.value}),className:"block w-full px-3 py-2 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-sm",children:Ux.map(k=>s.jsxs("option",{value:k.value,children:[k.label," - ",k.description]},k.value))})]}),s.jsxs("div",{children:[s.jsxs("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:["SMTP Verschlüsselung",s.jsxs("span",{className:"text-gray-400 font-normal ml-1",children:["(Port ",l.smtpEncryption==="SSL"?"465":l.smtpEncryption==="STARTTLS"?"587":"25",")"]})]}),s.jsx("select",{value:l.smtpEncryption,onChange:k=>o({...l,smtpEncryption:k.target.value}),className:"block w-full px-3 py-2 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-sm",children:Ux.map(k=>s.jsxs("option",{value:k.value,children:[k.label," - ",k.description]},k.value))})]})]}),s.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:l.allowSelfSignedCerts,onChange:k=>o({...l,allowSelfSignedCerts:k.target.checked}),className:"rounded border-gray-300"}),s.jsx("span",{className:"text-sm",children:"Selbstsignierte Zertifikate erlauben"})]}),s.jsx("p",{className:"text-xs text-gray-500",children:"Aktivieren Sie diese Option für Testumgebungen mit selbstsignierten SSL-Zertifikaten."})]})]}),s.jsxs("div",{className:"flex gap-4",children:[s.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:l.isActive,onChange:k=>o({...l,isActive:k.target.checked}),className:"rounded border-gray-300"}),s.jsx("span",{className:"text-sm",children:"Aktiv"})]}),s.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:l.isDefault,onChange:k=>o({...l,isDefault:k.target.checked}),className:"rounded border-gray-300"}),s.jsx("span",{className:"text-sm",children:"Als Standard verwenden"})]})]}),s.jsxs("div",{className:"pt-4 border-t",children:[s.jsx(F,{type:"button",variant:"secondary",onClick:I,disabled:p,className:"w-full",children:p?"Teste Verbindung...":s.jsxs(s.Fragment,{children:[s.jsx(Ca,{className:"w-4 h-4 mr-2"}),"Verbindung testen"]})}),u&&s.jsx("div",{className:`mt-2 p-3 rounded-lg text-sm ${u.success?"bg-green-50 text-green-800":"bg-red-50 text-red-800"}`,children:u.success?s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(fr,{className:"w-4 h-4 flex-shrink-0"}),s.jsx("span",{children:"Verbindung erfolgreich!"})]}):s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx(px,{className:"w-4 h-4 flex-shrink-0 mt-0.5"}),s.jsx("span",{children:M(u)})]})})]}),s.jsxs("div",{className:"flex justify-end gap-3 pt-4 border-t",children:[s.jsx(F,{type:"button",variant:"secondary",onClick:E,children:"Abbrechen"}),s.jsx(F,{type:"submit",disabled:N.isPending||D.isPending,children:N.isPending||D.isPending?"Speichern...":"Speichern"})]})]})]})})})]})}function JC(){const[e,t]=j.useState(null),[n,r]=j.useState(null),[a,i]=j.useState(!1),[l,o]=j.useState(""),[c,d]=j.useState(null),u=j.useRef(null),h=xe(),{logout:p}=He(),{data:m,isLoading:f}=me({queryKey:["backups"],queryFn:()=>jr.list()}),x=(m==null?void 0:m.data)||[],b=W({mutationFn:()=>jr.create(),onSuccess:()=>{h.invalidateQueries({queryKey:["backups"]})}}),y=W({mutationFn:S=>jr.restore(S),onSuccess:()=>{h.invalidateQueries({queryKey:["backups"]}),t(null)}}),g=W({mutationFn:S=>jr.delete(S),onSuccess:()=>{h.invalidateQueries({queryKey:["backups"]}),r(null)}}),v=W({mutationFn:S=>jr.upload(S),onSuccess:()=>{h.invalidateQueries({queryKey:["backups"]}),d(null),u.current&&(u.current.value="")},onError:S=>{d(S.message||"Upload fehlgeschlagen")}}),N=W({mutationFn:()=>jr.factoryReset(),onSuccess:()=>{i(!1),o(""),p()}}),D=S=>{var z;const E=(z=S.target.files)==null?void 0:z[0];if(E){if(!E.name.endsWith(".zip")){d("Nur ZIP-Dateien sind erlaubt");return}d(null),v.mutate(E)}},A=async S=>{const E=localStorage.getItem("token"),z=jr.getDownloadUrl(S);try{const I=await fetch(z,{headers:{Authorization:`Bearer ${E}`}});if(!I.ok)throw new Error("Download fehlgeschlagen");const B=await I.blob(),P=window.URL.createObjectURL(B),M=document.createElement("a");M.href=P,M.download=`opencrm-backup-${S}.zip`,document.body.appendChild(M),M.click(),document.body.removeChild(M),window.URL.revokeObjectURL(P)}catch(I){console.error("Download error:",I)}},R=S=>new Date(S).toLocaleString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit"}),w=S=>S<1024?`${S} B`:S<1024*1024?`${(S/1024).toFixed(1)} KB`:`${(S/(1024*1024)).toFixed(1)} MB`;return s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsxs("h2",{className:"text-lg font-semibold text-gray-900 flex items-center gap-2",children:[s.jsx(Tc,{className:"w-5 h-5"}),"Datenbank & Zurücksetzen"]}),s.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"Backups erstellen, wiederherstellen oder auf Werkseinstellungen zurücksetzen."})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"file",ref:u,accept:".zip",onChange:D,className:"hidden"}),s.jsx(F,{variant:"secondary",onClick:()=>{var S;return(S=u.current)==null?void 0:S.click()},disabled:v.isPending,children:v.isPending?s.jsxs(s.Fragment,{children:[s.jsx(wr,{className:"w-4 h-4 mr-2 animate-spin"}),"Hochladen..."]}):s.jsxs(s.Fragment,{children:[s.jsx(Vu,{className:"w-4 h-4 mr-2"}),"Backup hochladen"]})}),s.jsx(F,{onClick:()=>b.mutate(),disabled:b.isPending,children:b.isPending?s.jsxs(s.Fragment,{children:[s.jsx(wr,{className:"w-4 h-4 mr-2 animate-spin"}),"Wird erstellt..."]}):s.jsxs(s.Fragment,{children:[s.jsx(As,{className:"w-4 h-4 mr-2"}),"Neues Backup"]})})]})]}),c&&s.jsx("div",{className:"bg-red-50 border border-red-200 rounded-lg p-4 text-red-700",children:c}),s.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-4",children:[s.jsx("h4",{className:"text-sm font-medium text-blue-800 mb-2",children:"Hinweise zur Datensicherung"}),s.jsxs("ul",{className:"text-sm text-blue-700 space-y-1 list-disc list-inside",children:[s.jsx("li",{children:"Backups enthalten alle Datenbankdaten und hochgeladene Dokumente"}),s.jsx("li",{children:"Erstellen Sie vor Datenbankmigrationen immer ein Backup"}),s.jsx("li",{children:"Backups können als ZIP heruntergeladen und auf einem anderen System wiederhergestellt werden"}),s.jsx("li",{children:"Bei der Wiederherstellung werden bestehende Daten mit dem Backup-Stand überschrieben"})]})]}),s.jsxs("div",{className:"bg-white rounded-lg border border-gray-200 overflow-hidden",children:[s.jsx("div",{className:"px-4 py-3 bg-gray-50 border-b border-gray-200",children:s.jsx("h3",{className:"text-sm font-medium text-gray-700",children:"Verfügbare Backups"})}),f?s.jsx("div",{className:"flex items-center justify-center py-12",children:s.jsx(wr,{className:"w-6 h-6 animate-spin text-gray-400"})}):x.length===0?s.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-gray-500",children:[s.jsx(hx,{className:"w-12 h-12 mb-2 opacity-30"}),s.jsx("p",{children:"Keine Backups vorhanden"}),s.jsx("p",{className:"text-sm mt-1",children:"Erstellen Sie Ihr erstes Backup"})]}):s.jsx("div",{className:"divide-y divide-gray-200",children:x.map(S=>s.jsx("div",{className:"p-4 hover:bg-gray-50",children:s.jsxs("div",{className:"flex items-start justify-between",children:[s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[s.jsx("span",{className:"font-mono text-sm bg-gray-100 px-2 py-1 rounded",children:S.name}),s.jsxs("span",{className:"text-sm text-gray-500 flex items-center gap-1",children:[s.jsx(An,{className:"w-4 h-4"}),R(S.timestamp)]})]}),s.jsxs("div",{className:"flex items-center gap-4 text-sm text-gray-600",children:[s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(Ke,{className:"w-4 h-4"}),S.totalRecords.toLocaleString("de-DE")," Datensätze"]}),s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(hx,{className:"w-4 h-4"}),w(S.sizeBytes)]}),S.hasUploads&&s.jsxs("span",{className:"flex items-center gap-1 text-green-600",children:[s.jsx(F2,{className:"w-4 h-4"}),"Dokumente (",w(S.uploadSizeBytes),")"]})]}),s.jsxs("details",{className:"mt-2",children:[s.jsxs("summary",{className:"text-xs text-gray-500 cursor-pointer hover:text-gray-700",children:["Tabellen anzeigen (",S.tables.filter(E=>E.count>0).length," mit Daten)"]}),s.jsx("div",{className:"mt-2 flex flex-wrap gap-1",children:S.tables.filter(E=>E.count>0).map(E=>s.jsxs("span",{className:"text-xs bg-gray-100 px-2 py-0.5 rounded",children:[E.table,": ",E.count]},E.table))})]})]}),s.jsxs("div",{className:"flex items-center gap-2 ml-4",children:[s.jsx(F,{variant:"secondary",size:"sm",onClick:()=>A(S.name),title:"Als ZIP herunterladen",children:s.jsx(C2,{className:"w-4 h-4"})}),s.jsxs(F,{variant:"secondary",size:"sm",onClick:()=>t(S.name),disabled:y.isPending,children:[s.jsx(Vu,{className:"w-4 h-4 mr-1"}),"Wiederherstellen"]}),s.jsx(F,{variant:"danger",size:"sm",onClick:()=>r(S.name),disabled:g.isPending,children:s.jsx(be,{className:"w-4 h-4"})})]})]})},S.name))})]}),e&&s.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:s.jsxs("div",{className:"bg-white rounded-lg shadow-xl p-6 max-w-md mx-4",children:[s.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Backup wiederherstellen?"}),s.jsxs("p",{className:"text-gray-600 mb-4",children:["Möchten Sie das Backup ",s.jsx("strong",{children:e})," wirklich wiederherstellen?"]}),s.jsxs("p",{className:"text-amber-600 text-sm mb-4 bg-amber-50 p-3 rounded-lg",children:[s.jsx("strong",{children:"Achtung:"})," Bestehende Daten und Dokumente werden mit dem Backup-Stand überschrieben. Dies kann nicht rückgängig gemacht werden."]}),s.jsxs("div",{className:"flex justify-end gap-3",children:[s.jsx(F,{variant:"secondary",onClick:()=>t(null),disabled:y.isPending,children:"Abbrechen"}),s.jsx(F,{variant:"primary",onClick:()=>y.mutate(e),disabled:y.isPending,children:y.isPending?s.jsxs(s.Fragment,{children:[s.jsx(wr,{className:"w-4 h-4 mr-2 animate-spin"}),"Wird wiederhergestellt..."]}):"Ja, wiederherstellen"})]})]})}),n&&s.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:s.jsxs("div",{className:"bg-white rounded-lg shadow-xl p-6 max-w-md mx-4",children:[s.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Backup löschen?"}),s.jsxs("p",{className:"text-gray-600 mb-4",children:["Möchten Sie das Backup ",s.jsx("strong",{children:n})," wirklich löschen? Dies kann nicht rückgängig gemacht werden."]}),s.jsxs("div",{className:"flex justify-end gap-3",children:[s.jsx(F,{variant:"secondary",onClick:()=>r(null),disabled:g.isPending,children:"Abbrechen"}),s.jsx(F,{variant:"danger",onClick:()=>g.mutate(n),disabled:g.isPending,children:g.isPending?"Wird gelöscht...":"Ja, löschen"})]})]})}),s.jsx("div",{className:"bg-red-50 border border-red-200 rounded-lg p-6 mt-8",children:s.jsxs("div",{className:"flex items-start gap-4",children:[s.jsx("div",{className:"p-2 bg-red-100 rounded-lg",children:s.jsx(hs,{className:"w-6 h-6 text-red-600"})}),s.jsxs("div",{className:"flex-1",children:[s.jsx("h3",{className:"text-lg font-semibold text-red-800 mb-2",children:"Werkseinstellungen"}),s.jsxs("p",{className:"text-sm text-red-700 mb-4",children:["Setzt das System auf den Ausgangszustand zurück. ",s.jsx("strong",{children:"Alle Daten werden unwiderruflich gelöscht"})," - Kunden, Verträge, Benutzer, Dokumente und Einstellungen. Nur die hier gespeicherten Backups bleiben erhalten."]}),s.jsxs("ul",{className:"text-sm text-red-700 mb-4 list-disc list-inside space-y-1",children:[s.jsx("li",{children:"Alle Kunden und Verträge werden gelöscht"}),s.jsx("li",{children:"Alle Benutzer werden gelöscht"}),s.jsx("li",{children:"Alle hochgeladenen Dokumente werden gelöscht"}),s.jsx("li",{children:"Ein neuer Admin-Benutzer wird erstellt (admin@admin.com / admin)"}),s.jsxs("li",{children:[s.jsx("strong",{children:"Backups bleiben erhalten"})," und können danach wiederhergestellt werden"]})]}),s.jsxs(F,{variant:"danger",onClick:()=>i(!0),children:[s.jsx(mh,{className:"w-4 h-4 mr-2"}),"Werkseinstellungen"]})]})]})}),a&&s.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:s.jsxs("div",{className:"bg-white rounded-lg shadow-xl p-6 max-w-lg mx-4",children:[s.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[s.jsx("div",{className:"p-2 bg-red-100 rounded-lg",children:s.jsx(hs,{className:"w-6 h-6 text-red-600"})}),s.jsx("h3",{className:"text-lg font-semibold text-gray-900",children:"Wirklich auf Werkseinstellungen zurücksetzen?"})]}),s.jsxs("p",{className:"text-gray-600 mb-4",children:["Diese Aktion löscht ",s.jsx("strong",{children:"alle Daten unwiderruflich"}),". Es gibt kein Zurück!"]}),s.jsxs("p",{className:"text-sm text-gray-600 mb-4",children:["Geben Sie zur Bestätigung ",s.jsx("strong",{className:"font-mono bg-gray-100 px-1",children:"LÖSCHEN"})," ein:"]}),s.jsx("input",{type:"text",value:l,onChange:S=>o(S.target.value),placeholder:"LÖSCHEN",className:"w-full px-3 py-2 border border-gray-300 rounded-lg mb-4 focus:ring-2 focus:ring-red-500 focus:border-red-500"}),s.jsxs("div",{className:"flex justify-end gap-3",children:[s.jsx(F,{variant:"secondary",onClick:()=>{i(!1),o("")},disabled:N.isPending,children:"Abbrechen"}),s.jsx(F,{variant:"danger",onClick:()=>N.mutate(),disabled:l!=="LÖSCHEN"||N.isPending,children:N.isPending?s.jsxs(s.Fragment,{children:[s.jsx(wr,{className:"w-4 h-4 mr-2 animate-spin"}),"Wird zurückgesetzt..."]}):"Ja, alles löschen"})]})]})})]})}function XC(){var g;const[e,t]=j.useState(""),[n,r]=j.useState(1),[a,i]=j.useState(!1),[l,o]=j.useState(null),c=xe(),{refreshUser:d}=He(),{data:u,isLoading:h}=me({queryKey:["users",e,n],queryFn:()=>Ii.getAll({search:e||void 0,page:n,limit:20})}),{data:p}=me({queryKey:["roles"],queryFn:()=>Ii.getRoles()}),m=W({mutationFn:Ii.delete,onSuccess:()=>{c.invalidateQueries({queryKey:["users"]})},onError:v=>{alert((v==null?void 0:v.message)||"Fehler beim Löschen des Benutzers")}}),f=v=>{var N;return(N=v.roles)==null?void 0:N.some(D=>D.name==="Admin")},x=((g=u==null?void 0:u.data)==null?void 0:g.filter(v=>v.isActive&&f(v)).length)||0,b=v=>{o(v),i(!0)},y=()=>{i(!1),o(null)};return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-4 mb-6",children:[s.jsx(ke,{to:"/settings",children:s.jsx(F,{variant:"ghost",size:"sm",children:s.jsx(Qs,{className:"w-4 h-4"})})}),s.jsx("h1",{className:"text-2xl font-bold flex-1",children:"Benutzer"}),s.jsxs(F,{onClick:()=>i(!0),children:[s.jsx(Be,{className:"w-4 h-4 mr-2"}),"Neuer Benutzer"]})]}),s.jsx(Y,{className:"mb-6",children:s.jsxs("div",{className:"flex gap-4",children:[s.jsx("div",{className:"flex-1",children:s.jsx(V,{placeholder:"Suchen...",value:e,onChange:v=>t(v.target.value)})}),s.jsx(F,{variant:"secondary",children:s.jsx(Al,{className:"w-4 h-4"})})]})}),s.jsxs("div",{className:"mb-6 bg-blue-50 border border-blue-200 rounded-lg p-4 flex items-start gap-3",children:[s.jsx(Pl,{className:"w-5 h-5 text-blue-600 flex-shrink-0 mt-0.5"}),s.jsxs("div",{className:"text-sm text-blue-800",children:[s.jsx("strong",{children:"Hinweis:"})," Bei Änderungen an Rollen oder Berechtigungen wird der betroffene Benutzer automatisch ausgeloggt und muss sich erneut anmelden."]})]}),s.jsx(Y,{children:h?s.jsx("div",{className:"text-center py-8 text-gray-500",children:"Laden..."}):u!=null&&u.data&&u.data.length>0?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"overflow-x-auto",children:s.jsxs("table",{className:"w-full",children:[s.jsx("thead",{children:s.jsxs("tr",{className:"border-b",children:[s.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"Name"}),s.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"E-Mail"}),s.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"Rollen"}),s.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"Status"}),s.jsx("th",{className:"text-right py-3 px-4 font-medium text-gray-600",children:"Aktionen"})]})}),s.jsx("tbody",{children:u.data.map(v=>{var N;return s.jsxs("tr",{className:"border-b hover:bg-gray-50",children:[s.jsxs("td",{className:"py-3 px-4",children:[v.firstName," ",v.lastName]}),s.jsx("td",{className:"py-3 px-4",children:v.email}),s.jsx("td",{className:"py-3 px-4",children:s.jsx("div",{className:"flex gap-1 flex-wrap",children:(N=v.roles)==null?void 0:N.filter(D=>D.name!=="Developer").map(D=>s.jsx(ye,{variant:"info",children:D.name},D.id||D.name))})}),s.jsx("td",{className:"py-3 px-4",children:s.jsxs("div",{className:"flex gap-2",children:[s.jsx(ye,{variant:v.isActive?"success":"danger",children:v.isActive?"Aktiv":"Inaktiv"}),v.hasDeveloperAccess&&s.jsxs(ye,{variant:"warning",className:"flex items-center gap-1",children:[s.jsx(Mc,{className:"w-3 h-3"}),"Dev"]})]})}),s.jsx("td",{className:"py-3 px-4 text-right",children:s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx(F,{variant:"ghost",size:"sm",onClick:()=>b(v),children:s.jsx(Ye,{className:"w-4 h-4"})}),(()=>{const D=f(v)&&v.isActive&&x<=1;return s.jsx(F,{variant:"ghost",size:"sm",disabled:D,title:D?"Letzter Administrator kann nicht gelöscht werden":void 0,onClick:()=>{confirm("Benutzer wirklich löschen?")&&m.mutate(v.id)},children:s.jsx(be,{className:`w-4 h-4 ${D?"text-gray-300":"text-red-500"}`})})})()]})})]},v.id)})})]})}),u.pagination&&u.pagination.totalPages>1&&s.jsxs("div",{className:"mt-4 flex items-center justify-between",children:[s.jsxs("p",{className:"text-sm text-gray-500",children:["Seite ",u.pagination.page," von ",u.pagination.totalPages]}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx(F,{variant:"secondary",size:"sm",onClick:()=>r(v=>Math.max(1,v-1)),disabled:n===1,children:"Zurück"}),s.jsx(F,{variant:"secondary",size:"sm",onClick:()=>r(v=>v+1),disabled:n>=u.pagination.totalPages,children:"Weiter"})]})]})]}):s.jsx("div",{className:"text-center py-8 text-gray-500",children:"Keine Benutzer gefunden."})}),s.jsx(YC,{isOpen:a,onClose:y,user:l,roles:(p==null?void 0:p.data)||[],onUserUpdated:d})]})}function YC({isOpen:e,onClose:t,user:n,roles:r,onUserUpdated:a}){const i=xe(),[l,o]=j.useState(null),[c,d]=j.useState({email:"",password:"",firstName:"",lastName:"",roleIds:[],isActive:!0,hasDeveloperAccess:!1});j.useEffect(()=>{var x;e&&(o(null),d(n?{email:n.email,password:"",firstName:n.firstName,lastName:n.lastName,roleIds:((x=n.roles)==null?void 0:x.filter(b=>b.name!=="Developer").map(b=>b.id))||[],isActive:n.isActive??!0,hasDeveloperAccess:n.hasDeveloperAccess??!1}:{email:"",password:"",firstName:"",lastName:"",roleIds:[],isActive:!0,hasDeveloperAccess:!1}))},[e,n]);const u=W({mutationFn:Ii.create,onSuccess:()=>{i.invalidateQueries({queryKey:["users"]}),t()},onError:x=>{o((x==null?void 0:x.message)||"Fehler beim Erstellen des Benutzers")}}),h=W({mutationFn:x=>Ii.update(n.id,x),onSuccess:async()=>{i.invalidateQueries({queryKey:["users"]}),await a(),t()},onError:x=>{o((x==null?void 0:x.message)||"Fehler beim Aktualisieren des Benutzers")}}),p=x=>{if(x.preventDefault(),n){const b={email:c.email,firstName:c.firstName,lastName:c.lastName,roleIds:c.roleIds,isActive:c.isActive,hasDeveloperAccess:c.hasDeveloperAccess};c.password&&(b.password=c.password),h.mutate(b)}else u.mutate({email:c.email,password:c.password,firstName:c.firstName,lastName:c.lastName,roleIds:c.roleIds,hasDeveloperAccess:c.hasDeveloperAccess})},m=x=>{d(b=>({...b,roleIds:b.roleIds.includes(x)?b.roleIds.filter(y=>y!==x):[...b.roleIds,x]}))},f=u.isPending||h.isPending;return s.jsx(Ve,{isOpen:e,onClose:t,title:n?"Benutzer bearbeiten":"Neuer Benutzer",children:s.jsxs("form",{onSubmit:p,className:"space-y-4",children:[l&&s.jsxs("div",{className:"bg-red-50 border border-red-200 rounded-lg p-3 flex items-start gap-2",children:[s.jsx(hs,{className:"w-5 h-5 text-red-500 flex-shrink-0 mt-0.5"}),s.jsx("p",{className:"text-red-700 text-sm",children:l})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[s.jsx(V,{label:"Vorname *",value:c.firstName,onChange:x=>d({...c,firstName:x.target.value}),required:!0}),s.jsx(V,{label:"Nachname *",value:c.lastName,onChange:x=>d({...c,lastName:x.target.value}),required:!0})]}),s.jsx(V,{label:"E-Mail *",type:"email",value:c.email,onChange:x=>d({...c,email:x.target.value}),required:!0}),s.jsx(V,{label:n?"Neues Passwort (leer = unverändert)":"Passwort *",type:"password",value:c.password,onChange:x=>d({...c,password:x.target.value}),required:!n}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"Rollen"}),s.jsxs("div",{className:"space-y-2",children:[r.filter(x=>x.name!=="Developer").map(x=>s.jsxs("label",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"checkbox",checked:c.roleIds.includes(x.id),onChange:()=>m(x.id),className:"rounded"}),s.jsx("span",{children:x.name}),x.description&&s.jsxs("span",{className:"text-sm text-gray-500",children:["(",x.description,")"]})]},x.id)),s.jsxs("label",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"checkbox",checked:c.hasDeveloperAccess,onChange:x=>d({...c,hasDeveloperAccess:x.target.checked}),className:"rounded border-purple-300 text-purple-600 focus:ring-purple-500"}),s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(Mc,{className:"w-4 h-4 text-purple-600"}),"Entwicklerzugriff"]}),s.jsx("span",{className:"text-sm text-gray-500",children:"(Datenbanktools)"})]})]}),n&&s.jsxs("p",{className:"mt-2 text-xs text-amber-600 flex items-center gap-1",children:[s.jsx(hs,{className:"w-3 h-3"}),"Bei Rollenänderung wird der Benutzer automatisch ausgeloggt."]})]}),n&&s.jsx("div",{className:"space-y-3 pt-3 border-t",children:s.jsxs("label",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"checkbox",checked:c.isActive,onChange:x=>d({...c,isActive:x.target.checked}),className:"rounded"}),"Aktiv"]})}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx(F,{type:"button",variant:"secondary",onClick:t,children:"Abbrechen"}),s.jsx(F,{type:"submit",disabled:f,children:f?"Speichern...":"Speichern"})]})]})})}function e4(){const{hasPermission:e,developerMode:t,setDeveloperMode:n}=He(),r=[{to:"/settings/users",icon:V2,title:"Benutzer",description:"Verwalten Sie Benutzerkonten, Rollen und Berechtigungen.",show:e("users:read")},{to:"/settings/platforms",icon:B2,title:"Vertriebsplattformen",description:"Verwalten Sie die Plattformen, über die Verträge abgeschlossen werden.",show:e("platforms:read")},{to:"/settings/cancellation-periods",icon:An,title:"Kündigungsfristen",description:"Konfigurieren Sie die verfügbaren Kündigungsfristen für Verträge.",show:e("platforms:read")},{to:"/settings/contract-durations",icon:Sv,title:"Vertragslaufzeiten",description:"Konfigurieren Sie die verfügbaren Laufzeiten für Verträge.",show:e("platforms:read")},{to:"/settings/providers",icon:E2,title:"Anbieter & Tarife",description:"Verwalten Sie Anbieter und deren Tarife für Verträge.",show:e("providers:read")||e("platforms:read")},{to:"/settings/contract-categories",icon:T2,title:"Vertragstypen",description:"Konfigurieren Sie die verfügbaren Vertragstypen (Strom, Gas, Mobilfunk, etc.).",show:e("platforms:read")}];return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-3 mb-6",children:[s.jsx(Mv,{className:"w-6 h-6"}),s.jsx("h1",{className:"text-2xl font-bold",children:"Einstellungen"})]}),s.jsxs("div",{className:"mb-8",children:[s.jsx("h2",{className:"text-lg font-semibold mb-4 text-gray-700",children:"Stammdaten"}),s.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:r.filter(a=>a.show).map(a=>s.jsx(ke,{to:a.to,className:"block p-4 bg-white border border-gray-200 rounded-lg shadow-sm hover:shadow-md hover:border-blue-300 transition-all group",children:s.jsxs("div",{className:"flex items-start gap-4",children:[s.jsx("div",{className:"p-2 bg-blue-50 rounded-lg group-hover:bg-blue-100 transition-colors",children:s.jsx(a.icon,{className:"w-6 h-6 text-blue-600"})}),s.jsxs("div",{className:"flex-1",children:[s.jsxs("h3",{className:"font-semibold text-gray-900 group-hover:text-blue-600 transition-colors flex items-center gap-2",children:[a.title,s.jsx(Ft,{className:"w-4 h-4 opacity-0 group-hover:opacity-100 transition-opacity"})]}),s.jsx("p",{className:"text-sm text-gray-500 mt-1",children:a.description})]})]})},a.to))})]}),e("settings:update")&&s.jsxs("div",{className:"mb-8",children:[s.jsx("h2",{className:"text-lg font-semibold mb-4 text-gray-700",children:"System"}),s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[s.jsx(ke,{to:"/settings/portal",className:"block p-4 bg-white border border-gray-200 rounded-lg shadow-sm hover:shadow-md hover:border-blue-300 transition-all group",children:s.jsxs("div",{className:"flex items-start gap-4",children:[s.jsx("div",{className:"p-2 bg-blue-50 rounded-lg group-hover:bg-blue-100 transition-colors",children:s.jsx(dh,{className:"w-6 h-6 text-blue-600"})}),s.jsxs("div",{className:"flex-1",children:[s.jsxs("h3",{className:"font-semibold text-gray-900 group-hover:text-blue-600 transition-colors flex items-center gap-2",children:["Kundenportal",s.jsx(Ft,{className:"w-4 h-4 opacity-0 group-hover:opacity-100 transition-opacity"})]}),s.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"Konfigurieren Sie das Kundenportal und Support-Anfragen."})]})]})}),s.jsx(ke,{to:"/settings/deadlines",className:"block p-4 bg-white border border-gray-200 rounded-lg shadow-sm hover:shadow-md hover:border-blue-300 transition-all group",children:s.jsxs("div",{className:"flex items-start gap-4",children:[s.jsx("div",{className:"p-2 bg-blue-50 rounded-lg group-hover:bg-blue-100 transition-colors",children:s.jsx(An,{className:"w-6 h-6 text-blue-600"})}),s.jsxs("div",{className:"flex-1",children:[s.jsxs("h3",{className:"font-semibold text-gray-900 group-hover:text-blue-600 transition-colors flex items-center gap-2",children:["Fristenschwellen",s.jsx(Ft,{className:"w-4 h-4 opacity-0 group-hover:opacity-100 transition-opacity"})]}),s.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"Konfigurieren Sie die Farbkodierung für Vertragsfristen im Cockpit."})]})]})}),s.jsx(ke,{to:"/settings/email-providers",className:"block p-4 bg-white border border-gray-200 rounded-lg shadow-sm hover:shadow-md hover:border-blue-300 transition-all group",children:s.jsxs("div",{className:"flex items-start gap-4",children:[s.jsx("div",{className:"p-2 bg-blue-50 rounded-lg group-hover:bg-blue-100 transition-colors",children:s.jsx(nn,{className:"w-6 h-6 text-blue-600"})}),s.jsxs("div",{className:"flex-1",children:[s.jsxs("h3",{className:"font-semibold text-gray-900 group-hover:text-blue-600 transition-colors flex items-center gap-2",children:["Email-Provisionierung",s.jsx(Ft,{className:"w-4 h-4 opacity-0 group-hover:opacity-100 transition-opacity"})]}),s.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"Konfigurieren Sie die automatische E-Mail-Erstellung für Stressfrei-Wechseln Adressen."})]})]})}),s.jsx(ke,{to:"/settings/database-backup",className:"block p-4 bg-white border border-gray-200 rounded-lg shadow-sm hover:shadow-md hover:border-blue-300 transition-all group",children:s.jsxs("div",{className:"flex items-start gap-4",children:[s.jsx("div",{className:"p-2 bg-blue-50 rounded-lg group-hover:bg-blue-100 transition-colors",children:s.jsx(Tc,{className:"w-6 h-6 text-blue-600"})}),s.jsxs("div",{className:"flex-1",children:[s.jsxs("h3",{className:"font-semibold text-gray-900 group-hover:text-blue-600 transition-colors flex items-center gap-2",children:["Datenbank & Zurücksetzen",s.jsx(Ft,{className:"w-4 h-4 opacity-0 group-hover:opacity-100 transition-opacity"})]}),s.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"Backups erstellen, wiederherstellen oder auf Werkseinstellungen zurücksetzen."})]})]})})]})]}),s.jsxs("div",{className:"mb-8",children:[s.jsx("h2",{className:"text-lg font-semibold mb-4 text-gray-700",children:"Persönlich"}),s.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:s.jsx(ke,{to:"/settings/view",className:"block p-4 bg-white border border-gray-200 rounded-lg shadow-sm hover:shadow-md hover:border-blue-300 transition-all group",children:s.jsxs("div",{className:"flex items-start gap-4",children:[s.jsx("div",{className:"p-2 bg-blue-50 rounded-lg group-hover:bg-blue-100 transition-colors",children:s.jsx(Pe,{className:"w-6 h-6 text-blue-600"})}),s.jsxs("div",{className:"flex-1",children:[s.jsxs("h3",{className:"font-semibold text-gray-900 group-hover:text-blue-600 transition-colors flex items-center gap-2",children:["Ansicht",s.jsx(Ft,{className:"w-4 h-4 opacity-0 group-hover:opacity-100 transition-opacity"})]}),s.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"Passen Sie die Darstellung der Anwendung an."})]})]})})})]}),e("developer:access")&&s.jsxs(Y,{title:"Entwickleroptionen",className:"mb-6",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(Mc,{className:"w-5 h-5 text-gray-500"}),s.jsxs("div",{children:[s.jsx("p",{className:"font-medium",children:"Entwicklermodus"}),s.jsx("p",{className:"text-sm text-gray-500",children:"Aktiviert erweiterte Funktionen wie direkten Datenbankzugriff"})]})]}),s.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:t,onChange:a=>n(a.target.checked),className:"sr-only peer"}),s.jsx("div",{className:"w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"})]})]}),t&&s.jsx("div",{className:"mt-4 p-3 bg-yellow-50 border border-yellow-200 rounded-lg",children:s.jsxs("p",{className:"text-sm text-yellow-800",children:[s.jsx("strong",{children:"Warnung:"})," Der Entwicklermodus ermöglicht direkten Zugriff auf die Datenbank. Unsachgemäße Änderungen können zu Datenverlust oder Inkonsistenzen führen."]})})]}),s.jsx(Y,{title:"Über",children:s.jsxs("dl",{className:"space-y-3",children:[s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Version"}),s.jsx("dd",{children:"1.0.0"})]}),s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"System"}),s.jsx("dd",{children:"OpenCRM"})]})]})})]})}function t4({onSelectTable:e}){const t=j.useRef(null),[n,r]=j.useState(1),[a,i]=j.useState({x:0,y:0}),[l,o]=j.useState(!1),[c,d]=j.useState({x:0,y:0}),[u,h]=j.useState({}),[p,m]=j.useState(null),{data:f,isLoading:x}=me({queryKey:["developer-schema"],queryFn:Si.getSchema}),b=(f==null?void 0:f.data)||[];j.useEffect(()=>{if(b.length>0&&Object.keys(u).length===0){const w=Math.ceil(Math.sqrt(b.length)),S={x:280,y:200},E={};b.forEach((z,I)=>{const B=I%w,P=Math.floor(I/w);E[z.name]={x:50+B*S.x,y:50+P*S.y}}),h(E)}},[b,u]);const y=j.useCallback(w=>{(w.target===w.currentTarget||w.target.tagName==="svg")&&(o(!0),d({x:w.clientX-a.x,y:w.clientY-a.y}))},[a]),g=j.useCallback(w=>{var S;if(l&&!p)i({x:w.clientX-c.x,y:w.clientY-c.y});else if(p){const E=(S=t.current)==null?void 0:S.getBoundingClientRect();E&&h(z=>({...z,[p]:{x:(w.clientX-E.left-a.x)/n-100,y:(w.clientY-E.top-a.y)/n-20}}))}},[l,p,c,a,n]),v=j.useCallback(()=>{o(!1),m(null)},[]),N=w=>{r(S=>Math.min(2,Math.max(.3,S+w)))},D=()=>{r(1),i({x:0,y:0})},A=j.useCallback(()=>{const w=[];return b.forEach(S=>{const E=u[S.name];E&&S.foreignKeys.forEach(z=>{const I=u[z.targetTable];if(!I)return;const B=b.find(M=>M.name===z.targetTable),P=B==null?void 0:B.relations.find(M=>M.targetTable===S.name);w.push({from:{table:S.name,x:E.x+100,y:E.y+60},to:{table:z.targetTable,x:I.x+100,y:I.y+60},type:(P==null?void 0:P.type)||"one",label:z.field})})}),w},[b,u]);if(x)return s.jsx("div",{className:"flex items-center justify-center h-full",children:"Laden..."});const R=A();return s.jsxs("div",{className:"relative h-full w-full bg-gray-50 overflow-hidden",ref:t,children:[s.jsxs("div",{className:"absolute top-4 right-4 z-10 flex gap-2 bg-white rounded-lg shadow-md p-2",children:[s.jsx(F,{variant:"ghost",size:"sm",onClick:()=>N(.1),title:"Vergrößern",children:s.jsx(H2,{className:"w-4 h-4"})}),s.jsx(F,{variant:"ghost",size:"sm",onClick:()=>N(-.1),title:"Verkleinern",children:s.jsx(W2,{className:"w-4 h-4"})}),s.jsx(F,{variant:"ghost",size:"sm",onClick:D,title:"Zurücksetzen",children:s.jsx($2,{className:"w-4 h-4"})}),s.jsxs("div",{className:"text-xs text-gray-500 flex items-center px-2",children:[Math.round(n*100),"%"]})]}),s.jsxs("div",{className:"absolute top-4 left-4 z-10 bg-white rounded-lg shadow-md p-2 text-xs text-gray-500",children:[s.jsx(_2,{className:"w-3 h-3 inline mr-1"}),"Tabellen ziehen zum Verschieben"]}),s.jsx("svg",{className:"w-full h-full cursor-grab",style:{cursor:l?"grabbing":"grab"},onMouseDown:y,onMouseMove:g,onMouseUp:v,onMouseLeave:v,children:s.jsxs("g",{transform:`translate(${a.x}, ${a.y}) scale(${n})`,children:[s.jsxs("defs",{children:[s.jsx("marker",{id:"arrowhead",markerWidth:"10",markerHeight:"7",refX:"9",refY:"3.5",orient:"auto",children:s.jsx("polygon",{points:"0 0, 10 3.5, 0 7",fill:"#6b7280"})}),s.jsx("marker",{id:"many-marker",markerWidth:"12",markerHeight:"12",refX:"6",refY:"6",orient:"auto",children:s.jsx("circle",{cx:"6",cy:"6",r:"3",fill:"#6b7280"})})]}),R.map((w,S)=>{const E=w.to.x-w.from.x,z=w.to.y-w.from.y,I=w.from.x+E/2,B=w.from.y+z/2,P=w.from.x+E*.25,M=w.from.y,k=w.from.x+E*.75,_=w.to.y;return s.jsxs("g",{children:[s.jsx("path",{d:`M ${w.from.x} ${w.from.y} C ${P} ${M}, ${k} ${_}, ${w.to.x} ${w.to.y}`,fill:"none",stroke:"#9ca3af",strokeWidth:"2",markerEnd:"url(#arrowhead)"}),s.jsx("text",{x:I,y:B-8,fontSize:"10",fill:"#6b7280",textAnchor:"middle",className:"select-none",children:w.type==="many"?"1:n":"1:1"})]},S)}),b.map(w=>{const S=u[w.name];if(!S)return null;const E=200,z=32,I=20,B=[...new Set([w.primaryKey,...w.foreignKeys.map(M=>M.field)])],P=z+Math.min(B.length,5)*I+8;return s.jsxs("g",{transform:`translate(${S.x}, ${S.y})`,style:{cursor:"move"},onMouseDown:M=>{M.stopPropagation(),m(w.name)},children:[s.jsx("rect",{x:"3",y:"3",width:E,height:P,rx:"6",fill:"rgba(0,0,0,0.1)"}),s.jsx("rect",{x:"0",y:"0",width:E,height:P,rx:"6",fill:"white",stroke:"#e5e7eb",strokeWidth:"1"}),s.jsx("rect",{x:"0",y:"0",width:E,height:z,rx:"6",fill:"#3b82f6",className:"cursor-pointer",onClick:()=>e==null?void 0:e(w.name)}),s.jsx("rect",{x:"0",y:z-6,width:E,height:"6",fill:"#3b82f6"}),s.jsx("text",{x:E/2,y:"21",fontSize:"13",fontWeight:"bold",fill:"white",textAnchor:"middle",className:"select-none pointer-events-none",children:w.name}),B.slice(0,5).map((M,k)=>{const _=M===w.primaryKey||w.primaryKey.includes(M),K=w.foreignKeys.some(Z=>Z.field===M);return s.jsx("g",{transform:`translate(8, ${z+4+k*I})`,children:s.jsxs("text",{x:"0",y:"14",fontSize:"11",fill:_?"#dc2626":K?"#2563eb":"#374151",fontFamily:"monospace",className:"select-none",children:[_&&"🔑 ",K&&!_&&"🔗 ",M]})},M)}),B.length>5&&s.jsxs("text",{x:E/2,y:P-4,fontSize:"10",fill:"#9ca3af",textAnchor:"middle",className:"select-none",children:["+",B.length-5," mehr..."]})]},w.name)})]})}),s.jsxs("div",{className:"absolute bottom-4 left-4 bg-white rounded-lg shadow-md p-3 text-xs",children:[s.jsx("div",{className:"font-medium mb-2",children:"Legende"}),s.jsxs("div",{className:"space-y-1",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-red-600",children:"🔑"}),s.jsx("span",{children:"Primary Key"})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-blue-600",children:"🔗"}),s.jsx("span",{children:"Foreign Key"})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("div",{className:"w-6 h-0.5 bg-gray-400"}),s.jsx("span",{children:"Beziehung"})]})]})]})]})}function s4(){var R;const[e,t]=j.useState(null),[n,r]=j.useState(1),[a,i]=j.useState(null),[l,o]=j.useState(!1),c=xe(),{data:d,isLoading:u,error:h}=me({queryKey:["developer-schema"],queryFn:Si.getSchema});console.log("Schema data:",d),console.log("Schema error:",h);const{data:p,isLoading:m}=me({queryKey:["developer-table",e,n],queryFn:()=>Si.getTableData(e,n),enabled:!!e}),f=W({mutationFn:({tableName:w,id:S,data:E})=>Si.updateRow(w,S,E),onSuccess:()=>{c.invalidateQueries({queryKey:["developer-table",e]}),i(null)},onError:w=>{var S,E;alert(((E=(S=w.response)==null?void 0:S.data)==null?void 0:E.error)||"Fehler beim Speichern")}}),x=W({mutationFn:({tableName:w,id:S})=>Si.deleteRow(w,S),onSuccess:()=>{c.invalidateQueries({queryKey:["developer-table",e]})},onError:w=>{var S,E;alert(((E=(S=w.response)==null?void 0:S.data)==null?void 0:E.error)||"Fehler beim Löschen")}}),b=(d==null?void 0:d.data)||[],y=b.find(w=>w.name===e),g=(w,S)=>S.primaryKey.includes(",")?S.primaryKey.split(",").map(E=>w[E]).join("-"):String(w[S.primaryKey]),v=w=>w==null?"-":typeof w=="boolean"?w?"Ja":"Nein":typeof w=="object"?w instanceof Date||typeof w=="string"&&w.match(/^\d{4}-\d{2}-\d{2}/)?new Date(w).toLocaleString("de-DE"):JSON.stringify(w):String(w),N=()=>{!a||!e||f.mutate({tableName:e,id:a.id,data:a.data})},D=w=>{e&&confirm("Datensatz wirklich löschen?")&&x.mutate({tableName:e,id:w})};if(u)return s.jsx("div",{className:"text-center py-8",children:"Laden..."});const A=w=>{t(w),r(1),o(!1)};return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center justify-between mb-6",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(Tc,{className:"w-6 h-6"}),s.jsx("h1",{className:"text-2xl font-bold",children:"Datenbankstruktur"})]}),s.jsxs(F,{onClick:()=>o(!0),children:[s.jsx(mx,{className:"w-4 h-4 mr-2"}),"ER-Diagramm"]})]}),s.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-4 gap-6",children:[s.jsx(Y,{title:"Tabellen",className:"lg:col-span-1",children:s.jsx("div",{className:"space-y-1 max-h-[600px] overflow-y-auto",children:b.map(w=>s.jsxs("button",{onClick:()=>{t(w.name),r(1)},className:`w-full text-left px-3 py-2 rounded-lg flex items-center gap-2 transition-colors ${e===w.name?"bg-blue-100 text-blue-700":"hover:bg-gray-100"}`,children:[s.jsx(q2,{className:"w-4 h-4"}),s.jsx("span",{className:"text-sm font-mono",children:w.name})]},w.name))})}),s.jsx("div",{className:"lg:col-span-3 space-y-6",children:e&&y?s.jsxs(s.Fragment,{children:[s.jsxs(Y,{title:`${e} - Beziehungen`,children:[s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[s.jsxs("div",{children:[s.jsx("h4",{className:"text-sm font-medium text-gray-500 mb-2",children:"Fremdschlüssel (referenziert)"}),y.foreignKeys.length>0?s.jsx("div",{className:"space-y-1",children:y.foreignKeys.map(w=>s.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[s.jsx("span",{className:"font-mono text-gray-600",children:w.field}),s.jsx(Nv,{className:"w-4 h-4 text-gray-400"}),s.jsx(ye,{variant:"info",className:"cursor-pointer",onClick:()=>{t(w.targetTable),r(1)},children:w.targetTable})]},w.field))}):s.jsx("p",{className:"text-sm text-gray-400",children:"Keine"})]}),s.jsxs("div",{children:[s.jsx("h4",{className:"text-sm font-medium text-gray-500 mb-2",children:"Relationen (wird referenziert von)"}),y.relations.length>0?s.jsx("div",{className:"space-y-1",children:y.relations.map(w=>s.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[s.jsx("span",{className:"font-mono text-gray-600",children:w.field}),s.jsx(ye,{variant:w.type==="many"?"warning":"default",children:w.type==="many"?"1:n":"1:1"}),s.jsx(ye,{variant:"info",className:"cursor-pointer",onClick:()=>{t(w.targetTable),r(1)},children:w.targetTable})]},w.field))}):s.jsx("p",{className:"text-sm text-gray-400",children:"Keine"})]})]}),s.jsx("div",{className:"mt-4 pt-4 border-t",children:s.jsxs("div",{className:"flex gap-4 text-sm",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-gray-500",children:"Primary Key:"})," ",s.jsx("span",{className:"font-mono",children:y.primaryKey})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-gray-500",children:"Readonly:"})," ",s.jsx("span",{className:"font-mono text-red-600",children:y.readonlyFields.join(", ")||"-"})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-gray-500",children:"Required:"})," ",s.jsx("span",{className:"font-mono text-green-600",children:y.requiredFields.join(", ")||"-"})]})]})})]}),s.jsx(Y,{title:`${e} - Daten`,children:m?s.jsx("div",{className:"text-center py-4",children:"Laden..."}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"overflow-x-auto",children:s.jsxs("table",{className:"w-full text-sm",children:[s.jsx("thead",{children:s.jsxs("tr",{className:"border-b bg-gray-50",children:[(p==null?void 0:p.data)&&p.data.length>0&&Object.keys(p.data[0]).map(w=>s.jsxs("th",{className:"text-left py-2 px-3 font-medium text-gray-600 whitespace-nowrap",children:[w,y.readonlyFields.includes(w)&&s.jsx("span",{className:"ml-1 text-red-400 text-xs",children:"*"}),y.requiredFields.includes(w)&&s.jsx("span",{className:"ml-1 text-green-400 text-xs",children:"!"})]},w)),s.jsx("th",{className:"text-right py-2 px-3 font-medium text-gray-600",children:"Aktionen"})]})}),s.jsxs("tbody",{children:[(R=p==null?void 0:p.data)==null?void 0:R.map(w=>{const S=g(w,y);return s.jsxs("tr",{className:"border-b hover:bg-gray-50",children:[Object.entries(w).map(([E,z])=>s.jsx("td",{className:"py-2 px-3 font-mono text-xs max-w-[200px] truncate",children:v(z)},E)),s.jsx("td",{className:"py-2 px-3 text-right whitespace-nowrap",children:s.jsxs("div",{className:"flex justify-end gap-1",children:[s.jsx(F,{variant:"ghost",size:"sm",onClick:()=>i({id:S,data:{...w}}),children:s.jsx(Ye,{className:"w-4 h-4"})}),s.jsx(F,{variant:"ghost",size:"sm",onClick:()=>D(S),children:s.jsx(be,{className:"w-4 h-4 text-red-500"})})]})})]},S)}),(!(p!=null&&p.data)||p.data.length===0)&&s.jsx("tr",{children:s.jsx("td",{colSpan:100,className:"py-4 text-center text-gray-500",children:"Keine Daten vorhanden"})})]})]})}),(p==null?void 0:p.pagination)&&p.pagination.totalPages>1&&s.jsxs("div",{className:"mt-4 flex items-center justify-between",children:[s.jsxs("p",{className:"text-sm text-gray-500",children:["Seite ",p.pagination.page," von ",p.pagination.totalPages," (",p.pagination.total," Einträge)"]}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx(F,{variant:"secondary",size:"sm",onClick:()=>r(w=>Math.max(1,w-1)),disabled:n===1,children:s.jsx(A2,{className:"w-4 h-4"})}),s.jsx(F,{variant:"secondary",size:"sm",onClick:()=>r(w=>w+1),disabled:n>=p.pagination.totalPages,children:s.jsx(Ft,{className:"w-4 h-4"})})]})]})]})})]}):s.jsx(Y,{children:s.jsx("div",{className:"text-center py-8 text-gray-500",children:"Wähle eine Tabelle aus der Liste aus"})})})]}),s.jsx(Ve,{isOpen:!!a,onClose:()=>i(null),title:`${e} bearbeiten`,children:a&&y&&s.jsxs("div",{className:"space-y-4 max-h-[60vh] overflow-y-auto",children:[Object.entries(a.data).map(([w,S])=>{const E=y.readonlyFields.includes(w),z=y.requiredFields.includes(w);return s.jsxs("div",{children:[s.jsxs("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:[w,E&&s.jsx("span",{className:"ml-1 text-red-400",children:"(readonly)"}),z&&s.jsx("span",{className:"ml-1 text-green-600",children:"*"})]}),E?s.jsx("div",{className:"px-3 py-2 bg-gray-100 rounded-lg font-mono text-sm",children:v(S)}):typeof S=="boolean"?s.jsxs("select",{value:String(a.data[w]),onChange:I=>i({...a,data:{...a.data,[w]:I.target.value==="true"}}),className:"w-full px-3 py-2 border rounded-lg",children:[s.jsx("option",{value:"true",children:"Ja"}),s.jsx("option",{value:"false",children:"Nein"})]}):s.jsx("input",{type:typeof S=="number"?"number":"text",value:a.data[w]??"",onChange:I=>i({...a,data:{...a.data,[w]:typeof S=="number"?I.target.value?Number(I.target.value):null:I.target.value||null}}),className:"w-full px-3 py-2 border rounded-lg font-mono text-sm",disabled:E})]},w)}),s.jsxs("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[s.jsxs(F,{variant:"secondary",onClick:()=>i(null),children:[s.jsx(Vt,{className:"w-4 h-4 mr-2"}),"Abbrechen"]}),s.jsxs(F,{onClick:N,disabled:f.isPending,children:[s.jsx(Av,{className:"w-4 h-4 mr-2"}),f.isPending?"Speichern...":"Speichern"]})]})]})}),l&&s.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[s.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:()=>o(!1)}),s.jsxs("div",{className:"relative bg-white rounded-xl shadow-2xl w-[90vw] h-[85vh] flex flex-col",children:[s.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(mx,{className:"w-5 h-5 text-blue-600"}),s.jsx("h2",{className:"text-lg font-semibold",children:"ER-Diagramm - Datenbankbeziehungen"})]}),s.jsx("button",{onClick:()=>o(!1),className:"p-2 hover:bg-gray-100 rounded-lg transition-colors",children:s.jsx(Vt,{className:"w-5 h-5"})})]}),s.jsx("div",{className:"flex-1 overflow-hidden",children:s.jsx(t4,{onSelectTable:A})})]})]})]})}function n4({children:e}){const{isAuthenticated:t,isLoading:n}=He();return n?s.jsx("div",{className:"min-h-screen flex items-center justify-center",children:s.jsx("div",{className:"text-gray-500",children:"Laden..."})}):t?s.jsx(s.Fragment,{children:e}):s.jsx(ya,{to:"/login",replace:!0})}function r4({children:e}){const{hasPermission:t,developerMode:n}=He();return!t("developer:access")||!n?s.jsx(ya,{to:"/",replace:!0}):s.jsx(s.Fragment,{children:e})}function a4(){const{isAuthenticated:e,isLoading:t}=He();return t?s.jsx("div",{className:"min-h-screen flex items-center justify-center",children:s.jsx("div",{className:"text-gray-500",children:"Laden..."})}):s.jsxs(s.Fragment,{children:[s.jsx(N2,{}),s.jsxs(mw,{children:[s.jsx(ze,{path:"/login",element:e?s.jsx(ya,{to:"/",replace:!0}):s.jsx(X2,{})}),s.jsxs(ze,{path:"/",element:s.jsx(n4,{children:s.jsx(J2,{})}),children:[s.jsx(ze,{index:!0,element:s.jsx(Y2,{})}),s.jsx(ze,{path:"customers",element:s.jsx(tk,{})}),s.jsx(ze,{path:"customers/new",element:s.jsx(Ix,{})}),s.jsx(ze,{path:"customers/:id",element:s.jsx(ck,{})}),s.jsx(ze,{path:"customers/:id/edit",element:s.jsx(Ix,{})}),s.jsx(ze,{path:"contracts",element:s.jsx(Hk,{})}),s.jsx(ze,{path:"contracts/cockpit",element:s.jsx(CC,{})}),s.jsx(ze,{path:"contracts/new",element:s.jsx(_x,{})}),s.jsx(ze,{path:"contracts/:id",element:s.jsx(xC,{})}),s.jsx(ze,{path:"contracts/:id/edit",element:s.jsx(_x,{})}),s.jsx(ze,{path:"tasks",element:s.jsx(DC,{})}),s.jsx(ze,{path:"settings",element:s.jsx(e4,{})}),s.jsx(ze,{path:"settings/users",element:s.jsx(XC,{})}),s.jsx(ze,{path:"settings/platforms",element:s.jsx(MC,{})}),s.jsx(ze,{path:"settings/cancellation-periods",element:s.jsx(FC,{})}),s.jsx(ze,{path:"settings/contract-durations",element:s.jsx(RC,{})}),s.jsx(ze,{path:"settings/providers",element:s.jsx(OC,{})}),s.jsx(ze,{path:"settings/contract-categories",element:s.jsx(BC,{})}),s.jsx(ze,{path:"settings/view",element:s.jsx(QC,{})}),s.jsx(ze,{path:"settings/portal",element:s.jsx(HC,{})}),s.jsx(ze,{path:"settings/deadlines",element:s.jsx(WC,{})}),s.jsx(ze,{path:"settings/email-providers",element:s.jsx(ZC,{})}),s.jsx(ze,{path:"settings/database-backup",element:s.jsx(JC,{})}),s.jsx(ze,{path:"users",element:s.jsx(ya,{to:"/settings/users",replace:!0})}),s.jsx(ze,{path:"platforms",element:s.jsx(ya,{to:"/settings/platforms",replace:!0})}),s.jsx(ze,{path:"developer/database",element:s.jsx(r4,{children:s.jsx(s4,{})})})]}),s.jsx(ze,{path:"*",element:s.jsx(ya,{to:"/",replace:!0})})]})]})}const i4=new Jw({defaultOptions:{queries:{retry:1,staleTime:0,gcTime:0,refetchOnMount:"always"}}});jd.createRoot(document.getElementById("root")).render(s.jsx(Tt.StrictMode,{children:s.jsx(Xw,{client:i4,children:s.jsx(bw,{children:s.jsx(b2,{children:s.jsxs(j2,{children:[s.jsx(a4,{}),s.jsx(q1,{position:"top-right",toastOptions:{duration:4e3,style:{background:"#363636",color:"#fff"},success:{iconTheme:{primary:"#10b981",secondary:"#fff"}},error:{iconTheme:{primary:"#ef4444",secondary:"#fff"}}}})]})})})})}));