var xf=e=>{throw TypeError(e)};var Lc=(e,t,n)=>t.has(e)||xf("Cannot "+n);var T=(e,t,n)=>(Lc(e,t,"read from private field"),n?n.call(e):t.get(e)),ce=(e,t,n)=>t.has(e)?xf("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),te=(e,t,n,r)=>(Lc(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),ye=(e,t,n)=>(Lc(e,t,"access private method"),n);var Ll=(e,t,n,r)=>({set _(a){te(e,t,a,n)},get _(){return T(e,t,r)}});function Bv(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 Yx={exports:{}},nc={},eg={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"),Vv=Symbol.for("react.portal"),Qv=Symbol.for("react.fragment"),Hv=Symbol.for("react.strict_mode"),Wv=Symbol.for("react.profiler"),Gv=Symbol.for("react.provider"),Zv=Symbol.for("react.context"),Jv=Symbol.for("react.forward_ref"),Xv=Symbol.for("react.suspense"),Yv=Symbol.for("react.memo"),ej=Symbol.for("react.lazy"),gf=Symbol.iterator;function tj(e){return e===null||typeof e!="object"?null:(e=gf&&e[gf]||e["@@iterator"],typeof e=="function"?e:null)}var tg={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},sg=Object.assign,ng={};function Ja(e,t,n){this.props=e,this.context=t,this.refs=ng,this.updater=n||tg}Ja.prototype.isReactComponent={};Ja.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")};Ja.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function rg(){}rg.prototype=Ja.prototype;function Ju(e,t,n){this.props=e,this.context=t,this.refs=ng,this.updater=n||tg}var Xu=Ju.prototype=new rg;Xu.constructor=Ju;sg(Xu,Ja.prototype);Xu.isPureReactComponent=!0;var yf=Array.isArray,ag=Object.prototype.hasOwnProperty,Yu={current:null},ig={key:!0,ref:!0,__self:!0,__source:!0};function lg(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)ag.call(t,r)&&!ig.hasOwnProperty(r)&&(a[r]=t[r]);var o=arguments.length-2;if(o===1)a.children=n;else if(1>>1,le=U[fe];if(0>>1;fea(Ye,W))qea(et,Ye)?(U[fe]=et,U[qe]=W,fe=qe):(U[fe]=Ye,U[Re]=W,fe=Re);else if(qea(et,W))U[fe]=et,U[qe]=W,fe=qe;else break e}}return Z}function a(U,Z){var W=U.sortIndex-Z.sortIndex;return W!==0?W:U.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,g=!1,v=typeof setTimeout=="function"?setTimeout:null,j=typeof clearTimeout=="function"?clearTimeout:null,x=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function y(U){for(var Z=n(d);Z!==null;){if(Z.callback===null)r(d);else if(Z.startTime<=U)r(d),Z.sortIndex=Z.expirationTime,t(c,Z);else break;Z=n(d)}}function N(U){if(g=!1,y(U),!f)if(n(c)!==null)f=!0,S(D);else{var Z=n(d);Z!==null&&_(N,Z.startTime-U)}}function D(U,Z){f=!1,g&&(g=!1,j(w),w=-1),m=!0;var W=p;try{for(y(Z),h=n(c);h!==null&&(!(h.expirationTime>Z)||U&&!K());){var fe=h.callback;if(typeof fe=="function"){h.callback=null,p=h.priorityLevel;var le=fe(h.expirationTime<=Z);Z=e.unstable_now(),typeof le=="function"?h.callback=le:h===n(c)&&r(c),y(Z)}else r(c);h=n(c)}if(h!==null)var k=!0;else{var Re=n(d);Re!==null&&_(N,Re.startTime-Z),k=!1}return k}finally{h=null,p=W,m=!1}}var P=!1,F=null,w=-1,C=5,E=-1;function K(){return!(e.unstable_now()-EU||125fe?(U.sortIndex=W,t(d,U),n(c)===null&&U===n(d)&&(g?(j(w),w=-1):g=!0,_(N,W-fe))):(U.sortIndex=le,t(c,U),f||m||(f=!0,S(D))),U},e.unstable_shouldYield=K,e.unstable_wrapCallback=function(U){var Z=p;return function(){var W=p;p=Z;try{return U.apply(this,arguments)}finally{p=W}}}})(mg);ug.exports=mg;var hj=ug.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 fj=b,vs=hj;function J(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,pj=/^[: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]*$/,jf={},bf={};function xj(e){return bd.call(bf,e)?!0:bd.call(jf,e)?!1:pj.test(e)?bf[e]=!0:(jf[e]=!0,!1)}function gj(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 yj(e,t,n,r){if(t===null||typeof t>"u"||gj(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 Xt(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 Ft={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){Ft[e]=new Xt(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];Ft[t]=new Xt(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){Ft[e]=new Xt(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){Ft[e]=new Xt(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){Ft[e]=new Xt(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){Ft[e]=new Xt(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){Ft[e]=new Xt(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){Ft[e]=new Xt(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){Ft[e]=new Xt(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);Ft[t]=new Xt(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);Ft[t]=new Xt(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);Ft[t]=new Xt(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){Ft[e]=new Xt(e,1,!1,e.toLowerCase(),null,!1,!1)});Ft.xlinkHref=new Xt("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){Ft[e]=new Xt(e,1,!1,e.toLowerCase(),null,!0,!0)});function nm(e,t,n,r){var a=Ft.hasOwnProperty(t)?Ft[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:"")?yi(e):""}function vj(e){switch(e.tag){case 5:return yi(e.type);case 16:return yi("Lazy");case 13:return yi("Suspense");case 19:return yi("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 ia:return"Fragment";case aa: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 pg:return(e.displayName||"Context")+".Consumer";case fg: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 zn:t=e._payload,e=e._init;try{return kd(e(t))}catch{}}return null}function jj(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 hr(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function gg(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function bj(e){var t=gg(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=bj(e))}function yg(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=gg(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 wf(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=hr(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 vg(e,t){t=t.checked,t!=null&&nm(e,"checked",t,!1)}function Ed(e,t){vg(e,t);var n=hr(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,hr(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function Sf(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 vi=Array.isArray;function ya(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},Nj=["Webkit","ms","Moz","O"];Object.keys(ki).forEach(function(e){Nj.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),ki[t]=ki[e]})});function wg(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 Sg(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,a=wg(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,a):e[n]=a}}var wj=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(wj[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(J(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(J(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(J(61))}if(t.style!=null&&typeof t.style!="object")throw Error(J(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,va=null,ja=null;function Ef(e){if(e=Nl(e)){if(typeof Id!="function")throw Error(J(280));var t=e.stateNode;t&&(t=oc(t),Id(e.stateNode,e.type,t))}}function kg(e){va?ja?ja.push(e):ja=[e]:va=e}function Cg(){if(va){var e=va,t=ja;if(ja=va=null,Ef(e),t)for(e=0;e>>=0,e===0?32:31-(Ij(e)/Rj|0)|0}var Kl=64,Ul=4194304;function ji(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=ji(o):(i&=l,i!==0&&(r=ji(i)))}else l=n&~a,l!==0?r=ji(l):i!==0&&(r=ji(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-Us(t),e[t]=n}function $j(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),Lf=" ",Of=!1;function Qg(e,t){switch(e){case"keyup":return hb.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Hg(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var la=!1;function pb(e,t){switch(e){case"compositionend":return Hg(t);case"keypress":return t.which!==32?null:(Of=!0,Lf);case"textInput":return e=t.data,e===Lf&&Of?null:e;default:return null}}function xb(e,t){if(la)return e==="compositionend"||!pm&&Qg(e,t)?(e=qg(),lo=mm=er=null,la=!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=Kf(n)}}function Jg(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?Jg(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function Xg(){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 kb(e){var t=Xg(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&Jg(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=Uf(n,i);var l=Uf(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,oa=null,_d=null,Ai=null,Kd=!1;function Bf(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;Kd||oa==null||oa!==wo(r)||(r=oa,"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}),Ai&&qi(Ai,r)||(Ai=r,r=Po(_d,"onSelect"),0ua||(e.current=Hd[ua],Hd[ua]=null,ua--)}function Ve(e,t){ua++,Hd[ua]=e.current,e.current=t}var fr={},Ut=gr(fr),ls=gr(!1),Br=fr;function Ua(e,t){var n=e.type.contextTypes;if(!n)return fr;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 os(e){return e=e.childContextTypes,e!=null}function To(){Ge(ls),Ge(Ut)}function Zf(e,t,n){if(Ut.current!==fr)throw Error(J(168));Ve(Ut,t),Ve(ls,n)}function ly(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(J(108,jj(e)||"Unknown",a));return at({},n,r)}function Fo(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||fr,Br=Ut.current,Ve(Ut,e),Ve(ls,ls.current),!0}function Jf(e,t,n){var r=e.stateNode;if(!r)throw Error(J(169));n?(e=ly(e,t,Br),r.__reactInternalMemoizedMergedChildContext=e,Ge(ls),Ge(Ut),Ve(Ut,e)):Ge(ls),Ve(ls,n)}var pn=null,cc=!1,ed=!1;function oy(e){pn===null?pn=[e]:pn.push(e)}function Ob(e){cc=!0,oy(e)}function yr(){if(!ed&&pn!==null){ed=!0;var e=0,t=Ke;try{var n=pn;for(Ke=1;e>=l,a-=l,bn=1<<32-Us(t)+a|n<w?(C=F,F=null):C=F.sibling;var E=p(j,F,y[w],N);if(E===null){F===null&&(F=C);break}e&&F&&E.alternate===null&&t(j,F),x=i(E,x,w),P===null?D=E:P.sibling=E,P=E,F=C}if(w===y.length)return n(j,F),Je&&br(j,w),D;if(F===null){for(;ww?(C=F,F=null):C=F.sibling;var K=p(j,F,E.value,N);if(K===null){F===null&&(F=C);break}e&&F&&K.alternate===null&&t(j,F),x=i(K,x,w),P===null?D=K:P.sibling=K,P=K,F=C}if(E.done)return n(j,F),Je&&br(j,w),D;if(F===null){for(;!E.done;w++,E=y.next())E=h(j,E.value,N),E!==null&&(x=i(E,x,w),P===null?D=E:P.sibling=E,P=E);return Je&&br(j,w),D}for(F=r(j,F);!E.done;w++,E=y.next())E=m(F,j,w,E.value,N),E!==null&&(e&&E.alternate!==null&&F.delete(E.key===null?w:E.key),x=i(E,x,w),P===null?D=E:P.sibling=E,P=E);return e&&F.forEach(function(O){return t(j,O)}),Je&&br(j,w),D}function v(j,x,y,N){if(typeof y=="object"&&y!==null&&y.type===ia&&y.key===null&&(y=y.props.children),typeof y=="object"&&y!==null){switch(y.$$typeof){case zl:e:{for(var D=y.key,P=x;P!==null;){if(P.key===D){if(D=y.type,D===ia){if(P.tag===7){n(j,P.sibling),x=a(P,y.props.children),x.return=j,j=x;break e}}else if(P.elementType===D||typeof D=="object"&&D!==null&&D.$$typeof===zn&&ep(D)===P.type){n(j,P.sibling),x=a(P,y.props),x.ref=hi(j,P,y),x.return=j,j=x;break e}n(j,P);break}else t(j,P);P=P.sibling}y.type===ia?(x=_r(y.props.children,j.mode,N,y.key),x.return=j,j=x):(N=xo(y.type,y.key,y.props,null,j.mode,N),N.ref=hi(j,x,y),N.return=j,j=N)}return l(j);case aa:e:{for(P=y.key;x!==null;){if(x.key===P)if(x.tag===4&&x.stateNode.containerInfo===y.containerInfo&&x.stateNode.implementation===y.implementation){n(j,x.sibling),x=a(x,y.children||[]),x.return=j,j=x;break e}else{n(j,x);break}else t(j,x);x=x.sibling}x=od(y,j.mode,N),x.return=j,j=x}return l(j);case zn:return P=y._init,v(j,x,P(y._payload),N)}if(vi(y))return f(j,x,y,N);if(oi(y))return g(j,x,y,N);Gl(j,y)}return typeof y=="string"&&y!==""||typeof y=="number"?(y=""+y,x!==null&&x.tag===6?(n(j,x.sibling),x=a(x,y),x.return=j,j=x):(n(j,x),x=ld(y,j.mode,N),x.return=j,j=x),l(j)):n(j,x)}return v}var qa=my(!0),hy=my(!1),Lo=gr(null),Oo=null,fa=null,jm=null;function bm(){jm=fa=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 Na(e,t){Oo=e,jm=fa=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(is=!0),e.firstContext=null)}function Ts(e){var t=e._currentValue;if(jm!==e)if(e={context:e,memoizedValue:t,next:null},fa===null){if(Oo===null)throw Error(J(308));fa=e,Oo.dependencies={lanes:0,firstContext:e}}else fa=fa.next=e;return t}var kr=null;function wm(e){kr===null?kr=[e]:kr.push(e)}function fy(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,Dn(e,r)}function Dn(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 $n=!1;function Sm(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function py(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 Sn(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function lr(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,Dn(e,n)}return a=r.interleaved,a===null?(t.next=t,wm(r)):(t.next=a.next,a.next=t),r.interleaved=t,Dn(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 tp(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;$n=!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,g=o;switch(p=t,m=n,g.tag){case 1:if(f=g.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=g.payload,p=typeof f=="function"?f.call(m,h,p):f,p==null)break e;h=at({},h,p);break e;case 2:$n=!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 sp(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{Ke=n,sd.transition=r}}function Ty(){return Fs().memoizedState}function Kb(e,t,n){var r=cr(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},Fy(e))Iy(t,n);else if(n=fy(e,t,n,r),n!==null){var a=Gt();Bs(n,e,r,a),Ry(n,t,r)}}function Ub(e,t,n){var r=cr(e),a={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(Fy(e))Iy(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,qs(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=fy(e,t,a,r),n!==null&&(a=Gt(),Bs(n,e,r,a),Ry(n,t,r))}}function Fy(e){var t=e.alternate;return e===nt||t!==null&&t===nt}function Iy(e,t){Pi=_o=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function Ry(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:Ot,useContext:Ot,useEffect:Ot,useImperativeHandle:Ot,useInsertionEffect:Ot,useLayoutEffect:Ot,useMemo:Ot,useReducer:Ot,useRef:Ot,useState:Ot,useDebugValue:Ot,useDeferredValue:Ot,useTransition:Ot,useMutableSource:Ot,useSyncExternalStore:Ot,useId:Ot,unstable_isNewReconciler:!1},Bb={readContext:Ts,useCallback:function(e,t){return Gs().memoizedState=[e,t===void 0?null:t],e},useContext:Ts,useEffect:rp,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,mo(4194308,4,Ey.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=Gs();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=Gs();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=Kb.bind(null,nt,e),[r.memoizedState,e]},useRef:function(e){var t=Gs();return e={current:e},t.memoizedState=e},useState:np,useDebugValue:Tm,useDeferredValue:function(e){return Gs().memoizedState=e},useTransition:function(){var e=np(!1),t=e[0];return e=_b.bind(null,e[1]),Gs().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=nt,a=Gs();if(Je){if(n===void 0)throw Error(J(407));n=n()}else{if(n=t(),Ct===null)throw Error(J(349));Vr&30||vy(r,t,n)}a.memoizedState=n;var i={value:n,getSnapshot:t};return a.queue=i,rp(by.bind(null,r,i,e),[e]),r.flags|=2048,Xi(9,jy.bind(null,r,i,n,t),void 0,null),n},useId:function(){var e=Gs(),t=Ct.identifierPrefix;if(Je){var n=Nn,r=bn;n=(r&~(1<<32-Us(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[en]=t,e[Hi]=r,Vy(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;aHa&&(t.flags|=128,r=!0,fi(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),fi(i,!0),i.tail===null&&i.tailMode==="hidden"&&!l.alternate&&!Je)return zt(t),null}else 2*mt()-i.renderingStartTime>Ha&&n!==1073741824&&(t.flags|=128,r=!0,fi(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=mt(),t.sibling=null,n=st.current,Ve(st,r?n&1|2:n&1),t):(zt(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?fs&1073741824&&(zt(t),t.subtreeFlags&6&&(t.flags|=8192)):zt(t),null;case 24:return null;case 25:return null}throw Error(J(156,t.tag))}function Jb(e,t){switch(ym(t),t.tag){case 1:return os(t.type)&&To(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Va(),Ge(ls),Ge(Ut),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(J(340));Ba()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return Ge(st),null;case 4:return Va(),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,_t=!1,Xb=typeof WeakSet=="function"?WeakSet:Set,de=null;function pa(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){ct(e,t,r)}else n.current=null}function au(e,t,n){try{n()}catch(r){ct(e,t,r)}}var pp=!1;function Yb(e,t){if(Ud=Do,e=Xg(),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,de=t;de!==null;)if(t=de,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,de=e;else for(;de!==null;){t=de;try{var f=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(f!==null){var g=f.memoizedProps,v=f.memoizedState,j=t.stateNode,x=j.getSnapshotBeforeUpdate(t.elementType===t.type?g:Rs(t.type,g),v);j.__reactInternalSnapshotBeforeUpdate=x}break;case 3:var y=t.stateNode.containerInfo;y.nodeType===1?y.textContent="":y.nodeType===9&&y.documentElement&&y.removeChild(y.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(J(163))}}catch(N){ct(t,t.return,N)}if(e=t.sibling,e!==null){e.return=t.return,de=e;break}de=t.return}return f=pp,pp=!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 Wy(e){var t=e.alternate;t!==null&&(e.alternate=null,Wy(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[en],delete t[Hi],delete t[Qd],delete t[Rb],delete t[Lb])),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 Gy(e){return e.tag===5||e.tag===3||e.tag===4}function xp(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||Gy(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 Dt=null,zs=!1;function Ln(e,t,n){for(n=n.child;n!==null;)Zy(e,t,n),n=n.sibling}function Zy(e,t,n){if(nn&&typeof nn.onCommitFiberUnmount=="function")try{nn.onCommitFiberUnmount(rc,n)}catch{}switch(n.tag){case 5:_t||pa(n,t);case 6:var r=Dt,a=zs;Dt=null,Ln(e,t,n),Dt=r,zs=a,Dt!==null&&(zs?(e=Dt,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):Dt.removeChild(n.stateNode));break;case 18:Dt!==null&&(zs?(e=Dt,n=n.stateNode,e.nodeType===8?Yc(e.parentNode,n):e.nodeType===1&&Yc(e,n),Ui(e)):Yc(Dt,n.stateNode));break;case 4:r=Dt,a=zs,Dt=n.stateNode.containerInfo,zs=!0,Ln(e,t,n),Dt=r,zs=a;break;case 0:case 11:case 14:case 15:if(!_t&&(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)}Ln(e,t,n);break;case 1:if(!_t&&(pa(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(o){ct(n,t,o)}Ln(e,t,n);break;case 21:Ln(e,t,n);break;case 22:n.mode&1?(_t=(r=_t)||n.memoizedState!==null,Ln(e,t,n),_t=r):Ln(e,t,n);break;default:Ln(e,t,n)}}function gp(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new Xb),t.forEach(function(r){var a=oN.bind(null,e,r);n.has(r)||(n.add(r),r.then(a,a))})}}function Is(e,t){var n=t.deletions;if(n!==null)for(var r=0;ra&&(a=l),r&=~i}if(r=a,r=mt()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*tN(r/1960))-r,10e?16:e,tr===null)var r=!1;else{if(e=tr,tr=null,qo=0,Me&6)throw Error(J(331));var a=Me;for(Me|=4,de=e.current;de!==null;){var i=de,l=i.child;if(de.flags&16){var o=i.deletions;if(o!==null){for(var c=0;cmt()-Lm?$r(e,0):Rm|=n),cs(e,t)}function r0(e,t){t===0&&(e.mode&1?(t=Ul,Ul<<=1,!(Ul&130023424)&&(Ul=4194304)):t=1);var n=Gt();e=Dn(e,t),e!==null&&(jl(e,t,n),cs(e,n))}function lN(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),r0(e,n)}function oN(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(J(314))}r!==null&&r.delete(t),r0(e,n)}var a0;a0=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||ls.current)is=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return is=!1,Gb(e,t,n);is=!!(e.flags&131072)}else is=!1,Je&&t.flags&1048576&&cy(t,Ro,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;ho(e,t),e=t.pendingProps;var a=Ua(t,Ut.current);Na(t,n),a=Am(null,t,r,e,a,n);var i=Pm();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,os(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,Je&&i&&gm(t),Wt(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=dN(r),e=Rs(r,e),a){case 0:t=eu(null,t,r,e,n);break e;case 1:t=mp(null,t,r,e,n);break e;case 11:t=dp(null,t,r,e,n);break e;case 14:t=up(null,t,r,Rs(r.type,e),n);break e}throw Error(J(306,r,""))}return t;case 0:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:Rs(r,a),eu(e,t,r,a,n);case 1:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:Rs(r,a),mp(e,t,r,a,n);case 3:e:{if(Uy(t),e===null)throw Error(J(387));r=t.pendingProps,i=t.memoizedState,a=i.element,py(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=Qa(Error(J(423)),t),t=hp(e,t,r,n,a);break e}else if(r!==a){a=Qa(Error(J(424)),t),t=hp(e,t,r,n,a);break e}else for(gs=ir(t.stateNode.containerInfo.firstChild),ys=t,Je=!0,$s=null,n=hy(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(Ba(),r===a){t=An(e,t,n);break e}Wt(e,t,r,n)}t=t.child}return t;case 5:return xy(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),Ky(e,t),Wt(e,t,l,n),t.child;case 6:return e===null&&Gd(t),null;case 13:return By(e,t,n);case 4:return km(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=qa(t,null,r,n):Wt(e,t,r,n),t.child;case 11:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:Rs(r,a),dp(e,t,r,a,n);case 7:return Wt(e,t,t.pendingProps,n),t.child;case 8:return Wt(e,t,t.pendingProps.children,n),t.child;case 12:return Wt(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,Ve(Lo,r._currentValue),r._currentValue=l,i!==null)if(qs(i.value,l)){if(i.children===a.children&&!ls.current){t=An(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=Sn(-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(J(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}Wt(e,t,a.children,n),t=t.child}return t;case 9:return a=t.type,r=t.pendingProps.children,Na(t,n),a=Ts(a),r=r(a),t.flags|=1,Wt(e,t,r,n),t.child;case 14:return r=t.type,a=Rs(r,t.pendingProps),a=Rs(r.type,a),up(e,t,r,a,n);case 15:return $y(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:Rs(r,a),ho(e,t),t.tag=1,os(r)?(e=!0,Fo(t)):e=!1,Na(t,n),Ly(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 _y(e,t,n)}throw Error(J(156,t.tag))};function i0(e,t){return Fg(e,t)}function cN(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 cN(e,t,n,r)}function _m(e){return e=e.prototype,!(!e||!e.isReactComponent)}function dN(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 dr(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 ia: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 xg:return fc(n,a,i,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case fg:l=10;break e;case pg:l=9;break e;case am:l=11;break e;case im:l=14;break e;case zn:l=16,r=null;break e}throw Error(J(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=xg,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 uN(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 uN(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 mN(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(d0)}catch(e){console.error(e)}}d0(),dg.exports=js;var gN=dg.exports,kp=gN;jd.createRoot=kp.createRoot,jd.hydrateRoot=kp.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 vN(){return Math.random().toString(36).substr(2,8)}function Ep(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"?ei(t):t,{state:n,key:t&&t.key||r||vN()})}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 ei(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 jN(e,t,n,r){r===void 0&&(r={});let{window:a=document.defaultView,v5Compat:i=!1}=r,l=a.history,o=sr.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=sr.Pop;let v=u(),j=v==null?null:v-d;d=v,c&&c({action:o,location:g.location,delta:j})}function p(v,j){o=sr.Push;let x=hu(g.location,v,j);d=u()+1;let y=Ep(x,d),N=g.createHref(x);try{l.pushState(y,"",N)}catch(D){if(D instanceof DOMException&&D.name==="DataCloneError")throw D;a.location.assign(N)}i&&c&&c({action:o,location:g.location,delta:1})}function m(v,j){o=sr.Replace;let x=hu(g.location,v,j);d=u();let y=Ep(x,d),N=g.createHref(x);l.replaceState(y,"",N),i&&c&&c({action:o,location:g.location,delta:0})}function f(v){let j=a.location.origin!=="null"?a.location.origin:a.location.href,x=typeof v=="string"?v:Ho(v);return x=x.replace(/ $/,"%20"),rt(j,"No window.location.(origin|href) available to create URL for href: "+x),new URL(x,j)}let g={get action(){return o},get location(){return e(a,l)},listen(v){if(c)throw new Error("A history only accepts one active listener");return a.addEventListener(Cp,h),c=v,()=>{a.removeEventListener(Cp,h),c=null}},createHref(v){return t(a,v)},createURL:f,encodeLocation(v){let j=f(v);return{pathname:j.pathname,search:j.search,hash:j.hash}},push:p,replace:m,go(v){return l.go(v)}};return g}var Dp;(function(e){e.data="data",e.deferred="deferred",e.redirect="redirect",e.error="error"})(Dp||(Dp={}));function bN(e,t,n){return n===void 0&&(n="/"),NN(e,t,n)}function NN(e,t,n,r){let a=typeof t=="string"?ei(t):t,i=Wa(a.pathname||"/",n);if(i==null)return null;let l=u0(e);wN(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=ur([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+'".')),u0(i.children,t,u,d)),!(i.path==null&&!i.index)&&t.push({path:d,score:PN(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 m0(i.path))a(i,l,c)}),t}function m0(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=m0(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 wN(e){e.sort((t,n)=>t.score!==n.score?n.score-t.score:MN(t.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}const SN=/^:[\w-]+$/,kN=3,CN=2,EN=1,DN=10,AN=-2,Ap=e=>e==="*";function PN(e,t){let n=e.split("/"),r=n.length;return n.some(Ap)&&(r+=AN),t&&(r+=CN),n.filter(a=>!Ap(a)).reduce((a,i)=>a+(SN.test(i)?kN:i===""?EN:DN),r)}function MN(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 TN(e,t,n){let{routesMeta:r}=e,a={},i="/",l=[];for(let o=0;o{let{paramName:p,isOptional:m}=u;if(p==="*"){let g=o[h]||"";l=i.slice(0,i.length-g.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 FN(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 IN(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 Wa(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 RN=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,LN=e=>RN.test(e);function ON(e,t){t===void 0&&(t="/");let{pathname:n,search:r="",hash:a=""}=typeof e=="string"?ei(e):e,i;if(n)if(LN(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=Pp(n.substring(1),"/"):i=Pp(n,t)}else i=t;return{pathname:i,search:_N(r),hash:KN(a)}}function Pp(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 zN(e){return e.filter((t,n)=>n===0||t.route.path&&t.route.path.length>0)}function Qm(e,t){let n=zN(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=ei(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=ON(a,o),d=l&&l!=="/"&&l.endsWith("/"),u=(i||l===".")&&n.endsWith("/");return!c.pathname.endsWith("/")&&(d||u)&&(c.pathname+="/"),c}const ur=e=>e.join("/").replace(/\/\/+/g,"/"),$N=e=>e.replace(/\/+$/,"").replace(/^\/*/,"/"),_N=e=>!e||e==="?"?"":e.startsWith("?")?e:"?"+e,KN=e=>!e||e==="#"?"":e.startsWith("#")?e:"#"+e;function UN(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.internal=="boolean"&&"data"in e}const h0=["post","put","patch","delete"];new Set(h0);const BN=["get",...h0];new Set(BN);/** * 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}),b.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:ur([t,h.pathname])),(u.replace?r.replace:r.push)(h,u.state,u)},[t,r,l,i,e])}const QN=b.createContext(null);function HN(e){let t=b.useContext(ln).outlet;return t&&b.createElement(QN.Provider,{value:e},t)}function bc(){let{matches:e}=b.useContext(ln),t=e[e.length-1];return t?t.params:{}}function Nc(e,t){let{relative:n}=t===void 0?{}:t,{future:r}=b.useContext(Fn),{matches:a}=b.useContext(ln),{pathname:i}=In(),l=JSON.stringify(Qm(a,r.v7_relativeSplatPath));return b.useMemo(()=>Hm(e,JSON.parse(l),i,n==="path"),[e,l,i,n])}function WN(e,t){return GN(e,t)}function GN(e,t,n,r){ti()||rt(!1);let{navigator:a}=b.useContext(Fn),{matches:i}=b.useContext(ln),l=i[i.length-1],o=l?l.params:{};l&&l.pathname;let c=l?l.pathnameBase:"/";l&&l.route;let d=In(),u;if(t){var h;let v=typeof t=="string"?ei(t):t;c==="/"||(h=v.pathname)!=null&&h.startsWith(c)||rt(!1),u=v}else u=d;let p=u.pathname||"/",m=p;if(c!=="/"){let v=c.replace(/^\//,"").split("/");m="/"+p.replace(/^\//,"").split("/").slice(v.length).join("/")}let f=bN(e,{pathname:m}),g=ew(f&&f.map(v=>Object.assign({},v,{params:Object.assign({},o,v.params),pathname:ur([c,a.encodeLocation?a.encodeLocation(v.pathname).pathname:v.pathname]),pathnameBase:v.pathnameBase==="/"?c:ur([c,a.encodeLocation?a.encodeLocation(v.pathnameBase).pathname:v.pathnameBase])})),i,n,r);return t&&g?b.createElement(jc.Provider,{value:{location:tl({pathname:"/",search:"",hash:"",state:null,key:"default"},u),navigationType:sr.Pop}},g):g}function ZN(){let e=rw(),t=UN(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 b.createElement(b.Fragment,null,b.createElement("h2",null,"Unexpected Application Error!"),b.createElement("h3",{style:{fontStyle:"italic"}},t),n?b.createElement("pre",{style:a},n):null,null)}const JN=b.createElement(ZN,null);class XN extends b.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?b.createElement(ln.Provider,{value:this.props.routeContext},b.createElement(p0.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function YN(e){let{routeContext:t,match:n,children:r}=e,a=b.useContext(vc);return a&&a.static&&a.staticContext&&(n.route.errorElement||n.route.ErrorBoundary)&&(a.staticContext._deepestRenderedBoundaryId=n.route.id),b.createElement(ln.Provider,{value:t},r)}function ew(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,g=null,v=null;n&&(m=o&&h.route.id?o[h.route.id]:void 0,g=h.route.errorElement||JN,c&&(d<0&&p===0?(iw("route-fallback"),f=!0,v=null):d===p&&(f=!0,v=h.route.hydrateFallbackElement||null)));let j=t.concat(l.slice(0,p+1)),x=()=>{let y;return m?y=g:f?y=v:h.route.Component?y=b.createElement(h.route.Component,null):h.route.element?y=h.route.element:y=u,b.createElement(YN,{match:h,routeContext:{outlet:u,matches:j,isDataRoute:n!=null},children:y})};return n&&(h.route.ErrorBoundary||h.route.errorElement||p===0)?b.createElement(XN,{location:n.location,revalidation:n.revalidation,component:g,error:m,children:x(),routeContext:{outlet:null,matches:j,isDataRoute:!0}}):x()},null)}var g0=function(e){return e.UseBlocker="useBlocker",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e}(g0||{}),y0=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}(y0||{});function tw(e){let t=b.useContext(vc);return t||rt(!1),t}function sw(e){let t=b.useContext(f0);return t||rt(!1),t}function nw(e){let t=b.useContext(ln);return t||rt(!1),t}function v0(e){let t=nw(),n=t.matches[t.matches.length-1];return n.route.id||rt(!1),n.route.id}function rw(){var e;let t=b.useContext(p0),n=sw(),r=v0();return t!==void 0?t:(e=n.errors)==null?void 0:e[r]}function aw(){let{router:e}=tw(g0.UseNavigateStable),t=v0(y0.UseNavigateStable),n=b.useRef(!1);return x0(()=>{n.current=!0}),b.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 Mp={};function iw(e,t,n){Mp[e]||(Mp[e]=!0)}function lw(e,t){e==null||e.v7_startTransition,e==null||e.v7_relativeSplatPath}function ga(e){let{to:t,replace:n,state:r,relative:a}=e;ti()||rt(!1);let{future:i,static:l}=b.useContext(Fn),{matches:o}=b.useContext(ln),{pathname:c}=In(),d=Yt(),u=Hm(t,Qm(o,i.v7_relativeSplatPath),c,a==="path"),h=JSON.stringify(u);return b.useEffect(()=>d(JSON.parse(h),{replace:n,state:r,relative:a}),[d,h,a,n,r]),null}function ow(e){return HN(e.context)}function Oe(e){rt(!1)}function cw(e){let{basename:t="/",children:n=null,location:r,navigationType:a=sr.Pop,navigator:i,static:l=!1,future:o}=e;ti()&&rt(!1);let c=t.replace(/^\/*/,"/"),d=b.useMemo(()=>({basename:c,navigator:i,static:l,future:tl({v7_relativeSplatPath:!1},o)}),[c,o,i,l]);typeof r=="string"&&(r=ei(r));let{pathname:u="/",search:h="",hash:p="",state:m=null,key:f="default"}=r,g=b.useMemo(()=>{let v=Wa(u,c);return v==null?null:{location:{pathname:v,search:h,hash:p,state:m,key:f},navigationType:a}},[c,u,h,p,m,f,a]);return g==null?null:b.createElement(Fn.Provider,{value:d},b.createElement(jc.Provider,{children:n,value:g}))}function dw(e){let{children:t,location:n}=e;return WN(pu(t),n)}new Promise(()=>{});function pu(e,t){t===void 0&&(t=[]);let n=[];return b.Children.forEach(e,(r,a)=>{if(!b.isValidElement(r))return;let i=[...t,a];if(r.type===b.Fragment){n.push.apply(n,pu(r.props.children,i));return}r.type!==Oe&&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 uw(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function mw(e,t){return e.button===0&&(!t||t==="_self")&&!uw(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 hw(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 fw=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","viewTransition"],pw=["aria-current","caseSensitive","className","end","style","to","viewTransition","children"],xw="6";try{window.__reactRouterVersion=xw}catch{}const gw=b.createContext({isTransitioning:!1}),yw="startTransition",Tp=ij[yw];function vw(e){let{basename:t,children:n,future:r,window:a}=e,i=b.useRef();i.current==null&&(i.current=yN({window:a,v5Compat:!0}));let l=i.current,[o,c]=b.useState({action:l.action,location:l.location}),{v7_startTransition:d}=r||{},u=b.useCallback(h=>{d&&Tp?Tp(()=>c(h)):c(h)},[c,d]);return b.useLayoutEffect(()=>l.listen(u),[l,u]),b.useEffect(()=>lw(r),[r]),b.createElement(cw,{basename:t,children:n,location:o.location,navigationType:o.action,navigator:l,future:r})}const jw=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",bw=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,ke=b.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=j0(t,fw),{basename:m}=b.useContext(Fn),f,g=!1;if(typeof d=="string"&&bw.test(d)&&(f=d,jw))try{let y=new URL(window.location.href),N=d.startsWith("//")?new URL(y.protocol+d):new URL(d),D=Wa(N.pathname,m);N.origin===y.origin&&D!=null?d=D+N.search+N.hash:g=!0}catch{}let v=qN(d,{relative:a}),j=ww(d,{replace:l,state:o,target:c,preventScrollReset:u,relative:a,viewTransition:h});function x(y){r&&r(y),y.defaultPrevented||j(y)}return b.createElement("a",Wo({},p,{href:f||v,onClick:g||i?r:x,ref:n,target:c}))}),dd=b.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=j0(t,pw),p=Nc(c,{relative:h.relative}),m=In(),f=b.useContext(f0),{navigator:g,basename:v}=b.useContext(Fn),j=f!=null&&Sw(p)&&d===!0,x=g.encodeLocation?g.encodeLocation(p).pathname:p.pathname,y=m.pathname,N=f&&f.navigation&&f.navigation.location?f.navigation.location.pathname:null;a||(y=y.toLowerCase(),N=N?N.toLowerCase():null,x=x.toLowerCase()),N&&v&&(N=Wa(N,v)||N);const D=x!=="/"&&x.endsWith("/")?x.length-1:x.length;let P=y===x||!l&&y.startsWith(x)&&y.charAt(D)==="/",F=N!=null&&(N===x||!l&&N.startsWith(x)&&N.charAt(x.length)==="/"),w={isActive:P,isPending:F,isTransitioning:j},C=P?r:void 0,E;typeof i=="function"?E=i(w):E=[i,P?"active":null,F?"pending":null,j?"transitioning":null].filter(Boolean).join(" ");let K=typeof o=="function"?o(w):o;return b.createElement(ke,Wo({},h,{"aria-current":C,className:E,ref:n,style:K,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 Fp;(function(e){e.UseFetcher="useFetcher",e.UseFetchers="useFetchers",e.UseScrollRestoration="useScrollRestoration"})(Fp||(Fp={}));function Nw(e){let t=b.useContext(vc);return t||rt(!1),t}function ww(e,t){let{target:n,replace:r,state:a,preventScrollReset:i,relative:l,viewTransition:o}=t===void 0?{}:t,c=Yt(),d=In(),u=Nc(e,{relative:l});return b.useCallback(h=>{if(mw(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=b.useRef(xu(e)),n=b.useRef(!1),r=In(),a=b.useMemo(()=>hw(r.search,n.current?null:t.current),[r.search]),i=Yt(),l=b.useCallback((o,c)=>{const d=xu(typeof o=="function"?o(a):o);n.current=!0,i("?"+d,c)},[i,a]);return[a,l]}function Sw(e,t){t===void 0&&(t={});let n=b.useContext(gw);n==null&&rt(!1);let{basename:r}=Nw(gu.useViewTransitionState),a=Nc(e,{relative:t.relative});if(!n.isTransitioning)return!1;let i=Wa(n.currentLocation.pathname,r)||n.currentLocation.pathname,l=Wa(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(){}},kw={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},qn,Zu,Kx,Cw=(Kx=class{constructor(){ce(this,qn,kw);ce(this,Zu,!1)}setTimeoutProvider(e){te(this,qn,e)}setTimeout(e,t){return T(this,qn).setTimeout(e,t)}clearTimeout(e){T(this,qn).clearTimeout(e)}setInterval(e,t){return T(this,qn).setInterval(e,t)}clearInterval(e){T(this,qn).clearInterval(e)}},qn=new WeakMap,Zu=new WeakMap,Kx),Er=new Cw;function Ew(e){setTimeout(e,0)}var Wr=typeof window>"u"||"Deno"in globalThis;function $t(){}function Dw(e,t){return typeof e=="function"?e(t):e}function yu(e){return typeof e=="number"&&e>=0&&e!==1/0}function b0(e,t){return Math.max(e+(t||0)-Date.now(),0)}function mr(e,t){return typeof e=="function"?e(t):e}function ks(e,t){return typeof e=="function"?e(t):e}function Ip(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 Rp(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 Aw=Object.prototype.hasOwnProperty;function Gm(e,t,n=0){if(e===t)return e;if(n>500)return t;const r=Lp(e)&&Lp(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 Mw(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function Tw(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var Zm=Symbol();function N0(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 Fw(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 Pr,Vn,Ca,Ux,Iw=(Ux=class extends ea{constructor(){super();ce(this,Pr);ce(this,Vn);ce(this,Ca);te(this,Ca,t=>{if(!Wr&&window.addEventListener){const n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){T(this,Vn)||this.setEventListener(T(this,Ca))}onUnsubscribe(){var t;this.hasListeners()||((t=T(this,Vn))==null||t.call(this),te(this,Vn,void 0))}setEventListener(t){var n;te(this,Ca,t),(n=T(this,Vn))==null||n.call(this),te(this,Vn,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){T(this,Pr)!==t&&(te(this,Pr,t),this.onFocus())}onFocus(){const t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){var t;return typeof T(this,Pr)=="boolean"?T(this,Pr):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},Pr=new WeakMap,Vn=new WeakMap,Ca=new WeakMap,Ux),Xm=new Iw;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 Rw=Ew;function Lw(){let e=[],t=0,n=o=>{o()},r=o=>{o()},a=Rw;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 ut=Lw(),Ea,Qn,Da,Bx,Ow=(Bx=class extends ea{constructor(){super();ce(this,Ea,!0);ce(this,Qn);ce(this,Da);te(this,Da,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,Qn)||this.setEventListener(T(this,Da))}onUnsubscribe(){var t;this.hasListeners()||((t=T(this,Qn))==null||t.call(this),te(this,Qn,void 0))}setEventListener(t){var n;te(this,Da,t),(n=T(this,Qn))==null||n.call(this),te(this,Qn,t(this.setOnline.bind(this)))}setOnline(t){T(this,Ea)!==t&&(te(this,Ea,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return T(this,Ea)}},Ea=new WeakMap,Qn=new WeakMap,Da=new WeakMap,Bx),Go=new Ow;function zw(e){return Math.min(1e3*2**e,3e4)}function w0(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 S0(e){let t=!1,n=0,r;const a=bu(),i=()=>a.status!=="pending",l=g=>{var v;if(!i()){const j=new Nu(g);p(j),(v=e.onCancel)==null||v.call(e,j)}},o=()=>{t=!0},c=()=>{t=!1},d=()=>Xm.isFocused()&&(e.networkMode==="always"||Go.isOnline())&&e.canRun(),u=()=>w0(e.networkMode)&&e.canRun(),h=g=>{i()||(r==null||r(),a.resolve(g))},p=g=>{i()||(r==null||r(),a.reject(g))},m=()=>new Promise(g=>{var v;r=j=>{(i()||d())&&g(j)},(v=e.onPause)==null||v.call(e)}).then(()=>{var g;r=void 0,i()||(g=e.onContinue)==null||g.call(e)}),f=()=>{if(i())return;let g;const v=n===0?e.initialPromise:void 0;try{g=v??e.fn()}catch(j){g=Promise.reject(j)}Promise.resolve(g).then(h).catch(j=>{var P;if(i())return;const x=e.retry??(Wr?0:3),y=e.retryDelay??zw,N=typeof y=="function"?y(n,j):y,D=x===!0||typeof x=="number"&&nd()?void 0:m()).then(()=>{t?p(j):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,k0=(qx=class{constructor(){ce(this,Mr)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),yu(this.gcTime)&&te(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)),te(this,Mr,void 0))}},Mr=new WeakMap,qx),Tr,Aa,ws,Fr,Nt,dl,Ir,Ls,hn,Vx,$w=(Vx=class extends k0{constructor(t){super();ce(this,Ls);ce(this,Tr);ce(this,Aa);ce(this,ws);ce(this,Fr);ce(this,Nt);ce(this,dl);ce(this,Ir);te(this,Ir,!1),te(this,dl,t.defaultOptions),this.setOptions(t.options),this.observers=[],te(this,Fr,t.client),te(this,ws,T(this,Fr).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,te(this,Tr,$p(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,Nt))==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=$p(this.options);n.data!==void 0&&(this.setState(zp(n.data,n.dataUpdatedAt)),te(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 ye(this,Ls,hn).call(this,{data:r,type:"success",dataUpdatedAt:n==null?void 0:n.updatedAt,manual:n==null?void 0:n.manual}),r}setState(t,n){ye(this,Ls,hn).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){var r,a;const n=(r=T(this,Nt))==null?void 0:r.promise;return(a=T(this,Nt))==null||a.cancel(t),n?n.then($t).catch($t):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=>mr(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:!b0(this.state.dataUpdatedAt,t)}onFocus(){var n;const t=this.observers.find(r=>r.shouldFetchOnWindowFocus());t==null||t.refetch({cancelRefetch:!1}),(n=T(this,Nt))==null||n.continue()}onOnline(){var n;const t=this.observers.find(r=>r.shouldFetchOnReconnect());t==null||t.refetch({cancelRefetch:!1}),(n=T(this,Nt))==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,Nt)&&(T(this,Ir)?T(this,Nt).cancel({revert:!0}):T(this,Nt).cancelRetry()),this.scheduleGc()),T(this,ws).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||ye(this,Ls,hn).call(this,{type:"invalidate"})}async fetch(t,n){var c,d,u,h,p,m,f,g,v,j,x,y;if(this.state.fetchStatus!=="idle"&&((c=T(this,Nt))==null?void 0:c.status())!=="rejected"){if(this.state.data!==void 0&&(n!=null&&n.cancelRefetch))this.cancel({silent:!0});else if(T(this,Nt))return T(this,Nt).continueRetry(),T(this,Nt).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:()=>(te(this,Ir,!0),r.signal)})},i=()=>{const N=N0(this.options,n),P=(()=>{const F={client:T(this,Fr),queryKey:this.queryKey,meta:this.meta};return a(F),F})();return te(this,Ir,!1),this.options.persister?this.options.persister(N,P,this):N(P)},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),te(this,Aa,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((u=o.fetchOptions)==null?void 0:u.meta))&&ye(this,Ls,hn).call(this,{type:"fetch",meta:(h=o.fetchOptions)==null?void 0:h.meta}),te(this,Nt,S0({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)=>{ye(this,Ls,hn).call(this,{type:"failed",failureCount:N,error:D})},onPause:()=>{ye(this,Ls,hn).call(this,{type:"pause"})},onContinue:()=>{ye(this,Ls,hn).call(this,{type:"continue"})},retry:o.options.retry,retryDelay:o.options.retryDelay,networkMode:o.options.networkMode,canRun:()=>!0}));try{const N=await T(this,Nt).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),(g=(f=T(this,ws).config).onSettled)==null||g.call(f,N,this.state.error,this),N}catch(N){if(N instanceof Nu){if(N.silent)return T(this,Nt).promise;if(N.revert){if(this.state.data===void 0)throw N;return this.state.data}}throw ye(this,Ls,hn).call(this,{type:"error",error:N}),(j=(v=T(this,ws).config).onError)==null||j.call(v,N,this),(y=(x=T(this,ws).config).onSettled)==null||y.call(x,this.state.data,N,this),N}finally{this.scheduleGc()}}},Tr=new WeakMap,Aa=new WeakMap,ws=new WeakMap,Fr=new WeakMap,Nt=new WeakMap,dl=new WeakMap,Ir=new WeakMap,Ls=new WeakSet,hn=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,...C0(r.data,this.options),fetchMeta:t.meta??null};case"success":const a={...r,...zp(t.data,t.dataUpdatedAt),dataUpdateCount:r.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return te(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),ut.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),T(this,ws).notify({query:this,type:"updated",action:t})})},Vx);function C0(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:w0(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function zp(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function $p(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 ss,De,ul,Vt,Rr,Pa,gn,Hn,ml,Ma,Ta,Lr,Or,Wn,Fa,ze,Ni,wu,Su,ku,Cu,Eu,Du,Au,E0,Qx,Ym=(Qx=class extends ea{constructor(t,n){super();ce(this,ze);ce(this,ss);ce(this,De);ce(this,ul);ce(this,Vt);ce(this,Rr);ce(this,Pa);ce(this,gn);ce(this,Hn);ce(this,ml);ce(this,Ma);ce(this,Ta);ce(this,Lr);ce(this,Or);ce(this,Wn);ce(this,Fa,new Set);this.options=n,te(this,ss,t),te(this,Hn,null),te(this,gn,bu()),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(T(this,De).addObserver(this),_p(T(this,De),this.options)?ye(this,ze,Ni).call(this):this.updateResult(),ye(this,ze,Cu).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Pu(T(this,De),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Pu(T(this,De),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,ye(this,ze,Eu).call(this),ye(this,ze,Du).call(this),T(this,De).removeObserver(this)}setOptions(t){const n=this.options,r=T(this,De);if(this.options=T(this,ss).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");ye(this,ze,Au).call(this),T(this,De).setOptions(this.options),n._defaulted&&!nl(this.options,n)&&T(this,ss).getQueryCache().notify({type:"observerOptionsUpdated",query:T(this,De),observer:this});const a=this.hasListeners();a&&Kp(T(this,De),r,this.options,n)&&ye(this,ze,Ni).call(this),this.updateResult(),a&&(T(this,De)!==r||ks(this.options.enabled,T(this,De))!==ks(n.enabled,T(this,De))||mr(this.options.staleTime,T(this,De))!==mr(n.staleTime,T(this,De)))&&ye(this,ze,wu).call(this);const i=ye(this,ze,Su).call(this);a&&(T(this,De)!==r||ks(this.options.enabled,T(this,De))!==ks(n.enabled,T(this,De))||i!==T(this,Wn))&&ye(this,ze,ku).call(this,i)}getOptimisticResult(t){const n=T(this,ss).getQueryCache().build(T(this,ss),t),r=this.createResult(n,t);return Kw(this,r)&&(te(this,Vt,r),te(this,Pa,this.options),te(this,Rr,T(this,De).state)),r}getCurrentResult(){return T(this,Vt)}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,gn).status==="pending"&&T(this,gn).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(r,a))})}trackProp(t){T(this,Fa).add(t)}getCurrentQuery(){return T(this,De)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const n=T(this,ss).defaultQueryOptions(t),r=T(this,ss).getQueryCache().build(T(this,ss),n);return r.fetch().then(()=>this.createResult(r,n))}fetch(t){return ye(this,ze,Ni).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),T(this,Vt)))}createResult(t,n){var C;const r=T(this,De),a=this.options,i=T(this,Vt),l=T(this,Rr),o=T(this,Pa),d=t!==r?t.state:T(this,ul),{state:u}=t;let h={...u},p=!1,m;if(n._optimisticResults){const E=this.hasListeners(),K=!E&&_p(t,n),O=E&&Kp(t,r,n,a);(K||O)&&(h={...h,...C0(u.data,t.options)}),n._optimisticResults==="isRestoring"&&(h.fetchStatus="idle")}let{error:f,errorUpdatedAt:g,status:v}=h;m=h.data;let j=!1;if(n.placeholderData!==void 0&&m===void 0&&v==="pending"){let E;i!=null&&i.isPlaceholderData&&n.placeholderData===(o==null?void 0:o.placeholderData)?(E=i.data,j=!0):E=typeof n.placeholderData=="function"?n.placeholderData((C=T(this,Ta))==null?void 0:C.state.data,T(this,Ta)):n.placeholderData,E!==void 0&&(v="success",m=ju(i==null?void 0:i.data,E,n),p=!0)}if(n.select&&m!==void 0&&!j)if(i&&m===(l==null?void 0:l.data)&&n.select===T(this,ml))m=T(this,Ma);else try{te(this,ml,n.select),m=n.select(m),m=ju(i==null?void 0:i.data,m,n),te(this,Ma,m),te(this,Hn,null)}catch(E){te(this,Hn,E)}T(this,Hn)&&(f=T(this,Hn),m=T(this,Ma),g=Date.now(),v="error");const x=h.fetchStatus==="fetching",y=v==="pending",N=v==="error",D=y&&x,P=m!==void 0,w={status:v,fetchStatus:h.fetchStatus,isPending:y,isSuccess:v==="success",isError:N,isInitialLoading:D,isLoading:D,data:m,dataUpdatedAt:h.dataUpdatedAt,error:f,errorUpdatedAt:g,failureCount:h.fetchFailureCount,failureReason:h.fetchFailureReason,errorUpdateCount:h.errorUpdateCount,isFetched:h.dataUpdateCount>0||h.errorUpdateCount>0,isFetchedAfterMount:h.dataUpdateCount>d.dataUpdateCount||h.errorUpdateCount>d.errorUpdateCount,isFetching:x,isRefetching:x&&!y,isLoadingError:N&&!P,isPaused:h.fetchStatus==="paused",isPlaceholderData:p,isRefetchError:N&&P,isStale:eh(t,n),refetch:this.refetch,promise:T(this,gn),isEnabled:ks(n.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){const E=w.data!==void 0,K=w.status==="error"&&!E,O=M=>{K?M.reject(w.error):E&&M.resolve(w.data)},B=()=>{const M=te(this,gn,w.promise=bu());O(M)},A=T(this,gn);switch(A.status){case"pending":t.queryHash===r.queryHash&&O(A);break;case"fulfilled":(K||w.data!==A.value)&&B();break;case"rejected":(!K||w.error!==A.reason)&&B();break}}return w}updateResult(){const t=T(this,Vt),n=this.createResult(T(this,De),this.options);if(te(this,Rr,T(this,De).state),te(this,Pa,this.options),T(this,Rr).data!==void 0&&te(this,Ta,T(this,De)),nl(n,t))return;te(this,Vt,n);const r=()=>{if(!t)return!0;const{notifyOnChangeProps:a}=this.options,i=typeof a=="function"?a():a;if(i==="all"||!i&&!T(this,Fa).size)return!0;const l=new Set(i??T(this,Fa));return this.options.throwOnError&&l.add("error"),Object.keys(T(this,Vt)).some(o=>{const c=o;return T(this,Vt)[c]!==t[c]&&l.has(c)})};ye(this,ze,E0).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&ye(this,ze,Cu).call(this)}},ss=new WeakMap,De=new WeakMap,ul=new WeakMap,Vt=new WeakMap,Rr=new WeakMap,Pa=new WeakMap,gn=new WeakMap,Hn=new WeakMap,ml=new WeakMap,Ma=new WeakMap,Ta=new WeakMap,Lr=new WeakMap,Or=new WeakMap,Wn=new WeakMap,Fa=new WeakMap,ze=new WeakSet,Ni=function(t){ye(this,ze,Au).call(this);let n=T(this,De).fetch(this.options,t);return t!=null&&t.throwOnError||(n=n.catch($t)),n},wu=function(){ye(this,ze,Eu).call(this);const t=mr(this.options.staleTime,T(this,De));if(Wr||T(this,Vt).isStale||!yu(t))return;const r=b0(T(this,Vt).dataUpdatedAt,t)+1;te(this,Lr,Er.setTimeout(()=>{T(this,Vt).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){ye(this,ze,Du).call(this),te(this,Wn,t),!(Wr||ks(this.options.enabled,T(this,De))===!1||!yu(T(this,Wn))||T(this,Wn)===0)&&te(this,Or,Er.setInterval(()=>{(this.options.refetchIntervalInBackground||Xm.isFocused())&&ye(this,ze,Ni).call(this)},T(this,Wn)))},Cu=function(){ye(this,ze,wu).call(this),ye(this,ze,ku).call(this,ye(this,ze,Su).call(this))},Eu=function(){T(this,Lr)&&(Er.clearTimeout(T(this,Lr)),te(this,Lr,void 0))},Du=function(){T(this,Or)&&(Er.clearInterval(T(this,Or)),te(this,Or,void 0))},Au=function(){const t=T(this,ss).getQueryCache().build(T(this,ss),this.options);if(t===T(this,De))return;const n=T(this,De);te(this,De,t),te(this,ul,t.state),this.hasListeners()&&(n==null||n.removeObserver(this),t.addObserver(this))},E0=function(t){ut.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(T(this,Vt))}),T(this,ss).getQueryCache().notify({query:T(this,De),type:"observerResultsUpdated"})})},Qx);function _w(e,t){return ks(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function _p(e,t){return _w(e,t)||e.state.data!==void 0&&Pu(e,t,t.refetchOnMount)}function Pu(e,t,n){if(ks(t.enabled,e)!==!1&&mr(t.staleTime,e)!=="static"){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&eh(e,t)}return!1}function Kp(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(mr(t.staleTime,e))}function Kw(e,t){return!nl(e.getCurrentResult(),t)}function Up(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 g=!1;const v=y=>{Fw(y,()=>t.signal,()=>g=!0)},j=N0(t.options,t.fetchOptions),x=async(y,N,D)=>{if(g)return Promise.reject();if(N==null&&y.pages.length)return Promise.resolve(y);const F=(()=>{const K={client:t.client,queryKey:t.queryKey,pageParam:N,direction:D?"backward":"forward",meta:t.options.meta};return v(K),K})(),w=await j(F),{maxPages:C}=t.options,E=D?Tw:Mw;return{pages:E(y.pages,w,C),pageParams:E(y.pageParams,N,C)}};if(a&&i.length){const y=a==="backward",N=y?Uw:Bp,D={pages:i,pageParams:l},P=N(r,D);o=await x(D,P,y)}else{const y=e??i.length;do{const N=c===0?l[0]??r.initialPageParam:Bp(r,o);if(c>0&&N==null)break;o=await x(o,N),c++}while(c{var g,v;return(v=(g=t.options).persister)==null?void 0:v.call(g,d,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n)}:t.fetchFn=d}}}function Bp(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 Uw(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,Js,Qt,zr,Xs,On,Hx,Bw=(Hx=class extends k0{constructor(t){super();ce(this,Xs);ce(this,hl);ce(this,Js);ce(this,Qt);ce(this,zr);te(this,hl,t.client),this.mutationId=t.mutationId,te(this,Qt,t.mutationCache),te(this,Js,[]),this.state=t.state||D0(),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,Js).includes(t)||(T(this,Js).push(t),this.clearGcTimeout(),T(this,Qt).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){te(this,Js,T(this,Js).filter(n=>n!==t)),this.scheduleGc(),T(this,Qt).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){T(this,Js).length||(this.state.status==="pending"?this.scheduleGc():T(this,Qt).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,g,v,j,x,y,N,D,P,F,w,C;const n=()=>{ye(this,Xs,On).call(this,{type:"continue"})},r={client:T(this,hl),meta:this.options.meta,mutationKey:this.options.mutationKey};te(this,zr,S0({fn:()=>this.options.mutationFn?this.options.mutationFn(t,r):Promise.reject(new Error("No mutationFn found")),onFail:(E,K)=>{ye(this,Xs,On).call(this,{type:"failed",failureCount:E,error:K})},onPause:()=>{ye(this,Xs,On).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>T(this,Qt).canRun(this)}));const a=this.state.status==="pending",i=!T(this,zr).canStart();try{if(a)n();else{ye(this,Xs,On).call(this,{type:"pending",variables:t,isPaused:i}),await((o=(l=T(this,Qt).config).onMutate)==null?void 0:o.call(l,t,this,r));const K=await((d=(c=this.options).onMutate)==null?void 0:d.call(c,t,r));K!==this.state.context&&ye(this,Xs,On).call(this,{type:"pending",context:K,variables:t,isPaused:i})}const E=await T(this,zr).start();return await((h=(u=T(this,Qt).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((g=(f=T(this,Qt).config).onSettled)==null?void 0:g.call(f,E,null,this.state.variables,this.state.context,this,r)),await((j=(v=this.options).onSettled)==null?void 0:j.call(v,E,null,t,this.state.context,r)),ye(this,Xs,On).call(this,{type:"success",data:E}),E}catch(E){try{await((y=(x=T(this,Qt).config).onError)==null?void 0:y.call(x,E,t,this.state.context,this,r))}catch(K){Promise.reject(K)}try{await((D=(N=this.options).onError)==null?void 0:D.call(N,E,t,this.state.context,r))}catch(K){Promise.reject(K)}try{await((F=(P=T(this,Qt).config).onSettled)==null?void 0:F.call(P,void 0,E,this.state.variables,this.state.context,this,r))}catch(K){Promise.reject(K)}try{await((C=(w=this.options).onSettled)==null?void 0:C.call(w,void 0,E,t,this.state.context,r))}catch(K){Promise.reject(K)}throw ye(this,Xs,On).call(this,{type:"error",error:E}),E}finally{T(this,Qt).runNext(this)}}},hl=new WeakMap,Js=new WeakMap,Qt=new WeakMap,zr=new WeakMap,Xs=new WeakSet,On=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),ut.batch(()=>{T(this,Js).forEach(r=>{r.onMutationUpdate(t)}),T(this,Qt).notify({mutation:this,type:"updated",action:t})})},Hx);function D0(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var yn,Os,fl,Wx,qw=(Wx=class extends ea{constructor(t={}){super();ce(this,yn);ce(this,Os);ce(this,fl);this.config=t,te(this,yn,new Set),te(this,Os,new Map),te(this,fl,0)}build(t,n,r){const a=new Bw({client:t,mutationCache:this,mutationId:++Ll(this,fl)._,options:t.defaultMutationOptions(n),state:r});return this.add(a),a}add(t){T(this,yn).add(t);const n=eo(t);if(typeof n=="string"){const r=T(this,Os).get(n);r?r.push(t):T(this,Os).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(T(this,yn).delete(t)){const n=eo(t);if(typeof n=="string"){const r=T(this,Os).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,Os).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){const n=eo(t);if(typeof n=="string"){const r=T(this,Os).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,Os).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(){ut.batch(()=>{T(this,yn).forEach(t=>{this.notify({type:"removed",mutation:t})}),T(this,yn).clear(),T(this,Os).clear()})}getAll(){return Array.from(T(this,yn))}find(t){const n={exact:!0,...t};return this.getAll().find(r=>Rp(n,r))}findAll(t={}){return this.getAll().filter(n=>Rp(t,n))}notify(t){ut.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){const t=this.getAll().filter(n=>n.state.isPaused);return ut.batch(()=>Promise.all(t.map(n=>n.continue().catch($t))))}},yn=new WeakMap,Os=new WeakMap,fl=new WeakMap,Wx);function eo(e){var t;return(t=e.options.scope)==null?void 0:t.id}var vn,Gn,ns,jn,kn,go,Mu,Gx,Vw=(Gx=class extends ea{constructor(n,r){super();ce(this,kn);ce(this,vn);ce(this,Gn);ce(this,ns);ce(this,jn);te(this,vn,n),this.setOptions(r),this.bindMethods(),ye(this,kn,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,vn).defaultMutationOptions(n),nl(this.options,r)||T(this,vn).getMutationCache().notify({type:"observerOptionsUpdated",mutation:T(this,ns),observer:this}),r!=null&&r.mutationKey&&this.options.mutationKey&&Gr(r.mutationKey)!==Gr(this.options.mutationKey)?this.reset():((a=T(this,ns))==null?void 0:a.state.status)==="pending"&&T(this,ns).setOptions(this.options)}onUnsubscribe(){var n;this.hasListeners()||(n=T(this,ns))==null||n.removeObserver(this)}onMutationUpdate(n){ye(this,kn,go).call(this),ye(this,kn,Mu).call(this,n)}getCurrentResult(){return T(this,Gn)}reset(){var n;(n=T(this,ns))==null||n.removeObserver(this),te(this,ns,void 0),ye(this,kn,go).call(this),ye(this,kn,Mu).call(this)}mutate(n,r){var a;return te(this,jn,r),(a=T(this,ns))==null||a.removeObserver(this),te(this,ns,T(this,vn).getMutationCache().build(T(this,vn),this.options)),T(this,ns).addObserver(this),T(this,ns).execute(n)}},vn=new WeakMap,Gn=new WeakMap,ns=new WeakMap,jn=new WeakMap,kn=new WeakSet,go=function(){var r;const n=((r=T(this,ns))==null?void 0:r.state)??D0();te(this,Gn,{...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){ut.batch(()=>{var r,a,i,l,o,c,d,u;if(T(this,jn)&&this.hasListeners()){const h=T(this,Gn).variables,p=T(this,Gn).context,m={client:T(this,vn),meta:this.options.meta,mutationKey:this.options.mutationKey};if((n==null?void 0:n.type)==="success"){try{(a=(r=T(this,jn)).onSuccess)==null||a.call(r,n.data,h,p,m)}catch(f){Promise.reject(f)}try{(l=(i=T(this,jn)).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,jn)).onError)==null||c.call(o,n.error,h,p,m)}catch(f){Promise.reject(f)}try{(u=(d=T(this,jn)).onSettled)==null||u.call(d,void 0,n.error,h,p,m)}catch(f){Promise.reject(f)}}}this.listeners.forEach(h=>{h(T(this,Gn))})})},Gx);function qp(e,t){const n=new Set(t);return e.filter(r=>!n.has(r))}function Qw(e,t,n){const r=e.slice(0);return r[t]=n,r}var Ia,hs,Ra,La,Ss,Zn,pl,xl,gl,yl,It,Tu,Fu,Iu,Ru,Lu,Zx,Hw=(Zx=class extends ea{constructor(t,n,r){super();ce(this,It);ce(this,Ia);ce(this,hs);ce(this,Ra);ce(this,La);ce(this,Ss);ce(this,Zn);ce(this,pl);ce(this,xl);ce(this,gl);ce(this,yl,[]);te(this,Ia,t),te(this,La,r),te(this,Ra,[]),te(this,Ss,[]),te(this,hs,[]),this.setQueries(n)}onSubscribe(){this.listeners.size===1&&T(this,Ss).forEach(t=>{t.subscribe(n=>{ye(this,It,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){te(this,Ra,t),te(this,La,n),ut.batch(()=>{const r=T(this,Ss),a=ye(this,It,Iu).call(this,T(this,Ra));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,hs)[p];return!m||!nl(h,m)});!d&&!u||(d&&(te(this,yl,a),te(this,Ss,i)),te(this,hs,l),this.hasListeners()&&(d&&(qp(r,i).forEach(h=>{h.destroy()}),qp(i,r).forEach(h=>{h.subscribe(p=>{ye(this,It,Ru).call(this,h,p)})})),ye(this,It,Lu).call(this)))})}getCurrentResult(){return T(this,hs)}getQueries(){return T(this,Ss).map(t=>t.getCurrentQuery())}getObservers(){return T(this,Ss)}getOptimisticResult(t,n){const r=ye(this,It,Iu).call(this,t),a=r.map(l=>l.observer.getOptimisticResult(l.defaultedQueryOptions)),i=r.map(l=>l.defaultedQueryOptions.queryHash);return[a,l=>ye(this,It,Fu).call(this,l??a,n,i),()=>ye(this,It,Tu).call(this,a,r)]}},Ia=new WeakMap,hs=new WeakMap,Ra=new WeakMap,La=new WeakMap,Ss=new WeakMap,Zn=new WeakMap,pl=new WeakMap,xl=new WeakMap,gl=new WeakMap,yl=new WeakMap,It=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,Zn)||T(this,hs)!==T(this,xl)||i||n!==T(this,pl))&&(te(this,pl,n),te(this,xl,T(this,hs)),r!==void 0&&te(this,gl,r),te(this,Zn,Gm(T(this,Zn),n(t)))),T(this,Zn)}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,Ia).defaultQueryOptions(a),o=((c=n.get(i.queryHash))==null?void 0:c.shift())??new Ym(T(this,Ia),i);r.push({defaultedQueryOptions:i,observer:o})}),r},Ru=function(t,n){const r=T(this,Ss).indexOf(t);r!==-1&&(te(this,hs,Qw(T(this,hs),r,n)),ye(this,It,Lu).call(this))},Lu=function(){var t;if(this.hasListeners()){const n=T(this,Zn),r=ye(this,It,Tu).call(this,T(this,hs),T(this,yl)),a=ye(this,It,Fu).call(this,r,(t=T(this,La))==null?void 0:t.combine);n!==a&&ut.batch(()=>{this.listeners.forEach(i=>{i(T(this,hs))})})}},Zx),Ys,Jx,Ww=(Jx=class extends ea{constructor(t={}){super();ce(this,Ys);this.config=t,te(this,Ys,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 $w({client:t,queryKey:a,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(a)}),this.add(l)),l}add(t){T(this,Ys).has(t.queryHash)||(T(this,Ys).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const n=T(this,Ys).get(t.queryHash);n&&(t.destroy(),n===t&&T(this,Ys).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){ut.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return T(this,Ys).get(t)}getAll(){return[...T(this,Ys).values()]}find(t){const n={exact:!0,...t};return this.getAll().find(r=>Ip(n,r))}findAll(t={}){const n=this.getAll();return Object.keys(t).length>0?n.filter(r=>Ip(t,r)):n}notify(t){ut.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){ut.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){ut.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},Ys=new WeakMap,Jx),lt,Jn,Xn,Oa,za,Yn,$a,_a,Xx,Gw=(Xx=class{constructor(e={}){ce(this,lt);ce(this,Jn);ce(this,Xn);ce(this,Oa);ce(this,za);ce(this,Yn);ce(this,$a);ce(this,_a);te(this,lt,e.queryCache||new Ww),te(this,Jn,e.mutationCache||new qw),te(this,Xn,e.defaultOptions||{}),te(this,Oa,new Map),te(this,za,new Map),te(this,Yn,0)}mount(){Ll(this,Yn)._++,T(this,Yn)===1&&(te(this,$a,Xm.subscribe(async e=>{e&&(await this.resumePausedMutations(),T(this,lt).onFocus())})),te(this,_a,Go.subscribe(async e=>{e&&(await this.resumePausedMutations(),T(this,lt).onOnline())})))}unmount(){var e,t;Ll(this,Yn)._--,T(this,Yn)===0&&((e=T(this,$a))==null||e.call(this),te(this,$a,void 0),(t=T(this,_a))==null||t.call(this),te(this,_a,void 0))}isFetching(e){return T(this,lt).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return T(this,Jn).findAll({...e,status:"pending"}).length}getQueryData(e){var n;const t=this.defaultQueryOptions({queryKey:e});return(n=T(this,lt).get(t.queryHash))==null?void 0:n.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=T(this,lt).build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(mr(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return T(this,lt).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,lt).get(r.queryHash),i=a==null?void 0:a.state.data,l=Dw(t,i);if(l!==void 0)return T(this,lt).build(this,r).setData(l,{...n,manual:!0})}setQueriesData(e,t,n){return ut.batch(()=>T(this,lt).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,lt).get(t.queryHash))==null?void 0:n.state}removeQueries(e){const t=T(this,lt);ut.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=T(this,lt);return ut.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const n={revert:!0,...t},r=ut.batch(()=>T(this,lt).findAll(e).map(a=>a.cancel(n)));return Promise.all(r).then($t).catch($t)}invalidateQueries(e,t={}){return ut.batch(()=>(T(this,lt).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=ut.batch(()=>T(this,lt).findAll(e).filter(a=>!a.isDisabled()&&!a.isStatic()).map(a=>{let i=a.fetch(void 0,n);return n.throwOnError||(i=i.catch($t)),a.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then($t)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=T(this,lt).build(this,t);return n.isStaleByTime(mr(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then($t).catch($t)}fetchInfiniteQuery(e){return e.behavior=Up(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then($t).catch($t)}ensureInfiniteQueryData(e){return e.behavior=Up(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return Go.isOnline()?T(this,Jn).resumePausedMutations():Promise.resolve()}getQueryCache(){return T(this,lt)}getMutationCache(){return T(this,Jn)}getDefaultOptions(){return T(this,Xn)}setDefaultOptions(e){te(this,Xn,e)}setQueryDefaults(e,t){T(this,Oa).set(Gr(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...T(this,Oa).values()],n={};return t.forEach(r=>{sl(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){T(this,za).set(Gr(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...T(this,za).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,Xn).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,Xn).mutations,...(e==null?void 0:e.mutationKey)&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){T(this,lt).clear(),T(this,Jn).clear()}},lt=new WeakMap,Jn=new WeakMap,Xn=new WeakMap,Oa=new WeakMap,za=new WeakMap,Yn=new WeakMap,$a=new WeakMap,_a=new WeakMap,Xx),A0=b.createContext(void 0),pe=e=>{const t=b.useContext(A0);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},Zw=({client:e,children:t})=>(b.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),s.jsx(A0.Provider,{value:e,children:t})),P0=b.createContext(!1),M0=()=>b.useContext(P0);P0.Provider;function Jw(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Xw=b.createContext(Jw()),T0=()=>b.useContext(Xw),F0=(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))},I0=e=>{b.useEffect(()=>{e.clearReset()},[e])},R0=({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])),L0=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))}},O0=(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 Yw({queries:e,...t},n){const r=pe(),a=M0(),i=T0(),l=b.useMemo(()=>e.map(g=>{const v=r.defaultQueryOptions(g);return v._optimisticResults=a?"isRestoring":"optimistic",v}),[e,r,a]);l.forEach(g=>{L0(g);const v=r.getQueryCache().get(g.queryHash);F0(g,i,v)}),I0(i);const[o]=b.useState(()=>new Hw(r,l,t)),[c,d,u]=o.getOptimisticResult(l,t.combine),h=!a&&t.subscribed!==!1;b.useSyncExternalStore(b.useCallback(g=>h?o.subscribe(ut.batchCalls(g)):$t,[o,h]),()=>o.getCurrentResult(),()=>o.getCurrentResult()),b.useEffect(()=>{o.setQueries(l,t)},[l,t,o]);const m=c.some((g,v)=>Ou(l[v],g))?c.flatMap((g,v)=>{const j=l[v];if(j){const x=new Ym(r,j);if(Ou(j,g))return Zo(j,x,i);O0(g,a)&&Zo(j,x,i)}return[]}):[];if(m.length>0)throw Promise.all(m);const f=c.find((g,v)=>{const j=l[v];return j&&R0({result:g,errorResetBoundary:i,throwOnError:j.throwOnError,query:r.getQueryCache().get(j.queryHash),suspense:j.suspense})});if(f!=null&&f.error)throw f.error;return d(u())}function e1(e,t,n){var p,m,f,g;const r=M0(),a=T0(),i=pe(),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",L0(l),F0(l,a,o),I0(a);const c=!i.getQueryCache().get(l.queryHash),[d]=b.useState(()=>new t(i,l)),u=d.getOptimisticResult(l),h=!r&&e.subscribed!==!1;if(b.useSyncExternalStore(b.useCallback(v=>{const j=h?d.subscribe(ut.batchCalls(v)):$t;return d.updateResult(),j},[d,h]),()=>d.getCurrentResult(),()=>d.getCurrentResult()),b.useEffect(()=>{d.setOptions(l)},[l,d]),Ou(l,u))throw Zo(l,d,a);if(R0({result:u,errorResetBoundary:a,throwOnError:l.throwOnError,query:o,suspense:l.suspense}))throw u.error;if((g=(f=i.getDefaultOptions().queries)==null?void 0:f._experimental_afterQuery)==null||g.call(f,l,u),l.experimental_prefetchInRender&&!Wr&&O0(u,r)){const v=c?Zo(l,d,a):o==null?void 0:o.promise;v==null||v.catch($t).finally(()=>{d.updateResult()})}return l.notifyOnChangeProps?u:d.trackResult(u)}function ue(e,t){return e1(e,Ym)}function G(e,t){const n=pe(),[r]=b.useState(()=>new Vw(n,e));b.useEffect(()=>{r.setOptions(e)},[r,e]);const a=b.useSyncExternalStore(b.useCallback(l=>r.subscribe(ut.batchCalls(l)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),i=b.useCallback((l,o)=>{r.mutate(l,o).catch($t)},[r]);if(a.error&&Jm(r.options.throwOnError,[a.error]))throw a.error;return{...a,mutate:i,mutateAsync:a.mutate}}let t1={data:""},s1=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||t1},n1=/(?:([\u0080-\uFFFF\w-%@]+) *:? *([^{;]+?);|([^;}{]*?) *{)|(}\s*)/g,r1=/\/\*[^]*?\*\/| +/g,Vp=/\n+/g,Un=(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"?Un(l,i):i+"{"+Un(l,i[1]=="k"?"":t)+"}":typeof l=="object"?r+=Un(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+=Un.p?Un.p(i,l):i+":"+l+";")}return n+(t&&a?t+"{"+a+"}":a)+r},un={},z0=e=>{if(typeof e=="object"){let t="";for(let n in e)t+=n+z0(e[n]);return t}return e},a1=(e,t,n,r,a)=>{let i=z0(e),l=un[i]||(un[i]=(c=>{let d=0,u=11;for(;d>>0;return"go"+u})(i));if(!un[l]){let c=i!==e?e:(d=>{let u,h,p=[{}];for(;u=n1.exec(d.replace(r1,""));)u[4]?p.shift():u[3]?(h=u[3].replace(Vp," ").trim(),p.unshift(p[0][h]=p[0][h]||{})):p[0][u[1]]=u[2].replace(Vp," ").trim();return p[0]})(e);un[l]=Un(a?{["@keyframes "+l]:c}:c,n?"":"."+l)}let o=n&&un.g?un.g:null;return n&&(un.g=un[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)})(un[l],t,r,o),l},i1=(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?"":Un(o,""):o===!1?"":o}return r+a+(l??"")},"");function Sc(e){let t=this||{},n=e.call?e(t.p):e;return a1(n.unshift?n.raw?i1(n,[].slice.call(arguments,1),t.p):n.reduce((r,a)=>Object.assign(r,a&&a.call?a(t.p):a),{}):n,s1(t.target),t.g,t.o,t.k)}let $0,zu,$u;Sc.bind({g:1});let Pn=Sc.bind({k:1});function l1(e,t,n,r){Un.p=t,$0=e,zu=n,$u=r}function vr(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),$0(d,o)}return a}}var o1=e=>typeof e=="function",Jo=(e,t)=>o1(e)?e(t):e,c1=(()=>{let e=0;return()=>(++e).toString()})(),_0=(()=>{let e;return()=>{if(e===void 0&&typeof window<"u"){let t=matchMedia("(prefers-reduced-motion: reduce)");e=!t||t.matches}return e}})(),d1=20,th="default",K0=(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 K0(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=[],U0={toasts:[],pausedAt:void 0,settings:{toastLimit:d1}},tn={},B0=(e,t=th)=>{tn[t]=K0(tn[t]||U0,e),yo.forEach(([n,r])=>{n===t&&r(tn[t])})},q0=e=>Object.keys(tn).forEach(t=>B0(e,t)),u1=e=>Object.keys(tn).find(t=>tn[t].toasts.some(n=>n.id===e)),kc=(e=th)=>t=>{B0(t,e)},m1={blank:4e3,error:4e3,success:2e3,loading:1/0,custom:4e3},h1=(e={},t=th)=>{let[n,r]=b.useState(tn[t]||U0),a=b.useRef(tn[t]);b.useEffect(()=>(a.current!==tn[t]&&r(tn[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)||m1[l.type],style:{...e.style,...(d=e[l.type])==null?void 0:d.style,...l.style}}});return{...n,toasts:i}},f1=(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)||c1()}),Sl=e=>(t,n)=>{let r=f1(t,e,n);return kc(r.toasterId||u1(r.id))({type:2,toast:r}),r.id},jt=(e,t)=>Sl("blank")(e,t);jt.error=Sl("error");jt.success=Sl("success");jt.loading=Sl("loading");jt.custom=Sl("custom");jt.dismiss=(e,t)=>{let n={type:3,toastId:e};t?kc(t)(n):q0(n)};jt.dismissAll=e=>jt.dismiss(void 0,e);jt.remove=(e,t)=>{let n={type:4,toastId:e};t?kc(t)(n):q0(n)};jt.removeAll=e=>jt.remove(void 0,e);jt.promise=(e,t,n)=>{let r=jt.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?jt.success(i,{id:r,...n,...n==null?void 0:n.success}):jt.dismiss(r),a}).catch(a=>{let i=t.error?Jo(t.error,a):void 0;i?jt.error(i,{id:r,...n,...n==null?void 0:n.error}):jt.dismiss(r)}),e};var p1=1e3,x1=(e,t="default")=>{let{toasts:n,pausedAt:r}=h1(e,t),a=b.useRef(new Map).current,i=b.useCallback((h,p=p1)=>{if(a.has(h))return;let m=setTimeout(()=>{a.delete(h),l({type:4,toastId:h})},p);a.set(h,m)},[]);b.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&&jt.dismiss(m.id);return}return setTimeout(()=>jt.dismiss(m.id,t),f)});return()=>{p.forEach(m=>m&&clearTimeout(m))}},[n,r,t]);let l=b.useCallback(kc(t),[t]),o=b.useCallback(()=>{l({type:5,time:Date.now()})},[l]),c=b.useCallback((h,p)=>{l({type:1,toast:{id:h,height:p}})},[l]),d=b.useCallback(()=>{r&&l({type:6,time:Date.now()})},[r,l]),u=b.useCallback((h,p)=>{let{reverseOrder:m=!1,gutter:f=8,defaultPosition:g}=p||{},v=n.filter(y=>(y.position||g)===(h.position||g)&&y.height),j=v.findIndex(y=>y.id===h.id),x=v.filter((y,N)=>Ny.visible).slice(...m?[x+1]:[0,x]).reduce((y,N)=>y+(N.height||0)+f,0)},[n]);return b.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}}},g1=Pn` from { transform: scale(0) rotate(45deg); opacity: 0; } to { transform: scale(1) rotate(45deg); opacity: 1; }`,y1=Pn` from { transform: scale(0); opacity: 0; } to { transform: scale(1); opacity: 1; }`,v1=Pn` from { transform: scale(0) rotate(90deg); opacity: 0; } to { transform: scale(1) rotate(90deg); opacity: 1; }`,j1=vr("div")` width: 20px; opacity: 0; height: 20px; border-radius: 10px; background: ${e=>e.primary||"#ff4b4b"}; position: relative; transform: rotate(45deg); animation: ${g1} 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275) forwards; animation-delay: 100ms; &:after, &:before { content: ''; animation: ${y1} 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: ${v1} 0.15s ease-out forwards; animation-delay: 180ms; transform: rotate(90deg); } `,b1=Pn` from { transform: rotate(0deg); } to { transform: rotate(360deg); } `,N1=vr("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: ${b1} 1s linear infinite; `,w1=Pn` from { transform: scale(0) rotate(45deg); opacity: 0; } to { transform: scale(1) rotate(45deg); opacity: 1; }`,S1=Pn` 0% { height: 0; width: 0; opacity: 0; } 40% { height: 0; width: 6px; opacity: 1; } 100% { opacity: 1; height: 10px; }`,k1=vr("div")` width: 20px; opacity: 0; height: 20px; border-radius: 10px; background: ${e=>e.primary||"#61d345"}; position: relative; transform: rotate(45deg); animation: ${w1} 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275) forwards; animation-delay: 100ms; &:after { content: ''; box-sizing: border-box; animation: ${S1} 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; } `,C1=vr("div")` position: absolute; `,E1=vr("div")` position: relative; display: flex; justify-content: center; align-items: center; min-width: 20px; min-height: 20px; `,D1=Pn` from { transform: scale(0.6); opacity: 0.4; } to { transform: scale(1); opacity: 1; }`,A1=vr("div")` position: relative; transform: scale(0.6); opacity: 0.4; min-width: 20px; animation: ${D1} 0.3s 0.12s cubic-bezier(0.175, 0.885, 0.32, 1.275) forwards; `,P1=({toast:e})=>{let{icon:t,type:n,iconTheme:r}=e;return t!==void 0?typeof t=="string"?b.createElement(A1,null,t):t:n==="blank"?null:b.createElement(E1,null,b.createElement(N1,{...r}),n!=="loading"&&b.createElement(C1,null,n==="error"?b.createElement(j1,{...r}):b.createElement(k1,{...r})))},M1=e=>` 0% {transform: translate3d(0,${e*-200}%,0) scale(.6); opacity:.5;} 100% {transform: translate3d(0,0,0) scale(1); opacity:1;} `,T1=e=>` 0% {transform: translate3d(0,0,-1px) scale(1); opacity:1;} 100% {transform: translate3d(0,${e*-150}%,-1px) scale(.6); opacity:0;} `,F1="0%{opacity:0;} 100%{opacity:1;}",I1="0%{opacity:1;} 100%{opacity:0;}",R1=vr("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; `,L1=vr("div")` display: flex; justify-content: center; margin: 4px 10px; color: inherit; flex: 1 1 auto; white-space: pre-line; `,O1=(e,t)=>{let n=e.includes("top")?1:-1,[r,a]=_0()?[F1,I1]:[M1(n),T1(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)`}},z1=b.memo(({toast:e,position:t,style:n,children:r})=>{let a=e.height?O1(e.position||t||"top-center",e.visible):{opacity:0},i=b.createElement(P1,{toast:e}),l=b.createElement(L1,{...e.ariaProps},Jo(e.message,e));return b.createElement(R1,{className:e.className,style:{...a,...n,...e.style}},typeof r=="function"?r({icon:i,message:l}):b.createElement(b.Fragment,null,i,l))});l1(b.createElement);var $1=({id:e,className:t,style:n,onHeightUpdate:r,children:a})=>{let i=b.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 b.createElement("div",{ref:i,className:t,style:n},a)},_1=(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:_0()?void 0:"all 230ms cubic-bezier(.21,1.02,.73,1)",transform:`translateY(${t*(n?1:-1)}px)`,...r,...a}},K1=Sc` z-index: 9999; > * { pointer-events: auto; } `,to=16,U1=({reverseOrder:e,position:t="top-center",toastOptions:n,gutter:r,children:a,toasterId:i,containerStyle:l,containerClassName:o})=>{let{toasts:c,handlers:d}=x1(n,i);return b.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=_1(h,p);return b.createElement($1,{id:u.id,key:u.id,onHeightUpdate:d.updateHeight,className:u.visible?K1:"",style:m},u.type==="custom"?Jo(u.message,u):a?a(u):b.createElement(z1,{toast:u,position:h}))}))},Ie=jt;function V0(e,t){return function(){return e.apply(t,arguments)}}const{toString:B1}=Object.prototype,{getPrototypeOf:sh}=Object,{iterator:Cc,toStringTag:Q0}=Symbol,Ec=(e=>t=>{const n=B1.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),Qs=e=>(e=e.toLowerCase(),t=>Ec(t)===e),Dc=e=>t=>typeof t===e,{isArray:si}=Array,Ga=Dc("undefined");function kl(e){return e!==null&&!Ga(e)&&e.constructor!==null&&!Ga(e.constructor)&&ds(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const H0=Qs("ArrayBuffer");function q1(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&H0(e.buffer),t}const V1=Dc("string"),ds=Dc("function"),W0=Dc("number"),Cl=e=>e!==null&&typeof e=="object",Q1=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)&&!(Q0 in e)&&!(Cc in e)},H1=e=>{if(!Cl(e)||kl(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},W1=Qs("Date"),G1=Qs("File"),Z1=Qs("Blob"),J1=Qs("FileList"),X1=e=>Cl(e)&&ds(e.pipe),Y1=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||ds(e.append)&&((t=Ec(e))==="formdata"||t==="object"&&ds(e.toString)&&e.toString()==="[object FormData]"))},eS=Qs("URLSearchParams"),[tS,sS,nS,rS]=["ReadableStream","Request","Response","Headers"].map(Qs),aS=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]),si(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,Z0=e=>!Ga(e)&&e!==Dr;function _u(){const{caseless:e,skipUndefined:t}=Z0(this)&&this||{},n={},r=(a,i)=>{const l=e&&G0(n,i)||i;vo(n[l])&&vo(a)?n[l]=_u(n[l],a):vo(a)?n[l]=_u({},a):si(a)?n[l]=a.slice():(!t||!Ga(a))&&(n[l]=a)};for(let a=0,i=arguments.length;a(El(t,(a,i)=>{n&&ds(a)?e[i]=V0(a,n):e[i]=a},{allOwnKeys:r}),e),lS=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),oS=(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)},cS=(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},dS=(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},uS=e=>{if(!e)return null;if(si(e))return e;let t=e.length;if(!W0(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},mS=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&sh(Uint8Array)),hS=(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])}},fS=(e,t)=>{let n;const r=[];for(;(n=e.exec(t))!==null;)r.push(n);return r},pS=Qs("HTMLFormElement"),xS=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,a){return r.toUpperCase()+a}),Qp=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),gS=Qs("RegExp"),J0=(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)},yS=e=>{J0(e,(t,n)=>{if(ds(e)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const r=e[n];if(ds(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+"'")})}})},vS=(e,t)=>{const n={},r=a=>{a.forEach(i=>{n[i]=!0})};return si(e)?r(e):r(String(e).split(t)),n},jS=()=>{},bS=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function NS(e){return!!(e&&ds(e.append)&&e[Q0]==="FormData"&&e[Cc])}const wS=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=si(r)?[]:{};return El(r,(l,o)=>{const c=n(l,a+1);!Ga(c)&&(i[o]=c)}),t[a]=void 0,i}}return r};return n(e,0)},SS=Qs("AsyncFunction"),kS=e=>e&&(Cl(e)||ds(e))&&ds(e.then)&&ds(e.catch),X0=((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",ds(Dr.postMessage)),CS=typeof queueMicrotask<"u"?queueMicrotask.bind(Dr):typeof process<"u"&&process.nextTick||X0,ES=e=>e!=null&&ds(e[Cc]),V={isArray:si,isArrayBuffer:H0,isBuffer:kl,isFormData:Y1,isArrayBufferView:q1,isString:V1,isNumber:W0,isBoolean:Q1,isObject:Cl,isPlainObject:vo,isEmptyObject:H1,isReadableStream:tS,isRequest:sS,isResponse:nS,isHeaders:rS,isUndefined:Ga,isDate:W1,isFile:G1,isBlob:Z1,isRegExp:gS,isFunction:ds,isStream:X1,isURLSearchParams:eS,isTypedArray:mS,isFileList:J1,forEach:El,merge:_u,extend:iS,trim:aS,stripBOM:lS,inherits:oS,toFlatObject:cS,kindOf:Ec,kindOfTest:Qs,endsWith:dS,toArray:uS,forEachEntry:hS,matchAll:fS,isHTMLForm:pS,hasOwnProperty:Qp,hasOwnProp:Qp,reduceDescriptors:J0,freezeMethods:yS,toObjectSet:vS,toCamelCase:xS,noop:jS,toFiniteNumber:bS,findKey:G0,global:Dr,isContextDefined:Z0,isSpecCompliantForm:NS,toJSONObject:wS,isAsyncFn:SS,isThenable:kS,setImmediate:X0,asap:CS,isIterable:ES};function we(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)}V.inherits(we,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:V.toJSONObject(this.config),code:this.code,status:this.status}}});const Y0=we.prototype,ev={};["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=>{ev[e]={value:e}});Object.defineProperties(we,ev);Object.defineProperty(Y0,"isAxiosError",{value:!0});we.from=(e,t,n,r,a,i)=>{const l=Object.create(Y0);V.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 we.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 DS=null;function Ku(e){return V.isPlainObject(e)||V.isArray(e)}function tv(e){return V.endsWith(e,"[]")?e.slice(0,-2):e}function Hp(e,t,n){return e?e.concat(t).map(function(a,i){return a=tv(a),!n&&i?"["+a+"]":a}).join(n?".":""):t}function AS(e){return V.isArray(e)&&!e.some(Ku)}const PS=V.toFlatObject(V,{},null,function(t){return/^is[A-Z]/.test(t)});function Ac(e,t,n){if(!V.isObject(e))throw new TypeError("target must be an object");t=t||new FormData,n=V.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(g,v){return!V.isUndefined(v[g])});const r=n.metaTokens,a=n.visitor||u,i=n.dots,l=n.indexes,c=(n.Blob||typeof Blob<"u"&&Blob)&&V.isSpecCompliantForm(t);if(!V.isFunction(a))throw new TypeError("visitor must be a function");function d(f){if(f===null)return"";if(V.isDate(f))return f.toISOString();if(V.isBoolean(f))return f.toString();if(!c&&V.isBlob(f))throw new we("Blob is not supported. Use a Buffer instead.");return V.isArrayBuffer(f)||V.isTypedArray(f)?c&&typeof Blob=="function"?new Blob([f]):Buffer.from(f):f}function u(f,g,v){let j=f;if(f&&!v&&typeof f=="object"){if(V.endsWith(g,"{}"))g=r?g:g.slice(0,-2),f=JSON.stringify(f);else if(V.isArray(f)&&AS(f)||(V.isFileList(f)||V.endsWith(g,"[]"))&&(j=V.toArray(f)))return g=tv(g),j.forEach(function(y,N){!(V.isUndefined(y)||y===null)&&t.append(l===!0?Hp([g],N,i):l===null?g:g+"[]",d(y))}),!1}return Ku(f)?!0:(t.append(Hp(v,g,i),d(f)),!1)}const h=[],p=Object.assign(PS,{defaultVisitor:u,convertValue:d,isVisitable:Ku});function m(f,g){if(!V.isUndefined(f)){if(h.indexOf(f)!==-1)throw Error("Circular reference detected in "+g.join("."));h.push(f),V.forEach(f,function(j,x){(!(V.isUndefined(j)||j===null)&&a.call(t,j,V.isString(x)?x.trim():x,g,p))===!0&&m(j,g?g.concat(x):[x])}),h.pop()}}if(!V.isObject(e))throw new TypeError("data must be an object");return m(e),t}function Wp(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&&Ac(e,this,t)}const sv=nh.prototype;sv.append=function(t,n){this._pairs.push([t,n])};sv.toString=function(t){const n=t?function(r){return t.call(this,r,Wp)}:Wp;return this._pairs.map(function(a){return n(a[0])+"="+n(a[1])},"").join("&")};function MS(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function nv(e,t,n){if(!t)return e;const r=n&&n.encode||MS;V.isFunction(n)&&(n={serialize:n});const a=n&&n.serialize;let i;if(a?i=a(t,n):i=V.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 Gp{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){V.forEach(this.handlers,function(r){r!==null&&t(r)})}}const rv={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},TS=typeof URLSearchParams<"u"?URLSearchParams:nh,FS=typeof FormData<"u"?FormData:null,IS=typeof Blob<"u"?Blob:null,RS={isBrowser:!0,classes:{URLSearchParams:TS,FormData:FS,Blob:IS},protocols:["http","https","file","blob","url","data"]},rh=typeof window<"u"&&typeof document<"u",Uu=typeof navigator=="object"&&navigator||void 0,LS=rh&&(!Uu||["ReactNative","NativeScript","NS"].indexOf(Uu.product)<0),OS=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",zS=rh&&window.location.href||"http://localhost",$S=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:rh,hasStandardBrowserEnv:LS,hasStandardBrowserWebWorkerEnv:OS,navigator:Uu,origin:zS},Symbol.toStringTag,{value:"Module"})),Kt={...$S,...RS};function _S(e,t){return Ac(e,new Kt.classes.URLSearchParams,{visitor:function(n,r,a,i){return Kt.isNode&&V.isBuffer(n)?(this.append(r,n.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)},...t})}function KS(e){return V.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function US(e){const t={},n=Object.keys(e);let r;const a=n.length;let i;for(r=0;r=n.length;return l=!l&&V.isArray(a)?a.length:l,c?(V.hasOwnProp(a,l)?a[l]=[a[l],r]:a[l]=r,!o):((!a[l]||!V.isObject(a[l]))&&(a[l]=[]),t(n,r,a[l],i)&&V.isArray(a[l])&&(a[l]=US(a[l])),!o)}if(V.isFormData(e)&&V.isFunction(e.entries)){const n={};return V.forEachEntry(e,(r,a)=>{t(KS(r),a,n,0)}),n}return null}function BS(e,t,n){if(V.isString(e))try{return(t||JSON.parse)(e),V.trim(e)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(e)}const Dl={transitional:rv,adapter:["xhr","http","fetch"],transformRequest:[function(t,n){const r=n.getContentType()||"",a=r.indexOf("application/json")>-1,i=V.isObject(t);if(i&&V.isHTMLForm(t)&&(t=new FormData(t)),V.isFormData(t))return a?JSON.stringify(av(t)):t;if(V.isArrayBuffer(t)||V.isBuffer(t)||V.isStream(t)||V.isFile(t)||V.isBlob(t)||V.isReadableStream(t))return t;if(V.isArrayBufferView(t))return t.buffer;if(V.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 _S(t,this.formSerializer).toString();if((o=V.isFileList(t))||r.indexOf("multipart/form-data")>-1){const c=this.env&&this.env.FormData;return Ac(o?{"files[]":t}:t,c&&new c,this.formSerializer)}}return i||a?(n.setContentType("application/json",!1),BS(t)):t}],transformResponse:[function(t){const n=this.transitional||Dl.transitional,r=n&&n.forcedJSONParsing,a=this.responseType==="json";if(V.isResponse(t)||V.isReadableStream(t))return t;if(t&&V.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"?we.from(o,we.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:Kt.classes.FormData,Blob:Kt.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};V.forEach(["delete","get","head","post","put","patch"],e=>{Dl.headers[e]={}});const qS=V.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"]),VS=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},Zp=Symbol("internals");function xi(e){return e&&String(e).trim().toLowerCase()}function jo(e){return e===!1||e==null?e:V.isArray(e)?e.map(jo):String(e)}function QS(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 HS=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function ud(e,t,n,r,a){if(V.isFunction(r))return r.call(this,t,n);if(a&&(t=n),!!V.isString(t)){if(V.isString(r))return t.indexOf(r)!==-1;if(V.isRegExp(r))return r.test(t)}}function WS(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,n,r)=>n.toUpperCase()+r)}function GS(e,t){const n=V.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 us=class{constructor(t){t&&this.set(t)}set(t,n,r){const a=this;function i(o,c,d){const u=xi(c);if(!u)throw new Error("header name must be a non-empty string");const h=V.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)=>V.forEach(o,(d,u)=>i(d,u,c));if(V.isPlainObject(t)||t instanceof this.constructor)l(t,n);else if(V.isString(t)&&(t=t.trim())&&!HS(t))l(VS(t),n);else if(V.isObject(t)&&V.isIterable(t)){let o={},c,d;for(const u of t){if(!V.isArray(u))throw TypeError("Object iterator must return a key-value pair");o[d=u[0]]=(c=o[d])?V.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=xi(t),t){const r=V.findKey(this,t);if(r){const a=this[r];if(!n)return a;if(n===!0)return QS(a);if(V.isFunction(n))return n.call(this,a,r);if(V.isRegExp(n))return n.exec(a);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,n){if(t=xi(t),t){const r=V.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=xi(l),l){const o=V.findKey(r,l);o&&(!n||ud(r,r[o],o,n))&&(delete r[o],a=!0)}}return V.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 V.forEach(this,(a,i)=>{const l=V.findKey(r,i);if(l){n[l]=jo(a),delete n[i];return}const o=t?WS(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 V.forEach(this,(r,a)=>{r!=null&&r!==!1&&(n[a]=t&&V.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[Zp]=this[Zp]={accessors:{}}).accessors,a=this.prototype;function i(l){const o=xi(l);r[o]||(GS(a,l),r[o]=!0)}return V.isArray(t)?t.forEach(i):i(t),this}};us.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);V.reduceDescriptors(us.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}});V.freezeMethods(us);function md(e,t){const n=this||Dl,r=t||n,a=us.from(r.headers);let i=r.data;return V.forEach(e,function(o){i=o.call(n,i,a.normalize(),t?t.status:void 0)}),a.normalize(),i}function iv(e){return!!(e&&e.__CANCEL__)}function ni(e,t,n){we.call(this,e??"canceled",we.ERR_CANCELED,t,n),this.name="CanceledError"}V.inherits(ni,we,{__CANCEL__:!0});function lv(e,t,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new we("Request failed with status code "+n.status,[we.ERR_BAD_REQUEST,we.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function ZS(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function JS(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=JS(50,250);return XS(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)},Jp=(e,t)=>{const n=e!=null;return[r=>t[0]({lengthComputable:n,total:e,loaded:r}),t[1]]},Xp=e=>(...t)=>V.asap(()=>e(...t)),YS=Kt.hasStandardBrowserEnv?((e,t)=>n=>(n=new URL(n,Kt.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new URL(Kt.origin),Kt.navigator&&/(msie|trident)/i.test(Kt.navigator.userAgent)):()=>!0,e2=Kt.hasStandardBrowserEnv?{write(e,t,n,r,a,i,l){if(typeof document>"u")return;const o=[`${e}=${encodeURIComponent(t)}`];V.isNumber(n)&&o.push(`expires=${new Date(n).toUTCString()}`),V.isString(r)&&o.push(`path=${r}`),V.isString(a)&&o.push(`domain=${a}`),i===!0&&o.push("secure"),V.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 t2(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function s2(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function ov(e,t,n){let r=!t2(t);return e&&(r||n==!1)?s2(e,t):t}const Yp=e=>e instanceof us?{...e}:e;function Zr(e,t){t=t||{};const n={};function r(d,u,h,p){return V.isPlainObject(d)&&V.isPlainObject(u)?V.merge.call({caseless:p},d,u):V.isPlainObject(u)?V.merge({},u):V.isArray(u)?u.slice():u}function a(d,u,h,p){if(V.isUndefined(u)){if(!V.isUndefined(d))return r(void 0,d,h,p)}else return r(d,u,h,p)}function i(d,u){if(!V.isUndefined(u))return r(void 0,u)}function l(d,u){if(V.isUndefined(u)){if(!V.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(Yp(d),Yp(u),h,!0)};return V.forEach(Object.keys({...e,...t}),function(u){const h=c[u]||a,p=h(e[u],t[u],u);V.isUndefined(p)&&h!==o||(n[u]=p)}),n}const cv=e=>{const t=Zr({},e);let{data:n,withXSRFToken:r,xsrfHeaderName:a,xsrfCookieName:i,headers:l,auth:o}=t;if(t.headers=l=us.from(l),t.url=nv(ov(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),o&&l.set("Authorization","Basic "+btoa((o.username||"")+":"+(o.password?unescape(encodeURIComponent(o.password)):""))),V.isFormData(n)){if(Kt.hasStandardBrowserEnv||Kt.hasStandardBrowserWebWorkerEnv)l.setContentType(void 0);else if(V.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(Kt.hasStandardBrowserEnv&&(r&&V.isFunction(r)&&(r=r(t)),r||r!==!1&&YS(t.url))){const c=a&&i&&e2.read(i);c&&l.set(a,c)}return t},n2=typeof XMLHttpRequest<"u",r2=n2&&function(e){return new Promise(function(n,r){const a=cv(e);let i=a.data;const l=us.from(a.headers).normalize();let{responseType:o,onUploadProgress:c,onDownloadProgress:d}=a,u,h,p,m,f;function g(){m&&m(),f&&f(),a.cancelToken&&a.cancelToken.unsubscribe(u),a.signal&&a.signal.removeEventListener("abort",u)}let v=new XMLHttpRequest;v.open(a.method.toUpperCase(),a.url,!0),v.timeout=a.timeout;function j(){if(!v)return;const y=us.from("getAllResponseHeaders"in v&&v.getAllResponseHeaders()),D={data:!o||o==="text"||o==="json"?v.responseText:v.response,status:v.status,statusText:v.statusText,headers:y,config:e,request:v};lv(function(F){n(F),g()},function(F){r(F),g()},D),v=null}"onloadend"in v?v.onloadend=j:v.onreadystatechange=function(){!v||v.readyState!==4||v.status===0&&!(v.responseURL&&v.responseURL.indexOf("file:")===0)||setTimeout(j)},v.onabort=function(){v&&(r(new we("Request aborted",we.ECONNABORTED,e,v)),v=null)},v.onerror=function(N){const D=N&&N.message?N.message:"Network Error",P=new we(D,we.ERR_NETWORK,e,v);P.event=N||null,r(P),v=null},v.ontimeout=function(){let N=a.timeout?"timeout of "+a.timeout+"ms exceeded":"timeout exceeded";const D=a.transitional||rv;a.timeoutErrorMessage&&(N=a.timeoutErrorMessage),r(new we(N,D.clarifyTimeoutError?we.ETIMEDOUT:we.ECONNABORTED,e,v)),v=null},i===void 0&&l.setContentType(null),"setRequestHeader"in v&&V.forEach(l.toJSON(),function(N,D){v.setRequestHeader(D,N)}),V.isUndefined(a.withCredentials)||(v.withCredentials=!!a.withCredentials),o&&o!=="json"&&(v.responseType=a.responseType),d&&([p,f]=Xo(d,!0),v.addEventListener("progress",p)),c&&v.upload&&([h,m]=Xo(c),v.upload.addEventListener("progress",h),v.upload.addEventListener("loadend",m)),(a.cancelToken||a.signal)&&(u=y=>{v&&(r(!y||y.type?new ni(null,e,v):y),v.abort(),v=null)},a.cancelToken&&a.cancelToken.subscribe(u),a.signal&&(a.signal.aborted?u():a.signal.addEventListener("abort",u)));const x=ZS(a.url);if(x&&Kt.protocols.indexOf(x)===-1){r(new we("Unsupported protocol "+x+":",we.ERR_BAD_REQUEST,e));return}v.send(i||null)})},a2=(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 we?u:new ni(u instanceof Error?u.message:u))}};let l=t&&setTimeout(()=>{l=null,i(new we(`timeout ${t} of ms exceeded`,we.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=()=>V.asap(o),c}},i2=function*(e,t){let n=e.byteLength;if(n{const a=l2(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})},tx=64*1024,{isFunction:so}=V,c2=(({Request:e,Response:t})=>({Request:e,Response:t}))(V.global),{ReadableStream:sx,TextEncoder:nx}=V.global,rx=(e,...t)=>{try{return!!e(...t)}catch{return!1}},d2=e=>{e=V.merge.call({skipUndefined:!0},c2,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(sx),c=a&&(typeof nx=="function"?(f=>g=>f.encode(g))(new nx):async f=>new Uint8Array(await new n(f).arrayBuffer())),d=i&&o&&rx(()=>{let f=!1;const g=new n(Kt.origin,{body:new sx,method:"POST",get duplex(){return f=!0,"half"}}).headers.has("Content-Type");return f&&!g}),u=l&&o&&rx(()=>V.isReadableStream(new r("").body)),h={stream:u&&(f=>f.body)};a&&["text","arrayBuffer","blob","formData","stream"].forEach(f=>{!h[f]&&(h[f]=(g,v)=>{let j=g&&g[f];if(j)return j.call(g);throw new we(`Response type '${f}' is not supported`,we.ERR_NOT_SUPPORT,v)})});const p=async f=>{if(f==null)return 0;if(V.isBlob(f))return f.size;if(V.isSpecCompliantForm(f))return(await new n(Kt.origin,{method:"POST",body:f}).arrayBuffer()).byteLength;if(V.isArrayBufferView(f)||V.isArrayBuffer(f))return f.byteLength;if(V.isURLSearchParams(f)&&(f=f+""),V.isString(f))return(await c(f)).byteLength},m=async(f,g)=>{const v=V.toFiniteNumber(f.getContentLength());return v??p(g)};return async f=>{let{url:g,method:v,data:j,signal:x,cancelToken:y,timeout:N,onDownloadProgress:D,onUploadProgress:P,responseType:F,headers:w,withCredentials:C="same-origin",fetchOptions:E}=cv(f),K=t||fetch;F=F?(F+"").toLowerCase():"text";let O=a2([x,y&&y.toAbortSignal()],N),B=null;const A=O&&O.unsubscribe&&(()=>{O.unsubscribe()});let M;try{if(P&&d&&v!=="get"&&v!=="head"&&(M=await m(w,j))!==0){let fe=new n(g,{method:"POST",body:j,duplex:"half"}),le;if(V.isFormData(j)&&(le=fe.headers.get("content-type"))&&w.setContentType(le),fe.body){const[k,Re]=Jp(M,Xo(Xp(P)));j=ex(fe.body,tx,k,Re)}}V.isString(C)||(C=C?"include":"omit");const S=i&&"credentials"in n.prototype,_={...E,signal:O,method:v.toUpperCase(),headers:w.normalize().toJSON(),body:j,duplex:"half",credentials:S?C:void 0};B=i&&new n(g,_);let U=await(i?K(B,E):K(g,_));const Z=u&&(F==="stream"||F==="response");if(u&&(D||Z&&A)){const fe={};["status","statusText","headers"].forEach(Ye=>{fe[Ye]=U[Ye]});const le=V.toFiniteNumber(U.headers.get("content-length")),[k,Re]=D&&Jp(le,Xo(Xp(D),!0))||[];U=new r(ex(U.body,tx,k,()=>{Re&&Re(),A&&A()}),fe)}F=F||"text";let W=await h[V.findKey(h,F)||"text"](U,f);return!Z&&A&&A(),await new Promise((fe,le)=>{lv(fe,le,{data:W,headers:us.from(U.headers),status:U.status,statusText:U.statusText,config:f,request:B})})}catch(S){throw A&&A(),S&&S.name==="TypeError"&&/Load failed|fetch/i.test(S.message)?Object.assign(new we("Network Error",we.ERR_NETWORK,f,B),{cause:S.cause||S}):we.from(S,S&&S.code,f,B)}}},u2=new Map,dv=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=u2;for(;o--;)c=i[o],d=u.get(c),d===void 0&&u.set(c,d=o?new Map:d2(t)),u=d;return d};dv();const ah={http:DS,xhr:r2,fetch:{get:dv}};V.forEach(ah,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const ax=e=>`- ${e}`,m2=e=>V.isFunction(e)||e===null||e===!1;function h2(e,t){e=V.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(ax).join(` `):" "+ax(l[0]):"as no adapter specified";throw new we("There is no suitable adapter to dispatch the request "+o,"ERR_NOT_SUPPORT")}return a}const uv={getAdapter:h2,adapters:ah};function hd(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new ni(null,e)}function ix(e){return hd(e),e.headers=us.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),uv.getAdapter(e.adapter||Dl.adapter,e)(e).then(function(r){return hd(e),r.data=md.call(e,e.transformResponse,r),r.headers=us.from(r.headers),r},function(r){return iv(r)||(hd(e),r&&r.response&&(r.response.data=md.call(e,e.transformResponse,r.response),r.response.headers=us.from(r.response.headers))),Promise.reject(r)})}const mv="1.13.2",Pc={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{Pc[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const lx={};Pc.transitional=function(t,n,r){function a(i,l){return"[Axios v"+mv+"] Transitional option '"+i+"'"+l+(r?". "+r:"")}return(i,l,o)=>{if(t===!1)throw new we(a(l," has been removed"+(n?" in "+n:"")),we.ERR_DEPRECATED);return n&&!lx[l]&&(lx[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}};Pc.spelling=function(t){return(n,r)=>(console.warn(`${r} is likely a misspelling of ${t}`),!0)};function f2(e,t,n){if(typeof e!="object")throw new we("options must be an object",we.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 we("option "+i+" must be "+c,we.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new we("Unknown option "+i,we.ERR_BAD_OPTION)}}const bo={assertOptions:f2,validators:Pc},Ws=bo.validators;let Kr=class{constructor(t){this.defaults=t||{},this.interceptors={request:new Gp,response:new Gp}}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:Ws.transitional(Ws.boolean),forcedJSONParsing:Ws.transitional(Ws.boolean),clarifyTimeoutError:Ws.transitional(Ws.boolean)},!1),a!=null&&(V.isFunction(a)?n.paramsSerializer={serialize:a}:bo.assertOptions(a,{encode:Ws.function,serialize:Ws.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),bo.assertOptions(n,{baseUrl:Ws.spelling("baseURL"),withXsrfToken:Ws.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let l=i&&V.merge(i.common,i[n.method]);i&&V.forEach(["delete","get","head","post","put","patch","common"],f=>{delete i[f]}),n.headers=us.concat(l,i);const o=[];let c=!0;this.interceptors.request.forEach(function(g){typeof g.runWhen=="function"&&g.runWhen(n)===!1||(c=c&&g.synchronous,o.unshift(g.fulfilled,g.rejected))});const d=[];this.interceptors.response.forEach(function(g){d.push(g.fulfilled,g.rejected)});let u,h=0,p;if(!c){const f=[ix.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 ni(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 hv(function(a){t=a}),cancel:t}}};function x2(e){return function(n){return e.apply(null,n)}}function g2(e){return V.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 fv(e){const t=new Kr(e),n=V0(Kr.prototype.request,t);return V.extend(n,Kr.prototype,t,{allOwnKeys:!0}),V.extend(n,t,null,{allOwnKeys:!0}),n.create=function(a){return fv(Zr(e,a))},n}const ht=fv(Dl);ht.Axios=Kr;ht.CanceledError=ni;ht.CancelToken=p2;ht.isCancel=iv;ht.VERSION=mv;ht.toFormData=Ac;ht.AxiosError=we;ht.Cancel=ht.CanceledError;ht.all=function(t){return Promise.all(t)};ht.spread=x2;ht.isAxiosError=g2;ht.mergeConfig=Zr;ht.AxiosHeaders=us;ht.formToJSON=e=>av(V.isHTMLForm(e)?new FormData(e):e);ht.getAdapter=uv.getAdapter;ht.HttpStatusCode=Bu;ht.default=ht;const{Axios:d4,AxiosError:u4,CanceledError:m4,isCancel:h4,CancelToken:f4,VERSION:p4,all:x4,Cancel:g4,isAxiosError:y4,spread:v4,toFormData:j4,AxiosHeaders:b4,HttpStatusCode:N4,formToJSON:w4,getAdapter:S4,mergeConfig:k4}=ht,$=ht.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},kt={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},an={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},wi={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},ps={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},Pe={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}},$e={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},dt={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},Za={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},pv={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},ot={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},xn={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},xv=b.createContext(null);function y2({children:e}){const[t,n]=b.useState(null),[r,a]=b.useState(!0),[i,l]=b.useState(()=>localStorage.getItem("developerMode")==="true"),o=g=>{l(g),localStorage.setItem("developerMode",String(g))};b.useEffect(()=>{var g;console.log("useEffect check - user:",t==null?void 0:t.email,"developerMode:",i,"has developer:access:",(g=t==null?void 0:t.permissions)==null?void 0:g.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]),b.useEffect(()=>{localStorage.getItem("token")?no.me().then(v=>{v.success&&v.data?n(v.data):localStorage.removeItem("token")}).catch(()=>{localStorage.removeItem("token")}).finally(()=>{a(!1)}):a(!1)},[]);const c=async(g,v)=>{const j=await no.login(g,v);if(j.success&&j.data)localStorage.setItem("token",j.data.token),n(j.data.user);else throw new Error(j.error||"Login fehlgeschlagen")},d=async(g,v)=>{const j=await no.customerLogin(g,v);if(j.success&&j.data)localStorage.setItem("token",j.data.token),n(j.data.user);else throw new Error(j.error||"Login fehlgeschlagen")},u=()=>{localStorage.removeItem("token"),n(null)},h=async()=>{var v;if(localStorage.getItem("token"))try{const j=await no.me();console.log("refreshUser response:",j),console.log("permissions:",(v=j.data)==null?void 0:v.permissions),j.success&&j.data&&n(j.data)}catch(j){console.error("refreshUser error:",j)}},p=g=>t?t.permissions.includes(g):!1,m=!!(t!=null&&t.customerId),f=!!(t!=null&&t.isCustomerPortal);return s.jsx(xv.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 Qe(){const e=b.useContext(xv);if(!e)throw new Error("useAuth must be used within an AuthProvider");return e}const fd={scrollToTopThreshold:.7},gv=b.createContext(void 0),ox="opencrm_app_settings";function v2({children:e}){const[t,n]=b.useState(()=>{const a=localStorage.getItem(ox);if(a)try{return{...fd,...JSON.parse(a)}}catch{return fd}return fd});b.useEffect(()=>{localStorage.setItem(ox,JSON.stringify(t))},[t]);const r=a=>{n(i=>({...i,...a}))};return s.jsx(gv.Provider,{value:{settings:t,updateSettings:r},children:e})}function yv(){const e=b.useContext(gv);if(!e)throw new Error("useAppSettings must be used within AppSettingsProvider");return e}function j2(){const{pathname:e}=In();return b.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 b2=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),vv=(...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 N2={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 w2=b.forwardRef(({color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:r,className:a="",children:i,iconNode:l,...o},c)=>b.createElement("svg",{ref:c,...N2,width:t,height:t,stroke:e,strokeWidth:r?Number(n)*24/Number(t):n,className:vv("lucide",a),...o},[...l.map(([d,u])=>b.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=b.forwardRef(({className:r,...a},i)=>b.createElement(w2,{ref:i,iconNode:t,className:vv(`lucide-${b2(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 S2=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 Vs=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 jv=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 k2=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 C2=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 E2=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 bv=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 Nv=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 pr=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 Rn=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 D2=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 Pt=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 wn=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 As=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 cx=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 Mn=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 Ps=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 Mt=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 Ae=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 A2=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 _e=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 P2=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 wv=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 M2=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 Sv=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 dx=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 T2=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 ux=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 kv=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 Al=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 F2=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 I2=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 mx=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 R2=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 Cv=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 sn=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 L2=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 O2=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 z2=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 $2=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 Ue=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 Ev=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 _2=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 K2=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 Dv=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 Pl=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 Av=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 uh=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 Xe=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 mh=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 U2=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 B2=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 je=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 ms=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 Pv=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 Mv=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 q2=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 V2=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 Sa=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 hx=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 ka=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 Zt=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 hh=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 Q2=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 H2=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 W2(){const{user:e,logout:t,hasPermission:n,isCustomer:r,developerMode:a}=Qe(),i=[{to:"/",icon:I2,label:"Dashboard",show:!0,end:!0},{to:"/customers",icon:Sa,label:"Kunden",show:n("customers:read")&&!r},{to:"/contracts",icon:_e,label:"Verträge",show:n("contracts:read"),end:!0},{to:"/contracts/cockpit",icon:wn,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(Av,{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(R2,{className:"w-5 h-5"}),"Abmelden"]})]})]})}function G2(){const{settings:e}=yv(),[t,n]=b.useState(!1);b.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 Z2(){return s.jsxs("div",{className:"flex min-h-screen",children:[s.jsx(W2,{}),s.jsx("main",{className:"flex-1 p-8 overflow-auto",children:s.jsx(ow,{})}),s.jsx(G2,{})]})}const I=b.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})});I.displayName="Button";const Q=b.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(je,{className:"w-4 h-4"})})]}),n&&s.jsx("p",{className:"mt-1 text-sm text-red-600",children:n})]})});Q.displayName="Input";function X({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 J2(){const[e,t]=b.useState(""),[n,r]=b.useState(""),[a,i]=b.useState(""),[l,o]=b.useState(!1),{login:c,customerLogin:d}=Qe(),u=Yt(),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(X,{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(Q,{label:"E-Mail",type:"email",value:e,onChange:p=>t(p.target.value),required:!0,autoComplete:"email"}),s.jsx(Q,{label:"Passwort",type:"password",value:n,onChange:p=>r(p.target.value),required:!0,autoComplete:"current-password"}),s.jsx(I,{type:"submit",className:"w-full",disabled:l,children:l?"Anmeldung...":"Anmelden"})]})]})})}function He({isOpen:e,onClose:t,title:n,children:r,size:a="md"}){if(b.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(I,{variant:"ghost",size:"sm",onClick:t,children:s.jsx(Zt,{className:"w-5 h-5"})})]}),s.jsx("div",{className:"p-6",children:r})]})]})})}function X2(){var w,C,E,K,O,B;const{user:e,isCustomer:t,isCustomerPortal:n}=Qe(),[r,a]=b.useState(!1),{data:i,isLoading:l}=ue({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}=ue({queryKey:["customers-count"],queryFn:()=>kt.getAll({limit:1}),enabled:!t}),{data:d}=ue({queryKey:["contracts",t?e==null?void 0:e.customerId:void 0],queryFn:()=>$e.getAll(t?{customerId:e==null?void 0:e.customerId}:{limit:1})}),{data:u}=ue({queryKey:["contracts-active",t?e==null?void 0:e.customerId:void 0],queryFn:()=>$e.getAll({status:"ACTIVE",...t?{customerId:e==null?void 0:e.customerId}:{limit:1}})}),{data:h}=ue({queryKey:["contracts-pending",t?e==null?void 0:e.customerId:void 0],queryFn:()=>$e.getAll({status:"PENDING",...t?{customerId:e==null?void 0:e.customerId}:{limit:1}})}),{data:p}=ue({queryKey:["task-stats"],queryFn:()=>dt.getStats()}),{data:m}=ue({queryKey:["contract-cockpit"],queryFn:()=>$e.getCockpit(),enabled:!t,staleTime:0}),{ownContracts:f,representedContracts:g}=b.useMemo(()=>{if(!n||!(d!=null&&d.data))return{ownContracts:[],representedContracts:[]};const A=[],M={};for(const S of d.data)if(S.customerId===(e==null?void 0:e.customerId))A.push(S);else{const _=S.customerId;if(!M[_]){const U=S.customer?S.customer.companyName||`${S.customer.firstName} ${S.customer.lastName}`:`Kunde ${_}`;M[_]={customerName:U,contracts:[]}}M[_].contracts.push(S)}return{ownContracts:A,representedContracts:Object.values(M).sort((S,_)=>S.customerName.localeCompare(_.customerName))}},[d==null?void 0:d.data,n,e==null?void 0:e.customerId]),v=b.useMemo(()=>f.filter(A=>A.status==="ACTIVE").length,[f]),j=b.useMemo(()=>f.filter(A=>A.status==="PENDING").length,[f]),x=b.useMemo(()=>f.filter(A=>A.status==="EXPIRED").length,[f]),y=b.useMemo(()=>g.reduce((A,M)=>A+M.contracts.length,0),[g]),N=b.useMemo(()=>g.reduce((A,M)=>A+M.contracts.filter(S=>S.status==="ACTIVE").length,0),[g]),D=b.useMemo(()=>g.reduce((A,M)=>A+M.contracts.filter(S=>S.status==="EXPIRED").length,0),[g]),P=((C=p==null?void 0:p.data)==null?void 0:C.openCount)||0,F=A=>s.jsx(X,{className:A.link?"cursor-pointer hover:shadow-md transition-shadow":"",children:A.link?s.jsx(ke,{to:A.link,className:"block",children:s.jsxs("div",{className:"flex items-center",children:[s.jsx("div",{className:`p-3 rounded-lg ${A.color}`,children:s.jsx(A.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:A.label}),s.jsx("p",{className:"text-2xl font-bold",children:A.value})]})]})}):s.jsxs("div",{className:"flex items-center",children:[s.jsx("div",{className:`p-3 rounded-lg ${A.color}`,children:s.jsx(A.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:A.label}),s.jsx("p",{className:"text-2xl font-bold",children:A.value})]})]})},A.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(I,{onClick:()=>a(!0),children:[s.jsx(Ue,{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:[F({label:"Eigene Verträge",value:f.length,icon:_e,color:"bg-blue-500",link:"/contracts"}),F({label:"Davon aktiv",value:v,icon:As,color:"bg-green-500"}),F({label:"Davon ausstehend",value:j,icon:Mn,color:"bg-yellow-500"}),F({label:"Davon abgelaufen",value:x,icon:cx,color:"bg-red-500"})]})]}),y>0&&s.jsxs("div",{className:"mb-6",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[s.jsx(Sa,{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:[F({label:"Fremdverträge",value:y,icon:Sa,color:"bg-purple-500",link:"/contracts"}),F({label:"Davon aktiv",value:N,icon:As,color:"bg-green-500"}),s.jsx("div",{className:"hidden lg:block"}),F({label:"Davon abgelaufen",value:D,icon:cx,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:F({label:"Offene Anfragen",value:P,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:[F({label:"Kunden",value:((E=c==null?void 0:c.pagination)==null?void 0:E.total)||0,icon:Sa,color:"bg-blue-500",link:"/customers"}),F({label:"Verträge gesamt",value:((K=d==null?void 0:d.pagination)==null?void 0:K.total)||0,icon:_e,color:"bg-purple-500",link:"/contracts"}),F({label:"Aktive Verträge",value:((O=u==null?void 0:u.pagination)==null?void 0:O.total)||0,icon:As,color:"bg-green-500"}),F({label:"Ausstehende Verträge",value:((B=h==null?void 0:h.pagination)==null?void 0:B.total)||0,icon:wn,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(wn,{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(X,{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(wn,{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(X,{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(ms,{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(X,{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(As,{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(X,{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(_e,{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:F({label:"Offene Aufgaben",value:P,icon:ol,color:"bg-orange-500",link:"/tasks"})})]})]}),n&&s.jsx(Y2,{isOpen:r,onClose:()=>a(!1)})]})}function Y2({isOpen:e,onClose:t}){const{user:n}=Qe(),r=Yt(),a=pe(),[i,l]=b.useState("own"),[o,c]=b.useState(null),[d,u]=b.useState(""),[h,p]=b.useState(""),[m,f]=b.useState(!1),[g,v]=b.useState(""),{data:j}=ue({queryKey:["contracts",n==null?void 0:n.customerId],queryFn:()=>$e.getAll({customerId:n==null?void 0:n.customerId}),enabled:e}),x=b.useMemo(()=>{if(!(j!=null&&j.data))return{own:[],represented:{}};const w=[],C={};for(const E of j.data)if(E.customerId===(n==null?void 0:n.customerId))w.push(E);else{if(!C[E.customerId]){const K=E.customer?E.customer.companyName||`${E.customer.firstName} ${E.customer.lastName}`:`Kunde ${E.customerId}`;C[E.customerId]={name:K,contracts:[]}}C[E.customerId].contracts.push(E)}return{own:w,represented:C}},[j==null?void 0:j.data,n==null?void 0:n.customerId]),y=Object.keys(x.represented).length>0,N=b.useMemo(()=>{var w;return i==="own"?x.own:((w=x.represented[i])==null?void 0:w.contracts)||[]},[i,x]),D=b.useMemo(()=>{if(!g)return N;const w=g.toLowerCase();return N.filter(C=>C.contractNumber.toLowerCase().includes(w)||(C.providerName||"").toLowerCase().includes(w)||(C.tariffName||"").toLowerCase().includes(w))},[N,g]),P=async()=>{if(!(!o||!d.trim())){f(!0);try{await dt.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)}}},F=()=>{u(""),p(""),c(null),l("own"),v(""),t()};return s.jsx(He,{isOpen:e,onClose:F,title:"Neue Support-Anfrage",children:s.jsxs("div",{className:"space-y-4",children:[y&&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 C=w.target.value;l(C==="own"?"own":parseInt(C)),c(null),v("")},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(x.represented).map(([w,{name:C}])=>s.jsx("option",{value:w,children:C},w))]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Vertrag *"}),s.jsx(Q,{placeholder:"Vertrag suchen...",value:g,onChange:w=>v(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(Q,{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(I,{variant:"secondary",onClick:F,children:"Abbrechen"}),s.jsx(I,{onClick:P,disabled:!o||!d.trim()||m,children:m?"Wird erstellt...":"Anfrage erstellen"})]})]})})}function ge({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 ek(){const[e,t]=b.useState(""),[n,r]=b.useState(""),[a,i]=b.useState(1),{hasPermission:l}=Qe(),{data:o,isLoading:c}=ue({queryKey:["customers",e,n,a],queryFn:()=>kt.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(I,{children:[s.jsx(Ue,{className:"w-4 h-4 mr-2"}),"Neuer Kunde"]})})]}),s.jsx(X,{className:"mb-6",children:s.jsxs("div",{className:"flex gap-2 items-center",children:[s.jsx(Q,{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(I,{variant:"secondary",className:"flex-shrink-0",children:s.jsx(Pl,{className:"w-4 h-4"})})]})}),s.jsx(X,{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(ge,{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(I,{variant:"ghost",size:"sm",children:s.jsx(Ae,{className:"w-4 h-4"})})}),l("customers:update")&&s.jsx(ke,{to:`/customers/${d.id}/edit`,children:s.jsx(I,{variant:"ghost",size:"sm",children:s.jsx(Xe,{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(I,{variant:"secondary",size:"sm",onClick:()=>i(d=>Math.max(1,d-1)),disabled:a===1,children:"Zurück"}),s.jsx(I,{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 tk({emails:e,selectedEmailId:t,onSelectEmail:n,onEmailDeleted:r,isLoading:a,folder:i="INBOX",accountId:l}){const o=i==="SENT",[c,d]=b.useState(null),{hasPermission:u}=Qe(),h=C=>{if(o)try{const E=JSON.parse(C.toAddresses);if(E.length>0)return`An: ${E[0]}${E.length>1?` (+${E.length-1})`:""}`}catch{return"An: (Unbekannt)"}return C.fromName||C.fromAddress},p=pe(),m=G({mutationFn:C=>Pe.toggleStar(C),onSuccess:(C,E)=>{p.invalidateQueries({queryKey:["emails"]}),p.invalidateQueries({queryKey:["email",E]})}}),f=G({mutationFn:({emailId:C,isRead:E})=>Pe.markAsRead(C,E),onSuccess:(C,E)=>{p.invalidateQueries({queryKey:["emails"]}),p.invalidateQueries({queryKey:["email",E.emailId]}),l&&p.invalidateQueries({queryKey:["folder-counts",l]})}}),g=G({mutationFn:C=>Pe.delete(C),onSuccess:(C,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:C=>{console.error("Delete error:",C),Ie.error(C.message||"Fehler beim Löschen der E-Mail"),d(null)}}),v=G({mutationFn:C=>Pe.unassignFromContract(C),onSuccess:()=>{p.invalidateQueries({queryKey:["emails"]}),Ie.success("Vertragszuordnung aufgehoben")},onError:C=>{console.error("Unassign error:",C),Ie.error(C.message||"Fehler beim Aufheben der Zuordnung")}}),j=(C,E)=>{C.stopPropagation(),v.mutate(E)},x=(C,E)=>{C.stopPropagation(),d(E)},y=C=>{C.stopPropagation(),c&&g.mutate(c)},N=C=>{C.stopPropagation(),d(null)},D=C=>{const E=new Date(C),K=new Date;return E.toDateString()===K.toDateString()?E.toLocaleTimeString("de-DE",{hour:"2-digit",minute:"2-digit"}):E.toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit"})},P=(C,E)=>{C.stopPropagation(),m.mutate(E)},F=(C,E)=>{C.stopPropagation(),f.mutate({emailId:E.id,isRead:!E.isRead})},w=C=>{C.isRead||f.mutate({emailId:C.id,isRead:!0}),n(C)};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(sn,{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(C=>s.jsxs("div",{onClick:()=>w(C),className:["flex items-start gap-3 p-3 cursor-pointer transition-colors",t===C.id?"bg-blue-100":["hover:bg-gray-100",C.isRead?"bg-gray-50/50":"bg-white"].join(" ")].join(" "),style:{borderLeft:t===C.id?"4px solid #2563eb":"4px solid transparent"},children:[s.jsx("button",{onClick:E=>F(E,C),className:` flex-shrink-0 mt-1 p-1 -ml-1 rounded hover:bg-gray-200 ${C.isRead?"text-gray-400":"text-blue-600"} `,title:C.isRead?"Als ungelesen markieren":"Als gelesen markieren",children:C.isRead?s.jsx(Cv,{className:"w-4 h-4"}):s.jsx(sn,{className:"w-4 h-4"})}),s.jsx("button",{onClick:E=>P(E,C.id),className:` flex-shrink-0 mt-1 p-1 -ml-1 rounded hover:bg-gray-200 ${C.isStarred?"text-yellow-500":"text-gray-400"} `,title:C.isStarred?"Stern entfernen":"Als wichtig markieren",children:s.jsx(mh,{className:`w-4 h-4 ${C.isStarred?"fill-current":""}`})}),u("emails:delete")&&s.jsx("button",{onClick:E=>x(E,C.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(je,{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 ${C.isRead?"text-gray-700":"font-semibold text-gray-900"}`,children:h(C)}),s.jsx("span",{className:"text-xs text-gray-500 flex-shrink-0",children:D(C.receivedAt)})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:`text-sm truncate ${C.isRead?"text-gray-600":"font-medium text-gray-900"}`,children:C.subject||"(Kein Betreff)"}),C.hasAttachments&&s.jsx(Fc,{className:"w-3 h-3 text-gray-400 flex-shrink-0"})]}),C.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:C.contract.contractNumber}),(i==="INBOX"||i==="SENT"&&!C.isAutoAssigned)&&s.jsx("button",{onClick:E=>j(E,C.id),className:"p-0.5 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded",title:"Zuordnung aufheben",disabled:v.isPending,children:s.jsx(Zt,{className:"w-3.5 h-3.5"})})]})]}),s.jsx(Pt,{className:"w-4 h-4 text-gray-400 flex-shrink-0 mt-2"})]},C.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(I,{variant:"secondary",onClick:N,disabled:g.isPending,children:"Abbrechen"}),s.jsx(I,{variant:"danger",onClick:y,disabled:g.isPending,children:g.isPending?"Löschen...":"Löschen"})]})]})})]})}const Le=b.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})]})});Le.displayName="Select";function sk({isOpen:e,onClose:t,emailId:n,attachmentFilename:r,onSuccess:a}){var K,O,B;const[i,l]=b.useState(null),[o,c]=b.useState(new Set(["customer"])),[d,u]=b.useState("document"),[h,p]=b.useState({invoiceDate:new Date().toISOString().split("T")[0],invoiceType:"INTERIM",notes:""}),m=pe(),{data:f,isLoading:g,error:v}=ue({queryKey:["attachment-targets",n],queryFn:()=>Pe.getAttachmentTargets(n),enabled:e}),j=f==null?void 0:f.data,x=((K=j==null?void 0:j.contract)==null?void 0:K.type)==="ELECTRICITY"||((O=j==null?void 0:j.contract)==null?void 0:O.type)==="GAS",y=G({mutationFn:()=>{if(!i)throw new Error("Kein Ziel ausgewählt");return Pe.saveAttachmentTo(n,r,{entityType:i.entityType,entityId:i.entityId,targetKey:i.targetKey})},onSuccess:()=>{var A,M;Ie.success("Anhang gespeichert"),m.invalidateQueries({queryKey:["attachment-targets",n]}),m.invalidateQueries({queryKey:["customers"]}),m.invalidateQueries({queryKey:["contracts"]}),(A=j==null?void 0:j.customer)!=null&&A.id&&m.invalidateQueries({queryKey:["customer",j.customer.id.toString()]}),(M=j==null?void 0:j.contract)!=null&&M.id&&m.invalidateQueries({queryKey:["contract",j.contract.id.toString()]}),a==null||a(),D()},onError:A=>{Ie.error(A.message||"Fehler beim Speichern")}}),N=G({mutationFn:()=>Pe.saveAttachmentAsInvoice(n,r,{invoiceDate:h.invoiceDate,invoiceType:h.invoiceType,notes:h.notes||void 0}),onSuccess:()=>{var A;Ie.success("Anhang als Rechnung gespeichert"),m.invalidateQueries({queryKey:["attachment-targets",n]}),m.invalidateQueries({queryKey:["customers"]}),m.invalidateQueries({queryKey:["contracts"]}),(A=j==null?void 0:j.contract)!=null&&A.id&&m.invalidateQueries({queryKey:["contract",j.contract.id.toString()]}),a==null||a(),D()},onError:A=>{Ie.error(A.message||"Fehler beim Speichern der Rechnung")}}),D=()=>{l(null),u("document"),p({invoiceDate:new Date().toISOString().split("T")[0],invoiceType:"INTERIM",notes:""}),t()},P=A=>{const M=new Set(o);M.has(A)?M.delete(A):M.add(A),c(M)},F=(A,M,S,_)=>{l({entityType:A,entityId:S,targetKey:M.key,hasDocument:M.hasDocument,label:_?`${_} → ${M.label}`:M.label})},w=(A,M,S,_)=>A.map(U=>{const Z=(i==null?void 0:i.entityType)===M&&(i==null?void 0:i.entityId)===S&&(i==null?void 0:i.targetKey)===U.key;return s.jsxs("div",{onClick:()=>F(M,U,S,_),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:U.label}),U.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(ms,{className:"w-3 h-3"}),"Vorhanden"]})]})}),Z&&s.jsx(pr,{className:"w-5 h-5 text-blue-600"})]},U.key)}),C=(A,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:A.label}),w(A.slots,M,A.id,A.label)]},A.id),E=(A,M,S,_,U=!1)=>{const Z=o.has(M);return s.jsxs("div",{className:"border border-gray-200 rounded-lg overflow-hidden",children:[s.jsxs("button",{onClick:()=>P(M),className:"w-full flex items-center gap-2 p-3 bg-gray-50 hover:bg-gray-100 transition-colors",children:[Z?s.jsx(Rn,{className:"w-4 h-4 text-gray-500"}):s.jsx(Pt,{className:"w-4 h-4 text-gray-500"}),S,s.jsx("span",{className:"font-medium text-gray-900",children:A})]}),Z&&s.jsx("div",{className:"p-2",children:U?s.jsx("p",{className:"text-sm text-gray-500 text-center py-4",children:"Keine Einträge vorhanden"}):_})]})};return s.jsx(He,{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]})}),g&&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"})}),v&&s.jsx("div",{className:"p-4 bg-red-50 text-red-700 rounded-lg",children:"Fehler beim Laden der Dokumentziele"}),j&&s.jsxs(s.Fragment,{children:[x&&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(_e,{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(Ev,{className:"w-4 h-4"}),"Als Rechnung"]})]}),d==="document"&&s.jsxs("div",{className:"space-y-3 max-h-96 overflow-auto",children:[E(`Kunde: ${j.customer.name}`,"customer",s.jsx(Tl,{className:"w-4 h-4 text-blue-600"}),w(j.customer.slots,"customer"),j.customer.slots.length===0),E("Ausweisdokumente","identityDocuments",s.jsx(kv,{className:"w-4 h-4 text-green-600"}),j.identityDocuments.map(A=>C(A,"identityDocument")),j.identityDocuments.length===0),E("Bankkarten","bankCards",s.jsx(oh,{className:"w-4 h-4 text-purple-600"}),j.bankCards.map(A=>C(A,"bankCard")),j.bankCards.length===0),j.contract&&E(`Vertrag: ${j.contract.contractNumber}`,"contract",s.jsx(_e,{className:"w-4 h-4 text-orange-600"}),w(j.contract.slots,"contract"),j.contract.slots.length===0),!j.contract&&s.jsxs("div",{className:"p-3 bg-gray-50 rounded-lg text-sm text-gray-600",children:[s.jsx(_e,{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"&&x&&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=j.contract)==null?void 0:B.contractNumber})," gespeichert."]})}),s.jsx(Q,{label:"Rechnungsdatum",type:"date",value:h.invoiceDate,onChange:A=>p({...h,invoiceDate:A.target.value}),required:!0}),s.jsx(Le,{label:"Rechnungstyp",value:h.invoiceType,onChange:A=>p({...h,invoiceType:A.target.value}),options:[{value:"INTERIM",label:"Zwischenrechnung"},{value:"FINAL",label:"Schlussrechnung"}]}),s.jsx(Q,{label:"Notizen (optional)",value:h.notes,onChange:A=>p({...h,notes:A.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(ms,{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(I,{variant:"secondary",onClick:D,children:"Abbrechen"}),d==="document"?s.jsx(I,{onClick:()=>y.mutate(),disabled:!i||y.isPending||N.isPending,children:y.isPending?"Wird gespeichert...":"Speichern"}):s.jsx(I,{onClick:()=>N.mutate(),disabled:!h.invoiceDate||y.isPending||N.isPending,children:N.isPending?"Wird gespeichert...":"Als Rechnung speichern"})]})]})})}function nk({isOpen:e,onClose:t,emailId:n,onSuccess:r}){var K,O,B;const[a,i]=b.useState(null),[l,o]=b.useState(new Set(["customer"])),[c,d]=b.useState("document"),[u,h]=b.useState({invoiceDate:new Date().toISOString().split("T")[0],invoiceType:"INTERIM",notes:""}),p=pe(),{data:m,isLoading:f,error:g}=ue({queryKey:["attachment-targets",n],queryFn:()=>Pe.getAttachmentTargets(n),enabled:e}),v=m==null?void 0:m.data,j=((K=v==null?void 0:v.contract)==null?void 0:K.type)==="ELECTRICITY"||((O=v==null?void 0:v.contract)==null?void 0:O.type)==="GAS",x=G({mutationFn:()=>{if(!a)throw new Error("Kein Ziel ausgewählt");return Pe.saveEmailAsPdf(n,{entityType:a.entityType,entityId:a.entityId,targetKey:a.targetKey})},onSuccess:()=>{var A,M;Ie.success("E-Mail als PDF gespeichert"),p.invalidateQueries({queryKey:["attachment-targets",n]}),p.invalidateQueries({queryKey:["customers"]}),p.invalidateQueries({queryKey:["contracts"]}),(A=v==null?void 0:v.customer)!=null&&A.id&&p.invalidateQueries({queryKey:["customer",v.customer.id.toString()]}),(M=v==null?void 0:v.contract)!=null&&M.id&&p.invalidateQueries({queryKey:["contract",v.contract.id.toString()]}),r==null||r(),N()},onError:A=>{Ie.error(A.message||"Fehler beim Speichern")}}),y=G({mutationFn:()=>Pe.saveEmailAsInvoice(n,{invoiceDate:u.invoiceDate,invoiceType:u.invoiceType,notes:u.notes||void 0}),onSuccess:()=>{var A;Ie.success("E-Mail als Rechnung gespeichert"),p.invalidateQueries({queryKey:["attachment-targets",n]}),p.invalidateQueries({queryKey:["customers"]}),p.invalidateQueries({queryKey:["contracts"]}),(A=v==null?void 0:v.contract)!=null&&A.id&&p.invalidateQueries({queryKey:["contract",v.contract.id.toString()]}),r==null||r(),N()},onError:A=>{Ie.error(A.message||"Fehler beim Speichern der Rechnung")}}),N=()=>{i(null),d("document"),h({invoiceDate:new Date().toISOString().split("T")[0],invoiceType:"INTERIM",notes:""}),t()},D=A=>{const M=new Set(l);M.has(A)?M.delete(A):M.add(A),o(M)},P=(A,M,S,_)=>{i({entityType:A,entityId:S,targetKey:M.key,hasDocument:M.hasDocument,label:_?`${_} → ${M.label}`:M.label})},F=(A,M,S,_)=>A.map(U=>{const Z=(a==null?void 0:a.entityType)===M&&(a==null?void 0:a.entityId)===S&&(a==null?void 0:a.targetKey)===U.key;return s.jsxs("div",{onClick:()=>P(M,U,S,_),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:U.label}),U.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(ms,{className:"w-3 h-3"}),"Vorhanden"]})]})}),Z&&s.jsx(pr,{className:"w-5 h-5 text-blue-600"})]},U.key)}),w=(A,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:A.label}),F(A.slots,M,A.id,A.label)]},A.id),C=(A,M,S,_,U=!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(Rn,{className:"w-4 h-4 text-gray-500"}):s.jsx(Pt,{className:"w-4 h-4 text-gray-500"}),S,s.jsx("span",{className:"font-medium text-gray-900",children:A})]}),Z&&s.jsx("div",{className:"p-2",children:U?s.jsx("p",{className:"text-sm text-gray-500 text-center py-4",children:"Keine Einträge vorhanden"}):_})]})},E=x.isPending||y.isPending;return s.jsx(He,{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"})}),g&&s.jsx("div",{className:"p-4 bg-red-50 text-red-700 rounded-lg",children:"Fehler beim Laden der Dokumentziele"}),v&&s.jsxs(s.Fragment,{children:[j&&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(_e,{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(Ev,{className:"w-4 h-4"}),"Als Rechnung"]})]}),c==="document"&&s.jsxs("div",{className:"space-y-3 max-h-96 overflow-auto",children:[C(`Kunde: ${v.customer.name}`,"customer",s.jsx(Tl,{className:"w-4 h-4 text-blue-600"}),F(v.customer.slots,"customer"),v.customer.slots.length===0),C("Ausweisdokumente","identityDocuments",s.jsx(kv,{className:"w-4 h-4 text-green-600"}),v.identityDocuments.map(A=>w(A,"identityDocument")),v.identityDocuments.length===0),C("Bankkarten","bankCards",s.jsx(oh,{className:"w-4 h-4 text-purple-600"}),v.bankCards.map(A=>w(A,"bankCard")),v.bankCards.length===0),v.contract&&C(`Vertrag: ${v.contract.contractNumber}`,"contract",s.jsx(_e,{className:"w-4 h-4 text-orange-600"}),F(v.contract.slots,"contract"),v.contract.slots.length===0),!v.contract&&s.jsxs("div",{className:"p-3 bg-gray-50 rounded-lg text-sm text-gray-600",children:[s.jsx(_e,{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"&&j&&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=v.contract)==null?void 0:B.contractNumber})," gespeichert."]})}),s.jsx(Q,{label:"Rechnungsdatum",type:"date",value:u.invoiceDate,onChange:A=>h({...u,invoiceDate:A.target.value}),required:!0}),s.jsx(Le,{label:"Rechnungstyp",value:u.invoiceType,onChange:A=>h({...u,invoiceType:A.target.value}),options:[{value:"INTERIM",label:"Zwischenrechnung"},{value:"FINAL",label:"Schlussrechnung"}]}),s.jsx(Q,{label:"Notizen (optional)",value:u.notes,onChange:A=>h({...u,notes:A.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(ms,{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(I,{variant:"secondary",onClick:N,children:"Abbrechen"}),c==="document"?s.jsx(I,{onClick:()=>x.mutate(),disabled:!a||E,children:E?"Wird erstellt...":"Als PDF speichern"}):s.jsx(I,{onClick:()=>y.mutate(),disabled:!u.invoiceDate||E,children:E?"Wird erstellt...":"Als Rechnung speichern"})]})]})})}function Tv({email:e,onReply:t,onAssignContract:n,onDeleted:r,isSentFolder:a=!1,isContractView:i=!1,isTrashView:l=!1,onRestored:o,accountId:c}){const[d,u]=b.useState(!0),[h,p]=b.useState(e.isStarred),[m,f]=b.useState(!1),[g,v]=b.useState(!1),[j,x]=b.useState(!1),[y,N]=b.useState(null),[D,P]=b.useState(!1),F=pe(),{hasPermission:w}=Qe();b.useEffect(()=>{p(e.isStarred)},[e.id,e.isStarred]);const C=G({mutationFn:()=>Pe.toggleStar(e.id),onMutate:()=>{p(W=>!W)},onSuccess:()=>{F.invalidateQueries({queryKey:["emails"]}),F.invalidateQueries({queryKey:["email",e.id]})},onError:()=>{p(e.isStarred)}}),E=G({mutationFn:()=>Pe.unassignFromContract(e.id),onSuccess:()=>{F.invalidateQueries({queryKey:["emails"]}),F.invalidateQueries({queryKey:["email",e.id]}),e.contractId&&F.invalidateQueries({queryKey:["contract-folder-counts",e.contractId]}),Ie.success("Vertragszuordnung aufgehoben")},onError:W=>{console.error("Unassign error:",W),Ie.error(W.message||"Fehler beim Aufheben der Zuordnung")}}),K=G({mutationFn:()=>Pe.delete(e.id),onSuccess:()=>{F.invalidateQueries({queryKey:["emails"]}),c&&F.invalidateQueries({queryKey:["folder-counts",c]}),e.contractId&&F.invalidateQueries({queryKey:["contract-folder-counts",e.contractId]}),Ie.success("E-Mail in Papierkorb verschoben"),f(!1),r==null||r()},onError:W=>{console.error("Delete error:",W),Ie.error(W.message||"Fehler beim Löschen der E-Mail"),f(!1)}}),O=G({mutationFn:()=>Pe.restore(e.id),onSuccess:()=>{F.invalidateQueries({queryKey:["emails"]}),c&&F.invalidateQueries({queryKey:["folder-counts",c]}),e.contractId&&F.invalidateQueries({queryKey:["contract-folder-counts",e.contractId]}),Ie.success("E-Mail wiederhergestellt"),v(!1),o==null||o()},onError:W=>{console.error("Restore error:",W),Ie.error(W.message||"Fehler beim Wiederherstellen der E-Mail"),v(!1)}}),B=G({mutationFn:()=>Pe.permanentDelete(e.id),onSuccess:()=>{F.invalidateQueries({queryKey:["emails"]}),c&&F.invalidateQueries({queryKey:["folder-counts",c]}),Ie.success("E-Mail endgültig gelöscht"),x(!1),r==null||r()},onError:W=>{console.error("Permanent delete error:",W),Ie.error(W.message||"Fehler beim endgültigen Löschen der E-Mail"),x(!1)}}),A=W=>new Date(W).toLocaleString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit"}),M=W=>{try{return JSON.parse(W)}catch{return[]}},S=W=>{if(!W)return[];try{return JSON.parse(W)}catch{return[]}},_=M(e.toAddresses),U=e.ccAddresses?M(e.ccAddresses):[],Z=S(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(I,{variant:"secondary",size:"sm",onClick:()=>v(!0),title:"Wiederherstellen",children:[s.jsx(Mv,{className:"w-4 h-4 mr-1"}),"Wiederherstellen"]}),s.jsxs(I,{variant:"danger",size:"sm",onClick:()=>x(!0),title:"Endgültig löschen",children:[s.jsx(je,{className:"w-4 h-4 mr-1"}),"Endgültig löschen"]})]}):s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>C.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(mh,{className:`w-5 h-5 ${h?"fill-current":""}`})}),s.jsxs(I,{variant:"secondary",size:"sm",onClick:t,children:[s.jsx(_2,{className:"w-4 h-4 mr-1"}),"Antworten"]}),s.jsx(I,{variant:"ghost",size:"sm",onClick:()=>P(!0),title:"E-Mail als PDF speichern",children:s.jsx(A2,{className:"w-4 h-4"})}),w("emails:delete")&&s.jsx(I,{variant:"danger",size:"sm",onClick:()=>f(!0),title:"E-Mail löschen",children:s.jsx(je,{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(", ")})]}),U.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:U.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:A(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(mx,{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(Zt,{className:"w-4 h-4 text-green-600"})})]}):!i&&s.jsxs(I,{variant:"secondary",size:"sm",onClick:n,children:[s.jsx(mx,{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((W,fe)=>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:W}),s.jsx("a",{href:Pe.getAttachmentUrl(e.id,W,!0),target:"_blank",rel:"noopener noreferrer",className:"p-1 hover:bg-gray-200 rounded transition-colors",title:`${W} öffnen`,children:s.jsx(ch,{className:"w-4 h-4 text-gray-500"})}),s.jsx("a",{href:Pe.getAttachmentUrl(e.id,W),download:W,className:"p-1 hover:bg-gray-200 rounded transition-colors",title:`${W} herunterladen`,children:s.jsx(Ps,{className:"w-4 h-4 text-gray-500"})}),!l&&s.jsx("button",{onClick:()=>N(W),className:"p-1 hover:bg-blue-100 rounded transition-colors",title:`${W} speichern unter...`,children:s.jsx(Dv,{className:"w-4 h-4 text-blue-500"})})]},fe))})]})]}),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(I,{variant:"secondary",onClick:()=>f(!1),disabled:K.isPending,children:"Abbrechen"}),s.jsx(I,{variant:"danger",onClick:()=>K.mutate(),disabled:K.isPending,children:K.isPending?"Löschen...":"Löschen"})]})]})}),g&&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(I,{variant:"secondary",onClick:()=>v(!1),disabled:O.isPending,children:"Abbrechen"}),s.jsx(I,{variant:"primary",onClick:()=>O.mutate(),disabled:O.isPending,children:O.isPending?"Wird wiederhergestellt...":"Wiederherstellen"})]})]})}),j&&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(I,{variant:"secondary",onClick:()=>x(!1),disabled:B.isPending,children:"Abbrechen"}),s.jsx(I,{variant:"danger",onClick:()=>B.mutate(),disabled:B.isPending,children:B.isPending?"Wird gelöscht...":"Endgültig löschen"})]})]})}),y&&s.jsx(sk,{isOpen:!0,onClose:()=>N(null),emailId:e.id,attachmentFilename:y}),D&&s.jsx(nk,{isOpen:!0,onClose:()=>P(!1),emailId:e.id})]})}function Fv({isOpen:e,onClose:t,account:n,replyTo:r,onSuccess:a,contractId:i}){const[l,o]=b.useState(""),[c,d]=b.useState(""),[u,h]=b.useState(""),[p,m]=b.useState(""),[f,g]=b.useState([]),[v,j]=b.useState(null),x=b.useRef(null);b.useEffect(()=>{if(e){if(r){o(r.fromAddress||"");const O=r.subject||"",B=/^(Re|Aw|Fwd|Wg):\s*/i.test(O);h(B?O:`Re: ${O}`);const A=new Date(r.receivedAt).toLocaleString("de-DE"),M=r.textBody?` --- Ursprüngliche Nachricht --- Von: ${r.fromName||r.fromAddress} Am: ${A} ${r.textBody}`:"";m(M)}else o(""),h(""),m("");d(""),g([]),j(null)}},[e,r]);const y=10*1024*1024,N=25*1024*1024,D=O=>new Promise((B,A)=>{const M=new FileReader;M.readAsDataURL(O),M.onload=()=>{const _=M.result.split(",")[1];B(_)},M.onerror=A}),P=async O=>{const B=O.target.files;if(!B)return;const A=[];let M=f.reduce((S,_)=>S+_.content.length*.75,0);for(const S of Array.from(B)){if(S.size>y){j(`Datei "${S.name}" ist zu groß (max. 10 MB)`);continue}if(M+S.size>N){j("Maximale Gesamtgröße der Anhänge erreicht (25 MB)");break}try{const _=await D(S);A.push({filename:S.name,content:_,contentType:S.type||"application/octet-stream"}),M+=S.size}catch{j(`Fehler beim Lesen von "${S.name}"`)}}A.length>0&&g(S=>[...S,...A]),x.current&&(x.current.value="")},F=O=>{g(B=>B.filter((A,M)=>M!==O))},w=O=>{const B=O.length*.75;return B<1024?`${Math.round(B)} B`:B<1024*1024?`${(B/1024).toFixed(1)} KB`:`${(B/(1024*1024)).toFixed(1)} MB`},C=G({mutationFn:()=>ps.sendEmail(n.id,{to:l.split(",").map(O=>O.trim()).filter(Boolean),cc:c?c.split(",").map(O=>O.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:O=>{j(O instanceof Error?O.message:"Fehler beim Senden")}}),E=()=>{t()},K=()=>{if(!l.trim()){j("Bitte Empfänger angeben");return}if(!u.trim()){j("Bitte Betreff angeben");return}j(null),C.mutate()};return s.jsx(He,{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:O=>o(O.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:O=>d(O.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:O=>h(O.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:O=>m(O.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:x,onChange:P,multiple:!0,className:"hidden"}),s.jsxs("button",{type:"button",onClick:()=>{var O;return(O=x.current)==null?void 0:O.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((O,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(_e,{className:"w-4 h-4 text-gray-500 mr-2 flex-shrink-0"}),s.jsx("span",{className:"text-sm text-gray-700 truncate",children:O.filename}),s.jsxs("span",{className:"ml-2 text-xs text-gray-500 flex-shrink-0",children:["(",w(O.content),")"]})]}),s.jsx("button",{type:"button",onClick:()=>F(B),className:"ml-2 p-1 text-gray-400 hover:text-red-500 transition-colors",title:"Anhang entfernen",children:s.jsx(Zt,{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"})]}),v&&s.jsx("div",{className:"p-3 bg-red-50 border border-red-200 rounded-lg text-sm text-red-700",children:v}),s.jsxs("div",{className:"flex justify-end gap-3 pt-4",children:[s.jsx(I,{variant:"secondary",onClick:E,children:"Abbrechen"}),s.jsxs(I,{onClick:K,disabled:C.isPending,children:[s.jsx(Ml,{className:"w-4 h-4 mr-2"}),C.isPending?"Wird gesendet...":"Senden"]})]})]})})}function rk({isOpen:e,onClose:t,email:n,customerId:r,onSuccess:a}){const[i,l]=b.useState(""),[o,c]=b.useState(null),d=pe(),{data:u,isLoading:h}=ue({queryKey:["contracts","customer",r],queryFn:()=>$e.getAll({customerId:r}),enabled:e}),m=((u==null?void 0:u.data)||[]).filter(x=>{var N,D,P,F;if(!i)return!0;const y=i.toLowerCase();return x.contractNumber.toLowerCase().includes(y)||((D=(N=x.contractCategory)==null?void 0:N.name)==null?void 0:D.toLowerCase().includes(y))||((F=(P=x.provider)==null?void 0:P.name)==null?void 0:F.toLowerCase().includes(y))}),f=G({mutationFn:x=>Pe.assignToContract(n.id,x),onSuccess:(x,y)=>{d.invalidateQueries({queryKey:["emails"]}),d.invalidateQueries({queryKey:["email",n.id]}),d.invalidateQueries({queryKey:["contract-folder-counts",y]}),a==null||a(),g()}}),g=()=>{l(""),c(null),t()},v=()=>{o&&f.mutate(o)},j=x=>x?new Date(x).toLocaleDateString("de-DE"):"-";return s.jsx(He,{isOpen:e,onClose:g,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(Pl,{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:x=>l(x.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(_e,{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(x=>{var y;return s.jsx("div",{onClick:()=>c(x.id),className:` flex items-center gap-3 p-3 cursor-pointer transition-colors ${o===x.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:x.contractNumber}),s.jsx("span",{className:` px-2 py-0.5 text-xs rounded-full ${x.status==="ACTIVE"?"bg-green-100 text-green-800":x.status==="PENDING"?"bg-yellow-100 text-yellow-800":x.status==="CANCELLED"?"bg-red-100 text-red-800":"bg-gray-100 text-gray-800"} `,children:x.status})]}),s.jsxs("div",{className:"text-sm text-gray-600 truncate",children:[(y=x.contractCategory)==null?void 0:y.name,x.provider&&` - ${x.provider.name}`]}),s.jsxs("div",{className:"text-xs text-gray-500",children:["Start: ",j(x.startDate)]})]})},x.id)})})}),s.jsxs("div",{className:"flex justify-end gap-3 pt-4",children:[s.jsx(I,{variant:"secondary",onClick:g,children:"Abbrechen"}),s.jsx(I,{onClick:v,disabled:!o||f.isPending,children:f.isPending?"Wird zugeordnet...":"Zuordnen"})]})]})})}function Iv({emails:e,selectedEmailId:t,onSelectEmail:n,onEmailRestored:r,onEmailDeleted:a,isLoading:i}){const[l,o]=b.useState(null),[c,d]=b.useState(null),u=pe(),h=P=>{if(P.folder==="SENT")try{const F=JSON.parse(P.toAddresses);if(F.length>0)return`An: ${F[0]}${F.length>1?` (+${F.length-1})`:""}`}catch{return"An: (Unbekannt)"}return P.fromName||P.fromAddress},p=G({mutationFn:P=>Pe.restore(P),onSuccess:(P,F)=>{u.invalidateQueries({queryKey:["emails"]}),Ie.success("E-Mail wiederhergestellt"),o(null),d(null),r==null||r(F)},onError:P=>{console.error("Restore error:",P),Ie.error(P.message||"Fehler beim Wiederherstellen"),o(null),d(null)}}),m=G({mutationFn:P=>Pe.permanentDelete(P),onSuccess:(P,F)=>{u.invalidateQueries({queryKey:["emails"]}),Ie.success("E-Mail endgültig gelöscht"),o(null),d(null),a==null||a(F)},onError:P=>{console.error("Permanent delete error:",P),Ie.error(P.message||"Fehler beim endgültigen Löschen"),o(null),d(null)}}),f=G({mutationFn:P=>Pe.unassignFromContract(P),onSuccess:()=>{u.invalidateQueries({queryKey:["emails"]}),Ie.success("Vertragszuordnung aufgehoben")},onError:P=>{console.error("Unassign error:",P),Ie.error(P.message||"Fehler beim Aufheben der Zuordnung")}}),g=(P,F)=>{P.stopPropagation(),f.mutate(F)},v=(P,F)=>{P.stopPropagation(),o(F),d("restore")},j=(P,F)=>{P.stopPropagation(),o(F),d("delete")},x=P=>{P.stopPropagation(),l&&c&&(c==="restore"?p.mutate(l):m.mutate(l))},y=P=>{P.stopPropagation(),o(null),d(null)},N=P=>new Date(P).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit"}),D=P=>{if(!P)return"";const F=new Date(P),w=new Date;return F.toDateString()===w.toDateString()?`Gelöscht um ${F.toLocaleTimeString("de-DE",{hour:"2-digit",minute:"2-digit"})}`:`Gelöscht am ${F.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(je,{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(P=>s.jsxs("div",{onClick:()=>n(P),className:["flex items-start gap-3 p-3 cursor-pointer transition-colors",t===P.id?"bg-red-100":"hover:bg-gray-100 bg-gray-50/50"].join(" "),style:{borderLeft:t===P.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:P.folder==="SENT"?"Aus Gesendet":"Aus Posteingang",children:P.folder==="SENT"?s.jsx(Ml,{className:"w-4 h-4"}):s.jsx(Ur,{className:"w-4 h-4"})}),s.jsx("button",{onClick:F=>v(F,P.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(Mv,{className:"w-4 h-4"})}),s.jsx("button",{onClick:F=>j(F,P.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(je,{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(P)}),s.jsx("span",{className:"text-xs text-gray-500 flex-shrink-0",children:N(P.receivedAt)})]}),s.jsx("div",{className:"text-sm truncate text-gray-600",children:P.subject||"(Kein Betreff)"}),s.jsx("div",{className:"text-xs text-red-500 mt-1",children:D(P.deletedAt)}),P.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:P.contract.contractNumber}),(P.folder==="INBOX"||P.folder==="SENT"&&!P.isAutoAssigned)&&s.jsx("button",{onClick:F=>g(F,P.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(Zt,{className:"w-3.5 h-3.5"})})]})]}),s.jsx(Pt,{className:"w-4 h-4 text-gray-400 flex-shrink-0 mt-2"})]},P.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(I,{variant:"secondary",onClick:y,disabled:p.isPending||m.isPending,children:"Abbrechen"}),s.jsx(I,{variant:c==="restore"?"primary":"danger",onClick:x,disabled:p.isPending||m.isPending,children:p.isPending||m.isPending?"Wird ausgeführt...":c==="restore"?"Wiederherstellen":"Endgültig löschen"})]})]})})]})}function ak({customerId:e}){const[t,n]=b.useState(null),[r,a]=b.useState("INBOX"),[i,l]=b.useState(null),[o,c]=b.useState(!1),[d,u]=b.useState(!1),[h,p]=b.useState(null),m=pe(),{hasPermission:f}=Qe(),g=f("emails:delete"),{data:v,isLoading:j}=ue({queryKey:["mailbox-accounts",e],queryFn:()=>Pe.getMailboxAccounts(e)}),x=(v==null?void 0:v.data)||[];b.useEffect(()=>{x.length>0&&!t&&n(x[0].id)},[x,t]);const y=x.find(le=>le.id===t),{data:N,isLoading:D,refetch:P}=ue({queryKey:["emails","customer",e,t,r],queryFn:()=>Pe.getForCustomer(e,{accountId:t||void 0,folder:r}),enabled:!!t&&r!=="TRASH"}),F=(N==null?void 0:N.data)||[],{data:w,isLoading:C}=ue({queryKey:["emails","trash",e],queryFn:()=>Pe.getTrash(e),enabled:r==="TRASH"&&g}),E=(w==null?void 0:w.data)||[],{data:K}=ue({queryKey:["folder-counts",t],queryFn:()=>ps.getFolderCounts(t),enabled:!!t}),O=(K==null?void 0:K.data)||{inbox:0,inboxUnread:0,sent:0,sentUnread:0,trash:0,trashUnread:0},{data:B}=ue({queryKey:["email",i==null?void 0:i.id],queryFn:()=>Pe.getById(i.id),enabled:!!(i!=null&&i.id)}),A=(B==null?void 0:B.data)||i,M=G({mutationFn:le=>ps.syncEmails(le),onSuccess:()=>{m.invalidateQueries({queryKey:["emails"]}),m.invalidateQueries({queryKey:["folder-counts",t]}),m.invalidateQueries({queryKey:["mailbox-accounts",e]})}}),S=()=>{t&&M.mutate(t)},_=le=>{l(le)},U=()=>{p(A||null),c(!0)},Z=()=>{p(null),c(!0)},W=()=>{u(!0)};if(!j&&x.length===0)return s.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-gray-500",children:[s.jsx(sn,{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 fe=le=>{a(le),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:[x.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:le=>{n(Number(le.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:x.map(le=>s.jsx("option",{value:le.id,children:le.email},le.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:y==null?void 0:y.email})]}),s.jsxs("div",{className:"flex items-center gap-1 bg-gray-200 rounded-lg p-1",children:[s.jsxs("button",{onClick:()=>fe("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",O.inbox>0&&s.jsx("span",{className:`ml-1 px-1.5 py-0.5 text-xs rounded-full cursor-help ${O.inboxUnread>0?"bg-blue-100 text-blue-600 font-medium":"bg-gray-100 text-gray-500"}`,title:`${O.inboxUnread} ungelesen / ${O.inbox} gesamt`,children:O.inboxUnread>0?`${O.inboxUnread}/${O.inbox}`:O.inbox})]}),s.jsxs("button",{onClick:()=>fe("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",O.sent>0&&s.jsx("span",{className:`ml-1 px-1.5 py-0.5 text-xs rounded-full cursor-help ${O.sentUnread>0?"bg-blue-100 text-blue-600 font-medium":"bg-gray-100 text-gray-500"}`,title:`${O.sentUnread} ungelesen / ${O.sent} gesamt`,children:O.sentUnread>0?`${O.sentUnread}/${O.sent}`:O.sent})]}),g&&s.jsxs("button",{onClick:()=>fe("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(je,{className:"w-4 h-4"}),"Papierkorb",O.trash>0&&s.jsx("span",{className:`ml-1 px-1.5 py-0.5 text-xs rounded-full cursor-help ${O.trashUnread>0?"bg-red-100 text-red-600 font-medium":"bg-gray-100 text-gray-500"}`,title:`${O.trashUnread} ungelesen / ${O.trash} gesamt`,children:O.trashUnread>0?`${O.trashUnread}/${O.trash}`:O.trash})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[r!=="TRASH"&&s.jsxs(I,{variant:"secondary",size:"sm",onClick:S,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(I,{size:"sm",onClick:Z,disabled:!y,children:[s.jsx(Ue,{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(Iv,{emails:E,selectedEmailId:i==null?void 0:i.id,onSelectEmail:_,onEmailRestored:le=>{(i==null?void 0:i.id)===le&&l(null),m.invalidateQueries({queryKey:["emails"]}),m.invalidateQueries({queryKey:["folder-counts",t]})},onEmailDeleted:le=>{(i==null?void 0:i.id)===le&&l(null),m.invalidateQueries({queryKey:["emails","trash"]}),m.invalidateQueries({queryKey:["folder-counts",t]})},isLoading:C}):s.jsx(tk,{emails:F,selectedEmailId:i==null?void 0:i.id,onSelectEmail:_,onEmailDeleted:le=>{(i==null?void 0:i.id)===le&&l(null),m.invalidateQueries({queryKey:["folder-counts",t]})},isLoading:D,folder:r,accountId:t})}),s.jsx("div",{className:"flex-1 overflow-auto",children:A?s.jsx(Tv,{email:A,onReply:U,onAssignContract:W,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(sn,{className:"w-12 h-12 mb-2 opacity-30"}),s.jsx("p",{children:"Wählen Sie eine E-Mail aus"})]})})]}),y&&s.jsx(Fv,{isOpen:o,onClose:()=>{c(!1),p(null)},account:y,replyTo:h||void 0,onSuccess:()=>{m.invalidateQueries({queryKey:["emails","customer",e,t,"SENT"]}),m.invalidateQueries({queryKey:["folder-counts",t]}),r==="SENT"&&P()}}),A&&s.jsx(rk,{isOpen:d,onClose:()=>u(!1),email:A,customerId:e,onSuccess:()=>{P()}})]})}function ik({contractId:e,customerId:t}){const[n,r]=b.useState(null),[a,i]=b.useState("INBOX"),[l,o]=b.useState(null),[c,d]=b.useState(!1),[u,h]=b.useState(null),[p,m]=b.useState(null),f=pe(),{hasPermission:g}=Qe(),v=g("emails:delete"),{data:j,isLoading:x}=ue({queryKey:["mailbox-accounts",t],queryFn:()=>Pe.getMailboxAccounts(t)}),y=(j==null?void 0:j.data)||[];b.useEffect(()=>{y.length>0&&!n&&r(y[0].id)},[y,n]);const N=y.find(Y=>Y.id===n),{data:D,isLoading:P,refetch:F}=ue({queryKey:["emails","contract",e,a],queryFn:()=>Pe.getForContract(e,{folder:a}),enabled:a!=="TRASH"}),w=(D==null?void 0:D.data)||[],{data:C,isLoading:E}=ue({queryKey:["emails","trash",t],queryFn:()=>Pe.getTrash(t),enabled:a==="TRASH"&&v}),K=(C==null?void 0:C.data)||[],{data:O}=ue({queryKey:["contract-folder-counts",e],queryFn:()=>Pe.getContractFolderCounts(e)}),B=(O==null?void 0:O.data)||{inbox:0,inboxUnread:0,sent:0,sentUnread:0},{data:A}=ue({queryKey:["folder-counts",n],queryFn:()=>ps.getFolderCounts(n),enabled:!!n&&v}),M=(A==null?void 0:A.data)||{trash:0,trashUnread:0},{data:S}=ue({queryKey:["email",l==null?void 0:l.id],queryFn:()=>Pe.getById(l.id),enabled:!!(l!=null&&l.id)}),_=(S==null?void 0:S.data)||l,U=G({mutationFn:Y=>ps.syncEmails(Y),onSuccess:()=>{f.invalidateQueries({queryKey:["emails"]}),f.invalidateQueries({queryKey:["contract-folder-counts",e]}),n&&f.invalidateQueries({queryKey:["folder-counts",n]}),Ie.success("Synchronisation abgeschlossen")},onError:Y=>{Ie.error(Y.message||"Synchronisation fehlgeschlagen")}}),Z=G({mutationFn:Y=>Pe.toggleStar(Y),onSuccess:(Y,Se)=>{f.invalidateQueries({queryKey:["emails","contract",e]}),f.invalidateQueries({queryKey:["email",Se]})}}),W=G({mutationFn:({emailId:Y,isRead:Se})=>Pe.markAsRead(Y,Se),onSuccess:(Y,Se)=>{f.invalidateQueries({queryKey:["emails","contract",e]}),f.invalidateQueries({queryKey:["email",Se.emailId]}),f.invalidateQueries({queryKey:["contract-folder-counts",e]}),n&&f.invalidateQueries({queryKey:["folder-counts",n]})}}),fe=G({mutationFn:Y=>Pe.unassignFromContract(Y),onSuccess:()=>{f.invalidateQueries({queryKey:["emails","contract",e]}),f.invalidateQueries({queryKey:["contract-folder-counts",e]}),o(null),Ie.success("Zuordnung aufgehoben")},onError:Y=>{Ie.error(Y.message||"Fehler beim Aufheben der Zuordnung")}}),le=G({mutationFn:Y=>Pe.delete(Y),onSuccess:(Y,Se)=>{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)===Se&&o(null)},onError:Y=>{Ie.error(Y.message||"Fehler beim Löschen der E-Mail"),m(null)}}),k=()=>{n&&U.mutate(n)},Re=Y=>{const Se=new Date(Y),on=new Date;return Se.toDateString()===on.toDateString()?Se.toLocaleTimeString("de-DE",{hour:"2-digit",minute:"2-digit"}):Se.toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit"})},Ye=(Y,Se)=>{Y.stopPropagation(),Z.mutate(Se)},qe=(Y,Se)=>{Y.stopPropagation(),W.mutate({emailId:Se.id,isRead:!Se.isRead})},et=Y=>{Y.isRead||W.mutate({emailId:Y.id,isRead:!0}),o(Y)},Rt=()=>{h(_||null),d(!0)},Bt=()=>{h(null),d(!0)},z=(Y,Se)=>{Y.stopPropagation(),(l==null?void 0:l.id)===Se&&o(null),fe.mutate(Se)},Ne=(Y,Se)=>{Y.stopPropagation(),m(Se)},Be=Y=>{Y.stopPropagation(),p&&le.mutate(p)},es=Y=>{Y.stopPropagation(),m(null)},Lt=Y=>{i(Y),o(null)},Ns=Y=>{if(a==="SENT")try{const Se=JSON.parse(Y.toAddresses);if(Se.length>0)return`An: ${Se[0]}${Se.length>1?` (+${Se.length-1})`:""}`}catch{return"An: (Unbekannt)"}return Y.fromName||Y.fromAddress};return!x&&y.length===0?s.jsx(X,{title:"E-Mails",children:s.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-gray-500",children:[s.jsx(sn,{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(X,{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(I,{variant:"secondary",size:"sm",onClick:k,disabled:U.isPending||!n,children:[s.jsx(wr,{className:`w-4 h-4 mr-1 ${U.isPending?"animate-spin":""}`}),U.isPending?"Sync...":"Sync"]}),N&&s.jsxs(I,{size:"sm",onClick:Bt,children:[s.jsx(Ue,{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:[y.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:Y=>{r(Number(Y.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:y.map(Y=>s.jsx("option",{value:Y.id,children:Y.email},Y.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:()=>Lt("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:()=>Lt("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})]}),v&&s.jsxs("button",{onClick:()=>Lt("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(je,{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:P)?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"?K.length===0:w.length===0)?s.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-gray-500",children:[s.jsx(sn,{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(Iv,{emails:K,selectedEmailId:l==null?void 0:l.id,onSelectEmail:et,onEmailRestored:Y=>{(l==null?void 0:l.id)===Y&&o(null),f.invalidateQueries({queryKey:["emails"]}),f.invalidateQueries({queryKey:["folder-counts",n]}),f.invalidateQueries({queryKey:["contract-folder-counts",e]})},onEmailDeleted:Y=>{(l==null?void 0:l.id)===Y&&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(Y=>s.jsxs("div",{onClick:()=>et(Y),className:["flex items-start gap-2 p-3 cursor-pointer transition-colors",(l==null?void 0:l.id)===Y.id?"bg-blue-100":["hover:bg-gray-100",Y.isRead?"bg-gray-50/50":"bg-white"].join(" ")].join(" "),style:{borderLeft:(l==null?void 0:l.id)===Y.id?"4px solid #2563eb":"4px solid transparent"},children:[s.jsx("button",{onClick:Se=>qe(Se,Y),className:` flex-shrink-0 mt-1 p-1 -ml-1 rounded hover:bg-gray-200 ${Y.isRead?"text-gray-400":"text-blue-600"} `,title:Y.isRead?"Als ungelesen markieren":"Als gelesen markieren",children:Y.isRead?s.jsx(Cv,{className:"w-4 h-4"}):s.jsx(sn,{className:"w-4 h-4"})}),s.jsx("button",{onClick:Se=>Ye(Se,Y.id),className:` flex-shrink-0 mt-1 p-1 -ml-1 rounded hover:bg-gray-200 ${Y.isStarred?"text-yellow-500":"text-gray-400"} `,title:Y.isStarred?"Stern entfernen":"Als wichtig markieren",children:s.jsx(mh,{className:`w-4 h-4 ${Y.isStarred?"fill-current":""}`})}),g("emails:delete")&&s.jsx("button",{onClick:Se=>Ne(Se,Y.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(je,{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 ${Y.isRead?"text-gray-700":"font-semibold text-gray-900"}`,children:Ns(Y)}),s.jsx("span",{className:"text-xs text-gray-500 flex-shrink-0",children:Re(Y.receivedAt)})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:`text-sm truncate ${Y.isRead?"text-gray-600":"font-medium text-gray-900"}`,children:Y.subject||"(Kein Betreff)"}),Y.hasAttachments&&s.jsx(Fc,{className:"w-3 h-3 text-gray-400 flex-shrink-0"})]}),Y.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:Y.contract.contractNumber}),(a==="INBOX"||a==="SENT"&&!Y.isAutoAssigned)&&s.jsx("button",{onClick:Se=>z(Se,Y.id),className:"p-0.5 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded",title:"Zuordnung aufheben",disabled:fe.isPending,children:s.jsx(Zt,{className:"w-3.5 h-3.5"})})]})]}),s.jsx(Pt,{className:"w-4 h-4 text-gray-400 flex-shrink-0 mt-2"})]},Y.id))})}),s.jsx("div",{className:"flex-1 overflow-auto",children:_&&l?s.jsx(Tv,{email:_,onReply:Rt,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(sn,{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(I,{variant:"secondary",onClick:es,disabled:le.isPending,children:"Abbrechen"}),s.jsx(I,{variant:"danger",onClick:Be,disabled:le.isPending,children:le.isPending?"Löschen...":"Löschen"})]})]})}),N&&s.jsx(Fv,{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"&&F()}})]})}function lk({tabs:e,defaultTab:t}){var a,i;const[n,r]=b.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 St({onUpload:e,existingFile:t,accept:n=".pdf,.jpg,.jpeg,.png",label:r="Dokument hochladen",disabled:a=!1}){const i=b.useRef(null),[l,o]=b.useState(!1),[c,d]=b.useState(!1),u=async g=>{if(g){o(!0);try{await e(g)}catch(v){console.error("Upload failed:",v),alert("Upload fehlgeschlagen")}finally{o(!1)}}},h=g=>{var j;const v=(j=g.target.files)==null?void 0:j[0];v&&u(v)},p=g=>{var j;g.preventDefault(),d(!1);const v=(j=g.dataTransfer.files)==null?void 0:j[0];v&&u(v)},m=g=>{g.preventDefault(),d(!0)},f=()=>{d(!1)};return s.jsxs("div",{className:"space-y-2",children:[t?!a&&s.jsx(I,{variant:"secondary",size:"sm",onClick:()=>{var g;return(g=i.current)==null?void 0:g.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 g;return!a&&((g=i.current)==null?void 0:g.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 oe({value:e,className:t="",size:n="sm",title:r="In Zwischenablage kopieren"}){const[a,i]=b.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(pr,{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(oe,{value:a,className:"absolute top-0 right-0 opacity-60 group-hover:opacity-100",title:"Alles kopieren"})]}):s.jsx(s.Fragment,{children:n})}function ok(){var U,Z;const{id:e}=bc(),t=Yt(),n=pe(),{hasPermission:r}=Qe(),[a]=wc(),i=parseInt(e),l=a.get("tab")||"addresses",[o,c]=b.useState(!1),[d,u]=b.useState(!1),[h,p]=b.useState(!1),[m,f]=b.useState(!1),[g,v]=b.useState(!1),[j,x]=b.useState(!1),[y,N]=b.useState(null),[D,P]=b.useState(null),[F,w]=b.useState(null),[C,E]=b.useState(null),[K,O]=b.useState(null),{data:B,isLoading:A}=ue({queryKey:["customer",e],queryFn:()=>kt.getById(i)}),M=G({mutationFn:()=>kt.delete(i),onSuccess:()=>{t("/customers")}});if(A)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 S=B.data,_=[{id:"addresses",label:"Adressen",content:s.jsx(uk,{customerId:i,addresses:S.addresses||[],canEdit:r("customers:update"),onAdd:()=>c(!0),onEdit:W=>w(W)})},{id:"bankcards",label:"Bankkarten",content:s.jsx(mk,{customerId:i,bankCards:S.bankCards||[],canEdit:r("customers:update"),showInactive:j,onToggleInactive:()=>x(!j),onAdd:()=>u(!0),onEdit:W=>N(W)})},{id:"documents",label:"Ausweise",content:s.jsx(hk,{customerId:i,documents:S.identityDocuments||[],canEdit:r("customers:update"),showInactive:j,onToggleInactive:()=>x(!j),onAdd:()=>p(!0),onEdit:W=>P(W)})},{id:"meters",label:"Zähler",content:s.jsx(fk,{customerId:i,meters:S.meters||[],canEdit:r("customers:update"),showInactive:j,onToggleInactive:()=>x(!j),onAdd:()=>f(!0),onEdit:W=>E(W)})},{id:"stressfrei",label:"Stressfrei-Wechseln",content:s.jsx(yk,{customerId:i,emails:S.stressfreiEmails||[],canEdit:r("customers:update"),showInactive:j,onToggleInactive:()=>x(!j),onAdd:()=>v(!0),onEdit:W=>O(W)})},{id:"emails",label:"E-Mail-Postfach",content:s.jsx(ak,{customerId:i})},{id:"contracts",label:"Verträge",content:s.jsx(pk,{customerId:i})},...r("customers:update")?[{id:"portal",label:"Portal",content:s.jsx(gk,{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:S.type==="BUSINESS"&&S.companyName?S.companyName:`${S.firstName} ${S.lastName}`}),s.jsxs("p",{className:"text-gray-500 font-mono flex items-center gap-1",children:[S.customerNumber,s.jsx(oe,{value:S.customerNumber})]})]}),s.jsxs("div",{className:"flex gap-2",children:[r("customers:update")&&s.jsx(ke,{to:`/customers/${e}/edit`,children:s.jsxs(I,{variant:"secondary",children:[s.jsx(Xe,{className:"w-4 h-4 mr-2"}),"Bearbeiten"]})}),r("customers:delete")&&s.jsxs(I,{variant:"danger",onClick:()=>{confirm("Kunde wirklich löschen?")&&M.mutate()},children:[s.jsx(je,{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(X,{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(ge,{variant:S.type==="BUSINESS"?"info":"default",children:S.type==="BUSINESS"?"Geschäftskunde":"Privatkunde"})})]}),S.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:[S.salutation,s.jsx(oe,{value:S.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:[S.firstName,s.jsx(oe,{value:S.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:[S.lastName,s.jsx(oe,{value:S.lastName})]})]}),S.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:[S.companyName,s.jsx(oe,{value:S.companyName})]})]}),S.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(S.foundingDate).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"}),s.jsx(oe,{value:new Date(S.foundingDate).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"})})]})]}),S.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(S.birthDate).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"}),s.jsx(oe,{value:new Date(S.birthDate).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"})})]})]}),S.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:[S.birthPlace,s.jsx(oe,{value:S.birthPlace})]})]})]})}),s.jsx(X,{title:"Kontakt",children:s.jsxs("dl",{className:"space-y-3",children:[S.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:${S.email}`,className:"text-blue-600 hover:underline",children:S.email}),s.jsx(oe,{value:S.email})]})]}),S.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:${S.phone}`,className:"text-blue-600 hover:underline",children:S.phone}),s.jsx(oe,{value:S.phone})]})]}),S.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:${S.mobile}`,className:"text-blue-600 hover:underline",children:S.mobile}),s.jsx(oe,{value:S.mobile})]})]})]})})]}),S.type==="BUSINESS"&&s.jsx(ck,{customer:S,canEdit:r("customers:update"),onUpdate:()=>n.invalidateQueries({queryKey:["customer",e]})}),s.jsx(dk,{customer:S,canEdit:r("customers:update"),onUpdate:()=>n.invalidateQueries({queryKey:["customer",e]})}),S.notes&&s.jsx(X,{title:"Notizen",className:"mb-6",children:s.jsx("p",{className:"whitespace-pre-wrap",children:S.notes})}),s.jsx(X,{children:s.jsx(lk,{tabs:_,defaultTab:l})}),s.jsx(fx,{isOpen:o,onClose:()=>c(!1),customerId:i}),s.jsx(fx,{isOpen:!!F,onClose:()=>w(null),customerId:i,address:F}),s.jsx(px,{isOpen:d,onClose:()=>u(!1),customerId:i}),s.jsx(px,{isOpen:!!y,onClose:()=>N(null),customerId:i,bankCard:y}),s.jsx(xx,{isOpen:h,onClose:()=>p(!1),customerId:i}),s.jsx(xx,{isOpen:!!D,onClose:()=>P(null),customerId:i,document:D}),s.jsx(gx,{isOpen:m,onClose:()=>f(!1),customerId:i}),s.jsx(gx,{isOpen:!!C,onClose:()=>E(null),customerId:i,meter:C}),s.jsx(vx,{isOpen:g,onClose:()=>v(!1),customerId:i,customerEmail:(U=B==null?void 0:B.data)==null?void 0:U.email}),s.jsx(vx,{isOpen:!!K,onClose:()=>O(null),customerId:i,email:K,customerEmail:(Z=B==null?void 0:B.data)==null?void 0:Z.email})]})}function ck({customer:e,canEdit:t,onUpdate:n}){const r=async c=>{try{await ot.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 ot.deleteBusinessRegistration(e.id),n()}catch(c){console.error("Löschen fehlgeschlagen:",c),alert("Löschen fehlgeschlagen")}},i=async c=>{try{await ot.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 ot.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(X,{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(oe,{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(oe,{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(Ae,{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(Ps,{className:"w-4 h-4"}),"Download"]}),t&&s.jsxs(s.Fragment,{children:[s.jsx(St,{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(je,{className:"w-4 h-4"}),"Löschen"]})]})]}):t?s.jsx(St,{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(Ae,{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(Ps,{className:"w-4 h-4"}),"Download"]}),t&&s.jsxs(s.Fragment,{children:[s.jsx(St,{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(je,{className:"w-4 h-4"}),"Löschen"]})]})]}):t?s.jsx(St,{onUpload:i,accept:".pdf",label:"PDF hochladen"}):s.jsx("p",{className:"text-sm text-gray-400",children:"Nicht vorhanden"})]})]})]})}function dk({customer:e,canEdit:t,onUpdate:n}){const r=async i=>{try{await ot.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 ot.deletePrivacyPolicy(e.id),n()}catch(i){console.error("Löschen fehlgeschlagen:",i),alert("Löschen fehlgeschlagen")}};return!e.privacyPolicyPath&&!t?null:s.jsx(X,{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(Ae,{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(Ps,{className:"w-4 h-4"}),"Download"]}),t&&s.jsxs(s.Fragment,{children:[s.jsx(St,{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(je,{className:"w-4 h-4"}),"Löschen"]})]})]}):t?s.jsx(St,{onUpload:r,accept:".pdf",label:"PDF hochladen"}):s.jsx("p",{className:"text-sm text-gray-400",children:"Nicht vorhanden"})]})})}function uk({customerId:e,addresses:t,canEdit:n,onAdd:r,onEdit:a}){const i=pe(),l=G({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(I,{size:"sm",onClick:r,children:[s.jsx(Ue,{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(L2,{className:"w-4 h-4 text-gray-400"}),s.jsx(ge,{variant:o.type==="BILLING"?"info":"default",children:o.type==="BILLING"?"Rechnung":"Liefer-/Meldeadresse"}),o.isDefault&&s.jsx(ge,{variant:"success",children:"Standard"})]}),n&&s.jsxs("div",{className:"flex gap-1",children:[s.jsx(I,{variant:"ghost",size:"sm",onClick:()=>a(o),title:"Bearbeiten",children:s.jsx(Xe,{className:"w-4 h-4"})}),s.jsx(I,{variant:"ghost",size:"sm",onClick:()=>{confirm("Adresse wirklich löschen?")&&l.mutate(o.id)},title:"Löschen",children:s.jsx(je,{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 mk({customerId:e,bankCards:t,canEdit:n,showInactive:r,onToggleInactive:a,onAdd:i,onEdit:l}){const o=pe(),c=G({mutationFn:({id:m,data:f})=>Yo.update(m,f),onSuccess:()=>o.invalidateQueries({queryKey:["customer",e.toString()]})}),d=G({mutationFn:Yo.delete,onSuccess:()=>o.invalidateQueries({queryKey:["customer",e.toString()]})}),u=async(m,f)=>{try{await ot.uploadBankCardDocument(m,f),o.invalidateQueries({queryKey:["customer",e.toString()]})}catch(g){console.error("Upload fehlgeschlagen:",g),alert("Upload fehlgeschlagen")}},h=async m=>{if(confirm("Dokument wirklich löschen?"))try{await ot.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(I,{size:"sm",onClick:i,children:[s.jsx(Ue,{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(ge,{variant:"danger",children:"Inaktiv"}),m.expiryDate&&new Date(m.expiryDate)l(m),title:"Bearbeiten",children:s.jsx(Xe,{className:"w-4 h-4"})}),m.isActive?s.jsx(I,{variant:"ghost",size:"sm",onClick:()=>{confirm("Bankkarte deaktivieren?")&&c.mutate({id:m.id,data:{isActive:!1}})},title:"Deaktivieren",children:s.jsx(Mt,{className:"w-4 h-4"})}):s.jsx(I,{variant:"ghost",size:"sm",onClick:()=>{confirm("Bankkarte wieder aktivieren?")&&c.mutate({id:m.id,data:{isActive:!0}})},title:"Aktivieren",children:s.jsx(Ae,{className:"w-4 h-4"})}),s.jsx(I,{variant:"ghost",size:"sm",onClick:()=>{confirm("Bankkarte wirklich löschen?")&&d.mutate(m.id)},title:"Löschen",children:s.jsx(je,{className:"w-4 h-4 text-red-500"})})]})]}),s.jsxs("p",{className:"font-medium flex items-center gap-1",children:[m.accountHolder,s.jsx(oe,{value:m.accountHolder})]}),s.jsxs("p",{className:"font-mono flex items-center gap-1",children:[m.iban,s.jsx(oe,{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(oe,{value:m.bic})]}),m.bankName&&s.jsxs("p",{className:"text-sm text-gray-500 flex items-center gap-1",children:[m.bankName,s.jsx(oe,{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(Ae,{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(Ps,{className:"w-4 h-4"}),"Download"]}),n&&s.jsxs(s.Fragment,{children:[s.jsx(St,{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(je,{className:"w-4 h-4"}),"Löschen"]})]})]}):n&&m.isActive&&s.jsx(St,{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 hk({customerId:e,documents:t,canEdit:n,showInactive:r,onToggleInactive:a,onAdd:i,onEdit:l}){const o=pe(),c=G({mutationFn:({id:f,data:g})=>ec.update(f,g),onSuccess:()=>o.invalidateQueries({queryKey:["customer",e.toString()]})}),d=G({mutationFn:ec.delete,onSuccess:()=>o.invalidateQueries({queryKey:["customer",e.toString()]})}),u=async(f,g)=>{try{await ot.uploadIdentityDocument(f,g),o.invalidateQueries({queryKey:["customer",e.toString()]})}catch(v){console.error("Upload fehlgeschlagen:",v),alert("Upload fehlgeschlagen")}},h=async f=>{if(confirm("Dokument wirklich löschen?"))try{await ot.deleteIdentityDocument(f),o.invalidateQueries({queryKey:["customer",e.toString()]})}catch(g){console.error("Löschen fehlgeschlagen:",g),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(I,{size:"sm",onClick:i,children:[s.jsx(Ue,{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(_e,{className:"w-4 h-4 text-gray-400"}),s.jsx(ge,{children:m[f.type]}),!f.isActive&&s.jsx(ge,{variant:"danger",children:"Inaktiv"}),f.expiryDate&&new Date(f.expiryDate)l(f),title:"Bearbeiten",children:s.jsx(Xe,{className:"w-4 h-4"})}),f.isActive?s.jsx(I,{variant:"ghost",size:"sm",onClick:()=>{confirm("Ausweis deaktivieren?")&&c.mutate({id:f.id,data:{isActive:!1}})},title:"Deaktivieren",children:s.jsx(Mt,{className:"w-4 h-4"})}):s.jsx(I,{variant:"ghost",size:"sm",onClick:()=>{confirm("Ausweis wieder aktivieren?")&&c.mutate({id:f.id,data:{isActive:!0}})},title:"Aktivieren",children:s.jsx(Ae,{className:"w-4 h-4"})}),s.jsx(I,{variant:"ghost",size:"sm",onClick:()=>{confirm("Ausweis wirklich löschen?")&&d.mutate(f.id)},title:"Löschen",children:s.jsx(je,{className:"w-4 h-4 text-red-500"})})]})]}),s.jsxs("p",{className:"font-mono flex items-center gap-1",children:[f.documentNumber,s.jsx(oe,{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(oe,{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(oe,{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(Ae,{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(Ps,{className:"w-4 h-4"}),"Download"]}),n&&s.jsxs(s.Fragment,{children:[s.jsx(St,{onUpload:g=>u(f.id,g),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(je,{className:"w-4 h-4"}),"Löschen"]})]})]}):n&&f.isActive&&s.jsx(St,{onUpload:g=>u(f.id,g),accept:".pdf",label:"PDF hochladen"})})]},f.id))}):s.jsx("p",{className:"text-gray-500",children:"Keine Ausweise vorhanden."})]})}function fk({customerId:e,meters:t,canEdit:n,showInactive:r,onToggleInactive:a,onAdd:i,onEdit:l}){const[o,c]=b.useState(null),[d,u]=b.useState(null),[h,p]=b.useState(null),m=pe(),f=G({mutationFn:({id:y,data:N})=>an.update(y,N),onSuccess:()=>m.invalidateQueries({queryKey:["customer",e.toString()]})}),g=G({mutationFn:an.delete,onSuccess:()=>m.invalidateQueries({queryKey:["customer",e.toString()]})}),v=G({mutationFn:({meterId:y,readingId:N})=>an.deleteReading(y,N),onSuccess:()=>m.invalidateQueries({queryKey:["customer",e.toString()]})}),j=r?t:t.filter(y=>y.isActive),x=y=>y?[...y].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(I,{size:"sm",onClick:i,children:[s.jsx(Ue,{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"]})]}),j.length>0?s.jsx("div",{className:"space-y-4",children:j.map(y=>{const N=x(y.readings),D=d===y.id;return s.jsxs("div",{className:`border rounded-lg p-4 ${y.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(Sv,{className:"w-4 h-4 text-gray-400"}),s.jsx(ge,{variant:y.type==="ELECTRICITY"?"warning":"info",children:y.type==="ELECTRICITY"?"Strom":"Gas"}),!y.isActive&&s.jsx(ge,{variant:"danger",children:"Inaktiv"})]}),n&&s.jsxs("div",{className:"flex gap-1",children:[y.isActive&&s.jsx(I,{variant:"ghost",size:"sm",onClick:()=>c({meterId:y.id,meterType:y.type}),title:"Zählerstand hinzufügen",children:s.jsx(Ue,{className:"w-4 h-4"})}),s.jsx(I,{variant:"ghost",size:"sm",onClick:()=>l(y),title:"Bearbeiten",children:s.jsx(Xe,{className:"w-4 h-4"})}),y.isActive?s.jsx(I,{variant:"ghost",size:"sm",onClick:()=>{confirm("Zähler deaktivieren?")&&f.mutate({id:y.id,data:{isActive:!1}})},title:"Deaktivieren",children:s.jsx(Mt,{className:"w-4 h-4"})}):s.jsx(I,{variant:"ghost",size:"sm",onClick:()=>{confirm("Zähler wieder aktivieren?")&&f.mutate({id:y.id,data:{isActive:!0}})},title:"Aktivieren",children:s.jsx(Ae,{className:"w-4 h-4"})}),s.jsx(I,{variant:"ghost",size:"sm",onClick:()=>{confirm("Zähler wirklich löschen? Alle Zählerstände werden ebenfalls gelöscht.")&&g.mutate(y.id)},title:"Löschen",children:s.jsx(je,{className:"w-4 h-4 text-red-500"})})]})]}),s.jsxs("p",{className:"font-mono text-lg flex items-center gap-1",children:[y.meterNumber,s.jsx(oe,{value:y.meterNumber})]}),y.location&&s.jsxs("p",{className:"text-sm text-gray-500 flex items-center gap-1",children:["Standort: ",y.location,s.jsx(oe,{value:y.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(I,{variant:"ghost",size:"sm",onClick:()=>u(D?null:y.id),children:D?"Weniger anzeigen":`Alle ${N.length} anzeigen`})]}),s.jsx("div",{className:"space-y-1",children:(D?N:N.slice(0,3)).map(P=>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(P.readingDate).toLocaleDateString("de-DE"),s.jsx(oe,{value:new Date(P.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:[P.value.toLocaleString("de-DE")," ",P.unit,s.jsx(oe,{value:P.value.toString(),title:"Nur Wert kopieren"}),s.jsx(oe,{value:`${P.value.toLocaleString("de-DE")} ${P.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:y.id,meterType:y.type,reading:P}),className:"text-gray-400 hover:text-blue-600",title:"Bearbeiten",children:s.jsx(Xe,{className:"w-3 h-3"})}),s.jsx("button",{onClick:()=>{confirm("Zählerstand wirklich löschen?")&&v.mutate({meterId:y.id,readingId:P.id})},className:"text-gray-400 hover:text-red-600",title:"Löschen",children:s.jsx(je,{className:"w-3 h-3"})})]})]})]},P.id))})]})]},y.id)})}):s.jsx("p",{className:"text-gray-500",children:"Keine Zähler vorhanden."}),o&&s.jsx(yx,{isOpen:!0,onClose:()=>c(null),meterId:o.meterId,meterType:o.meterType,customerId:e}),h&&s.jsx(yx,{isOpen:!0,onClose:()=>p(null),meterId:h.meterId,meterType:h.meterType,customerId:e,reading:h.reading})]})}function pk({customerId:e}){const{hasPermission:t}=Qe(),n=Yt(),r=pe(),[a,i]=b.useState(new Set),[l,o]=b.useState(!1),{data:c,isLoading:d}=ue({queryKey:["contract-tree",e],queryFn:()=>$e.getTreeForCustomer(e)}),u=(c==null?void 0:c.data)||[],h=G({mutationFn:$e.delete,onSuccess:()=>{r.invalidateQueries({queryKey:["customer",e.toString()]}),r.invalidateQueries({queryKey:["customers"]}),r.invalidateQueries({queryKey:["contracts"]}),r.invalidateQueries({queryKey:["contract-tree",e]})},onError:x=>{alert((x==null?void 0:x.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"}],g=x=>{i(y=>{const N=new Set(y);return N.has(x)?N.delete(x):N.add(x),N})},v=(x,y)=>x.map(N=>s.jsx("div",{children:j(N,y)},N.contract.id)),j=(x,y=0)=>{var C,E,K,O,B,A,M;const{contract:N,predecessors:D,hasHistory:P}=x,F=a.has(N.id),w=y>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&&P?s.jsx("button",{onClick:()=>g(N.id),className:"p-1 hover:bg-gray-200 rounded transition-colors",title:F?"Einklappen":"Vorgänger anzeigen",children:F?s.jsx(Rn,{className:"w-4 h-4 text-gray-500"}):s.jsx(Pt,{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(oe,{value:N.contractNumber})]}),s.jsx(ge,{children:p[N.type]||N.type}),s.jsx(ge,{variant:m[N.status]||"default",children:N.status}),y===0&&!w&&s.jsx("button",{onClick:S=>{S.stopPropagation(),o(!0)},className:"text-gray-400 hover:text-blue-600 transition-colors",title:"Status-Erklärung",children:s.jsx(Al,{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(I,{variant:"ghost",size:"sm",onClick:()=>n(`/contracts/${N.id}`,{state:{from:"customer",customerId:e.toString()}}),title:"Ansehen",children:s.jsx(Ae,{className:"w-4 h-4"})}),t("contracts:update")&&s.jsx(I,{variant:"ghost",size:"sm",onClick:()=>n(`/contracts/${N.id}/edit`),title:"Bearbeiten",children:s.jsx(Xe,{className:"w-4 h-4"})}),t("contracts:delete")&&s.jsx(I,{variant:"ghost",size:"sm",onClick:()=>{confirm("Vertrag wirklich löschen?")&&h.mutate(N.id)},title:"Löschen",children:s.jsx(je,{className:"w-4 h-4 text-red-500"})})]})]}),(N.providerName||((C=N.provider)==null?void 0:C.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||((K=N.tariff)==null?void 0:K.name))&&` - ${N.tariffName||((O=N.tariff)==null?void 0:O.name)}`,s.jsx(oe,{value:(N.providerName||((B=N.provider)==null?void 0:B.name)||"")+(N.tariffName||(A=N.tariff)!=null&&A.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")}`]})]}),(y===0&&F||y>0)&&D.length>0&&s.jsx("div",{className:"mt-2",children:v(D,y+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(I,{size:"sm",children:[s.jsx(Ue,{className:"w-4 h-4 mr-2"}),"Vertrag anlegen"]})})}),u.length>0?s.jsx("div",{className:"space-y-4",children:u.map(x=>j(x,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(Zt,{className:"w-4 h-4"})})]}),s.jsx("div",{className:"space-y-2",children:f.map(({status:x,label:y,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:y}),s.jsx("span",{className:"text-sm text-gray-600",children:N})]},x))})]})]})]})}function xk({customerId:e}){const[t,n]=b.useState(!1),[r,a]=b.useState(null),[i,l]=b.useState(!1),o=async()=>{var c;if(t){n(!1);return}l(!0);try{const d=await kt.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(Mt,{className:"w-3 h-3"}),"Verbergen"]}):s.jsxs(s.Fragment,{children:[s.jsx(Ae,{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(oe,{value:r})]}),t&&!r&&s.jsx("span",{className:"text-xs text-gray-500",children:"(Passwort nicht verfügbar)"})]})}function gk({customerId:e,canEdit:t}){const n=pe(),[r,a]=b.useState(!1),[i,l]=b.useState(""),[o,c]=b.useState(""),[d,u]=b.useState([]),[h,p]=b.useState(!1),{data:m,isLoading:f}=ue({queryKey:["customer-portal",e],queryFn:()=>kt.getPortalSettings(e)}),{data:g,isLoading:v}=ue({queryKey:["customer-representatives",e],queryFn:()=>kt.getRepresentatives(e)}),j=G({mutationFn:w=>kt.updatePortalSettings(e,w),onSuccess:()=>{n.invalidateQueries({queryKey:["customer-portal",e]})}}),x=G({mutationFn:w=>kt.setPortalPassword(e,w),onSuccess:()=>{l(""),n.invalidateQueries({queryKey:["customer-portal",e]}),alert("Passwort wurde gesetzt")},onError:w=>{alert(w.message)}}),y=G({mutationFn:w=>kt.addRepresentative(e,w),onSuccess:()=>{n.invalidateQueries({queryKey:["customer-representatives",e]}),c(""),u([])},onError:w=>{alert(w.message)}}),N=G({mutationFn:w=>kt.removeRepresentative(e,w),onSuccess:()=>{n.invalidateQueries({queryKey:["customer-representatives",e]})}}),D=async()=>{if(!(o.length<2)){p(!0);try{const w=await kt.searchForRepresentative(e,o);u(w.data||[])}catch(w){console.error("Suche fehlgeschlagen:",w)}finally{p(!1)}}};if(f||v)return s.jsx("div",{className:"text-center py-4 text-gray-500",children:"Laden..."});const P=m==null?void 0:m.data,F=(g==null?void 0:g.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:(P==null?void 0:P.portalEnabled)||!1,onChange:w=>j.mutate({portalEnabled:w.target.checked}),className:"rounded w-5 h-5",disabled:!t}),s.jsx("span",{children:"Portal aktiviert"}),(P==null?void 0:P.portalEnabled)&&s.jsx(ge,{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(Q,{value:(P==null?void 0:P.portalEmail)||"",onChange:w=>j.mutate({portalEmail:w.target.value||null}),placeholder:"portal@example.com",disabled:!t||!(P!=null&&P.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."})]}),(P==null?void 0:P.portalEnabled)&&s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:P!=null&&P.hasPassword?"Neues Passwort setzen":"Passwort setzen"}),s.jsxs("div",{className:"flex gap-2",children:[s.jsxs("div",{className:"relative flex-1",children:[s.jsx(Q,{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(Mt,{className:"w-4 h-4"}):s.jsx(Ae,{className:"w-4 h-4"})})]}),s.jsx(I,{onClick:()=>x.mutate(i),disabled:!t||i.length<6||x.isPending,children:x.isPending?"Speichern...":"Setzen"})]}),(P==null?void 0:P.hasPassword)&&s.jsx(xk,{customerId:e})]}),(P==null?void 0:P.portalLastLogin)&&s.jsxs("p",{className:"text-sm text-gray-500",children:["Letzte Anmeldung: ",new Date(P.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(V2,{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(Q,{value:o,onChange:w=>c(w.target.value),placeholder:"Kunden suchen (Name, Kundennummer)...",onKeyDown:w=>w.key==="Enter"&&D(),className:"flex-1"}),s.jsx(I,{variant:"secondary",onClick:D,disabled:o.length<2||h,children:s.jsx(Pl,{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(I,{size:"sm",onClick:()=>y.mutate(w.id),disabled:y.isPending,children:[s.jsx(Ue,{className:"w-4 h-4 mr-1"}),"Hinzufügen"]})]},w.id))})]}),F.length>0?s.jsx("div",{className:"space-y-2",children:F.map(w=>{var C,E,K,O;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:((C=w.representative)==null?void 0:C.companyName)||`${(E=w.representative)==null?void 0:E.firstName} ${(K=w.representative)==null?void 0:K.lastName}`}),s.jsx("p",{className:"text-sm text-gray-500",children:(O=w.representative)==null?void 0:O.customerNumber})]}),t&&s.jsx(I,{variant:"ghost",size:"sm",onClick:()=>{confirm("Vertreter wirklich entfernen?")&&N.mutate(w.representativeId)},children:s.jsx(Zt,{className:"w-4 h-4 text-red-500"})})]},w.id)})}):s.jsx("p",{className:"text-gray-500 text-sm",children:"Keine Vertreter konfiguriert."})]})]})}function fx({isOpen:e,onClose:t,customerId:n,address:r}){const a=pe(),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]=b.useState(l),d=G({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=G({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(He,{isOpen:e,onClose:t,title:i?"Adresse bearbeiten":"Adresse hinzufügen",children:s.jsxs("form",{onSubmit:h,className:"space-y-4",children:[s.jsx(Le,{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(Q,{label:"Straße",value:o.street,onChange:m=>c({...o,street:m.target.value}),required:!0})}),s.jsx(Q,{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(Q,{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(Q,{label:"Ort",value:o.city,onChange:m=>c({...o,city:m.target.value}),required:!0})})]}),s.jsx(Q,{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(I,{type:"button",variant:"secondary",onClick:t,children:"Abbrechen"}),s.jsx(I,{type:"submit",disabled:p,children:p?"Speichern...":"Speichern"})]})]})})}function px({isOpen:e,onClose:t,customerId:n,bankCard:r}){const a=pe(),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]=b.useState(l);b.useState(()=>{c(l())});const d=G({mutationFn:m=>Yo.create(n,m),onSuccess:()=>{a.invalidateQueries({queryKey:["customer",n.toString()]}),t(),c({accountHolder:"",iban:"",bic:"",bankName:"",expiryDate:"",isActive:!0})}}),u=G({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(He,{isOpen:e,onClose:t,title:i?"Bankkarte bearbeiten":"Bankkarte hinzufügen",children:s.jsxs("form",{onSubmit:h,className:"space-y-4",children:[s.jsx(Q,{label:"Kontoinhaber",value:o.accountHolder,onChange:m=>c({...o,accountHolder:m.target.value}),required:!0}),s.jsx(Q,{label:"IBAN",value:o.iban,onChange:m=>c({...o,iban:m.target.value}),required:!0}),s.jsx(Q,{label:"BIC",value:o.bic,onChange:m=>c({...o,bic:m.target.value})}),s.jsx(Q,{label:"Bank",value:o.bankName,onChange:m=>c({...o,bankName:m.target.value})}),s.jsx(Q,{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(I,{type:"button",variant:"secondary",onClick:t,children:"Abbrechen"}),s.jsx(I,{type:"submit",disabled:p,children:p?"Speichern...":"Speichern"})]})]})})}function xx({isOpen:e,onClose:t,customerId:n,document:r}){const a=pe(),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]=b.useState(l),d=G({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=G({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(He,{isOpen:e,onClose:t,title:i?"Ausweis bearbeiten":"Ausweis hinzufügen",children:s.jsxs("form",{onSubmit:h,className:"space-y-4",children:[s.jsx(Le,{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(Q,{label:"Ausweisnummer",value:o.documentNumber,onChange:m=>c({...o,documentNumber:m.target.value}),required:!0}),s.jsx(Q,{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(Q,{label:"Ausstellungsdatum",type:"date",value:o.issueDate,onChange:m=>c({...o,issueDate:m.target.value}),onClear:()=>c({...o,issueDate:""})}),s.jsx(Q,{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(Q,{label:"Führerscheinklassen",value:o.licenseClasses,onChange:m=>c({...o,licenseClasses:m.target.value}),placeholder:"z.B. B, BE, AM, L"}),s.jsx(Q,{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(I,{type:"button",variant:"secondary",onClick:t,children:"Abbrechen"}),s.jsx(I,{type:"submit",disabled:p,children:p?"Speichern...":"Speichern"})]})]})})}function gx({isOpen:e,onClose:t,customerId:n,meter:r}){const a=pe(),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]=b.useState(l),d=G({mutationFn:m=>an.create(n,m),onSuccess:()=>{a.invalidateQueries({queryKey:["customer",n.toString()]}),t(),c({meterNumber:"",type:"ELECTRICITY",location:"",isActive:!0})}}),u=G({mutationFn:m=>an.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(He,{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(Q,{label:"Zählernummer",value:o.meterNumber,onChange:m=>c({...o,meterNumber:m.target.value}),required:!0}),s.jsx(Le,{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(Q,{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(I,{type:"button",variant:"secondary",onClick:t,children:"Abbrechen"}),s.jsx(I,{type:"submit",disabled:p,children:p?"Speichern...":"Speichern"})]})]})})}function yx({isOpen:e,onClose:t,meterId:n,meterType:r,customerId:a,reading:i}){const l=pe(),o=!!i,c=r==="ELECTRICITY"?"kWh":"m³",d=()=>{var v;return{readingDate:i!=null&&i.readingDate?new Date(i.readingDate).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],value:((v=i==null?void 0:i.value)==null?void 0:v.toString())||"",notes:(i==null?void 0:i.notes)||""}},[u,h]=b.useState(d),p=G({mutationFn:v=>an.addReading(n,v),onSuccess:()=>{l.invalidateQueries({queryKey:["customer",a.toString()]}),t()}}),m=G({mutationFn:v=>an.updateReading(n,i.id,v),onSuccess:()=>{l.invalidateQueries({queryKey:["customer",a.toString()]}),t()}}),f=v=>{v.preventDefault();const j={readingDate:new Date(u.readingDate),value:parseFloat(u.value),unit:c,notes:u.notes||void 0};o?m.mutate(j):p.mutate(j)},g=p.isPending||m.isPending;return o&&u.value!==i.value.toString()&&h(d()),s.jsx(He,{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(Q,{label:"Ablesedatum",type:"date",value:u.readingDate,onChange:v=>h({...u,readingDate:v.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(Q,{label:"Zählerstand",type:"number",step:"0.01",value:u.value,onChange:v=>h({...u,value:v.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(Q,{label:"Notizen",value:u.notes,onChange:v=>h({...u,notes:v.target.value}),placeholder:"Optionale Notizen..."}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx(I,{type:"button",variant:"secondary",onClick:t,children:"Abbrechen"}),s.jsx(I,{type:"submit",disabled:g,children:g?"Speichern...":"Speichern"})]})]})})}const pd="@stressfrei-wechseln.de";function yk({customerId:e,emails:t,canEdit:n,showInactive:r,onToggleInactive:a,onAdd:i,onEdit:l}){const o=pe(),c=G({mutationFn:({id:h,data:p})=>ps.update(h,p),onSuccess:()=>o.invalidateQueries({queryKey:["customer",e.toString()]})}),d=G({mutationFn:ps.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(I,{size:"sm",onClick:i,children:[s.jsx(Ue,{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(sn,{className:"w-4 h-4 text-gray-400"}),s.jsx("span",{className:"font-mono text-sm",children:h.email}),s.jsx(oe,{value:h.email}),!h.isActive&&s.jsx(ge,{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(_e,{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(I,{variant:"ghost",size:"sm",onClick:()=>l(h),title:"Bearbeiten",children:s.jsx(Xe,{className:"w-4 h-4"})}),h.isActive?s.jsx(I,{variant:"ghost",size:"sm",onClick:()=>{confirm("Adresse deaktivieren?")&&c.mutate({id:h.id,data:{isActive:!1}})},title:"Deaktivieren",children:s.jsx(Mt,{className:"w-4 h-4"})}):s.jsx(I,{variant:"ghost",size:"sm",onClick:()=>{confirm("Adresse wieder aktivieren?")&&c.mutate({id:h.id,data:{isActive:!0}})},title:"Aktivieren",children:s.jsx(Ae,{className:"w-4 h-4"})}),s.jsx(I,{variant:"ghost",size:"sm",onClick:()=>{confirm("Adresse wirklich löschen?")&&d.mutate(h.id)},title:"Löschen",children:s.jsx(je,{className:"w-4 h-4 text-red-500"})})]})]})},h.id))}):s.jsx("p",{className:"text-gray-500",children:"Keine Stressfrei-Wechseln Adressen vorhanden."})]})}function vk({credentials:e,onHide:t,onResetPassword:n,isResettingPassword:r}){const[a,i]=b.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(pr,{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(Mt,{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 vx({isOpen:e,onClose:t,customerId:n,email:r,customerEmail:a}){const[i,l]=b.useState(""),[o,c]=b.useState(""),[d,u]=b.useState(!1),[h,p]=b.useState(!1),[m,f]=b.useState(null),[g,v]=b.useState("idle"),[j,x]=b.useState(!1),[y,N]=b.useState(!1),[D,P]=b.useState(!1),[F,w]=b.useState(!1),[C,E]=b.useState(null),[K,O]=b.useState(!1),[B,A]=b.useState(!1),M=pe(),S=!!r,{data:_}=ue({queryKey:["email-provider-configs"],queryFn:()=>xn.getConfigs(),enabled:e}),U=((_==null?void 0:_.data)||[]).some(z=>z.isActive&&z.isDefault),Z=z=>{if(!z)return"";const Ne=z.indexOf("@");return Ne>0?z.substring(0,Ne):z},W=async z=>{var Ne;if(!(!U||!z)){v("checking");try{const Be=await xn.checkEmailExists(z);v((Ne=Be.data)!=null&&Ne.exists?"exists":"not_exists")}catch{v("error")}}},fe=async()=>{var z,Ne;if(!(!a||!i)){x(!0),f(null);try{const Be=await xn.provisionEmail(i,a);(z=Be.data)!=null&&z.success?v("exists"):f(((Ne=Be.data)==null?void 0:Ne.error)||"Provisionierung fehlgeschlagen")}catch(Be){f(Be instanceof Error?Be.message:"Fehler bei der Provisionierung")}finally{x(!1)}}},le=async()=>{if(r){N(!0),f(null);try{const z=await ps.enableMailbox(r.id);z.success?(P(!0),M.invalidateQueries({queryKey:["customer",n.toString()]}),M.invalidateQueries({queryKey:["mailbox-accounts",n]})):f(z.error||"Mailbox-Aktivierung fehlgeschlagen")}catch(z){f(z instanceof Error?z.message:"Fehler bei der Mailbox-Aktivierung")}finally{N(!1)}}},k=async()=>{if(r)try{const z=await ps.syncMailboxStatus(r.id);z.success&&z.data&&(P(z.data.hasMailbox),z.data.wasUpdated&&M.invalidateQueries({queryKey:["customer",n.toString()]}))}catch(z){console.error("Fehler beim Synchronisieren des Mailbox-Status:",z)}},Re=async()=>{if(r){O(!0);try{const z=await ps.getMailboxCredentials(r.id);z.success&&z.data&&(E(z.data),w(!0))}catch(z){console.error("Fehler beim Laden der Zugangsdaten:",z)}finally{O(!1)}}},Ye=async()=>{if(r&&confirm("Neues Passwort generieren? Das alte Passwort wird ungültig.")){A(!0);try{const z=await ps.resetPassword(r.id);z.success&&z.data?(C&&E({...C,password:z.data.password}),alert("Passwort wurde erfolgreich zurückgesetzt.")):alert(z.error||"Fehler beim Zurücksetzen des Passworts")}catch(z){console.error("Fehler beim Zurücksetzen des Passworts:",z),alert(z instanceof Error?z.message:"Fehler beim Zurücksetzen des Passworts")}finally{A(!1)}}};b.useEffect(()=>{if(e){if(r){const z=Z(r.email);l(z),c(r.notes||""),v("idle"),P(r.hasMailbox||!1),U&&(W(z),k())}else l(""),c(""),u(!1),p(!1),v("idle"),P(!1);f(null),w(!1),E(null)}},[e,r,U]);const qe=G({mutationFn:async z=>ps.create(n,{email:z.email,notes:z.notes,provisionAtProvider:z.provision,createMailbox:z.createMailbox}),onSuccess:()=>{M.invalidateQueries({queryKey:["customer",n.toString()]}),M.invalidateQueries({queryKey:["mailbox-accounts",n]}),l(""),c(""),u(!1),p(!1),t()},onError:z=>{f(z instanceof Error?z.message:"Fehler bei der Provisionierung")}}),et=G({mutationFn:z=>ps.update(r.id,z),onSuccess:()=>{M.invalidateQueries({queryKey:["customer",n.toString()]}),t()}}),Rt=z=>{z.preventDefault(),f(null);const Ne=i+pd;S?et.mutate({email:Ne,notes:o||void 0}):qe.mutate({email:Ne,notes:o||void 0,provision:d,createMailbox:d&&h})},Bt=qe.isPending||et.isPending;return s.jsx(He,{isOpen:e,onClose:t,title:S?"Adresse bearbeiten":"Adresse hinzufügen",children:s.jsxs("form",{onSubmit:Rt,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:z=>l(z.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:z=>c(z.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..."})]}),U&&a&&s.jsx("div",{className:"bg-blue-50 p-3 rounded-lg",children:S?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"}),g==="checking"&&s.jsx("span",{className:"text-xs text-gray-500",children:"Prüfe..."}),g==="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"]}),g==="not_exists"&&s.jsx("span",{className:"text-xs text-orange-600",children:"Nicht beim Provider angelegt"}),g==="error"&&s.jsx("span",{className:"text-xs text-red-600",children:"Status konnte nicht geprüft werden"})]}),g==="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(I,{type:"button",size:"sm",onClick:fe,disabled:j,children:j?"Wird angelegt...":"Jetzt beim Provider anlegen"})]}),g==="error"&&s.jsx(I,{type:"button",size:"sm",variant:"secondary",onClick:()=>W(i),children:"Erneut prüfen"}),g==="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(I,{type:"button",size:"sm",onClick:le,disabled:y,children:y?"Wird aktiviert...":"Mailbox aktivieren"})]}),D&&s.jsx("div",{className:"mt-3",children:F?C&&s.jsx(vk,{credentials:C,onHide:()=>w(!1),onResetPassword:Ye,isResettingPassword:B}):s.jsx(I,{type:"button",size:"sm",variant:"secondary",onClick:Re,disabled:K,children:K?"Laden...":s.jsxs(s.Fragment,{children:[s.jsx(Ae,{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:z=>{u(z.target.checked),z.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:z=>p(z.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(I,{type:"button",variant:"secondary",onClick:t,children:"Abbrechen"}),s.jsx(I,{type:"submit",disabled:Bt||!i,children:Bt?"Speichern...":"Speichern"})]})]})})}var Fl=e=>e.type==="checkbox",Ar=e=>e instanceof Date,rs=e=>e==null;const Rv=e=>typeof e=="object";var xt=e=>!rs(e)&&!Array.isArray(e)&&Rv(e)&&!Ar(e),jk=e=>xt(e)&&e.target?Fl(e.target)?e.target.checked:e.target.value:e,bk=e=>e.substring(0,e.search(/\.\d+(\.|$)/))||e,Nk=(e,t)=>e.has(bk(t)),wk=e=>{const t=e.constructor&&e.constructor.prototype;return xt(t)&&t.hasOwnProperty("isPrototypeOf")},fh=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function yt(e){if(e instanceof Date)return new Date(e);const t=typeof FileList<"u"&&e instanceof FileList;if(fh&&(e instanceof Blob||t))return e;const n=Array.isArray(e);if(!n&&!(xt(e)&&wk(e)))return e;const r=n?[]:Object.create(Object.getPrototypeOf(e));for(const a in e)Object.prototype.hasOwnProperty.call(e,a)&&(r[a]=yt(e[a]));return r}var Ic=e=>/^\w*$/.test(e),tt=e=>e===void 0,ph=e=>Array.isArray(e)?e.filter(Boolean):[],xh=e=>ph(e.replace(/["|']|\]/g,"").split(/\.|\[/)),he=(e,t,n)=>{if(!t||!xt(e))return n;const r=(Ic(t)?[t]:xh(t)).reduce((a,i)=>rs(a)?a:a[i],e);return tt(r)||r===e?tt(e[t])?n:e[t]:r},Zs=e=>typeof e=="boolean",_s=e=>typeof e=="function",Ze=(e,t,n)=>{let r=-1;const a=Ic(t)?[t]:xh(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]!==Ks.all&&(t._proxyFormState[l]=!r||Ks.all),e[l]}});return a};const Ck=typeof window<"u"?At.useLayoutEffect:At.useEffect;var xs=e=>typeof e=="string",Ek=(e,t,n,r,a)=>xs(e)?(r&&t.watch.add(e),he(n,e,a)):Array.isArray(e)?e.map(i=>(r&&t.watch.add(i),he(n,i))):(r&&(t.watchAll=!0),n),Hu=e=>rs(e)||!Rv(e);function Bn(e,t,n=new WeakSet){if(Hu(e)||Hu(t))return Object.is(e,t);if(Ar(e)&&Ar(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(Ar(l)&&Ar(o)||xt(l)&&xt(o)||Array.isArray(l)&&Array.isArray(o)?!Bn(l,o,n):!Object.is(l,o))return!1}}return!0}const Dk=At.createContext(null);Dk.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],bx=()=>{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 Lv(e,t){const n={};for(const r in e)if(e.hasOwnProperty(r)){const a=e[r],i=t[r];if(a&&xt(a)&&i){const l=Lv(a,i);xt(l)&&(n[r]=l)}else e[r]&&(n[r]=i)}return n}var Ht=e=>xt(e)&&!Object.keys(e).length,gh=e=>e.type==="file",tc=e=>{if(!fh)return!1;const t=e?e.ownerDocument:0;return e instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},Ov=e=>e.type==="select-multiple",yh=e=>e.type==="radio",Pk=e=>yh(e)||Fl(e),xd=e=>tc(e)&&e.isConnected;function Mk(e,t){const n=t.slice(0,-1).length;let r=0;for(;r{for(const t in e)if(_s(e[t]))return!0;return!1};function zv(e){return Array.isArray(e)||xt(e)&&!Fk(e)}function Wu(e,t={}){for(const n in e){const r=e[n];zv(r)?(t[n]=Array.isArray(r)?[]:{},Wu(r,t[n])):tt(r)||(t[n]=!0)}return t}function ra(e,t,n){n||(n=Wu(t));for(const r in e){const a=e[r];if(zv(a))tt(t)||Hu(n[r])?n[r]=Wu(a,Array.isArray(a)?[]:{}):ra(a,rs(t)?{}:t[r],n[r]);else{const i=t[r];n[r]=!Bn(a,i)}}return n}const Nx={value:!1,isValid:!1},wx={value:!0,isValid:!0};var $v=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===""?wx:{value:e[0].value,isValid:!0}:wx:Nx}return Nx},_v=(e,{valueAsNumber:t,valueAsDate:n,setValueAs:r})=>tt(e)?e:t?e===""?NaN:e&&+e:n&&xs(e)?new Date(e):r?r(e):e;const Sx={isValid:!1,value:null};var Kv=e=>Array.isArray(e)?e.reduce((t,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:t,Sx):Sx;function kx(e){const t=e.ref;return gh(t)?t.files:yh(t)?Kv(e.refs).value:Ov(t)?[...t.selectedOptions].map(({value:n})=>n):Fl(t)?$v(e.refs).value:_v(tt(t.value)?e.ref.value:t.value,e)}var Ik=(e,t,n,r)=>{const a={};for(const i of e){const l=he(t,i);l&&Ze(a,i,l._f)}return{criteriaMode:n,names:[...e],fields:a,shouldUseNativeValidation:r}},sc=e=>e instanceof RegExp,gi=e=>tt(e)?e:sc(e)?e.source:xt(e)?sc(e.value)?e.value.source:e.value:e,Cx=e=>({isOnSubmit:!e||e===Ks.onSubmit,isOnBlur:e===Ks.onBlur,isOnChange:e===Ks.onChange,isOnAll:e===Ks.all,isOnTouch:e===Ks.onTouched});const Ex="AsyncFunction";var Rk=e=>!!e&&!!e.validate&&!!(_s(e.validate)&&e.validate.constructor.name===Ex||xt(e.validate)&&Object.values(e.validate).find(t=>t.constructor.name===Ex)),Lk=e=>e.mount&&(e.required||e.min||e.max||e.maxLength||e.minLength||e.pattern||e.validate),Dx=(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=he(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(xt(o)&&Li(o,t))break}}};function Ax(e,t,n){const r=he(e,n);if(r||Ic(n))return{error:r,name:n};const a=n.split(".");for(;a.length;){const i=a.join("."),l=he(t,i),o=he(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 Ok=(e,t,n,r)=>{n(e);const{name:a,...i}=e;return Ht(i)||Object.keys(i).length>=Object.keys(t).length||Object.keys(i).find(l=>t[l]===(!r||Ks.all))},zk=(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,_k=(e,t)=>!ph(he(e,t)).length&&ft(e,t),Kk=(e,t,n)=>{const r=Ri(he(e,n));return Ze(r,"root",t[n]),Ze(e,n,r),e};function Px(e,t,n="validate"){if(xs(e)||Array.isArray(e)&&e.every(xs)||Zs(e)&&!e)return{type:n,message:xs(e)?e:"",ref:t}}var na=e=>xt(e)&&!sc(e)?e:{value:e,message:""},Mx=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:g,valueAsNumber:v,mount:j}=e._f,x=he(n,g);if(!j||t.has(g))return{};const y=o?o[0]:l,N=O=>{a&&y.reportValidity&&(y.setCustomValidity(Zs(O)?"":O||""),y.reportValidity())},D={},P=yh(l),F=Fl(l),w=P||F,C=(v||gh(l))&&tt(l.value)&&tt(x)||tc(l)&&l.value===""||x===""||Array.isArray(x)&&!x.length,E=Ak.bind(null,g,r,D),K=(O,B,A,M=mn.maxLength,S=mn.minLength)=>{const _=O?B:A;D[g]={type:O?M:S,message:_,ref:l,...E(O?M:S,_)}};if(i?!Array.isArray(x)||!x.length:c&&(!w&&(C||rs(x))||Zs(x)&&!x||F&&!$v(o).isValid||P&&!Kv(o).isValid)){const{value:O,message:B}=xs(c)?{value:!!c,message:c}:na(c);if(O&&(D[g]={type:mn.required,message:B,ref:y,...E(mn.required,B)},!r))return N(B),D}if(!C&&(!rs(h)||!rs(p))){let O,B;const A=na(p),M=na(h);if(!rs(x)&&!isNaN(x)){const S=l.valueAsNumber||x&&+x;rs(A.value)||(O=S>A.value),rs(M.value)||(B=Snew Date(new Date().toDateString()+" "+W),U=l.type=="time",Z=l.type=="week";xs(A.value)&&x&&(O=U?_(x)>_(A.value):Z?x>A.value:S>new Date(A.value)),xs(M.value)&&x&&(B=U?_(x)<_(M.value):Z?x+O.value,M=!rs(B.value)&&x.length<+B.value;if((A||M)&&(K(A,O.message,B.message),!r))return N(D[g].message),D}if(m&&!C&&xs(x)){const{value:O,message:B}=na(m);if(sc(O)&&!x.match(O)&&(D[g]={type:mn.pattern,message:B,ref:l,...E(mn.pattern,B)},!r))return N(B),D}if(f){if(_s(f)){const O=await f(x,n),B=Px(O,y);if(B&&(D[g]={...B,...E(mn.validate,B.message)},!r))return N(B.message),D}else if(xt(f)){let O={};for(const B in f){if(!Ht(O)&&!r)break;const A=Px(await f[B](x,n),y,B);A&&(O={...A,...E(B,A.message)},N(A.message),r&&(D[g]=O))}if(!Ht(O)&&(D[g]={ref:y,...O},!r))return D}}return N(!0),D};const Uk={mode:Ks.onSubmit,reValidateMode:Ks.onChange,shouldFocusError:!0};function Bk(e={}){let t={...Uk,...e},n={submitCount:0,isDirty:!1,isReady:!1,isLoading:_s(t.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{},errors:t.errors||{},disabled:t.disabled||!1},r={},a=xt(t.defaultValues)||xt(t.values)?yt(t.defaultValues||t.values)||{}:{},i=t.shouldUnregister?{}:yt(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:bx(),state:bx()},f=t.criteriaMode===Ks.all,g=L=>q=>{clearTimeout(d),d=setTimeout(L,q)},v=async L=>{if(!l.keepIsValid&&!t.disabled&&(h.isValid||p.isValid||L)){let q;t.resolver?(q=Ht((await w()).errors),j()):q=await E(r,!0),q!==n.isValid&&m.state.next({isValid:q})}},j=(L,q)=>{!t.disabled&&(h.isValidating||h.validatingFields||p.isValidating||p.validatingFields)&&((L||Array.from(o.mount)).forEach(H=>{H&&(q?Ze(n.validatingFields,H,q):ft(n.validatingFields,H))}),m.state.next({validatingFields:n.validatingFields,isValidating:!Ht(n.validatingFields)}))},x=(L,q=[],H,ie,se=!0,ee=!0)=>{if(ie&&H&&!t.disabled){if(l.action=!0,ee&&Array.isArray(he(r,L))){const xe=H(he(r,L),ie.argA,ie.argB);se&&Ze(r,L,xe)}if(ee&&Array.isArray(he(n.errors,L))){const xe=H(he(n.errors,L),ie.argA,ie.argB);se&&Ze(n.errors,L,xe),_k(n.errors,L)}if((h.touchedFields||p.touchedFields)&&ee&&Array.isArray(he(n.touchedFields,L))){const xe=H(he(n.touchedFields,L),ie.argA,ie.argB);se&&Ze(n.touchedFields,L,xe)}(h.dirtyFields||p.dirtyFields)&&(n.dirtyFields=ra(a,i)),m.state.next({name:L,isDirty:O(L,q),dirtyFields:n.dirtyFields,errors:n.errors,isValid:n.isValid})}else Ze(i,L,q)},y=(L,q)=>{Ze(n.errors,L,q),m.state.next({errors:n.errors})},N=L=>{n.errors=L,m.state.next({errors:n.errors,isValid:!1})},D=(L,q,H,ie)=>{const se=he(r,L);if(se){const ee=he(i,L,tt(H)?he(a,L):H);tt(ee)||ie&&ie.defaultChecked||q?Ze(i,L,q?ee:kx(se._f)):M(L,ee),l.mount&&!l.action&&v()}},P=(L,q,H,ie,se)=>{let ee=!1,xe=!1;const Te={name:L};if(!t.disabled){if(!H||ie){(h.isDirty||p.isDirty)&&(xe=n.isDirty,n.isDirty=Te.isDirty=O(),ee=xe!==Te.isDirty);const Fe=Bn(he(a,L),q);xe=!!he(n.dirtyFields,L),Fe?ft(n.dirtyFields,L):Ze(n.dirtyFields,L,!0),Te.dirtyFields=n.dirtyFields,ee=ee||(h.dirtyFields||p.dirtyFields)&&xe!==!Fe}if(H){const Fe=he(n.touchedFields,L);Fe||(Ze(n.touchedFields,L,H),Te.touchedFields=n.touchedFields,ee=ee||(h.touchedFields||p.touchedFields)&&Fe!==H)}ee&&se&&m.state.next(Te)}return ee?Te:{}},F=(L,q,H,ie)=>{const se=he(n.errors,L),ee=(h.isValid||p.isValid)&&Zs(q)&&n.isValid!==q;if(t.delayError&&H?(c=g(()=>y(L,H)),c(t.delayError)):(clearTimeout(d),c=null,H?Ze(n.errors,L,H):ft(n.errors,L)),(H?!Bn(se,H):se)||!Ht(ie)||ee){const xe={...ie,...ee&&Zs(q)?{isValid:q}:{},errors:n.errors,name:L};n={...n,...xe},m.state.next(xe)}},w=async L=>(j(L,!0),await t.resolver(i,t.context,Ik(L||o.mount,r,t.criteriaMode,t.shouldUseNativeValidation))),C=async L=>{const{errors:q}=await w(L);if(j(L),L)for(const H of L){const ie=he(q,H);ie?Ze(n.errors,H,ie):ft(n.errors,H)}else n.errors=q;return q},E=async(L,q,H={valid:!0})=>{for(const ie in L){const se=L[ie];if(se){const{_f:ee,...xe}=se;if(ee){const Te=o.array.has(ee.name),Fe=se._f&&Rk(se._f);Fe&&h.validatingFields&&j([ee.name],!0);const Et=await Mx(se,o.disabled,i,f,t.shouldUseNativeValidation&&!q,Te);if(Fe&&h.validatingFields&&j([ee.name]),Et[ee.name]&&(H.valid=!1,q||e.shouldUseNativeValidation))break;!q&&(he(Et,ee.name)?Te?Kk(n.errors,Et,ee.name):Ze(n.errors,ee.name,Et[ee.name]):ft(n.errors,ee.name))}!Ht(xe)&&await E(xe,q,H)}}return H.valid},K=()=>{for(const L of o.unMount){const q=he(r,L);q&&(q._f.refs?q._f.refs.every(H=>!xd(H)):!xd(q._f.ref))&&Rt(L)}o.unMount=new Set},O=(L,q)=>!t.disabled&&(L&&q&&Ze(i,L,q),!Bn(fe(),a)),B=(L,q,H)=>Ek(L,o,{...l.mount?i:tt(q)?a:xs(L)?{[L]:q}:q},H,q),A=L=>ph(he(l.mount?i:a,L,t.shouldUnregister?he(a,L,[]):[])),M=(L,q,H={})=>{const ie=he(r,L);let se=q;if(ie){const ee=ie._f;ee&&(!ee.disabled&&Ze(i,L,_v(q,ee)),se=tc(ee.ref)&&rs(q)?"":q,Ov(ee.ref)?[...ee.ref.options].forEach(xe=>xe.selected=se.includes(xe.value)):ee.refs?Fl(ee.ref)?ee.refs.forEach(xe=>{(!xe.defaultChecked||!xe.disabled)&&(Array.isArray(se)?xe.checked=!!se.find(Te=>Te===xe.value):xe.checked=se===xe.value||!!se)}):ee.refs.forEach(xe=>xe.checked=xe.value===se):gh(ee.ref)?ee.ref.value="":(ee.ref.value=se,ee.ref.type||m.state.next({name:L,values:yt(i)})))}(H.shouldDirty||H.shouldTouch)&&P(L,se,H.shouldTouch,H.shouldDirty,!0),H.shouldValidate&&W(L)},S=(L,q,H)=>{for(const ie in q){if(!q.hasOwnProperty(ie))return;const se=q[ie],ee=L+"."+ie,xe=he(r,ee);(o.array.has(L)||xt(se)||xe&&!xe._f)&&!Ar(se)?S(ee,se,H):M(ee,se,H)}},_=(L,q,H={})=>{const ie=he(r,L),se=o.array.has(L),ee=yt(q);Ze(i,L,ee),se?(m.array.next({name:L,values:yt(i)}),(h.isDirty||h.dirtyFields||p.isDirty||p.dirtyFields)&&H.shouldDirty&&m.state.next({name:L,dirtyFields:ra(a,i),isDirty:O(L,ee)})):ie&&!ie._f&&!rs(ee)?S(L,ee,H):M(L,ee,H),Dx(L,o)?m.state.next({...n,name:L,values:yt(i)}):m.state.next({name:l.mount?L:void 0,values:yt(i)})},U=async L=>{l.mount=!0;const q=L.target;let H=q.name,ie=!0;const se=he(r,H),ee=Fe=>{ie=Number.isNaN(Fe)||Ar(Fe)&&isNaN(Fe.getTime())||Bn(Fe,he(i,H,Fe))},xe=Cx(t.mode),Te=Cx(t.reValidateMode);if(se){let Fe,Et;const dn=q.type?kx(se._f):jk(L),qt=L.type===jx.BLUR||L.type===jx.FOCUS_OUT,Rc=!Lk(se._f)&&!t.resolver&&!he(n.errors,H)&&!se._f.deps||$k(qt,he(n.touchedFields,H),n.isSubmitted,Te,xe),ta=Dx(H,o,qt);Ze(i,H,dn),qt?(!q||!q.readOnly)&&(se._f.onBlur&&se._f.onBlur(L),c&&c(0)):se._f.onChange&&se._f.onChange(L);const ri=P(H,dn,qt),Il=!Ht(ri)||ta;if(!qt&&m.state.next({name:H,type:L.type,values:yt(i)}),Rc)return(h.isValid||p.isValid)&&(t.mode==="onBlur"?qt&&v():qt||v()),Il&&m.state.next({name:H,...ta?{}:ri});if(!qt&&ta&&m.state.next({...n}),t.resolver){const{errors:ai}=await w([H]);if(j([H]),ee(dn),ie){const Rl=Ax(n.errors,r,H),ii=Ax(ai,r,Rl.name||H);Fe=ii.error,H=ii.name,Et=Ht(ai)}}else j([H],!0),Fe=(await Mx(se,o.disabled,i,f,t.shouldUseNativeValidation))[H],j([H]),ee(dn),ie&&(Fe?Et=!1:(h.isValid||p.isValid)&&(Et=await E(r,!0)));ie&&(se._f.deps&&(!Array.isArray(se._f.deps)||se._f.deps.length>0)&&W(se._f.deps),F(H,Et,Fe,ri))}},Z=(L,q)=>{if(he(n.errors,q)&&L.focus)return L.focus(),1},W=async(L,q={})=>{let H,ie;const se=Ri(L);if(t.resolver){const ee=await C(tt(L)?L:se);H=Ht(ee),ie=L?!se.some(xe=>he(ee,xe)):H}else L?(ie=(await Promise.all(se.map(async ee=>{const xe=he(r,ee);return await E(xe&&xe._f?{[ee]:xe}:xe)}))).every(Boolean),!(!ie&&!n.isValid)&&v()):ie=H=await E(r);return m.state.next({...!xs(L)||(h.isValid||p.isValid)&&H!==n.isValid?{}:{name:L},...t.resolver||!L?{isValid:H}:{},errors:n.errors}),q.shouldFocus&&!ie&&Li(r,Z,L?se:o.mount),ie},fe=(L,q)=>{let H={...l.mount?i:a};return q&&(H=Lv(q.dirtyFields?n.dirtyFields:n.touchedFields,H)),tt(L)?H:xs(L)?he(H,L):L.map(ie=>he(H,ie))},le=(L,q)=>({invalid:!!he((q||n).errors,L),isDirty:!!he((q||n).dirtyFields,L),error:he((q||n).errors,L),isValidating:!!he(n.validatingFields,L),isTouched:!!he((q||n).touchedFields,L)}),k=L=>{L&&Ri(L).forEach(q=>ft(n.errors,q)),m.state.next({errors:L?n.errors:{}})},Re=(L,q,H)=>{const ie=(he(r,L,{_f:{}})._f||{}).ref,se=he(n.errors,L)||{},{ref:ee,message:xe,type:Te,...Fe}=se;Ze(n.errors,L,{...Fe,...q,ref:ie}),m.state.next({name:L,errors:n.errors,isValid:!1}),H&&H.shouldFocus&&ie&&ie.focus&&ie.focus()},Ye=(L,q)=>_s(L)?m.state.subscribe({next:H=>"values"in H&&L(B(void 0,q),H)}):B(L,q,!0),qe=L=>m.state.subscribe({next:q=>{zk(L.name,q.name,L.exact)&&Ok(q,L.formState||h,on,L.reRenderRoot)&&L.callback({values:{...i},...n,...q,defaultValues:a})}}).unsubscribe,et=L=>(l.mount=!0,p={...p,...L.formState},qe({...L,formState:{...u,...L.formState}})),Rt=(L,q={})=>{for(const H of L?Ri(L):o.mount)o.mount.delete(H),o.array.delete(H),q.keepValue||(ft(r,H),ft(i,H)),!q.keepError&&ft(n.errors,H),!q.keepDirty&&ft(n.dirtyFields,H),!q.keepTouched&&ft(n.touchedFields,H),!q.keepIsValidating&&ft(n.validatingFields,H),!t.shouldUnregister&&!q.keepDefaultValue&&ft(a,H);m.state.next({values:yt(i)}),m.state.next({...n,...q.keepDirty?{isDirty:O()}:{}}),!q.keepIsValid&&v()},Bt=({disabled:L,name:q})=>{if(Zs(L)&&l.mount||L||o.disabled.has(q)){const se=o.disabled.has(q)!==!!L;L?o.disabled.add(q):o.disabled.delete(q),se&&l.mount&&!l.action&&v()}},z=(L,q={})=>{let H=he(r,L);const ie=Zs(q.disabled)||Zs(t.disabled);return Ze(r,L,{...H||{},_f:{...H&&H._f?H._f:{ref:{name:L}},name:L,mount:!0,...q}}),o.mount.add(L),H?Bt({disabled:Zs(q.disabled)?q.disabled:t.disabled,name:L}):D(L,!0,q.value),{...ie?{disabled:q.disabled||t.disabled}:{},...t.progressive?{required:!!q.required,min:gi(q.min),max:gi(q.max),minLength:gi(q.minLength),maxLength:gi(q.maxLength),pattern:gi(q.pattern)}:{},name:L,onChange:U,onBlur:U,ref:se=>{if(se){z(L,q),H=he(r,L);const ee=tt(se.value)&&se.querySelectorAll&&se.querySelectorAll("input,select,textarea")[0]||se,xe=Pk(ee),Te=H._f.refs||[];if(xe?Te.find(Fe=>Fe===ee):ee===H._f.ref)return;Ze(r,L,{_f:{...H._f,...xe?{refs:[...Te.filter(xd),ee,...Array.isArray(he(a,L))?[{}]:[]],ref:{type:ee.type,name:L}}:{ref:ee}}}),D(L,!1,void 0,ee)}else H=he(r,L,{}),H._f&&(H._f.mount=!1),(t.shouldUnregister||q.shouldUnregister)&&!(Nk(o.array,L)&&l.action)&&o.unMount.add(L)}}},Ne=()=>t.shouldFocusError&&Li(r,Z,o.mount),Be=L=>{Zs(L)&&(m.state.next({disabled:L}),Li(r,(q,H)=>{const ie=he(r,H);ie&&(q.disabled=ie._f.disabled||L,Array.isArray(ie._f.refs)&&ie._f.refs.forEach(se=>{se.disabled=ie._f.disabled||L}))},0,!1))},es=(L,q)=>async H=>{let ie;H&&(H.preventDefault&&H.preventDefault(),H.persist&&H.persist());let se=yt(i);if(m.state.next({isSubmitting:!0}),t.resolver){const{errors:ee,values:xe}=await w();j(),n.errors=ee,se=yt(xe)}else await E(r);if(o.disabled.size)for(const ee of o.disabled)ft(se,ee);if(ft(n.errors,"root"),Ht(n.errors)){m.state.next({errors:{}});try{await L(se,H)}catch(ee){ie=ee}}else q&&await q({...n.errors},H),Ne(),setTimeout(Ne);if(m.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:Ht(n.errors)&&!ie,submitCount:n.submitCount+1,errors:n.errors}),ie)throw ie},Lt=(L,q={})=>{he(r,L)&&(tt(q.defaultValue)?_(L,yt(he(a,L))):(_(L,q.defaultValue),Ze(a,L,yt(q.defaultValue))),q.keepTouched||ft(n.touchedFields,L),q.keepDirty||(ft(n.dirtyFields,L),n.isDirty=q.defaultValue?O(L,yt(he(a,L))):O()),q.keepError||(ft(n.errors,L),h.isValid&&v()),m.state.next({...n}))},Ns=(L,q={})=>{const H=L?yt(L):a,ie=yt(H),se=Ht(L),ee=se?a:ie;if(q.keepDefaultValues||(a=H),!q.keepValues){if(q.keepDirtyValues){const xe=new Set([...o.mount,...Object.keys(ra(a,i))]);for(const Te of Array.from(xe)){const Fe=he(n.dirtyFields,Te),Et=he(i,Te),dn=he(ee,Te);Fe&&!tt(Et)?Ze(ee,Te,Et):!Fe&&!tt(dn)&&_(Te,dn)}}else{if(fh&&tt(L))for(const xe of o.mount){const Te=he(r,xe);if(Te&&Te._f){const Fe=Array.isArray(Te._f.refs)?Te._f.refs[0]:Te._f.ref;if(tc(Fe)){const Et=Fe.closest("form");if(Et){Et.reset();break}}}}if(q.keepFieldsRef)for(const xe of o.mount)_(xe,he(ee,xe));else r={}}i=t.shouldUnregister?q.keepDefaultValues?yt(a):{}:yt(ee),m.array.next({values:{...ee}}),m.state.next({values:{...ee}})}o={mount:q.keepDirtyValues?o.mount:new Set,unMount:new Set,array:new Set,disabled:new Set,watch:new Set,watchAll:!1,focus:""},l.mount=!h.isValid||!!q.keepIsValid||!!q.keepDirtyValues||!t.shouldUnregister&&!Ht(ee),l.watch=!!t.shouldUnregister,l.keepIsValid=!!q.keepIsValid,l.action=!1,q.keepErrors||(n.errors={}),m.state.next({submitCount:q.keepSubmitCount?n.submitCount:0,isDirty:se?!1:q.keepDirty?n.isDirty:!!(q.keepDefaultValues&&!Bn(L,a)),isSubmitted:q.keepIsSubmitted?n.isSubmitted:!1,dirtyFields:se?{}:q.keepDirtyValues?q.keepDefaultValues&&i?ra(a,i):n.dirtyFields:q.keepDefaultValues&&L?ra(a,L):q.keepDirty?n.dirtyFields:{},touchedFields:q.keepTouched?n.touchedFields:{},errors:q.keepErrors?n.errors:{},isSubmitSuccessful:q.keepIsSubmitSuccessful?n.isSubmitSuccessful:!1,isSubmitting:!1,defaultValues:a})},Y=(L,q)=>Ns(_s(L)?L(i):L,{...t.resetOptions,...q}),Se=(L,q={})=>{const H=he(r,L),ie=H&&H._f;if(ie){const se=ie.refs?ie.refs[0]:ie.ref;se.focus&&setTimeout(()=>{se.focus(),q.shouldSelect&&_s(se.select)&&se.select()})}},on=L=>{n={...n,...L}},cn={control:{register:z,unregister:Rt,getFieldState:le,handleSubmit:es,setError:Re,_subscribe:qe,_runSchema:w,_updateIsValidating:j,_focusError:Ne,_getWatch:B,_getDirty:O,_setValid:v,_setFieldArray:x,_setDisabledField:Bt,_setErrors:N,_getFieldArray:A,_reset:Ns,_resetDefaultValues:()=>_s(t.defaultValues)&&t.defaultValues().then(L=>{Y(L,t.resetOptions),m.state.next({isLoading:!1})}),_removeUnmounted:K,_disableForm:Be,_subjects:m,_proxyFormState:h,get _fields(){return r},get _formValues(){return i},get _state(){return l},set _state(L){l=L},get _defaultValues(){return a},get _names(){return o},set _names(L){o=L},get _formState(){return n},get _options(){return t},set _options(L){t={...t,...L}}},subscribe:et,trigger:W,register:z,handleSubmit:es,watch:Ye,setValue:_,getValues:fe,reset:Y,resetField:Lt,clearErrors:k,unregister:Rt,setError:Re,setFocus:Se,getFieldState:le};return{...cn,formControl:cn}}function Uv(e={}){const t=At.useRef(void 0),n=At.useRef(void 0),[r,a]=At.useState({isDirty:!1,isValidating:!1,isLoading:_s(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:_s(e.defaultValues)?void 0:e.defaultValues});if(!t.current)if(e.formControl)t.current={...e.formControl,formState:r},e.defaultValues&&!_s(e.defaultValues)&&e.formControl.reset(e.defaultValues,e.resetOptions);else{const{formControl:l,...o}=Bk(e);t.current={...o,formState:r}}const i=t.current.control;return i._options=e,Ck(()=>{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]),At.useEffect(()=>i._disableForm(e.disabled),[i,e.disabled]),At.useEffect(()=>{e.mode&&(i._options.mode=e.mode),e.reValidateMode&&(i._options.reValidateMode=e.reValidateMode)},[i,e.mode,e.reValidateMode]),At.useEffect(()=>{e.errors&&(i._setErrors(e.errors),i._focusError())},[i,e.errors]),At.useEffect(()=>{e.shouldUnregister&&i._subjects.state.next({values:i._getWatch()})},[i,e.shouldUnregister]),At.useEffect(()=>{if(i._proxyFormState.isDirty){const l=i._getDirty();l!==r.isDirty&&i._subjects.state.next({isDirty:l})}},[i,r.isDirty]),At.useEffect(()=>{var l;e.values&&!Bn(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]),At.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=At.useMemo(()=>kk(r,i),[i,r]),t.current}function Tx(){var j,x;const{id:e}=bc(),t=Yt(),n=pe(),r=!!e,{register:a,handleSubmit:i,reset:l,watch:o,setValue:c,formState:{errors:d}}=Uv(),u=o("type"),{data:h}=ue({queryKey:["customer",e],queryFn:()=>kt.getById(parseInt(e)),enabled:r});b.useEffect(()=>{if(h!=null&&h.data){const y={...h.data};y.birthDate&&(y.birthDate=y.birthDate.split("T")[0]),y.foundingDate&&(y.foundingDate=y.foundingDate.split("T")[0]),l(y)}},[h,l]);const p=G({mutationFn:kt.create,onSuccess:()=>{n.invalidateQueries({queryKey:["customers"]}),t("/customers")}}),m=G({mutationFn:y=>kt.update(parseInt(e),y),onSuccess:()=>{n.invalidateQueries({queryKey:["customers"]}),n.invalidateQueries({queryKey:["customer",e]}),t(`/customers/${e}`)}}),f=y=>{const N={type:y.type,salutation:y.salutation||void 0,firstName:y.firstName,lastName:y.lastName,companyName:y.companyName||void 0,email:y.email||void 0,phone:y.phone||void 0,mobile:y.mobile||void 0,taxNumber:y.taxNumber||void 0,commercialRegisterNumber:y.commercialRegisterNumber||void 0,notes:y.notes||void 0,birthPlace:y.birthPlace||void 0};y.birthDate&&typeof y.birthDate=="string"&&y.birthDate.trim()!==""?N.birthDate=new Date(y.birthDate).toISOString():N.birthDate=null,y.foundingDate&&typeof y.foundingDate=="string"&&y.foundingDate.trim()!==""?N.foundingDate=new Date(y.foundingDate).toISOString():N.foundingDate=null,r?m.mutate(N):p.mutate(N)},g=p.isPending||m.isPending,v=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"}),v&&s.jsx("div",{className:"mb-4 p-4 bg-red-50 border border-red-200 text-red-700 rounded-lg",children:v instanceof Error?v.message:"Ein Fehler ist aufgetreten"}),s.jsxs("form",{onSubmit:i(f),children:[s.jsx(X,{className:"mb-6",title:"Stammdaten",children:s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[s.jsx(Le,{label:"Kundentyp",...a("type"),options:[{value:"PRIVATE",label:"Privatkunde"},{value:"BUSINESS",label:"Geschäftskunde"}]}),s.jsx(Le,{label:"Anrede",...a("salutation"),options:[{value:"Herr",label:"Herr"},{value:"Frau",label:"Frau"},{value:"Divers",label:"Divers"}]}),s.jsx(Q,{label:"Vorname",...a("firstName",{required:"Vorname erforderlich"}),error:(j=d.firstName)==null?void 0:j.message}),s.jsx(Q,{label:"Nachname",...a("lastName",{required:"Nachname erforderlich"}),error:(x=d.lastName)==null?void 0:x.message}),u==="BUSINESS"&&s.jsxs(s.Fragment,{children:[s.jsx(Q,{label:"Firmenname",...a("companyName"),className:"md:col-span-2"}),s.jsx(Q,{label:"Gründungsdatum",type:"date",...a("foundingDate"),value:o("foundingDate")||"",onClear:()=>c("foundingDate","")})]}),u!=="BUSINESS"&&s.jsxs(s.Fragment,{children:[s.jsx(Q,{label:"Geburtsdatum",type:"date",...a("birthDate"),value:o("birthDate")||"",onClear:()=>c("birthDate","")}),s.jsx(Q,{label:"Geburtsort",...a("birthPlace")})]})]})}),s.jsx(X,{className:"mb-6",title:"Kontaktdaten",children:s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[s.jsx(Q,{label:"E-Mail",type:"email",...a("email")}),s.jsx(Q,{label:"Telefon",...a("phone")}),s.jsx(Q,{label:"Mobil",...a("mobile")})]})}),u==="BUSINESS"&&s.jsxs(X,{className:"mb-6",title:"Geschäftsdaten",children:[s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[s.jsx(Q,{label:"Steuernummer",...a("taxNumber")}),s.jsx(Q,{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(X,{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(I,{type:"button",variant:"secondary",onClick:()=>t(-1),children:"Abbrechen"}),s.jsx(I,{type:"submit",disabled:g,children:g?"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"},Fx={ACTIVE:"success",PENDING:"warning",CANCELLED:"danger",EXPIRED:"danger",DRAFT:"default",DEACTIVATED:"default"},qk=[{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 Vk({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(Zt,{className:"w-4 h-4"})})]}),s.jsx("div",{className:"space-y-2",children:qk.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 Qk(){const[e,t]=wc(),n=Yt(),[r,a]=b.useState(e.get("search")||""),[i,l]=b.useState(e.get("type")||""),[o,c]=b.useState(e.get("status")||""),[d,u]=b.useState(parseInt(e.get("page")||"1",10)),[h,p]=b.useState(new Set),[m,f]=b.useState(!1),{hasPermission:g,isCustomer:v,isCustomerPortal:j,user:x}=Qe(),y=pe();b.useEffect(()=>{const A=new URLSearchParams;r&&A.set("search",r),i&&A.set("type",i),o&&A.set("status",o),d>1&&A.set("page",d.toString()),t(A,{replace:!0})},[r,i,o,d,t]);const N=G({mutationFn:$e.delete,onSuccess:()=>{y.invalidateQueries({queryKey:["contracts"]})}}),{data:D,isLoading:P}=ue({queryKey:["contracts",r,i,o,d,v?x==null?void 0:x.customerId:null],queryFn:()=>$e.getAll({search:r||void 0,type:i||void 0,status:o||void 0,page:d,limit:20,customerId:v?x==null?void 0:x.customerId:void 0})}),F=b.useMemo(()=>{if(!j||!(D!=null&&D.data))return[];const A=new Set;return x!=null&&x.customerId&&A.add(x.customerId),D.data.forEach(M=>A.add(M.customerId)),[...A]},[D==null?void 0:D.data,j,x==null?void 0:x.customerId]),w=Yw({queries:F.map(A=>({queryKey:["contract-tree",A],queryFn:()=>$e.getTreeForCustomer(A),enabled:j}))}),C=b.useMemo(()=>{const A=new Map;return F.forEach((M,S)=>{var U;const _=w[S];(U=_==null?void 0:_.data)!=null&&U.data&&A.set(M,_.data.data)}),A},[F,w]),E=b.useMemo(()=>{if(!j||!(D!=null&&D.data))return null;const A={};for(const M of D.data){const S=M.customerId;if(!A[S]){const _=M.customer?M.customer.companyName||`${M.customer.firstName} ${M.customer.lastName}`:`Kunde ${S}`;A[S]={customerId:S,customerName:_,isOwn:S===(x==null?void 0:x.customerId),contracts:[],tree:C.get(S)||[]}}A[S].contracts.push(M)}return Object.values(A).sort((M,S)=>M.isOwn&&!S.isOwn?-1:!M.isOwn&&S.isOwn?1:M.customerName.localeCompare(S.customerName))},[D==null?void 0:D.data,j,x==null?void 0:x.customerId,C]),K=A=>{p(M=>{const S=new Set(M);return S.has(A)?S.delete(A):S.add(A),S})},O=(A,M)=>A.map(S=>s.jsx("div",{children:B(S,M)},S.contract.id)),B=(A,M=0)=>{var fe,le,k,Re,Ye,qe,et;const{contract:S,predecessors:_,hasHistory:U}=A,Z=h.has(S.id),W=M>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&&U?s.jsx("button",{onClick:()=>K(S.id),className:"p-1 hover:bg-gray-200 rounded transition-colors",title:Z?"Einklappen":"Vorgänger anzeigen",children:Z?s.jsx(Rn,{className:"w-4 h-4 text-gray-500"}):s.jsx(Pt,{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:[S.contractNumber,s.jsx(oe,{value:S.contractNumber})]}),s.jsx(ge,{children:gd[S.type]||S.type}),s.jsx(ge,{variant:Fx[S.status]||"default",children:yd[S.status]||S.status}),W&&s.jsx("span",{className:"text-xs text-gray-500 ml-2",children:"(Vorgänger)"})]}),s.jsx("div",{className:"flex gap-2",children:s.jsx(I,{variant:"ghost",size:"sm",onClick:()=>n(`/contracts/${S.id}`,{state:{from:"contracts"}}),title:"Ansehen",children:s.jsx(Ae,{className:"w-4 h-4"})})})]}),(S.providerName||((fe=S.provider)==null?void 0:fe.name))&&s.jsxs("p",{className:`flex items-center gap-1 ${W?"ml-6":""}`,children:[S.providerName||((le=S.provider)==null?void 0:le.name),(S.tariffName||((k=S.tariff)==null?void 0:k.name))&&` - ${S.tariffName||((Re=S.tariff)==null?void 0:Re.name)}`,s.jsx(oe,{value:(S.providerName||((Ye=S.provider)==null?void 0:Ye.name)||"")+(S.tariffName||(qe=S.tariff)!=null&&qe.name?` - ${S.tariffName||((et=S.tariff)==null?void 0:et.name)}`:"")})]}),S.startDate&&s.jsxs("p",{className:`text-sm text-gray-500 ${W?"ml-6":""}`,children:["Beginn: ",new Date(S.startDate).toLocaleDateString("de-DE"),S.endDate&&` | Ende: ${new Date(S.endDate).toLocaleDateString("de-DE")}`]})]}),(M===0&&Z||M>0)&&_.length>0&&s.jsx("div",{className:"mt-2",children:O(_,M+1)})]},S.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"}),g("contracts:create")&&!v&&s.jsx(ke,{to:"/contracts/new",children:s.jsxs(I,{children:[s.jsx(Ue,{className:"w-4 h-4 mr-2"}),"Neuer Vertrag"]})})]}),s.jsx(X,{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(Q,{placeholder:"Suchen...",value:r,onChange:A=>a(A.target.value)})}),s.jsx(Le,{value:i,onChange:A=>l(A.target.value),options:Object.entries(gd).map(([A,M])=>({value:A,label:M})),className:"w-48"}),s.jsx(Le,{value:o,onChange:A=>c(A.target.value),options:Object.entries(yd).map(([A,M])=>({value:A,label:M})),className:"w-48"}),s.jsx(I,{variant:"secondary",children:s.jsx(Pl,{className:"w-4 h-4"})})]})}),P?s.jsx(X,{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:j&&E?s.jsx("div",{className:"space-y-6",children:E.map(A=>s.jsxs(X,{children:[s.jsx("div",{className:"flex items-center gap-3 mb-4 pb-3 border-b",children:A.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(ge,{variant:"default",children:A.contracts.length})]}):s.jsxs(s.Fragment,{children:[s.jsx(Sa,{className:"w-5 h-5 text-purple-600"}),s.jsxs("h2",{className:"text-lg font-semibold text-gray-900",children:["Verträge von ",A.customerName]}),s.jsx(ge,{variant:"default",children:A.contracts.length})]})}),A.tree.length>0?s.jsx("div",{className:"space-y-4",children:A.tree.map(M=>B(M,0))}):s.jsx("p",{className:"text-gray-500",children:"Keine Verträge vorhanden."})]},A.isOwn?"own":A.customerName))}):s.jsxs(X,{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."}),!v&&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(Al,{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(A=>s.jsxs("tr",{className:"border-b hover:bg-gray-50",children:[s.jsx("td",{className:"py-3 px-4 font-mono text-sm",children:A.contractNumber}),!v&&s.jsx("td",{className:"py-3 px-4",children:A.customer&&s.jsx(ke,{to:`/customers/${A.customer.id}`,className:"text-blue-600 hover:underline",children:A.customer.companyName||`${A.customer.firstName} ${A.customer.lastName}`})}),s.jsx("td",{className:"py-3 px-4",children:s.jsx(ge,{children:gd[A.type]})}),s.jsxs("td",{className:"py-3 px-4",children:[A.providerName||"-",A.tariffName&&s.jsxs("span",{className:"text-gray-500",children:[" / ",A.tariffName]})]}),s.jsx("td",{className:"py-3 px-4",children:s.jsx(ge,{variant:Fx[A.status],children:yd[A.status]})}),s.jsx("td",{className:"py-3 px-4",children:A.startDate?new Date(A.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(I,{variant:"ghost",size:"sm",onClick:()=>n(`/contracts/${A.id}`,{state:{from:"contracts"}}),children:s.jsx(Ae,{className:"w-4 h-4"})}),g("contracts:update")&&!v&&s.jsx(ke,{to:`/contracts/${A.id}/edit`,children:s.jsx(I,{variant:"ghost",size:"sm",children:s.jsx(Xe,{className:"w-4 h-4"})})}),g("contracts:delete")&&!v&&s.jsx(I,{variant:"ghost",size:"sm",onClick:()=>{confirm("Vertrag wirklich löschen?")&&N.mutate(A.id)},children:s.jsx(je,{className:"w-4 h-4 text-red-500"})})]})})]},A.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(I,{variant:"secondary",size:"sm",onClick:()=>u(A=>Math.max(1,A-1)),disabled:d===1,children:"Zurück"}),s.jsx(I,{variant:"secondary",size:"sm",onClick:()=>u(A=>A+1),disabled:d>=D.pagination.totalPages,children:"Weiter"})]})]})]})}):s.jsx(X,{children:s.jsx("div",{className:"text-center py-8 text-gray-500",children:"Keine Verträge gefunden."})}),s.jsx(Vk,{isOpen:m,onClose:()=>f(!1)})]})}const Hk={ELECTRICITY:"Strom",GAS:"Gas",DSL:"DSL",CABLE:"Kabelinternet",FIBER:"Glasfaser",MOBILE:"Mobilfunk",TV:"TV",CAR_INSURANCE:"KFZ-Versicherung"},Wk={DRAFT:"Entwurf",PENDING:"Ausstehend",ACTIVE:"Aktiv",CANCELLED:"Gekündigt",EXPIRED:"Abgelaufen",DEACTIVATED:"Deaktiviert"},Gk={ACTIVE:"success",PENDING:"warning",CANCELLED:"danger",EXPIRED:"danger",DRAFT:"default",DEACTIVATED:"default"};function Zk({contractId:e,isOpen:t,onClose:n}){var o,c,d,u,h,p,m,f,g,v;const{data:r,isLoading:a,error:i}=ue({queryKey:["contract",e],queryFn:()=>$e.getById(e),enabled:t}),l=r==null?void 0:r.data;return s.jsxs(He,{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(oe,{value:l.contractNumber})]}),s.jsx(ge,{children:Hk[l.type]||l.type}),s.jsx(ge,{variant:Gk[l.status]||"default",children:Wk[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(X,{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(oe,{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(oe,{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(oe,{value:l.customerNumberAtProvider})]})]})]})}),s.jsx(X,{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||((g=l.provider)==null?void 0:g.portalUrl))&&s.jsx(X,{title:"Portal-Zugangsdaten",children:s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[((v=l.provider)==null?void 0:v.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(oe,{value:l.portalUsername})]})]})]})}),l.address&&s.jsxs(X,{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(X,{title:"Notizen",children:s.jsx("p",{className:"whitespace-pre-wrap text-gray-700",children:l.notes})})]})]})}const Ix={INTERIM:"Zwischenrechnung",FINAL:"Schlussrechnung",NOT_AVAILABLE:"Nicht verfügbar"};function Jk({ecdId:e,invoices:t,contractId:n,canEdit:r}){const[a,i]=b.useState(!1),[l,o]=b.useState(!1),[c,d]=b.useState(null),u=pe(),h=G({mutationFn:g=>wi.deleteInvoice(e,g),onSuccess:()=>{u.invalidateQueries({queryKey:["contract",n.toString()]})}}),p=[...t].sort((g,v)=>new Date(v.invoiceDate).getTime()-new Date(g.invoiceDate).getTime()),m=t.some(g=>g.invoiceType==="FINAL"),f=t.some(g=>g.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(_e,{className:"w-4 h-4 text-gray-500"}),s.jsx("h4",{className:"text-sm font-medium text-gray-700",children:"Rechnungen"}),s.jsx(ge,{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(pr,{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(ms,{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(ms,{className:"w-3 h-3"}),"Schlussrechnung fehlt"]}):null]}),s.jsxs("div",{className:"flex items-center gap-2",children:[r&&s.jsx(I,{variant:"ghost",size:"sm",onClick:()=>o(!0),children:s.jsx(Ue,{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(Rn,{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")," - ",Ix[p[0].invoiceType]]}),a&&p.length>0&&s.jsx("div",{className:"space-y-2",children:p.map(g=>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(g.invoiceDate).toLocaleDateString("de-DE")}),s.jsx("div",{className:"text-xs text-gray-500",children:Ix[g.invoiceType]})]}),g.documentPath&&s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("a",{href:`/api${g.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(Ae,{className:"w-4 h-4"})}),s.jsx("a",{href:`/api${g.documentPath}`,download:!0,className:"flex items-center gap-1 text-blue-600 hover:text-blue-800 text-sm",title:"Download",children:s.jsx(Ps,{className:"w-4 h-4"})})]}),g.notes&&s.jsx("span",{className:"text-xs text-gray-400 italic",children:g.notes})]}),r&&s.jsxs("div",{className:"flex items-center gap-2 opacity-0 group-hover:opacity-100",children:[s.jsx("button",{onClick:()=>d(g),className:"text-gray-500 hover:text-blue-600",title:"Bearbeiten",children:s.jsx(Xe,{className:"w-4 h-4"})}),s.jsx("button",{onClick:()=>{confirm("Rechnung wirklich löschen?")&&h.mutate(g.id)},className:"text-gray-500 hover:text-red-600",title:"Löschen",children:s.jsx(je,{className:"w-4 h-4"})})]})]},g.id))}),a&&p.length===0&&s.jsx("p",{className:"text-sm text-gray-500 italic",children:"Keine Rechnungen vorhanden."}),(l||c)&&s.jsx(Xk,{isOpen:!0,onClose:()=>{o(!1),d(null)},ecdId:e,contractId:n,invoice:c})]})}function Xk({isOpen:e,onClose:t,ecdId:n,contractId:r,invoice:a}){const i=pe(),l=!!a,o=b.useRef(null),[c,d]=b.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]=b.useState(null),[p,m]=b.useState(null),f=G({mutationFn:async()=>{var N;if(c.invoiceType!=="NOT_AVAILABLE"&&!u)throw new Error("Bitte laden Sie ein Dokument hoch");const y=await wi.addInvoice(n,{invoiceDate:c.invoiceDate,invoiceType:c.invoiceType,notes:c.notes||void 0});return u&&((N=y.data)!=null&&N.id)&&await wi.uploadDocument(y.data.id,u),y},onSuccess:()=>{i.invalidateQueries({queryKey:["contract",r.toString()]}),t()},onError:y=>{m(y.message)}}),g=G({mutationFn:async()=>{if(c.invoiceType!=="NOT_AVAILABLE"&&!(a!=null&&a.documentPath)&&!u)throw new Error("Bitte laden Sie ein Dokument hoch");const y=await wi.updateInvoice(n,a.id,{invoiceDate:c.invoiceDate,invoiceType:c.invoiceType,notes:c.notes||void 0});return u&&await wi.uploadDocument(a.id,u),y},onSuccess:()=>{i.invalidateQueries({queryKey:["contract",r.toString()]}),t()},onError:y=>{m(y.message)}}),v=y=>{y.preventDefault(),m(null),l?g.mutate():f.mutate()},j=y=>{var D;const N=(D=y.target.files)==null?void 0:D[0];if(N){if(N.type!=="application/pdf"){m("Nur PDF-Dateien sind erlaubt");return}if(N.size>10*1024*1024){m("Datei ist zu groß (max. 10 MB)");return}h(N),m(null)}},x=f.isPending||g.isPending;return s.jsx(He,{isOpen:e,onClose:t,title:l?"Rechnung bearbeiten":"Rechnung hinzufügen",children:s.jsxs("form",{onSubmit:v,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(Q,{label:"Rechnungsdatum",type:"date",value:c.invoiceDate,onChange:y=>d({...c,invoiceDate:y.target.value}),required:!0}),s.jsx(Le,{label:"Rechnungstyp",value:c.invoiceType,onChange:y=>d({...c,invoiceType:y.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(pr,{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(_e,{className:"w-4 h-4"}),u.name]}),s.jsx("input",{type:"file",ref:o,accept:".pdf",onChange:j,className:"hidden"}),s.jsx(I,{type:"button",variant:"secondary",onClick:()=>{var y;return(y=o.current)==null?void 0:y.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(Q,{label:"Notizen (optional)",value:c.notes,onChange:y=>d({...c,notes:y.target.value}),placeholder:"Optionale Anmerkungen..."}),s.jsxs("div",{className:"flex justify-end gap-3 pt-4",children:[s.jsx(I,{type:"button",variant:"secondary",onClick:t,children:"Abbrechen"}),s.jsx(I,{type:"submit",disabled:x,children:x?"Wird gespeichert...":l?"Speichern":"Hinzufügen"})]})]})})}const Yk=10.5;function Rx(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 eC(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 tC(e,t,n,r){const a=eC(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,g)=>new Date(f.readingDate).getTime()-new Date(g.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 Lx("exact",f,r,l,o)}const u=Rx(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=Rx(t,n),m=(o.value-l.value)/u*h;return Lx("projected",m,r,l,o,n)}function Lx(e,t,n,r,a,i){return n==="GAS"?{type:e,consumptionM3:t,consumptionKwh:t*Yk,startReading:r,endReading:a,projectedEndDate:i}:{type:e,consumptionKwh:t,startReading:r,endReading:a,projectedEndDate:i}}function sC(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 nC={ELECTRICITY:"Strom",GAS:"Gas",DSL:"DSL",CABLE:"Kabelinternet",FIBER:"Glasfaser",MOBILE:"Mobilfunk",TV:"TV",CAR_INSURANCE:"KFZ-Versicherung"},rC={DRAFT:"Entwurf",PENDING:"Ausstehend",ACTIVE:"Aktiv",CANCELLED:"Gekündigt",EXPIRED:"Abgelaufen",DEACTIVATED:"Deaktiviert"},aC={ACTIVE:"success",PENDING:"warning",CANCELLED:"danger",EXPIRED:"danger",DRAFT:"default",DEACTIVATED:"default"},iC=[{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 lC({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(Zt,{className:"w-4 h-4"})})]}),s.jsx("div",{className:"space-y-2",children:iC.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 oC(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 cC({simCard:e}){const[t,n]=b.useState(!1),[r,a]=b.useState(null),[i,l]=b.useState(!1),o=async()=>{if(t)n(!1),a(null);else{l(!0);try{const c=await $e.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(ge,{variant:"success",children:"Hauptkarte"}),e.isMultisim&&s.jsx(ge,{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(oe,{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(oe,{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(oe,{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(oe,{value:r.puk})]}):"••••••••"})]})]}),s.jsx("div",{className:"mt-2",children:s.jsx(I,{variant:"ghost",size:"sm",onClick:o,disabled:i,children:i?"Laden...":t?s.jsxs(s.Fragment,{children:[s.jsx(Mt,{className:"w-4 h-4 mr-1"})," PIN/PUK verbergen"]}):s.jsxs(s.Fragment,{children:[s.jsx(Ae,{className:"w-4 h-4 mr-1"})," PIN/PUK anzeigen"]})})})]})}function dC({meterId:e,meterType:t,readings:n,contractId:r,canEdit:a}){const[i,l]=b.useState(!1),[o,c]=b.useState(!1),[d,u]=b.useState(null),h=pe(),p=G({mutationFn:g=>an.deleteReading(e,g),onSuccess:()=>{h.invalidateQueries({queryKey:["contract",r.toString()]})}}),m=[...n].sort((g,v)=>new Date(v.readingDate).getTime()-new Date(g.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(Sv,{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(ge,{variant:"default",children:n.length})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[a&&s.jsx(I,{variant:"ghost",size:"sm",onClick:()=>c(!0),title:"Zählerstand erfassen",children:s.jsx(Ue,{className:"w-4 h-4"})}),n.length>0&&s.jsx(I,{variant:"ghost",size:"sm",onClick:()=>l(!i),children:i?s.jsx(ih,{className:"w-4 h-4"}):s.jsx(Rn,{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(g=>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(g.readingDate).toLocaleDateString("de-DE"),s.jsx(oe,{value:new Date(g.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:[g.value.toLocaleString("de-DE")," ",g.unit,s.jsx(oe,{value:g.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(g),className:"text-gray-400 hover:text-blue-600",title:"Bearbeiten",children:s.jsx(Xe,{className:"w-3 h-3"})}),s.jsx("button",{onClick:()=>{confirm("Zählerstand wirklich löschen?")&&p.mutate(g.id)},className:"text-gray-400 hover:text-red-600",title:"Löschen",children:s.jsx(je,{className:"w-3 h-3"})})]})]})]},g.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(uC,{isOpen:!0,onClose:()=>{c(!1),u(null)},meterId:e,contractId:r,reading:d,defaultUnit:f})]})}function uC({isOpen:e,onClose:t,meterId:n,contractId:r,reading:a,defaultUnit:i}){var f;const l=pe(),o=!!a,[c,d]=b.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=G({mutationFn:g=>an.addReading(n,g),onSuccess:()=>{l.invalidateQueries({queryKey:["contract",r.toString()]}),t()}}),h=G({mutationFn:g=>an.updateReading(n,a.id,g),onSuccess:()=>{l.invalidateQueries({queryKey:["contract",r.toString()]}),t()}}),p=g=>{g.preventDefault();const v={readingDate:new Date(c.readingDate),value:parseFloat(c.value),unit:i,notes:c.notes||void 0};o?h.mutate(v):u.mutate(v)},m=u.isPending||h.isPending;return s.jsx(He,{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(Q,{label:"Ablesedatum",type:"date",value:c.readingDate,onChange:g=>d({...c,readingDate:g.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(Q,{label:"Zählerstand",type:"number",step:"0.01",value:c.value,onChange:g=>d({...c,value:g.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(Q,{label:"Notizen (optional)",value:c.notes,onChange:g=>d({...c,notes:g.target.value})}),s.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[s.jsx(I,{type:"button",variant:"secondary",onClick:t,children:"Abbrechen"}),s.jsx(I,{type:"submit",disabled:m||!c.value,children:m?"Speichern...":o?"Speichern":"Erfassen"})]})]})})}function mC({contractType:e,readings:t,startDate:n,endDate:r,basePrice:a,unitPrice:i,bonus:l}){const o=tC(t,n,r,e),c=o.consumptionKwh>0?sC(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(E2,{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(ge,{variant:"success",children:"Exakt"}),o.type==="projected"&&s.jsx(ge,{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 Ox({task:e,contractId:t,canEdit:n,isCustomerPortal:r,isCompleted:a,onEdit:i}){const[l,o]=b.useState(""),[c,d]=b.useState(!1),[u,h]=b.useState(null),[p,m]=b.useState(""),f=pe(),g=G({mutationFn:_=>dt.complete(_),onSuccess:async()=>{await f.refetchQueries({queryKey:["contract-tasks",t]})}}),v=G({mutationFn:_=>dt.reopen(_),onSuccess:async()=>{await f.refetchQueries({queryKey:["contract-tasks",t]})}}),j=G({mutationFn:_=>dt.delete(_),onSuccess:async()=>{await f.refetchQueries({queryKey:["contract-tasks",t]})}}),x=G({mutationFn:_=>dt.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.")}}),y=G({mutationFn:_=>dt.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=G({mutationFn:({id:_,title:U})=>dt.updateSubtask(_,U),onSuccess:async()=>{await f.refetchQueries({queryKey:["contract-tasks",t]}),h(null),m("")}}),D=G({mutationFn:_=>dt.completeSubtask(_),onSuccess:async()=>{await f.refetchQueries({queryKey:["contract-tasks",t]})}}),P=G({mutationFn:_=>dt.reopenSubtask(_),onSuccess:async()=>{await f.refetchQueries({queryKey:["contract-tasks",t]})}}),F=G({mutationFn:_=>dt.deleteSubtask(_),onSuccess:async()=>{await f.refetchQueries({queryKey:["contract-tasks",t]})}}),w=_=>{_.preventDefault(),l.trim()&&(r?y.mutate(l.trim()):x.mutate(l.trim()))},C=_=>{_.preventDefault(),p.trim()&&u&&N.mutate({id:u,title:p.trim()})},E=(_,U)=>{h(_),m(U)},K=()=>{h(null),m("")},O=e.subtasks||[],B=O.filter(_=>_.status==="OPEN"),A=O.filter(_=>_.status==="COMPLETED"),M=r?{singular:"Antwort",placeholder:"Antwort...",deleteConfirm:"Antwort löschen?"}:{singular:"Unteraufgabe",placeholder:"Unteraufgabe...",deleteConfirm:"Unteraufgabe löschen?"},S=(_,U)=>u===_.id?s.jsx("div",{className:"py-1",children:s.jsxs("form",{onSubmit:C,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:W=>m(W.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(I,{type:"submit",size:"sm",disabled:!p.trim()||N.isPending,children:"✓"}),s.jsx(I,{type:"button",variant:"ghost",size:"sm",onClick:K,children:"×"})]})},_.id):s.jsx("div",{className:`py-1 group/subtask ${U?"opacity-60":""}`,children:s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx("button",{onClick:()=>U?P.mutate(_.id):D.mutate(_.id),disabled:D.isPending||P.isPending||r,className:`flex-shrink-0 mt-0.5 ${r?"cursor-default":U?"hover:text-yellow-600":"hover:text-green-600"}`,children:U?s.jsx(As,{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 ${U?"line-through text-gray-500":""}`,children:_.title}),n&&!r&&!U&&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(Xe,{className:"w-3 h-3"})}),s.jsx("button",{onClick:()=>{confirm(M.deleteConfirm)&&F.mutate(_.id)},className:"text-gray-400 hover:text-red-600 p-0.5",title:"Löschen",children:s.jsx(je,{className:"w-3 h-3"})})]}),n&&!r&&U&&s.jsx("button",{onClick:()=>{confirm(M.deleteConfirm)&&F.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(je,{className:"w-3 h-3"})})]}),s.jsxs("p",{className:"text-xs text-gray-400",children:[_.createdBy&&`${_.createdBy} • `,U?`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?v.mutate(e.id):g.mutate(e.id),disabled:g.isPending||v.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(As,{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(ge,{variant:"default",className:"text-xs",children:"Portal"}),O.length>0&&s.jsxs("span",{className:"text-xs text-gray-400",children:["(",A.length,"/",O.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")]}),O.length>0&&s.jsxs("div",{className:"mt-3 ml-2 space-y-0 border-l-2 border-gray-200 pl-3",children:[B.map(_=>S(_,!1)),A.map(_=>S(_,!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(I,{type:"submit",size:"sm",disabled:!l.trim()||x.isPending||y.isPending,children:s.jsx(Ue,{className:"w-3 h-3"})}),s.jsx(I,{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(Ue,{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(Xe,{className:"w-4 h-4"})}),s.jsx("button",{onClick:()=>{confirm("Aufgabe wirklich löschen?")&&j.mutate(e.id)},className:"text-gray-400 hover:text-red-600 p-1",title:"Löschen",children:s.jsx(je,{className:"w-4 h-4"})})]})]})})}function hC({contractId:e,canEdit:t,isCustomerPortal:n}){var y;const[r,a]=b.useState(!1),[i,l]=b.useState(null),{data:o,isLoading:c}=ue({queryKey:["contract-tasks",e],queryFn:()=>dt.getByContract(e),staleTime:0,gcTime:0,refetchOnMount:"always"}),{data:d,isLoading:u}=ue({queryKey:["app-settings-public"],queryFn:()=>Jr.getPublic(),enabled:n,staleTime:0}),h=!u&&((y=d==null?void 0:d.data)==null?void 0:y.customerSupportTicketsEnabled)==="true",p=(o==null?void 0:o.data)||[],m=p.filter(N=>N.status==="OPEN"),f=p.filter(N=>N.status==="COMPLETED"),g=n?{title:"Support-Anfragen",button:"Anfrage erstellen",empty:"Keine Support-Anfragen vorhanden."}:{title:"Aufgaben",button:"Aufgabe",empty:"Keine Aufgaben vorhanden."},v=n?cl:ol;if(c||n&&u)return s.jsx(X,{className:"mb-6",title:g.title,children:s.jsx("div",{className:"text-center py-4 text-gray-500",children:"Laden..."})});const x=t&&!n||n&&h;return s.jsxs(X,{className:"mb-6",title:g.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(v,{className:"w-5 h-5 text-gray-500"}),s.jsxs("span",{className:"text-sm text-gray-600",children:[m.length," offen, ",f.length," erledigt"]})]}),x&&s.jsxs(I,{size:"sm",onClick:()=>a(!0),children:[s.jsx(Ue,{className:"w-4 h-4 mr-1"}),g.button]})]}),p.length===0?s.jsx("p",{className:"text-center py-4 text-gray-500",children:g.empty}):s.jsxs("div",{className:"space-y-2",children:[m.map(N=>s.jsx(Ox,{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(Ox,{task:N,contractId:e,canEdit:t,isCustomerPortal:n,isCompleted:!0,onEdit:()=>{}},N.id))]}),(r||i)&&s.jsx(fC,{isOpen:!0,onClose:()=>{a(!1),l(null)},contractId:e,task:i,isCustomerPortal:n})]})}function fC({isOpen:e,onClose:t,contractId:n,task:r,isCustomerPortal:a=!1}){const i=pe(),l=!!r,[o,c]=b.useState({title:(r==null?void 0:r.title)||"",description:(r==null?void 0:r.description)||"",visibleInPortal:(r==null?void 0:r.visibleInPortal)||!1});b.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=G({mutationFn:g=>dt.create(n,g),onSuccess:async()=>{await i.refetchQueries({queryKey:["contract-tasks",n]}),t()}}),u=G({mutationFn:g=>dt.createSupportTicket(n,g),onSuccess:async()=>{await i.refetchQueries({queryKey:["contract-tasks",n]}),t()}}),h=G({mutationFn:g=>dt.update(r.id,g),onSuccess:async()=>{await i.refetchQueries({queryKey:["contract-tasks",n]}),t()}}),p=g=>{g.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(He,{isOpen:e,onClose:t,title:f.modalTitle,children:s.jsxs("form",{onSubmit:p,className:"space-y-4",children:[s.jsx(Q,{label:f.titleLabel,value:o.title,onChange:g=>c({...o,title:g.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:g=>c({...o,description:g.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:g=>c({...o,visibleInPortal:g.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(I,{type:"button",variant:"secondary",onClick:t,children:"Abbrechen"}),s.jsx(I,{type:"submit",disabled:m||!o.title.trim(),children:m?"Speichern...":f.submitBtn})]})]})})}function pC(){var Re,Ye,qe,et,Rt,Bt;const{id:e}=bc(),t=Yt(),r=In().state,a=pe(),{hasPermission:i,isCustomer:l,isCustomerPortal:o}=Qe(),c=parseInt(e),[d,u]=b.useState(!1),[h,p]=b.useState(null),[m,f]=b.useState(!1),[g,v]=b.useState(!1),[j,x]=b.useState(null),[y,N]=b.useState({}),[D,P]=b.useState({}),[F,w]=b.useState(!1),[C,E]=b.useState(!1),[K,O]=b.useState(!1),{data:B,isLoading:A}=ue({queryKey:["contract",e],queryFn:()=>$e.getById(c)}),M=G({mutationFn:()=>$e.delete(c),onSuccess:()=>{t("/contracts")}}),S=G({mutationFn:()=>$e.createFollowUp(c),onSuccess:z=>{z.data?t(`/contracts/${z.data.id}/edit`):alert("Folgevertrag wurde erstellt, aber keine ID zurückgegeben")},onError:z=>{console.error("Folgevertrag Fehler:",z),alert(`Fehler beim Erstellen des Folgevertrags: ${z instanceof Error?z.message:"Unbekannter Fehler"}`)}}),_=G({mutationFn:z=>{const Be={cancellationConfirmationDate:z?new Date(z).toISOString():null};return $e.update(c,Be)},onSuccess:()=>{a.invalidateQueries({queryKey:["contract",e]}),a.invalidateQueries({queryKey:["contract-cockpit"]})},onError:z=>{console.error("Fehler beim Speichern des Datums:",z),alert("Fehler beim Speichern des Datums")}}),U=G({mutationFn:z=>{const Be={cancellationConfirmationOptionsDate:z?new Date(z).toISOString():null};return $e.update(c,Be)},onSuccess:()=>{a.invalidateQueries({queryKey:["contract",e]}),a.invalidateQueries({queryKey:["contract-cockpit"]})},onError:z=>{console.error("Fehler beim Speichern des Datums:",z),alert("Fehler beim Speichern des Datums")}}),Z=async()=>{var z;if(d)u(!1),p(null);else try{const Ne=await $e.getPassword(c);(z=Ne.data)!=null&&z.password&&(p(Ne.data.password),u(!0))}catch{alert("Passwort konnte nicht entschlüsselt werden")}},W=async()=>{var z;if(g)v(!1),x(null);else try{const Ne=await $e.getInternetCredentials(c);(z=Ne.data)!=null&&z.password&&(x(Ne.data.password),v(!0))}catch{alert("Internet-Passwort konnte nicht entschlüsselt werden")}},fe=async z=>{var Ne;if(y[z])N(Be=>({...Be,[z]:!1})),P(Be=>({...Be,[z]:null}));else try{const es=(Ne=(await $e.getSipCredentials(z)).data)==null?void 0:Ne.password;es&&(P(Lt=>({...Lt,[z]:es})),N(Lt=>({...Lt,[z]:!0})))}catch{alert("SIP-Passwort konnte nicht entschlüsselt werden")}},le=async()=>{var Be,es,Lt;const z=B==null?void 0:B.data,Ne=((Be=z==null?void 0:z.stressfreiEmail)==null?void 0:Be.email)||(z==null?void 0:z.portalUsername);if(!((es=z==null?void 0:z.provider)!=null&&es.portalUrl)||!Ne){alert("Portal-URL oder Benutzername fehlt");return}f(!0);try{const Ns=await $e.getPassword(c);if(!((Lt=Ns.data)!=null&&Lt.password)){alert("Passwort konnte nicht entschlüsselt werden");return}const Y=z.provider,Se=Y.portalUrl,on=Y.usernameFieldName||"username",gt=Y.passwordFieldName||"password",cn=new URL(Se);cn.searchParams.set(on,Ne),cn.searchParams.set(gt,Ns.data.password),window.open(cn.toString(),"_blank")}catch{alert("Fehler beim Auto-Login")}finally{f(!1)}};if(A)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:"Vertrag nicht gefunden"});const k=B.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(I,{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 z=r.filter?`?filter=${r.filter}`:"";t(`/contracts/cockpit${z}`)}else(r==null?void 0:r.from)==="contracts"?t("/contracts"):k.customer?t(`/customers/${k.customer.id}?tab=contracts`):t("/contracts")},children:s.jsx(Vs,{className:"w-4 h-4"})}),s.jsx("h1",{className:"text-2xl font-bold",children:k.contractNumber}),s.jsx(ge,{children:nC[k.type]}),s.jsx(ge,{variant:aC[k.status],children:rC[k.status]}),s.jsx("button",{onClick:()=>O(!0),className:"text-gray-400 hover:text-blue-600 transition-colors",title:"Status-Erklärung",children:s.jsx(Al,{className:"w-4 h-4"})})]}),k.customer&&s.jsxs("p",{className:"text-gray-500 ml-10",children:["Kunde:"," ",s.jsx(ke,{to:`/customers/${k.customer.id}`,className:"text-blue-600 hover:underline",children:k.customer.companyName||`${k.customer.firstName} ${k.customer.lastName}`})]})]}),!l&&s.jsxs("div",{className:"flex gap-2",children:[k.previousContract&&s.jsx(ke,{to:`/contracts/${k.previousContract.id}`,children:s.jsxs(I,{variant:"secondary",children:[s.jsx(Vs,{className:"w-4 h-4 mr-2"}),"Vorgängervertrag"]})}),i("contracts:create")&&!k.followUpContract&&s.jsxs(I,{variant:"secondary",onClick:()=>E(!0),disabled:S.isPending,children:[s.jsx(lh,{className:"w-4 h-4 mr-2"}),S.isPending?"Erstelle...":"Folgevertrag anlegen"]}),k.followUpContract&&s.jsx(ke,{to:`/contracts/${k.followUpContract.id}`,children:s.jsxs(I,{variant:"secondary",children:[s.jsx(jv,{className:"w-4 h-4 mr-2"}),"Folgevertrag anzeigen"]})}),i("contracts:update")&&s.jsx(ke,{to:`/contracts/${e}/edit`,children:s.jsxs(I,{variant:"secondary",children:[s.jsx(Xe,{className:"w-4 h-4 mr-2"}),"Bearbeiten"]})}),i("contracts:delete")&&s.jsxs(I,{variant:"danger",onClick:()=>{confirm("Vertrag wirklich löschen?")&&M.mutate()},children:[s.jsx(je,{className:"w-4 h-4 mr-2"}),"Löschen"]})]})]}),k.previousContract&&s.jsx(X,{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:k.previousContract.contractNumber})})]}),k.previousContract.providerName&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Anbieter"}),s.jsx("dd",{children:k.previousContract.providerName})]}),k.previousContract.customerNumberAtProvider&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Kundennummer"}),s.jsx("dd",{className:"font-mono",children:k.previousContract.customerNumberAtProvider})]}),k.previousContract.portalUsername&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Zugangsdaten"}),s.jsx("dd",{children:k.previousContract.portalUsername})]})]})}),k.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(k.cancellationConfirmationDate).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"})}),".",k.cancellationConfirmationOptionsDate&&s.jsxs(s.Fragment,{children:[" Optionen-Bestätigung: ",s.jsx("strong",{children:new Date(k.cancellationConfirmationOptionsDate).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"})}),"."]})]})]})]}),k.type==="MOBILE"&&((Re=k.mobileDetails)==null?void 0:Re.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(X,{title:"Anbieter & Tarif",children:s.jsxs("dl",{className:"space-y-3",children:[(k.provider||k.providerName)&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Anbieter"}),s.jsx("dd",{className:"font-medium",children:((Ye=k.provider)==null?void 0:Ye.name)||k.providerName})]}),(k.tariff||k.tariffName)&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Tarif"}),s.jsx("dd",{children:((qe=k.tariff)==null?void 0:qe.name)||k.tariffName})]}),k.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:[k.customerNumberAtProvider,s.jsx(oe,{value:k.customerNumberAtProvider})]})]}),k.salesPlatform&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Vertriebsplattform"}),s.jsx("dd",{children:k.salesPlatform.name})]}),k.commission!==null&&k.commission!==void 0&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Provision"}),s.jsx("dd",{children:k.commission.toLocaleString("de-DE",{style:"currency",currency:"EUR"})})]}),k.priceFirst12Months&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Preis erste 12 Monate"}),s.jsx("dd",{children:k.priceFirst12Months})]}),k.priceFrom13Months&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Preis ab 13. Monat"}),s.jsx("dd",{children:k.priceFrom13Months})]}),k.priceAfter24Months&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Preis nach 24 Monaten"}),s.jsx("dd",{children:k.priceAfter24Months})]})]})}),s.jsxs(X,{title:"Laufzeit und Kündigung",className:k.cancellationConfirmationDate?"border-2 border-red-400":"",children:[k.contractDuration&&oC(k.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:[k.startDate&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Vertragsbeginn"}),s.jsx("dd",{children:new Date(k.startDate).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"})})]}),k.endDate&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Vertragsende"}),s.jsx("dd",{children:new Date(k.endDate).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"})})]}),k.contractDuration&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Vertragslaufzeit"}),s.jsx("dd",{children:k.contractDuration.description})]}),k.cancellationPeriod&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Kündigungsfrist"}),s.jsx("dd",{children:k.cancellationPeriod.description})]}),k.cancellationConfirmationDate&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Kündigungsbestätigungsdatum"}),s.jsx("dd",{children:new Date(k.cancellationConfirmationDate).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"})})]}),k.cancellationConfirmationOptionsDate&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Kündigungsbestätigungsoptionendatum"}),s.jsx("dd",{children:new Date(k.cancellationConfirmationOptionsDate).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"})})]}),k.wasSpecialCancellation&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Sonderkündigung"}),s.jsx("dd",{children:s.jsx(ge,{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"}),k.cancellationLetterPath?s.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[s.jsxs("a",{href:`/api${k.cancellationLetterPath}`,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:underline text-sm flex items-center gap-1",children:[s.jsx(Ae,{className:"w-4 h-4"}),"Anzeigen"]}),s.jsxs("a",{href:`/api${k.cancellationLetterPath}`,download:!0,className:"text-blue-600 hover:underline text-sm flex items-center gap-1",children:[s.jsx(Ps,{className:"w-4 h-4"}),"Download"]}),s.jsx(St,{onUpload:async z=>{await ot.uploadCancellationLetter(c,z),a.invalidateQueries({queryKey:["contract",e]})},existingFile:k.cancellationLetterPath,accept:".pdf",label:"Ersetzen"}),s.jsxs("button",{onClick:async()=>{confirm("Dokument wirklich löschen?")&&(await ot.deleteCancellationLetter(c),a.invalidateQueries({queryKey:["contract",e]}))},className:"text-red-600 hover:underline text-sm flex items-center gap-1",children:[s.jsx(je,{className:"w-4 h-4"}),"Löschen"]})]}):s.jsx(St,{onUpload:async z=>{await ot.uploadCancellationLetter(c,z),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"}),k.cancellationConfirmationPath?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[s.jsxs("a",{href:`/api${k.cancellationConfirmationPath}`,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:underline text-sm flex items-center gap-1",children:[s.jsx(Ae,{className:"w-4 h-4"}),"Anzeigen"]}),s.jsxs("a",{href:`/api${k.cancellationConfirmationPath}`,download:!0,className:"text-blue-600 hover:underline text-sm flex items-center gap-1",children:[s.jsx(Ps,{className:"w-4 h-4"}),"Download"]}),s.jsx(St,{onUpload:async z=>{await ot.uploadCancellationConfirmation(c,z),a.invalidateQueries({queryKey:["contract",e]})},existingFile:k.cancellationConfirmationPath,accept:".pdf",label:"Ersetzen"}),s.jsxs("button",{onClick:async()=>{confirm("Dokument wirklich löschen?")&&(await ot.deleteCancellationConfirmation(c),a.invalidateQueries({queryKey:["contract",e]}))},className:"text-red-600 hover:underline text-sm flex items-center gap-1",children:[s.jsx(je,{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:k.cancellationConfirmationDate?k.cancellationConfirmationDate.split("T")[0]:"",onChange:z=>{const Ne=z.target.value||null;_.mutate(Ne)},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"}),k.cancellationConfirmationDate&&s.jsx("button",{onClick:()=>_.mutate(null),className:"p-1 text-red-500 hover:text-red-700 hover:bg-red-50 rounded",title:"Datum löschen",children:s.jsx(je,{className:"w-4 h-4"})})]})]})]}):s.jsx(St,{onUpload:async z=>{await ot.uploadCancellationConfirmation(c,z),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"}),k.cancellationLetterOptionsPath?s.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[s.jsxs("a",{href:`/api${k.cancellationLetterOptionsPath}`,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:underline text-sm flex items-center gap-1",children:[s.jsx(Ae,{className:"w-4 h-4"}),"Anzeigen"]}),s.jsxs("a",{href:`/api${k.cancellationLetterOptionsPath}`,download:!0,className:"text-blue-600 hover:underline text-sm flex items-center gap-1",children:[s.jsx(Ps,{className:"w-4 h-4"}),"Download"]}),s.jsx(St,{onUpload:async z=>{await ot.uploadCancellationLetterOptions(c,z),a.invalidateQueries({queryKey:["contract",e]})},existingFile:k.cancellationLetterOptionsPath,accept:".pdf",label:"Ersetzen"}),s.jsxs("button",{onClick:async()=>{confirm("Dokument wirklich löschen?")&&(await ot.deleteCancellationLetterOptions(c),a.invalidateQueries({queryKey:["contract",e]}))},className:"text-red-600 hover:underline text-sm flex items-center gap-1",children:[s.jsx(je,{className:"w-4 h-4"}),"Löschen"]})]}):s.jsx(St,{onUpload:async z=>{await ot.uploadCancellationLetterOptions(c,z),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"}),k.cancellationConfirmationOptionsPath?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[s.jsxs("a",{href:`/api${k.cancellationConfirmationOptionsPath}`,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:underline text-sm flex items-center gap-1",children:[s.jsx(Ae,{className:"w-4 h-4"}),"Anzeigen"]}),s.jsxs("a",{href:`/api${k.cancellationConfirmationOptionsPath}`,download:!0,className:"text-blue-600 hover:underline text-sm flex items-center gap-1",children:[s.jsx(Ps,{className:"w-4 h-4"}),"Download"]}),s.jsx(St,{onUpload:async z=>{await ot.uploadCancellationConfirmationOptions(c,z),a.invalidateQueries({queryKey:["contract",e]})},existingFile:k.cancellationConfirmationOptionsPath,accept:".pdf",label:"Ersetzen"}),s.jsxs("button",{onClick:async()=>{confirm("Dokument wirklich löschen?")&&(await ot.deleteCancellationConfirmationOptions(c),a.invalidateQueries({queryKey:["contract",e]}))},className:"text-red-600 hover:underline text-sm flex items-center gap-1",children:[s.jsx(je,{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:k.cancellationConfirmationOptionsDate?k.cancellationConfirmationOptionsDate.split("T")[0]:"",onChange:z=>{const Ne=z.target.value||null;U.mutate(Ne)},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"}),k.cancellationConfirmationOptionsDate&&s.jsx("button",{onClick:()=>U.mutate(null),className:"p-1 text-red-500 hover:text-red-700 hover:bg-red-50 rounded",title:"Datum löschen",children:s.jsx(je,{className:"w-4 h-4"})})]})]})]}):s.jsx(St,{onUpload:async z=>{await ot.uploadCancellationConfirmationOptions(c,z),a.invalidateQueries({queryKey:["contract",e]})},accept:".pdf",label:"PDF hochladen"})]})]})]})]})]}),(k.portalUsername||k.stressfreiEmail||k.portalPasswordEncrypted)&&s.jsxs(X,{className:"mb-6",title:"Zugangsdaten",children:[s.jsxs("dl",{className:"grid grid-cols-2 gap-4",children:[(k.portalUsername||k.stressfreiEmail)&&s.jsxs("div",{children:[s.jsxs("dt",{className:"text-sm text-gray-500",children:["Benutzername",k.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:[((et=k.stressfreiEmail)==null?void 0:et.email)||k.portalUsername,s.jsx(oe,{value:((Rt=k.stressfreiEmail)==null?void 0:Rt.email)||k.portalUsername||""})]})]}),k.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(oe,{value:h}),s.jsx(I,{variant:"ghost",size:"sm",onClick:Z,children:d?s.jsx(Mt,{className:"w-4 h-4"}):s.jsx(Ae,{className:"w-4 h-4"})})]})]})]}),((Bt=k.provider)==null?void 0:Bt.portalUrl)&&(k.portalUsername||k.stressfreiEmail)&&k.portalPasswordEncrypted&&s.jsxs("div",{className:"mt-4 pt-4 border-t",children:[s.jsxs(I,{onClick:le,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:[k.address&&s.jsx(X,{title:"Lieferadresse",children:s.jsxs(Qu,{values:[`${k.address.street} ${k.address.houseNumber}`,`${k.address.postalCode} ${k.address.city}`,k.address.country],children:[s.jsxs("p",{children:[k.address.street," ",k.address.houseNumber]}),s.jsxs("p",{children:[k.address.postalCode," ",k.address.city]}),s.jsx("p",{className:"text-gray-500",children:k.address.country})]})}),(k.billingAddress||k.address)&&s.jsx(X,{title:"Rechnungsadresse",children:(()=>{const z=k.billingAddress||k.address;return z?s.jsxs(Qu,{values:[`${z.street} ${z.houseNumber}`,`${z.postalCode} ${z.city}`,z.country],children:[s.jsxs("p",{children:[z.street," ",z.houseNumber]}),s.jsxs("p",{children:[z.postalCode," ",z.city]}),s.jsx("p",{className:"text-gray-500",children:z.country}),!k.billingAddress&&k.address&&s.jsx("p",{className:"text-xs text-gray-400 mt-1",children:"(wie Lieferadresse)"})]}):null})()}),k.bankCard&&s.jsxs(X,{title:"Bankkarte",children:[s.jsx("p",{className:"font-medium",children:k.bankCard.accountHolder}),s.jsxs("p",{className:"font-mono flex items-center gap-1",children:[k.bankCard.iban,s.jsx(oe,{value:k.bankCard.iban})]}),k.bankCard.bankName&&s.jsx("p",{className:"text-gray-500",children:k.bankCard.bankName})]}),k.identityDocument&&s.jsxs(X,{title:"Ausweis",children:[s.jsxs("p",{className:"font-mono flex items-center gap-1",children:[k.identityDocument.documentNumber,s.jsx(oe,{value:k.identityDocument.documentNumber})]}),s.jsx("p",{className:"text-gray-500",children:k.identityDocument.type})]})]}),k.energyDetails&&s.jsxs(X,{className:"mb-6",title:k.type==="ELECTRICITY"?"Strom-Details":"Gas-Details",children:[s.jsxs("dl",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[k.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:[k.energyDetails.meter.meterNumber,s.jsx(oe,{value:k.energyDetails.meter.meterNumber})]})]}),k.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:[k.energyDetails.maloId,s.jsx(oe,{value:k.energyDetails.maloId})]})]}),k.energyDetails.annualConsumption&&s.jsxs("div",{children:[s.jsxs("dt",{className:"text-sm text-gray-500",children:["Jahresverbrauch ",k.type==="ELECTRICITY"?"":"(m³)"]}),s.jsxs("dd",{children:[k.energyDetails.annualConsumption.toLocaleString("de-DE")," ",k.type==="ELECTRICITY"?"kWh":"m³"]})]}),k.type==="GAS"&&k.energyDetails.annualConsumptionKwh&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Jahresverbrauch (kWh)"}),s.jsxs("dd",{children:[k.energyDetails.annualConsumptionKwh.toLocaleString("de-DE")," kWh"]})]}),k.energyDetails.basePrice!=null&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Grundpreis"}),s.jsxs("dd",{children:[k.energyDetails.basePrice.toLocaleString("de-DE",{minimumFractionDigits:2,maximumFractionDigits:10})," €/Monat"]})]}),k.energyDetails.unitPrice!=null&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Arbeitspreis"}),s.jsxs("dd",{children:[k.energyDetails.unitPrice.toLocaleString("de-DE",{minimumFractionDigits:2,maximumFractionDigits:10})," €/kWh"]})]}),k.energyDetails.bonus&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Bonus"}),s.jsxs("dd",{children:[k.energyDetails.bonus.toLocaleString("de-DE")," €"]})]}),k.energyDetails.previousProviderName&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Vorversorger"}),s.jsx("dd",{children:k.energyDetails.previousProviderName})]}),k.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:[k.energyDetails.previousCustomerNumber,s.jsx(oe,{value:k.energyDetails.previousCustomerNumber})]})]})]}),k.energyDetails.meter&&s.jsx(dC,{meterId:k.energyDetails.meter.id,meterType:k.energyDetails.meter.type,readings:k.energyDetails.meter.readings||[],contractId:c,canEdit:i("contracts:update")&&!l}),k.energyDetails.meter&&k.startDate&&k.endDate&&s.jsx(mC,{contractType:k.type,readings:k.energyDetails.meter.readings||[],startDate:k.startDate,endDate:k.endDate,basePrice:k.energyDetails.basePrice,unitPrice:k.energyDetails.unitPrice,bonus:k.energyDetails.bonus}),s.jsx(Jk,{ecdId:k.energyDetails.id,invoices:k.energyDetails.invoices||[],contractId:c,canEdit:i("contracts:update")&&!l})]}),k.internetDetails&&s.jsxs(X,{className:"mb-6",title:k.type==="DSL"?"DSL-Details":k.type==="CABLE"?"Kabelinternet-Details":"Glasfaser-Details",children:[s.jsxs("dl",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[k.internetDetails.downloadSpeed&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Download"}),s.jsxs("dd",{children:[k.internetDetails.downloadSpeed," Mbit/s"]})]}),k.internetDetails.uploadSpeed&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Upload"}),s.jsxs("dd",{children:[k.internetDetails.uploadSpeed," Mbit/s"]})]}),k.internetDetails.routerModel&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Router"}),s.jsx("dd",{children:k.internetDetails.routerModel})]}),k.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:[k.internetDetails.routerSerialNumber,s.jsx(oe,{value:k.internetDetails.routerSerialNumber})]})]}),k.internetDetails.installationDate&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Installation"}),s.jsx("dd",{children:new Date(k.internetDetails.installationDate).toLocaleDateString("de-DE")})]}),k.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:[k.internetDetails.homeId,s.jsx(oe,{value:k.internetDetails.homeId})]})]}),k.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:[k.internetDetails.activationCode,s.jsx(oe,{value:k.internetDetails.activationCode})]})]})]}),(k.internetDetails.internetUsername||k.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:[k.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:[k.internetDetails.internetUsername,s.jsx(oe,{value:k.internetDetails.internetUsername})]})]}),k.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:g&&j?j:"••••••••"}),g&&j&&s.jsx(oe,{value:j}),s.jsx(I,{variant:"ghost",size:"sm",onClick:W,children:g?s.jsx(Mt,{className:"w-4 h-4"}):s.jsx(Ae,{className:"w-4 h-4"})})]})]})]})]}),k.internetDetails.phoneNumbers&&k.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:k.internetDetails.phoneNumbers.map(z=>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:[z.phoneNumber,s.jsx(oe,{value:z.phoneNumber})]}),z.isMain&&s.jsx(ge,{variant:"success",children:"Hauptnummer"})]}),(z.sipUsername||z.sipPasswordEncrypted||z.sipServer)&&s.jsxs("dl",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 text-sm",children:[z.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:[z.sipUsername,s.jsx(oe,{value:z.sipUsername})]})]}),z.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:y[z.id]&&D[z.id]?D[z.id]:"••••••••"}),y[z.id]&&D[z.id]&&s.jsx(oe,{value:D[z.id]}),s.jsx(I,{variant:"ghost",size:"sm",onClick:()=>fe(z.id),children:y[z.id]?s.jsx(Mt,{className:"w-3 h-3"}):s.jsx(Ae,{className:"w-3 h-3"})})]})]}),z.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:[z.sipServer,s.jsx(oe,{value:z.sipServer})]})]})]})]},z.id))})]})]}),k.mobileDetails&&s.jsxs(X,{className:"mb-6",title:"Mobilfunk-Details",children:[s.jsxs("dl",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[k.mobileDetails.dataVolume&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Datenvolumen"}),s.jsxs("dd",{children:[k.mobileDetails.dataVolume," GB"]})]}),k.mobileDetails.includedMinutes&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Inklusiv-Minuten"}),s.jsx("dd",{children:k.mobileDetails.includedMinutes})]}),k.mobileDetails.includedSMS&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Inklusiv-SMS"}),s.jsx("dd",{children:k.mobileDetails.includedSMS})]}),k.mobileDetails.deviceModel&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Gerät"}),s.jsx("dd",{children:k.mobileDetails.deviceModel})]}),k.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:[k.mobileDetails.deviceImei,s.jsx(oe,{value:k.mobileDetails.deviceImei})]})]}),k.mobileDetails.requiresMultisim&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Multisim"}),s.jsx("dd",{children:s.jsx(ge,{variant:"warning",children:"Erforderlich"})})]})]}),k.mobileDetails.simCards&&k.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:k.mobileDetails.simCards.map(z=>s.jsx(cC,{simCard:z},z.id))})]}),(!k.mobileDetails.simCards||k.mobileDetails.simCards.length===0)&&(k.mobileDetails.phoneNumber||k.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:[k.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:[k.mobileDetails.phoneNumber,s.jsx(oe,{value:k.mobileDetails.phoneNumber})]})]}),k.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:[k.mobileDetails.simCardNumber,s.jsx(oe,{value:k.mobileDetails.simCardNumber})]})]})]})]})]}),k.tvDetails&&s.jsx(X,{className:"mb-6",title:"TV-Details",children:s.jsxs("dl",{className:"grid grid-cols-2 md:grid-cols-3 gap-4",children:[k.tvDetails.receiverModel&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Receiver"}),s.jsx("dd",{children:k.tvDetails.receiverModel})]}),k.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:[k.tvDetails.smartcardNumber,s.jsx(oe,{value:k.tvDetails.smartcardNumber})]})]}),k.tvDetails.package&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Paket"}),s.jsx("dd",{children:k.tvDetails.package})]})]})}),k.carInsuranceDetails&&s.jsx(X,{className:"mb-6",title:"KFZ-Versicherung Details",children:s.jsxs("dl",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[k.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:[k.carInsuranceDetails.licensePlate,s.jsx(oe,{value:k.carInsuranceDetails.licensePlate})]})]}),k.carInsuranceDetails.vehicleType&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Fahrzeug"}),s.jsx("dd",{children:k.carInsuranceDetails.vehicleType})]}),k.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:[k.carInsuranceDetails.hsn,"/",k.carInsuranceDetails.tsn,s.jsx(oe,{value:`${k.carInsuranceDetails.hsn}/${k.carInsuranceDetails.tsn}`})]})]}),k.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:[k.carInsuranceDetails.vin,s.jsx(oe,{value:k.carInsuranceDetails.vin})]})]}),k.carInsuranceDetails.firstRegistration&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Erstzulassung"}),s.jsx("dd",{children:new Date(k.carInsuranceDetails.firstRegistration).toLocaleDateString("de-DE")})]}),k.carInsuranceDetails.noClaimsClass&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"SF-Klasse"}),s.jsx("dd",{children:k.carInsuranceDetails.noClaimsClass})]}),s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Versicherungsart"}),s.jsx("dd",{children:s.jsx(ge,{variant:k.carInsuranceDetails.insuranceType==="FULL"?"success":k.carInsuranceDetails.insuranceType==="PARTIAL"?"warning":"default",children:k.carInsuranceDetails.insuranceType==="FULL"?"Vollkasko":k.carInsuranceDetails.insuranceType==="PARTIAL"?"Teilkasko":"Haftpflicht"})})]}),k.carInsuranceDetails.deductiblePartial&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"SB Teilkasko"}),s.jsxs("dd",{children:[k.carInsuranceDetails.deductiblePartial," €"]})]}),k.carInsuranceDetails.deductibleFull&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"SB Vollkasko"}),s.jsxs("dd",{children:[k.carInsuranceDetails.deductibleFull," €"]})]}),k.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:[k.carInsuranceDetails.policyNumber,s.jsx(oe,{value:k.carInsuranceDetails.policyNumber})]})]}),k.carInsuranceDetails.previousInsurer&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Vorversicherer"}),s.jsx("dd",{children:k.carInsuranceDetails.previousInsurer})]})]})}),s.jsx(hC,{contractId:c,canEdit:i("contracts:update"),isCustomerPortal:o}),!o&&i("contracts:read")&&k.customerId&&s.jsx(ik,{contractId:c,customerId:k.customerId}),k.notes&&s.jsx(X,{title:"Notizen",children:s.jsx("p",{className:"whitespace-pre-wrap",children:k.notes})}),F&&k.previousContract&&s.jsx(Zk,{contractId:k.previousContract.id,isOpen:!0,onClose:()=>w(!1)}),s.jsx(He,{isOpen:C,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(I,{variant:"secondary",onClick:()=>E(!1),children:"Nein"}),s.jsx(I,{onClick:()=>{E(!1),S.mutate()},children:"Ja, anlegen"})]})]})}),s.jsx(lC,{isOpen:K,onClose:()=>O(!1)})]})}const xC=[{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"}],gC=[{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 yC({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(Zt,{className:"w-4 h-4"})})]}),s.jsx("div",{className:"space-y-2",children:gC.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 zx(){var Il,ai,Rl,ii,vh,jh,bh,Nh,wh;const{id:e}=bc(),[t]=wc(),n=Yt(),r=pe(),a=!!e,i=t.get("customerId"),{register:l,handleSubmit:o,reset:c,watch:d,setValue:u,formState:{errors:h}}=Uv({defaultValues:{customerId:i||"",type:"ELECTRICITY",status:"DRAFT",previousContractId:""}}),p=d("type"),m=d("customerId"),{data:f}=ue({queryKey:["contract",e],queryFn:()=>$e.getById(parseInt(e)),enabled:a}),{data:g}=ue({queryKey:["customers-all"],queryFn:()=>kt.getAll({limit:1e3})}),{data:v}=ue({queryKey:["customer",m],queryFn:()=>kt.getById(parseInt(m)),enabled:!!m}),{data:j}=ue({queryKey:["customer-contracts-for-predecessor",m],queryFn:()=>$e.getAll({customerId:parseInt(m),limit:1e3}),enabled:!!m}),{data:x}=ue({queryKey:["platforms"],queryFn:()=>rl.getAll()}),{data:y}=ue({queryKey:["cancellation-periods"],queryFn:()=>al.getAll()}),{data:N}=ue({queryKey:["contract-durations"],queryFn:()=>il.getAll()}),{data:D}=ue({queryKey:["providers"],queryFn:()=>Za.getAll()}),{data:P}=ue({queryKey:["contract-categories"],queryFn:()=>ll.getAll()}),F=d("providerId"),[w,C]=b.useState(null),[E,K]=b.useState([]),[O,B]=b.useState([]),[A,M]=b.useState(!1),[S,_]=b.useState("manual"),[U,Z]=b.useState(""),[W,fe]=b.useState(!1),[le,k]=b.useState(!1),[Re,Ye]=b.useState({}),[qe,et]=b.useState({}),[Rt,Bt]=b.useState({}),[z,Ne]=b.useState(!1);b.useEffect(()=>{a||M(!0)},[a]),b.useEffect(()=>{!a&&i&&(g!=null&&g.data)&&g.data.some(ae=>ae.id.toString()===i)&&u("customerId",i)},[a,i,g,u]),b.useEffect(()=>{A&&w&&F!==w&&u("tariffId",""),C(F)},[F,w,u,A]),b.useEffect(()=>{if(!a&&(P!=null&&P.data)&&P.data.length>0){const R=d("type"),ae=P.data.filter(me=>me.isActive),be=ae.some(me=>me.code===R);if(!R||!be){const me=ae.sort((ve,it)=>ve.sortOrder-it.sortOrder)[0];me&&u("type",me.code)}}},[P,a,u,d]),b.useEffect(()=>{a&&(f!=null&&f.data)&&!m&&u("customerId",f.data.customerId.toString())},[a,f,m,u]),b.useEffect(()=>{var R,ae,be,me,ve,it,Ce,li,Sh,kh,Ch,Eh,Dh,Ah,Ph,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;if(f!=null&&f.data&&(x!=null&&x.data)&&(P!=null&&P.data)&&(D!=null&&D.data)&&(v!=null&&v.data)){const ne=f.data;c({customerId:ne.customerId.toString(),type:ne.type,status:ne.status,addressId:((R=ne.addressId)==null?void 0:R.toString())||"",billingAddressId:((ae=ne.billingAddressId)==null?void 0:ae.toString())||"",bankCardId:((be=ne.bankCardId)==null?void 0:be.toString())||"",identityDocumentId:((me=ne.identityDocumentId)==null?void 0:me.toString())||"",salesPlatformId:((ve=ne.salesPlatformId)==null?void 0:ve.toString())||"",providerId:((it=ne.providerId)==null?void 0:it.toString())||"",tariffId:((Ce=ne.tariffId)==null?void 0:Ce.toString())||"",providerName:ne.providerName||"",tariffName:ne.tariffName||"",customerNumberAtProvider:ne.customerNumberAtProvider||"",priceFirst12Months:ne.priceFirst12Months||"",priceFrom13Months:ne.priceFrom13Months||"",priceAfter24Months:ne.priceAfter24Months||"",startDate:ne.startDate?ne.startDate.split("T")[0]:"",endDate:ne.endDate?ne.endDate.split("T")[0]:"",cancellationPeriodId:((li=ne.cancellationPeriodId)==null?void 0:li.toString())||"",contractDurationId:((Sh=ne.contractDurationId)==null?void 0:Sh.toString())||"",commission:ne.commission||"",portalUsername:ne.portalUsername||"",notes:ne.notes||"",meterId:((Ch=(kh=ne.energyDetails)==null?void 0:kh.meterId)==null?void 0:Ch.toString())||"",maloId:((Eh=ne.energyDetails)==null?void 0:Eh.maloId)||"",annualConsumption:((Dh=ne.energyDetails)==null?void 0:Dh.annualConsumption)||"",annualConsumptionKwh:((Ah=ne.energyDetails)==null?void 0:Ah.annualConsumptionKwh)||"",basePrice:((Ph=ne.energyDetails)==null?void 0:Ph.basePrice)||"",unitPrice:((Mh=ne.energyDetails)==null?void 0:Mh.unitPrice)||"",bonus:((Th=ne.energyDetails)==null?void 0:Th.bonus)||"",previousProviderName:((Fh=ne.energyDetails)==null?void 0:Fh.previousProviderName)||"",previousCustomerNumber:((Ih=ne.energyDetails)==null?void 0:Ih.previousCustomerNumber)||"",downloadSpeed:((Rh=ne.internetDetails)==null?void 0:Rh.downloadSpeed)||"",uploadSpeed:((Lh=ne.internetDetails)==null?void 0:Lh.uploadSpeed)||"",routerModel:((Oh=ne.internetDetails)==null?void 0:Oh.routerModel)||"",routerSerialNumber:((zh=ne.internetDetails)==null?void 0:zh.routerSerialNumber)||"",installationDate:($h=ne.internetDetails)!=null&&$h.installationDate?ne.internetDetails.installationDate.split("T")[0]:"",internetUsername:((_h=ne.internetDetails)==null?void 0:_h.internetUsername)||"",homeId:((Kh=ne.internetDetails)==null?void 0:Kh.homeId)||"",activationCode:((Uh=ne.internetDetails)==null?void 0:Uh.activationCode)||"",requiresMultisim:((Bh=ne.mobileDetails)==null?void 0:Bh.requiresMultisim)||!1,dataVolume:((qh=ne.mobileDetails)==null?void 0:qh.dataVolume)||"",includedMinutes:((Vh=ne.mobileDetails)==null?void 0:Vh.includedMinutes)||"",includedSMS:((Qh=ne.mobileDetails)==null?void 0:Qh.includedSMS)||"",deviceModel:((Hh=ne.mobileDetails)==null?void 0:Hh.deviceModel)||"",deviceImei:((Wh=ne.mobileDetails)==null?void 0:Wh.deviceImei)||"",phoneNumber:((Gh=ne.mobileDetails)==null?void 0:Gh.phoneNumber)||"",simCardNumber:((Zh=ne.mobileDetails)==null?void 0:Zh.simCardNumber)||"",receiverModel:((Jh=ne.tvDetails)==null?void 0:Jh.receiverModel)||"",smartcardNumber:((Xh=ne.tvDetails)==null?void 0:Xh.smartcardNumber)||"",tvPackage:((Yh=ne.tvDetails)==null?void 0:Yh.package)||"",licensePlate:((ef=ne.carInsuranceDetails)==null?void 0:ef.licensePlate)||"",hsn:((tf=ne.carInsuranceDetails)==null?void 0:tf.hsn)||"",tsn:((sf=ne.carInsuranceDetails)==null?void 0:sf.tsn)||"",vin:((nf=ne.carInsuranceDetails)==null?void 0:nf.vin)||"",vehicleType:((rf=ne.carInsuranceDetails)==null?void 0:rf.vehicleType)||"",firstRegistration:(af=ne.carInsuranceDetails)!=null&&af.firstRegistration?ne.carInsuranceDetails.firstRegistration.split("T")[0]:"",noClaimsClass:((lf=ne.carInsuranceDetails)==null?void 0:lf.noClaimsClass)||"",insuranceType:((of=ne.carInsuranceDetails)==null?void 0:of.insuranceType)||"LIABILITY",deductiblePartial:((cf=ne.carInsuranceDetails)==null?void 0:cf.deductiblePartial)||"",deductibleFull:((df=ne.carInsuranceDetails)==null?void 0:df.deductibleFull)||"",policyNumber:((uf=ne.carInsuranceDetails)==null?void 0:uf.policyNumber)||"",previousInsurer:((mf=ne.carInsuranceDetails)==null?void 0:mf.previousInsurer)||"",cancellationConfirmationDate:ne.cancellationConfirmationDate?ne.cancellationConfirmationDate.split("T")[0]:"",cancellationConfirmationOptionsDate:ne.cancellationConfirmationOptionsDate?ne.cancellationConfirmationOptionsDate.split("T")[0]:"",wasSpecialCancellation:ne.wasSpecialCancellation||!1,previousContractId:((hf=ne.previousContractId)==null?void 0:hf.toString())||""}),(ff=ne.mobileDetails)!=null&&ff.simCards&&ne.mobileDetails.simCards.length>0?K(ne.mobileDetails.simCards.map(ts=>({id:ts.id,phoneNumber:ts.phoneNumber||"",simCardNumber:ts.simCardNumber||"",pin:"",puk:"",hasExistingPin:!!ts.pin,hasExistingPuk:!!ts.puk,isMultisim:ts.isMultisim,isMain:ts.isMain}))):K([]),(pf=ne.internetDetails)!=null&&pf.phoneNumbers&&ne.internetDetails.phoneNumbers.length>0?B(ne.internetDetails.phoneNumbers.map(ts=>({id:ts.id,phoneNumber:ts.phoneNumber||"",sipUsername:ts.sipUsername||"",sipPassword:"",hasExistingSipPassword:!!ts.sipPasswordEncrypted,sipServer:ts.sipServer||"",isMain:ts.isMain}))):B([]),ne.stressfreiEmailId?(_("stressfrei"),Z(ne.stressfreiEmailId.toString())):(_("manual"),Z("")),M(!0)}},[f,c,x,P,D,v]);const Be=d("startDate"),es=d("contractDurationId");b.useEffect(()=>{if(Be&&es&&(N!=null&&N.data)){const R=N.data.find(ae=>ae.id===parseInt(es));if(R){const ae=new Date(Be),me=R.code.match(/^(\d+)([MTJ])$/);if(me){const ve=parseInt(me[1]),it=me[2];let Ce=new Date(ae);it==="T"?Ce.setDate(Ce.getDate()+ve):it==="M"?Ce.setMonth(Ce.getMonth()+ve):it==="J"&&Ce.setFullYear(Ce.getFullYear()+ve),u("endDate",Ce.toISOString().split("T")[0])}}}},[Be,es,N,u]);const Lt=G({mutationFn:$e.create,onSuccess:(R,ae)=>{r.invalidateQueries({queryKey:["contracts"]}),ae.customerId&&r.invalidateQueries({queryKey:["customer",ae.customerId.toString()]}),r.invalidateQueries({queryKey:["customers"]}),n(i?`/customers/${i}?tab=contracts`:"/contracts")}}),Ns=G({mutationFn:R=>$e.update(parseInt(e),R),onSuccess:(R,ae)=>{r.invalidateQueries({queryKey:["contracts"]}),r.invalidateQueries({queryKey:["contract",e]}),ae.customerId&&r.invalidateQueries({queryKey:["customer",ae.customerId.toString()]}),r.invalidateQueries({queryKey:["customers"]}),n(`/contracts/${e}`)}}),Y=R=>{const ae=Ce=>{if(Ce==null||Ce==="")return;const li=parseInt(String(Ce));return isNaN(li)?void 0:li},be=Fe.find(Ce=>Ce.code===R.type),me=ae(R.customerId);if(!me){alert("Bitte wählen Sie einen Kunden aus");return}if(!R.type||!be){alert("Bitte wählen Sie einen Vertragstyp aus");return}const ve=Ce=>Ce==null||Ce===""?null:Ce,it={customerId:me,type:R.type,contractCategoryId:be.id,status:R.status,addressId:ae(R.addressId)??null,billingAddressId:ae(R.billingAddressId)??null,bankCardId:ae(R.bankCardId)??null,identityDocumentId:ae(R.identityDocumentId)??null,salesPlatformId:ae(R.salesPlatformId)??null,providerId:ae(R.providerId)??null,tariffId:ae(R.tariffId)??null,providerName:ve(R.providerName),tariffName:ve(R.tariffName),customerNumberAtProvider:ve(R.customerNumberAtProvider),priceFirst12Months:ve(R.priceFirst12Months),priceFrom13Months:ve(R.priceFrom13Months),priceAfter24Months:ve(R.priceAfter24Months),startDate:R.startDate?new Date(R.startDate):null,endDate:R.endDate?new Date(R.endDate):null,cancellationPeriodId:ae(R.cancellationPeriodId)??null,contractDurationId:ae(R.contractDurationId)??null,commission:R.commission?parseFloat(R.commission):null,portalUsername:S==="manual"?ve(R.portalUsername):null,stressfreiEmailId:S==="stressfrei"&&U?parseInt(U):null,portalPassword:R.portalPassword||void 0,notes:ve(R.notes),cancellationConfirmationDate:R.cancellationConfirmationDate?new Date(R.cancellationConfirmationDate):null,cancellationConfirmationOptionsDate:R.cancellationConfirmationOptionsDate?new Date(R.cancellationConfirmationOptionsDate):null,wasSpecialCancellation:R.wasSpecialCancellation||!1,previousContractId:ae(R.previousContractId)??null};["ELECTRICITY","GAS"].includes(R.type)&&(it.energyDetails={meterId:ae(R.meterId)??null,maloId:ve(R.maloId),annualConsumption:R.annualConsumption?parseFloat(R.annualConsumption):null,annualConsumptionKwh:R.annualConsumptionKwh?parseFloat(R.annualConsumptionKwh):null,basePrice:R.basePrice?parseFloat(R.basePrice):null,unitPrice:R.unitPrice?parseFloat(R.unitPrice):null,bonus:R.bonus?parseFloat(R.bonus):null,previousProviderName:ve(R.previousProviderName),previousCustomerNumber:ve(R.previousCustomerNumber)}),["DSL","CABLE","FIBER"].includes(R.type)&&(it.internetDetails={downloadSpeed:ae(R.downloadSpeed)??null,uploadSpeed:ae(R.uploadSpeed)??null,routerModel:ve(R.routerModel),routerSerialNumber:ve(R.routerSerialNumber),installationDate:R.installationDate?new Date(R.installationDate):null,internetUsername:ve(R.internetUsername),internetPassword:R.internetPassword||void 0,homeId:ve(R.homeId),activationCode:ve(R.activationCode),phoneNumbers:O.length>0?O.map(Ce=>({id:Ce.id,phoneNumber:Ce.phoneNumber||"",isMain:Ce.isMain??!1,sipUsername:ve(Ce.sipUsername),sipPassword:Ce.sipPassword||void 0,sipServer:ve(Ce.sipServer)})):void 0}),R.type==="MOBILE"&&(it.mobileDetails={requiresMultisim:R.requiresMultisim||!1,dataVolume:R.dataVolume?parseFloat(R.dataVolume):null,includedMinutes:ae(R.includedMinutes)??null,includedSMS:ae(R.includedSMS)??null,deviceModel:ve(R.deviceModel),deviceImei:ve(R.deviceImei),phoneNumber:ve(R.phoneNumber),simCardNumber:ve(R.simCardNumber),simCards:E.length>0?E.map(Ce=>({id:Ce.id,phoneNumber:ve(Ce.phoneNumber),simCardNumber:ve(Ce.simCardNumber),pin:Ce.pin||void 0,puk:Ce.puk||void 0,isMultisim:Ce.isMultisim,isMain:Ce.isMain})):void 0}),R.type==="TV"&&(it.tvDetails={receiverModel:ve(R.receiverModel),smartcardNumber:ve(R.smartcardNumber),package:ve(R.tvPackage)}),R.type==="CAR_INSURANCE"&&(it.carInsuranceDetails={licensePlate:ve(R.licensePlate),hsn:ve(R.hsn),tsn:ve(R.tsn),vin:ve(R.vin),vehicleType:ve(R.vehicleType),firstRegistration:R.firstRegistration?new Date(R.firstRegistration):null,noClaimsClass:ve(R.noClaimsClass),insuranceType:R.insuranceType,deductiblePartial:R.deductiblePartial?parseFloat(R.deductiblePartial):null,deductibleFull:R.deductibleFull?parseFloat(R.deductibleFull):null,policyNumber:ve(R.policyNumber),previousInsurer:ve(R.previousInsurer)}),a?Ns.mutate(it):Lt.mutate(it)},Se=Lt.isPending||Ns.isPending,on=Lt.error||Ns.error,gt=v==null?void 0:v.data,cn=(gt==null?void 0:gt.addresses)||[],L=((Il=gt==null?void 0:gt.bankCards)==null?void 0:Il.filter(R=>R.isActive))||[],q=((ai=gt==null?void 0:gt.identityDocuments)==null?void 0:ai.filter(R=>R.isActive))||[],H=((Rl=gt==null?void 0:gt.meters)==null?void 0:Rl.filter(R=>R.isActive))||[],ie=((ii=gt==null?void 0:gt.stressfreiEmails)==null?void 0:ii.filter(R=>R.isActive))||[],se=(x==null?void 0:x.data)||[],ee=(y==null?void 0:y.data)||[],xe=(N==null?void 0:N.data)||[],Te=((vh=D==null?void 0:D.data)==null?void 0:vh.filter(R=>R.isActive))||[],Fe=((jh=P==null?void 0:P.data)==null?void 0:jh.filter(R=>R.isActive).sort((R,ae)=>R.sortOrder-ae.sortOrder))||[],Et=Fe.map(R=>({value:R.code,label:R.name})),dn=((j==null?void 0:j.data)||[]).filter(R=>!a||R.id!==parseInt(e)).sort((R,ae)=>new Date(ae.startDate||0).getTime()-new Date(R.startDate||0).getTime()),qt=Te.find(R=>R.id===parseInt(F||"0")),Rc=((bh=qt==null?void 0:qt.tariffs)==null?void 0:bh.filter(R=>R.isActive))||[],ta=R=>{const ae=R.companyName||`${R.firstName} ${R.lastName}`,be=R.birthDate?` (geb. ${new Date(R.birthDate).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"})})`:"";return`${R.customerNumber} - ${ae}${be}`},ri=(()=>{var be;const ae=((g==null?void 0:g.data)||[]).map(me=>({value:me.id.toString(),label:ta(me)}));if(a&&((be=f==null?void 0:f.data)!=null&&be.customer)){const me=f.data.customer;ae.some(it=>it.value===me.id.toString())||ae.unshift({value:me.id.toString(),label:ta(me)})}return ae})();return s.jsxs("div",{children:[s.jsx("h1",{className:"text-2xl font-bold mb-6",children:a?"Vertrag bearbeiten":"Neuer Vertrag"}),on&&s.jsx("div",{className:"mb-4 p-4 bg-red-50 border border-red-200 text-red-700 rounded-lg",children:on instanceof Error?on.message:"Ein Fehler ist aufgetreten"}),s.jsxs("form",{onSubmit:o(Y),children:[s.jsx(X,{className:"mb-6",title:"Vertragsdaten",children:s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[s.jsx(Le,{label:"Kunde *",...l("customerId",{required:"Kunde erforderlich"}),options:ri,error:(Nh=h.customerId)==null?void 0:Nh.message}),s.jsx(Le,{label:"Vertragstyp *",...l("type",{required:"Typ erforderlich"}),options:Et}),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:()=>Ne(!0),className:"text-gray-400 hover:text-blue-600 transition-colors",title:"Status-Erklärung",children:s.jsx(Al,{className:"w-4 h-4"})})]}),s.jsx(Le,{...l("status"),options:xC})]}),s.jsx(Le,{label:"Vertriebsplattform",...l("salesPlatformId"),options:se.map(R=>({value:R.id,label:R.name}))}),m&&s.jsx(Le,{label:"Vorgänger-Vertrag",...l("previousContractId"),options:dn.map(R=>({value:R.id,label:`${R.contractNumber} (${R.type}${R.startDate?` - ${new Date(R.startDate).toLocaleDateString("de-DE")}`:""})`})),placeholder:"Keinen Vorgänger auswählen"})]})}),m&&s.jsxs(X,{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(Le,{label:"Lieferadresse",...l("addressId"),options:cn.filter(R=>R.type==="DELIVERY_RESIDENCE").map(R=>({value:R.id,label:`${R.street} ${R.houseNumber}, ${R.postalCode} ${R.city}`}))}),s.jsx(Le,{label:"Rechnungsadresse",...l("billingAddressId"),options:cn.filter(R=>R.type==="BILLING").map(R=>({value:R.id,label:`${R.street} ${R.houseNumber}, ${R.postalCode} ${R.city}`})),placeholder:"Wie Lieferadresse"})]}),s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[s.jsx(Le,{label:"Bankkarte",...l("bankCardId"),options:L.map(R=>({value:R.id,label:`${R.iban} (${R.accountHolder})`}))}),s.jsx(Le,{label:"Ausweis",...l("identityDocumentId"),options:q.map(R=>({value:R.id,label:`${R.documentNumber} (${R.type})`}))})]})]}),s.jsx(X,{className:"mb-6",title:"Anbieter & Tarif",children:s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[s.jsx(Le,{label:"Anbieter",...l("providerId"),options:Te.map(R=>({value:R.id,label:R.name}))}),s.jsx(Le,{label:"Tarif",...l("tariffId"),options:Rc.map(R=>({value:R.id,label:R.name})),disabled:!F}),s.jsx(Q,{label:"Kundennummer beim Anbieter",...l("customerNumberAtProvider")}),s.jsx(Q,{label:"Provision (€)",type:"number",step:"0.01",...l("commission")}),s.jsx(Q,{label:"Preis erste 12 Monate",...l("priceFirst12Months"),placeholder:"z.B. 29,99 €/Monat"}),s.jsx(Q,{label:"Preis ab 13. Monat",...l("priceFrom13Months"),placeholder:"z.B. 39,99 €/Monat"}),s.jsx(Q,{label:"Preis nach 24 Monaten",...l("priceAfter24Months"),placeholder:"z.B. 49,99 €/Monat"})]})}),s.jsxs(X,{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(Q,{label:"Vertragsbeginn",type:"date",...l("startDate"),value:d("startDate")||"",onClear:()=>u("startDate","")}),s.jsx(Q,{label:"Vertragsende (berechnet)",type:"date",...l("endDate"),disabled:!0,className:"bg-gray-50"}),s.jsx(Le,{label:"Vertragslaufzeit",...l("contractDurationId"),options:xe.map(R=>({value:R.id,label:R.description}))}),s.jsx(Le,{label:"Kündigungsfrist",...l("cancellationPeriodId"),options:ee.map(R=>({value:R.id,label:R.description}))}),s.jsx(Q,{label:"Kündigungsbestätigungsdatum",type:"date",...l("cancellationConfirmationDate"),value:d("cancellationConfirmationDate")||"",onClear:()=>u("cancellationConfirmationDate","")}),s.jsx(Q,{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(X,{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:S==="manual",onChange:()=>{_("manual"),Z("")},className:"text-blue-600"}),s.jsx("span",{className:"text-sm",children:"Manuell eingeben"})]}),S==="manual"&&s.jsx(Q,{...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:S==="stressfrei",onChange:()=>{_("stressfrei"),u("portalUsername","")},className:"text-blue-600"}),s.jsx("span",{className:"text-sm",children:"Stressfrei-Wechseln Adresse"})]}),S==="stressfrei"&&s.jsx(Le,{value:U,onChange:R=>Z(R.target.value),options:ie.map(R=>({value:R.id,label:R.email+(R.notes?` (${R.notes})`:"")})),placeholder:ie.length===0?"Keine Stressfrei-Adressen vorhanden":"Adresse auswählen..."}),S==="stressfrei"&&ie.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:W?"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:()=>fe(!W),className:"absolute inset-y-0 right-0 flex items-center pr-3 text-gray-400 hover:text-gray-600",children:W?s.jsx(Mt,{className:"w-4 h-4"}):s.jsx(Ae,{className:"w-4 h-4"})})]})]})]})}),["ELECTRICITY","GAS"].includes(p)&&s.jsx(X,{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(Le,{label:"Zähler",...l("meterId"),options:H.filter(R=>R.type===p).map(R=>({value:R.id,label:`${R.meterNumber}${R.location?` (${R.location})`:""}`}))}),s.jsx(Q,{label:"MaLo-ID (Marktlokations-ID)",...l("maloId")}),s.jsx(Q,{label:`Jahresverbrauch (${p==="ELECTRICITY"?"kWh":"m³"})`,type:"number",...l("annualConsumption")}),p==="GAS"&&s.jsx(Q,{label:"Jahresverbrauch (kWh)",type:"number",...l("annualConsumptionKwh")}),s.jsx(Q,{label:"Grundpreis (€/Monat)",type:"number",step:"any",...l("basePrice")}),s.jsx(Q,{label:"Arbeitspreis (€/kWh)",type:"number",step:"any",...l("unitPrice")}),s.jsx(Q,{label:"Bonus (€)",type:"number",step:"0.01",...l("bonus")}),s.jsx(Q,{label:"Vorversorger",...l("previousProviderName")}),s.jsx(Q,{label:"Kundennr. beim Vorversorger",...l("previousCustomerNumber")})]})}),["DSL","CABLE","FIBER"].includes(p)&&s.jsxs(s.Fragment,{children:[s.jsx(X,{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(Q,{label:"Download (Mbit/s)",type:"number",...l("downloadSpeed")}),s.jsx(Q,{label:"Upload (Mbit/s)",type:"number",...l("uploadSpeed")}),s.jsx(Q,{label:"Router Modell",...l("routerModel")}),s.jsx(Q,{label:"Router Seriennummer",...l("routerSerialNumber")}),s.jsx(Q,{label:"Installationsdatum",type:"date",...l("installationDate"),value:d("installationDate")||"",onClear:()=>u("installationDate","")}),p==="FIBER"&&s.jsx(Q,{label:"Home-ID",...l("homeId")}),((wh=qt==null?void 0:qt.name)==null?void 0:wh.toLowerCase().includes("vodafone"))&&["DSL","CABLE"].includes(p)&&s.jsx(Q,{label:"Aktivierungscode",...l("activationCode")})]})}),s.jsx(X,{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(Q,{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:le?"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:()=>k(!le),className:"absolute inset-y-0 right-0 flex items-center pr-3 text-gray-400 hover:text-gray-600",children:le?s.jsx(Mt,{className:"w-4 h-4"}):s.jsx(Ae,{className:"w-4 h-4"})})]})]})]})}),s.jsxs(X,{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."}),O.length>0&&s.jsx("div",{className:"space-y-4 mb-4",children:O.map((R,ae)=>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 ",ae+1]}),s.jsxs("label",{className:"flex items-center gap-1 text-sm",children:[s.jsx("input",{type:"checkbox",checked:R.isMain,onChange:be=>{const me=[...O];be.target.checked?me.forEach((ve,it)=>ve.isMain=it===ae):me[ae].isMain=!1,B(me)},className:"rounded border-gray-300"}),"Hauptnummer"]})]}),s.jsx(I,{type:"button",variant:"ghost",size:"sm",onClick:()=>{B(O.filter((be,me)=>me!==ae))},children:s.jsx(je,{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(Q,{label:"Rufnummer",value:R.phoneNumber,onChange:be=>{const me=[...O];me[ae].phoneNumber=be.target.value,B(me)},placeholder:"z.B. 030 123456"}),s.jsx(Q,{label:"SIP-Benutzername",value:R.sipUsername,onChange:be=>{const me=[...O];me[ae].sipUsername=be.target.value,B(me)}}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:R.hasExistingSipPassword?"SIP-Passwort (bereits hinterlegt)":"SIP-Passwort"}),s.jsxs("div",{className:"relative",children:[s.jsx("input",{type:Re[ae]?"text":"password",value:R.sipPassword,onChange:be=>{const me=[...O];me[ae].sipPassword=be.target.value,B(me)},placeholder:R.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:()=>Ye(be=>({...be,[ae]:!be[ae]})),className:"absolute inset-y-0 right-0 flex items-center pr-3 text-gray-400 hover:text-gray-600",children:Re[ae]?s.jsx(Mt,{className:"w-4 h-4"}):s.jsx(Ae,{className:"w-4 h-4"})})]})]}),s.jsx(Q,{label:"SIP-Server",value:R.sipServer,onChange:be=>{const me=[...O];me[ae].sipServer=be.target.value,B(me)},placeholder:"z.B. sip.provider.de"})]})]},ae))}),s.jsxs(I,{type:"button",variant:"secondary",onClick:()=>{B([...O,{phoneNumber:"",sipUsername:"",sipPassword:"",sipServer:"",isMain:O.length===0}])},children:[s.jsx(Ue,{className:"w-4 h-4 mr-2"}),"Rufnummer hinzufügen"]})]})]}),p==="MOBILE"&&s.jsxs(s.Fragment,{children:[s.jsxs(X,{className:"mb-6",title:"Mobilfunk-Details",children:[s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[s.jsx(Q,{label:"Datenvolumen (GB)",type:"number",...l("dataVolume")}),s.jsx(Q,{label:"Inklusiv-Minuten",type:"number",...l("includedMinutes")}),s.jsx(Q,{label:"Inklusiv-SMS",type:"number",...l("includedSMS")}),s.jsx(Q,{label:"Gerät (Modell)",...l("deviceModel")}),s.jsx(Q,{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(X,{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((R,ae)=>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 ",ae+1]}),s.jsxs("label",{className:"flex items-center gap-1 text-sm",children:[s.jsx("input",{type:"checkbox",checked:R.isMain,onChange:be=>{const me=[...E];be.target.checked?me.forEach((ve,it)=>ve.isMain=it===ae):me[ae].isMain=!1,K(me)},className:"rounded border-gray-300"}),"Hauptkarte"]}),s.jsxs("label",{className:"flex items-center gap-1 text-sm",children:[s.jsx("input",{type:"checkbox",checked:R.isMultisim,onChange:be=>{const me=[...E];me[ae].isMultisim=be.target.checked,K(me)},className:"rounded border-gray-300"}),"Multisim"]})]}),s.jsx(I,{type:"button",variant:"ghost",size:"sm",onClick:()=>{K(E.filter((be,me)=>me!==ae))},children:s.jsx(je,{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(Q,{label:"Rufnummer",value:R.phoneNumber,onChange:be=>{const me=[...E];me[ae].phoneNumber=be.target.value,K(me)},placeholder:"z.B. 0171 1234567"}),s.jsx(Q,{label:"SIM-Kartennummer",value:R.simCardNumber,onChange:be=>{const me=[...E];me[ae].simCardNumber=be.target.value,K(me)},placeholder:"ICCID"}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:R.hasExistingPin?"PIN (bereits hinterlegt)":"PIN"}),s.jsxs("div",{className:"relative",children:[s.jsx("input",{type:qe[ae]?"text":"password",value:R.pin,onChange:be=>{const me=[...E];me[ae].pin=be.target.value,K(me)},placeholder:R.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(be=>({...be,[ae]:!be[ae]})),className:"absolute inset-y-0 right-0 flex items-center pr-3 text-gray-400 hover:text-gray-600",children:qe[ae]?s.jsx(Mt,{className:"w-4 h-4"}):s.jsx(Ae,{className:"w-4 h-4"})})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:R.hasExistingPuk?"PUK (bereits hinterlegt)":"PUK"}),s.jsxs("div",{className:"relative",children:[s.jsx("input",{type:Rt[ae]?"text":"password",value:R.puk,onChange:be=>{const me=[...E];me[ae].puk=be.target.value,K(me)},placeholder:R.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:()=>Bt(be=>({...be,[ae]:!be[ae]})),className:"absolute inset-y-0 right-0 flex items-center pr-3 text-gray-400 hover:text-gray-600",children:Rt[ae]?s.jsx(Mt,{className:"w-4 h-4"}):s.jsx(Ae,{className:"w-4 h-4"})})]})]})]})]},ae))}),s.jsxs(I,{type:"button",variant:"secondary",onClick:()=>{K([...E,{phoneNumber:"",simCardNumber:"",pin:"",puk:"",isMultisim:!1,isMain:E.length===0}])},children:[s.jsx(Ue,{className:"w-4 h-4 mr-2"}),"SIM-Karte hinzufügen"]})]})]}),p==="TV"&&s.jsx(X,{className:"mb-6",title:"TV-Details",children:s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[s.jsx(Q,{label:"Receiver Modell",...l("receiverModel")}),s.jsx(Q,{label:"Smartcard-Nummer",...l("smartcardNumber")}),s.jsx(Q,{label:"Paket",...l("tvPackage"),placeholder:"z.B. Basis, Premium, Sport"})]})}),p==="CAR_INSURANCE"&&s.jsx(X,{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(Q,{label:"Kennzeichen",...l("licensePlate")}),s.jsx(Q,{label:"HSN",...l("hsn")}),s.jsx(Q,{label:"TSN",...l("tsn")}),s.jsx(Q,{label:"FIN (VIN)",...l("vin")}),s.jsx(Q,{label:"Fahrzeugtyp",...l("vehicleType")}),s.jsx(Q,{label:"Erstzulassung",type:"date",...l("firstRegistration"),value:d("firstRegistration")||"",onClear:()=>u("firstRegistration","")}),s.jsx(Q,{label:"SF-Klasse",...l("noClaimsClass")}),s.jsx(Le,{label:"Versicherungsart",...l("insuranceType"),options:[{value:"LIABILITY",label:"Haftpflicht"},{value:"PARTIAL",label:"Teilkasko"},{value:"FULL",label:"Vollkasko"}]}),s.jsx(Q,{label:"SB Teilkasko (€)",type:"number",...l("deductiblePartial")}),s.jsx(Q,{label:"SB Vollkasko (€)",type:"number",...l("deductibleFull")}),s.jsx(Q,{label:"Versicherungsscheinnummer",...l("policyNumber")}),s.jsx(Q,{label:"Vorversicherer",...l("previousInsurer")})]})}),s.jsx(X,{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(I,{type:"button",variant:"secondary",onClick:()=>n(-1),children:"Abbrechen"}),s.jsx(I,{type:"submit",disabled:Se,children:Se?"Speichern...":"Speichern"})]})]}),s.jsx(yC,{isOpen:z,onClose:()=>Ne(!1)})]})}const vC={ELECTRICITY:hh,GAS:wv,DSL:ka,CABLE:ka,FIBER:ka,MOBILE:uh,TV:Pv,CAR_INSURANCE:Nv},jC={ELECTRICITY:"Strom",GAS:"Gas",DSL:"DSL",CABLE:"Kabel",FIBER:"Glasfaser",MOBILE:"Mobilfunk",TV:"TV",CAR_INSURANCE:"KFZ"},bC={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"},NC={critical:"danger",warning:"warning",ok:"success",none:"default"},wC={cancellation_deadline:bv,contract_ending:Mn,missing_cancellation_letter:_e,missing_cancellation_confirmation:_e,missing_portal_credentials:F2,missing_customer_number:_e,missing_provider:_e,missing_address:_e,missing_bank:_e,missing_meter:hh,missing_sim:uh,open_tasks:ol,pending_status:Mn,draft_status:_e},SC={cancellationDeadlines:"Kündigungsfristen",contractEnding:"Vertragsenden",missingCredentials:"Fehlende Zugangsdaten",missingData:"Fehlende Daten",openTasks:"Offene Aufgaben",pendingContracts:"Wartende Verträge"};function kC(){var g;const[e,t]=wc(),[n,r]=b.useState(new Set),a=e.get("filter"),[i,l]=b.useState(a||"all");b.useEffect(()=>{i==="all"?e.delete("filter"):e.set("filter",i),t(e,{replace:!0})},[i,e,t]);const{data:o,isLoading:c,error:d}=ue({queryKey:["contract-cockpit"],queryFn:()=>$e.getCockpit(),staleTime:0}),u=v=>{r(j=>{const x=new Set(j);return x.has(v)?x.delete(v):x.add(v),x})},h=b.useMemo(()=>{var j;if(!((j=o==null?void 0:o.data)!=null&&j.contracts))return[];const v=o.data.contracts;switch(i){case"critical":return v.filter(x=>x.highestUrgency==="critical");case"warning":return v.filter(x=>x.highestUrgency==="warning");case"ok":return v.filter(x=>x.highestUrgency==="ok");case"deadlines":return v.filter(x=>x.issues.some(y=>["cancellation_deadline","contract_ending"].includes(y.type)));case"credentials":return v.filter(x=>x.issues.some(y=>y.type.includes("credentials")));case"data":return v.filter(x=>x.issues.some(y=>y.type.startsWith("missing_")&&!y.type.includes("credentials")));case"tasks":return v.filter(x=>x.issues.some(y=>["open_tasks","pending_status","draft_status"].includes(y.type)));default:return v}},[(g=o==null?void 0:o.data)==null?void 0:g.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:p,thresholds:m}=o.data,f=v=>{var y,N,D,P;const j=n.has(v.id),x=vC[v.type]||_e;return s.jsxs("div",{className:`border rounded-lg mb-2 ${bC[v.highestUrgency]}`,children:[s.jsxs("div",{className:"flex items-center p-4 cursor-pointer hover:bg-opacity-50",onClick:()=>u(v.id),children:[s.jsx("div",{className:"w-6 mr-2",children:j?s.jsx(Rn,{className:"w-5 h-5"}):s.jsx(Pt,{className:"w-5 h-5"})}),s.jsx(x,{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/${v.id}`,state:{from:"cockpit",filter:i!=="all"?i:void 0},className:"font-medium hover:underline",onClick:F=>F.stopPropagation(),children:v.contractNumber}),s.jsxs(ge,{variant:NC[v.highestUrgency],children:[v.issues.length," ",v.highestUrgency==="ok"?v.issues.length===1?"Hinweis":"Hinweise":v.issues.length===1?"Problem":"Probleme"]}),s.jsx("span",{className:"text-sm",children:jC[v.type]})]}),s.jsxs("div",{className:"text-sm mt-1",children:[s.jsxs(ke,{to:`/customers/${v.customer.id}`,className:"hover:underline",onClick:F=>F.stopPropagation(),children:[v.customer.customerNumber," - ",v.customer.name]}),(((y=v.provider)==null?void 0:y.name)||v.providerName)&&s.jsxs("span",{className:"ml-2",children:["| ",((N=v.provider)==null?void 0:N.name)||v.providerName,(((D=v.tariff)==null?void 0:D.name)||v.tariffName)&&` - ${((P=v.tariff)==null?void 0:P.name)||v.tariffName}`]})]})]}),s.jsx(ke,{to:`/contracts/${v.id}`,state:{from:"cockpit",filter:i!=="all"?i:void 0},className:"ml-4 p-2 hover:bg-white hover:bg-opacity-50 rounded",onClick:F=>F.stopPropagation(),title:"Zum Vertrag",children:s.jsx(Ae,{className:"w-4 h-4"})})]}),j&&s.jsx("div",{className:"border-t px-4 py-3 bg-white bg-opacity-50",children:s.jsx("div",{className:"space-y-2",children:v.issues.map((F,w)=>{const C=wC[F.type]||wn,E=F.urgency==="critical"?wn:F.urgency==="warning"?ms:F.urgency==="ok"?As:Mn;return s.jsxs("div",{className:"flex items-start gap-3 text-sm",children:[s.jsx(E,{className:`w-4 h-4 mt-0.5 flex-shrink-0 ${F.urgency==="critical"?"text-red-500":F.urgency==="warning"?"text-yellow-500":F.urgency==="ok"?"text-green-500":"text-gray-500"}`}),s.jsx(C,{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:F.label}),F.details&&s.jsx("span",{className:"text-gray-600 ml-2",children:F.details})]})]},w)})})})]},v.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(wn,{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(X,{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(wn,{className:"w-6 h-6 text-red-500"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-2xl font-bold text-red-600",children:p.criticalCount}),s.jsxs("p",{className:"text-sm text-gray-500",children:["Kritisch (<",m.criticalDays," Tage)"]})]})]})}),s.jsx(X,{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(ms,{className:"w-6 h-6 text-yellow-500"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-2xl font-bold text-yellow-600",children:p.warningCount}),s.jsxs("p",{className:"text-sm text-gray-500",children:["Warnung (<",m.warningDays," Tage)"]})]})]})}),s.jsx(X,{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(As,{className:"w-6 h-6 text-green-500"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-2xl font-bold text-green-600",children:p.okCount}),s.jsxs("p",{className:"text-sm text-gray-500",children:["OK (<",m.okDays," Tage)"]})]})]})}),s.jsx(X,{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(_e,{className:"w-6 h-6 text-gray-500"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-2xl font-bold text-gray-600",children:p.totalContracts}),s.jsx("p",{className:"text-sm text-gray-500",children:"Verträge mit Handlungsbedarf"})]})]})})]}),s.jsx(X,{className:"mb-6",children:s.jsx("div",{className:"flex flex-wrap gap-4",children:Object.entries(p.byCategory).map(([v,j])=>j>0&&s.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[s.jsxs("span",{className:"font-medium",children:[SC[v]||v,":"]}),s.jsx(ge,{variant:"default",children:j})]},v))})}),s.jsx(X,{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(Le,{value:i,onChange:v=>l(v.target.value),options:[{value:"all",label:`Alle (${o.data.contracts.length})`},{value:"critical",label:`Kritisch (${p.criticalCount})`},{value:"warning",label:`Warnung (${p.warningCount})`},{value:"ok",label:`OK (${p.okCount})`},{value:"deadlines",label:`Fristen (${p.byCategory.cancellationDeadlines+p.byCategory.contractEnding})`},{value:"credentials",label:`Zugangsdaten (${p.byCategory.missingCredentials})`},{value:"data",label:`Fehlende Daten (${p.byCategory.missingData})`},{value:"tasks",label:`Aufgaben/Status (${p.byCategory.openTasks+p.byCategory.pendingContracts})`}],className:"w-64"}),s.jsxs("span",{className:"text-sm text-gray-500",children:[h.length," Verträge angezeigt"]})]})}),h.length===0?s.jsx(X,{children:s.jsx("div",{className:"text-center py-8 text-gray-500",children:i==="all"?s.jsxs(s.Fragment,{children:[s.jsx(As,{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:h.map(f)})]})}const $x={OPEN:"Offen",COMPLETED:"Erledigt"},CC={OPEN:"warning",COMPLETED:"success"};function EC(){var A;const e=Yt(),t=pe(),{isCustomerPortal:n,user:r,hasPermission:a}=Qe(),[i,l]=b.useState("OPEN"),[o,c]=b.useState(new Set),[d,u]=b.useState(!1),[h,p]=b.useState({}),m=n?"Support-Anfragen":"Aufgaben",f=n?"Anfrage":"Aufgabe",{data:g,isLoading:v}=ue({queryKey:["app-settings-public"],queryFn:()=>Jr.getPublic(),enabled:n,staleTime:0}),j=!v&&((A=g==null?void 0:g.data)==null?void 0:A.customerSupportTicketsEnabled)==="true",{data:x,isLoading:y}=ue({queryKey:["all-tasks",i],queryFn:()=>dt.getAll({status:i||void 0}),staleTime:0}),N=G({mutationFn:M=>dt.completeSubtask(M),onSuccess:()=>{t.invalidateQueries({queryKey:["all-tasks"]}),t.invalidateQueries({queryKey:["task-stats"]})}}),D=G({mutationFn:M=>dt.reopenSubtask(M),onSuccess:()=>{t.invalidateQueries({queryKey:["all-tasks"]}),t.invalidateQueries({queryKey:["task-stats"]})}}),P=G({mutationFn:({taskId:M,title:S})=>n?dt.createReply(M,S):dt.createSubtask(M,S),onSuccess:(M,{taskId:S})=>{t.invalidateQueries({queryKey:["all-tasks"]}),p(_=>({..._,[S]:""}))}}),F=b.useMemo(()=>{var U;if(!(x!=null&&x.data))return{ownTasks:[],representedTasks:[],allTasks:[]};const M=x.data;if(!n)return{allTasks:M,ownTasks:[],representedTasks:[]};const S=[],_=[];for(const Z of M)((U=Z.contract)==null?void 0:U.customerId)===(r==null?void 0:r.customerId)?S.push(Z):_.push(Z);return{ownTasks:S,representedTasks:_,allTasks:[]}},[x==null?void 0:x.data,n,r==null?void 0:r.customerId]),w=M=>{c(S=>{const _=new Set(S);return _.has(M)?_.delete(M):_.add(M),_})},C=M=>{N.isPending||D.isPending||(M.status==="COMPLETED"?D.mutate(M.id):N.mutate(M.id))},E=M=>{var _;const S=(_=h[M])==null?void 0:_.trim();S&&P.mutate({taskId:M,title:S})},K=!n&&a("contracts:update"),O=(M,S=!1)=>{var Re,Ye,qe,et,Rt,Bt;const _=o.has(M.id),U=M.subtasks&&M.subtasks.length>0,Z=((Re=M.subtasks)==null?void 0:Re.filter(z=>z.status==="COMPLETED").length)||0,W=((Ye=M.subtasks)==null?void 0:Ye.length)||0,fe=M.status==="COMPLETED",le=M.contract?`${M.contract.contractNumber} - ${((qe=M.contract.provider)==null?void 0:qe.name)||M.contract.providerName||"Kein Anbieter"}`:`Vertrag #${M.contractId}`,k=(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(Rn,{className:"w-5 h-5 text-gray-400"}):s.jsx(Pt,{className:"w-5 h-5 text-gray-400"})}),s.jsx("div",{className:"mr-3",children:M.status==="COMPLETED"?s.jsx(As,{className:"w-5 h-5 text-green-500"}):s.jsx(Mn,{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(ge,{variant:CC[M.status],children:$x[M.status]}),U&&s.jsxs("span",{className:"text-xs text-gray-500",children:["(",Z,"/",W," erledigt)"]})]}),s.jsxs("div",{className:"text-sm text-gray-500 mt-1 flex items-center gap-2",children:[s.jsx(_e,{className:"w-4 h-4"}),s.jsx(ke,{to:`/contracts/${M.contractId}`,className:"text-blue-600 hover:underline",onClick:z=>z.stopPropagation(),children:le}),S&&k&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-gray-400",children:"|"}),s.jsx("span",{children:k})]})]}),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(I,{variant:"ghost",size:"sm",onClick:z=>{z.stopPropagation(),e(`/contracts/${M.contractId}`)},title:"Zum Vertrag",children:s.jsx(Ae,{className:"w-4 h-4"})})})]}),_&&s.jsxs("div",{className:"border-t bg-gray-50 px-4 py-3",children:[U&&s.jsx("div",{className:"space-y-2 mb-4",children:(Rt=M.subtasks)==null?void 0:Rt.map(z=>{const Ne=new Date(z.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 ${K?"cursor-pointer hover:bg-gray-100 rounded px-2 py-1 -mx-2":""}`,onClick:K?()=>C(z):void 0,children:[s.jsx("span",{className:"flex-shrink-0 mt-0.5",children:z.status==="COMPLETED"?s.jsx(As,{className:"w-4 h-4 text-green-500"}):s.jsx(No,{className:"w-4 h-4 text-gray-400"})}),s.jsxs("span",{className:z.status==="COMPLETED"?"text-gray-500 line-through":"",children:[z.title,s.jsxs("span",{className:"text-xs text-gray-400 ml-2",children:[z.createdBy," • ",Ne]})]})]},z.id)})}),!fe&&(K||n)&&s.jsxs("div",{className:"flex gap-2 ml-6",children:[s.jsx(Q,{placeholder:n?"Antwort schreiben...":"Neue Unteraufgabe...",value:h[M.id]||"",onChange:z=>p(Ne=>({...Ne,[M.id]:z.target.value})),onKeyDown:z=>{z.key==="Enter"&&!z.shiftKey&&(z.preventDefault(),E(M.id))},className:"flex-1"}),s.jsx(I,{size:"sm",onClick:()=>E(M.id),disabled:!((Bt=h[M.id])!=null&&Bt.trim())||P.isPending,children:s.jsx(Ml,{className:"w-4 h-4"})})]}),!U&&fe&&s.jsx("p",{className:"text-gray-500 text-sm text-center py-2",children:"Keine Unteraufgaben vorhanden."})]})]},M.id)},B=n?j: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(I,{onClick:()=>u(!0),children:[s.jsx(Ue,{className:"w-4 h-4 mr-2"}),"Neue ",f]})]}),s.jsx(X,{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(Le,{value:i,onChange:M=>l(M.target.value),options:[{value:"",label:"Alle"},...Object.entries($x).map(([M,S])=>({value:M,label:S}))],className:"w-40"})]})})}),y?s.jsx(X,{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(X,{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(ge,{variant:"default",children:F.ownTasks.length})]}),F.ownTasks.length>0?s.jsx("div",{children:F.ownTasks.map(M=>O(M,!1))}):s.jsxs("p",{className:"text-gray-500 text-center py-4",children:["Keine eigenen ",m.toLowerCase()," vorhanden."]})]}),F.representedTasks.length>0&&s.jsxs(X,{children:[s.jsxs("div",{className:"flex items-center gap-3 mb-4 pb-3 border-b",children:[s.jsx(Sa,{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(ge,{variant:"default",children:F.representedTasks.length})]}),s.jsx("div",{children:F.representedTasks.map(M=>O(M,!0))})]})]}):s.jsx(X,{children:F.allTasks&&F.allTasks.length>0?s.jsx("div",{children:F.allTasks.map(M=>O(M,!0))}):s.jsxs("div",{className:"text-center py-8 text-gray-500",children:["Keine ",m.toLowerCase()," gefunden."]})})}),n?s.jsx(DC,{isOpen:d,onClose:()=>u(!1)}):s.jsx(AC,{isOpen:d,onClose:()=>u(!1)})]})}function DC({isOpen:e,onClose:t}){const{user:n}=Qe(),r=Yt(),a=pe(),[i,l]=b.useState("own"),[o,c]=b.useState(null),[d,u]=b.useState(""),[h,p]=b.useState(""),[m,f]=b.useState(!1),[g,v]=b.useState(""),{data:j}=ue({queryKey:["contracts",n==null?void 0:n.customerId],queryFn:()=>$e.getAll({customerId:n==null?void 0:n.customerId}),enabled:e}),x=b.useMemo(()=>{if(!(j!=null&&j.data))return{own:[],represented:{}};const w=[],C={};for(const E of j.data)if(E.customerId===(n==null?void 0:n.customerId))w.push(E);else{if(!C[E.customerId]){const K=E.customer?E.customer.companyName||`${E.customer.firstName} ${E.customer.lastName}`:`Kunde ${E.customerId}`;C[E.customerId]={name:K,contracts:[]}}C[E.customerId].contracts.push(E)}return{own:w,represented:C}},[j==null?void 0:j.data,n==null?void 0:n.customerId]),y=Object.keys(x.represented).length>0,N=b.useMemo(()=>{var w;return i==="own"?x.own:((w=x.represented[i])==null?void 0:w.contracts)||[]},[i,x]),D=b.useMemo(()=>{if(!g)return N;const w=g.toLowerCase();return N.filter(C=>C.contractNumber.toLowerCase().includes(w)||(C.providerName||"").toLowerCase().includes(w)||(C.tariffName||"").toLowerCase().includes(w))},[N,g]),P=async()=>{if(!(!o||!d.trim())){f(!0);try{await dt.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)}}},F=()=>{u(""),p(""),c(null),l("own"),v(""),t()};return s.jsx(He,{isOpen:e,onClose:F,title:"Neue Support-Anfrage",children:s.jsxs("div",{className:"space-y-4",children:[y&&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 C=w.target.value;l(C==="own"?"own":parseInt(C)),c(null),v("")},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(x.represented).map(([w,{name:C}])=>s.jsx("option",{value:w,children:C},w))]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Vertrag *"}),s.jsx(Q,{placeholder:"Vertrag suchen...",value:g,onChange:w=>v(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(Q,{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(I,{variant:"secondary",onClick:F,children:"Abbrechen"}),s.jsx(I,{onClick:P,disabled:!o||!d.trim()||m,children:m?"Wird erstellt...":"Anfrage erstellen"})]})]})})}function AC({isOpen:e,onClose:t}){const n=Yt(),r=pe(),[a,i]=b.useState(null),[l,o]=b.useState(null),[c,d]=b.useState(""),[u,h]=b.useState(""),[p,m]=b.useState(!1),[f,g]=b.useState(!1),[v,j]=b.useState(""),[x,y]=b.useState(""),{data:N}=ue({queryKey:["customers-for-task"],queryFn:()=>kt.getAll({limit:100}),enabled:e}),{data:D}=ue({queryKey:["contracts-for-task",a],queryFn:()=>$e.getAll({customerId:a}),enabled:e&&a!==null}),P=b.useMemo(()=>{if(!(N!=null&&N.data))return[];if(!v)return N.data;const K=v.toLowerCase();return N.data.filter(O=>O.customerNumber.toLowerCase().includes(K)||O.firstName.toLowerCase().includes(K)||O.lastName.toLowerCase().includes(K)||(O.companyName||"").toLowerCase().includes(K))},[N==null?void 0:N.data,v]),F=b.useMemo(()=>{if(!(D!=null&&D.data))return[];if(!x)return D.data;const K=x.toLowerCase();return D.data.filter(O=>O.contractNumber.toLowerCase().includes(K)||(O.providerName||"").toLowerCase().includes(K)||(O.tariffName||"").toLowerCase().includes(K))},[D==null?void 0:D.data,x]),w=async()=>{if(!(!l||!c.trim())){g(!0);try{await dt.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(K){console.error("Fehler beim Erstellen der Aufgabe:",K),alert("Fehler beim Erstellen der Aufgabe. Bitte versuchen Sie es erneut.")}finally{g(!1)}}},C=()=>{d(""),h(""),m(!1),o(null),i(null),j(""),y(""),t()},E=K=>{const O=K.companyName||`${K.firstName} ${K.lastName}`;return`${K.customerNumber} - ${O}`};return s.jsx(He,{isOpen:e,onClose:C,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(Q,{placeholder:"Kunde suchen...",value:v,onChange:K=>j(K.target.value),className:"mb-2"}),s.jsx("div",{className:"max-h-40 overflow-y-auto border rounded-lg",children:P.length>0?P.map(K=>s.jsx("div",{onClick:()=>{i(K.id),o(null),y("")},className:`p-3 cursor-pointer border-b last:border-b-0 hover:bg-gray-50 ${a===K.id?"bg-blue-50 border-blue-200":""}`,children:s.jsx("div",{className:"font-medium",children:E(K)})},K.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(Q,{placeholder:"Vertrag suchen...",value:x,onChange:K=>y(K.target.value),className:"mb-2"}),s.jsx("div",{className:"max-h-40 overflow-y-auto border rounded-lg",children:F.length>0?F.map(K=>s.jsxs("div",{onClick:()=>o(K.id),className:`p-3 cursor-pointer border-b last:border-b-0 hover:bg-gray-50 ${l===K.id?"bg-blue-50 border-blue-200":""}`,children:[s.jsx("div",{className:"font-medium",children:K.contractNumber}),s.jsxs("div",{className:"text-sm text-gray-500",children:[K.providerName||"Kein Anbieter",K.tariffName&&` - ${K.tariffName}`]})]},K.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(Q,{value:c,onChange:K=>d(K.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:K=>h(K.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:K=>m(K.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(I,{variant:"secondary",onClick:C,children:"Abbrechen"}),s.jsx(I,{onClick:w,disabled:!l||!c.trim()||f,children:f?"Wird erstellt...":"Aufgabe erstellen"})]})]})})}function PC(){const[e,t]=b.useState(!1),[n,r]=b.useState(null),[a,i]=b.useState(!1),{hasPermission:l}=Qe(),o=pe(),{data:c,isLoading:d}=ue({queryKey:["platforms",a],queryFn:()=>rl.getAll(a)}),u=G({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(I,{onClick:()=>t(!0),children:[s.jsx(Ue,{className:"w-4 h-4 mr-2"}),"Neue Plattform"]})]}),s.jsxs(X,{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(ge,{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(I,{variant:"ghost",size:"sm",onClick:()=>h(m),children:s.jsx(Xe,{className:"w-4 h-4"})}),l("platforms:delete")&&s.jsx(I,{variant:"ghost",size:"sm",onClick:()=>{confirm("Plattform wirklich löschen?")&&u.mutate(m.id)},children:s.jsx(je,{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(MC,{isOpen:e,onClose:p,platform:n})]})}function MC({isOpen:e,onClose:t,platform:n}){const r=pe(),[a,i]=b.useState({name:"",contactInfo:"",isActive:!0});b.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=G({mutationFn:rl.create,onSuccess:()=>{r.invalidateQueries({queryKey:["platforms"]}),t(),i({name:"",contactInfo:"",isActive:!0})}}),o=G({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(He,{isOpen:e,onClose:t,title:n?"Plattform bearbeiten":"Neue Plattform",children:s.jsxs("form",{onSubmit:c,className:"space-y-4",children:[s.jsx(Q,{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(I,{type:"button",variant:"secondary",onClick:t,children:"Abbrechen"}),s.jsx(I,{type:"submit",disabled:d,children:d?"Speichern...":"Speichern"})]})]})})}function TC(){const[e,t]=b.useState(!1),[n,r]=b.useState(null),[a,i]=b.useState(!1),{hasPermission:l}=Qe(),o=pe(),{data:c,isLoading:d}=ue({queryKey:["cancellation-periods",a],queryFn:()=>al.getAll(a)}),u=G({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(I,{variant:"ghost",size:"sm",children:s.jsx(Vs,{className:"w-4 h-4"})})}),s.jsx("h1",{className:"text-2xl font-bold flex-1",children:"Kündigungsfristen"}),l("platforms:create")&&s.jsxs(I,{onClick:()=>t(!0),children:[s.jsx(Ue,{className:"w-4 h-4 mr-2"}),"Neue Frist"]})]}),s.jsxs(X,{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(ge,{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(I,{variant:"ghost",size:"sm",onClick:()=>h(m),children:s.jsx(Xe,{className:"w-4 h-4"})}),l("platforms:delete")&&s.jsx(I,{variant:"ghost",size:"sm",onClick:()=>{confirm("Kündigungsfrist wirklich löschen?")&&u.mutate(m.id)},children:s.jsx(je,{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(FC,{isOpen:e,onClose:p,period:n})]})}function FC({isOpen:e,onClose:t,period:n}){const r=pe(),[a,i]=b.useState({code:"",description:"",isActive:!0});b.useEffect(()=>{e&&i(n?{code:n.code,description:n.description,isActive:n.isActive}:{code:"",description:"",isActive:!0})},[e,n]);const l=G({mutationFn:al.create,onSuccess:()=>{r.invalidateQueries({queryKey:["cancellation-periods"]}),t(),i({code:"",description:"",isActive:!0})}}),o=G({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(He,{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(Q,{label:"Code *",value:a.code,onChange:u=>i({...a,code:u.target.value.toUpperCase()}),required:!0,placeholder:"z.B. 14T, 3M, 1J"}),s.jsx(Q,{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(I,{type:"button",variant:"secondary",onClick:t,children:"Abbrechen"}),s.jsx(I,{type:"submit",disabled:d,children:d?"Speichern...":"Speichern"})]})]})})}function IC(){const[e,t]=b.useState(!1),[n,r]=b.useState(null),[a,i]=b.useState(!1),{hasPermission:l}=Qe(),o=pe(),{data:c,isLoading:d}=ue({queryKey:["contract-durations",a],queryFn:()=>il.getAll(a)}),u=G({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(I,{variant:"ghost",size:"sm",children:s.jsx(Vs,{className:"w-4 h-4"})})}),s.jsx("h1",{className:"text-2xl font-bold flex-1",children:"Vertragslaufzeiten"}),l("platforms:create")&&s.jsxs(I,{onClick:()=>t(!0),children:[s.jsx(Ue,{className:"w-4 h-4 mr-2"}),"Neue Laufzeit"]})]}),s.jsxs(X,{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(ge,{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(I,{variant:"ghost",size:"sm",onClick:()=>h(m),children:s.jsx(Xe,{className:"w-4 h-4"})}),l("platforms:delete")&&s.jsx(I,{variant:"ghost",size:"sm",onClick:()=>{confirm("Laufzeit wirklich löschen?")&&u.mutate(m.id)},children:s.jsx(je,{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(RC,{isOpen:e,onClose:p,duration:n})]})}function RC({isOpen:e,onClose:t,duration:n}){const r=pe(),[a,i]=b.useState({code:"",description:"",isActive:!0});b.useEffect(()=>{e&&i(n?{code:n.code,description:n.description,isActive:n.isActive}:{code:"",description:"",isActive:!0})},[e,n]);const l=G({mutationFn:il.create,onSuccess:()=>{r.invalidateQueries({queryKey:["contract-durations"]}),t(),i({code:"",description:"",isActive:!0})}}),o=G({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(He,{isOpen:e,onClose:t,title:n?"Laufzeit bearbeiten":"Neue Laufzeit",children:s.jsxs("form",{onSubmit:c,className:"space-y-4",children:[s.jsx(Q,{label:"Code *",value:a.code,onChange:u=>i({...a,code:u.target.value.toUpperCase()}),required:!0,placeholder:"z.B. 12M, 24M, 2J"}),s.jsx(Q,{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(I,{type:"button",variant:"secondary",onClick:t,children:"Abbrechen"}),s.jsx(I,{type:"submit",disabled:d,children:d?"Speichern...":"Speichern"})]})]})})}function LC(){const[e,t]=b.useState(!1),[n,r]=b.useState(null),[a,i]=b.useState(!1),[l,o]=b.useState(new Set),{hasPermission:c}=Qe(),d=pe(),{data:u,isLoading:h}=ue({queryKey:["providers",a],queryFn:()=>Za.getAll(a)}),p=G({mutationFn:Za.delete,onSuccess:()=>{d.invalidateQueries({queryKey:["providers"]})},onError:v=>{alert(v.message)}}),m=v=>{o(j=>{const x=new Set(j);return x.has(v)?x.delete(v):x.add(v),x})},f=v=>{r(v),t(!0)},g=()=>{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(I,{variant:"ghost",size:"sm",children:s.jsx(Vs,{className:"w-4 h-4"})})}),s.jsx("h1",{className:"text-2xl font-bold flex-1",children:"Anbieter & Tarife"}),c("providers:create")&&s.jsxs(I,{onClick:()=>t(!0),children:[s.jsx(Ue,{className:"w-4 h-4 mr-2"}),"Neuer Anbieter"]})]}),s.jsxs(X,{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:v=>i(v.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(v=>s.jsx(OC,{provider:v,isExpanded:l.has(v.id),onToggle:()=>m(v.id),onEdit:()=>f(v),onDelete:()=>{confirm("Anbieter wirklich löschen?")&&p.mutate(v.id)},hasPermission:c,showInactive:a},v.id))}):s.jsx("div",{className:"text-center py-8 text-gray-500",children:"Keine Anbieter vorhanden."})]}),s.jsx(zC,{isOpen:e,onClose:g,provider:n})]})}function OC({provider:e,isExpanded:t,onToggle:n,onEdit:r,onDelete:a,hasPermission:i,showInactive:l}){var f,g;const[o,c]=b.useState(!1),[d,u]=b.useState(null),h=pe(),p=G({mutationFn:pv.delete,onSuccess:()=>{h.invalidateQueries({queryKey:["providers"]})},onError:v=>{alert(v.message)}}),m=((f=e.tariffs)==null?void 0:f.filter(v=>l||v.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(Rn,{className:"w-5 h-5 text-gray-400"}):s.jsx(Pt,{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(ge,{variant:e.isActive?"success":"danger",children:e.isActive?"Aktiv":"Inaktiv"}),s.jsxs("span",{className:"text-sm text-gray-500",children:["(",m.length," Tarife, ",((g=e._count)==null?void 0:g.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(I,{variant:"ghost",size:"sm",onClick:r,title:"Bearbeiten",children:s.jsx(Xe,{className:"w-4 h-4"})}),i("providers:delete")&&s.jsx(I,{variant:"ghost",size:"sm",onClick:a,title:"Löschen",children:s.jsx(je,{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(I,{size:"sm",onClick:()=>c(!0),children:[s.jsx(Ue,{className:"w-4 h-4 mr-1"}),"Tarif hinzufügen"]})]}),m.length>0?s.jsx("div",{className:"space-y-2",children:m.map(v=>{var j;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:v.name}),s.jsx(ge,{variant:v.isActive?"success":"danger",className:"text-xs",children:v.isActive?"Aktiv":"Inaktiv"}),((j=v._count)==null?void 0:j.contracts)!==void 0&&s.jsxs("span",{className:"text-xs text-gray-500",children:["(",v._count.contracts," Verträge)"]})]}),s.jsxs("div",{className:"flex gap-1",children:[i("providers:update")&&s.jsx(I,{variant:"ghost",size:"sm",onClick:()=>{u(v),c(!0)},title:"Bearbeiten",children:s.jsx(Xe,{className:"w-3 h-3"})}),i("providers:delete")&&s.jsx(I,{variant:"ghost",size:"sm",onClick:()=>{confirm("Tarif wirklich löschen?")&&p.mutate(v.id)},title:"Löschen",children:s.jsx(je,{className:"w-3 h-3 text-red-500"})})]})]},v.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 zC({isOpen:e,onClose:t,provider:n}){const r=pe(),[a,i]=b.useState({name:"",portalUrl:"",usernameFieldName:"",passwordFieldName:"",isActive:!0});b.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=G({mutationFn:Za.create,onSuccess:()=>{r.invalidateQueries({queryKey:["providers"]}),t()},onError:u=>{alert(u.message)}}),o=G({mutationFn:u=>Za.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(He,{isOpen:e,onClose:t,title:n?"Anbieter bearbeiten":"Neuer Anbieter",children:s.jsxs("form",{onSubmit:c,className:"space-y-4",children:[s.jsx(Q,{label:"Anbietername *",value:a.name,onChange:u=>i({...a,name:u.target.value}),required:!0,placeholder:"z.B. Vodafone, E.ON, Allianz"}),s.jsx(Q,{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(Q,{label:"Benutzername-Feldname",value:a.usernameFieldName,onChange:u=>i({...a,usernameFieldName:u.target.value}),placeholder:"z.B. username, email, login"}),s.jsx(Q,{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(I,{type:"button",variant:"secondary",onClick:t,children:"Abbrechen"}),s.jsx(I,{type:"submit",disabled:d,children:d?"Speichern...":"Speichern"})]})]})})}function $C({isOpen:e,onClose:t,providerId:n,tariff:r}){const a=pe(),[i,l]=b.useState({name:"",isActive:!0});b.useEffect(()=>{e&&l(r?{name:r.name,isActive:r.isActive}:{name:"",isActive:!0})},[e,r]);const o=G({mutationFn:h=>Za.createTariff(n,h),onSuccess:()=>{a.invalidateQueries({queryKey:["providers"]}),t()},onError:h=>{alert(h.message)}}),c=G({mutationFn:h=>pv.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(He,{isOpen:e,onClose:t,title:r?"Tarif bearbeiten":"Neuer Tarif",children:s.jsxs("form",{onSubmit:d,className:"space-y-4",children:[s.jsx(Q,{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(I,{type:"button",variant:"secondary",onClick:t,children:"Abbrechen"}),s.jsx(I,{type:"submit",disabled:u,children:u?"Speichern...":"Speichern"})]})]})})}const Gu={Zap:s.jsx(hh,{className:"w-5 h-5"}),Flame:s.jsx(wv,{className:"w-5 h-5"}),Wifi:s.jsx(ka,{className:"w-5 h-5"}),Cable:s.jsx(C2,{className:"w-5 h-5"}),Network:s.jsx($2,{className:"w-5 h-5"}),Smartphone:s.jsx(uh,{className:"w-5 h-5"}),Tv:s.jsx(Pv,{className:"w-5 h-5"}),Car:s.jsx(Nv,{className:"w-5 h-5"}),FileText:s.jsx(_e,{className:"w-5 h-5"})},_C=[{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)"}],KC=[{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 UC(){const[e,t]=b.useState(!1),[n,r]=b.useState(null),[a,i]=b.useState(!1),{hasPermission:l}=Qe(),o=pe(),{data:c,isLoading:d}=ue({queryKey:["contract-categories",a],queryFn:()=>ll.getAll(a)}),u=G({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(I,{variant:"ghost",size:"sm",children:s.jsx(Vs,{className:"w-4 h-4"})})}),s.jsx("h1",{className:"text-2xl font-bold flex-1",children:"Vertragstypen"}),l("developer:access")&&s.jsxs(I,{onClick:()=>t(!0),children:[s.jsx(Ue,{className:"w-4 h-4 mr-2"}),"Neuer Vertragstyp"]})]}),s.jsxs(X,{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(T2,{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(_e,{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(ge,{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(I,{variant:"ghost",size:"sm",onClick:()=>h(m),title:"Bearbeiten",children:s.jsx(Xe,{className:"w-4 h-4"})}),l("developer:access")&&s.jsx(I,{variant:"ghost",size:"sm",onClick:()=>{confirm("Vertragstyp wirklich löschen?")&&u.mutate(m.id)},title:"Löschen",children:s.jsx(je,{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(BC,{isOpen:e,onClose:p,category:n})]})}function BC({isOpen:e,onClose:t,category:n}){const r=pe(),[a,i]=b.useState({code:"",name:"",icon:"FileText",color:"#607D8B",sortOrder:0,isActive:!0});b.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=G({mutationFn:ll.create,onSuccess:()=>{r.invalidateQueries({queryKey:["contract-categories"]}),t()},onError:u=>{alert(u.message)}}),o=G({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(He,{isOpen:e,onClose:t,title:n?"Vertragstyp bearbeiten":"Neuer Vertragstyp",children:s.jsxs("form",{onSubmit:c,className:"space-y-4",children:[s.jsx(Q,{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(Q,{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:_C.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:KC.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(Q,{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(I,{type:"button",variant:"secondary",onClick:t,children:"Abbrechen"}),s.jsx(I,{type:"submit",disabled:d,children:d?"Speichern...":"Speichern"})]})]})})}const qC=[{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 VC(){const{settings:e,updateSettings:t}=yv();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(Vs,{className:"w-5 h-5"})}),s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(Ae,{className:"w-6 h-6"}),s.jsx("h1",{className:"text-2xl font-bold",children:"Ansicht"})]})]}),s.jsx(X,{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(Le,{options:qC,value:e.scrollToTopThreshold.toString(),onChange:n=>t({scrollToTopThreshold:parseFloat(n.target.value)})})})]})})})]})}function QC(){const e=pe(),{data:t,isLoading:n}=ue({queryKey:["app-settings"],queryFn:()=>Jr.getAll()}),[r,a]=b.useState(!1);b.useEffect(()=>{t!=null&&t.data&&a(t.data.customerSupportTicketsEnabled==="true")},[t]);const i=G({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(Vs,{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(X,{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 HC(){const e=pe(),{data:t,isLoading:n}=ue({queryKey:["app-settings"],queryFn:()=>Jr.getAll()}),[r,a]=b.useState("14"),[i,l]=b.useState("42"),[o,c]=b.useState("90"),[d,u]=b.useState(!1);b.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=G({mutationFn:f=>Jr.update(f),onSuccess:()=>{e.invalidateQueries({queryKey:["app-settings"]}),e.invalidateQueries({queryKey:["contract-cockpit"]}),u(!1)}}),p=()=>{const f=parseInt(r),g=parseInt(i),v=parseInt(o);if(isNaN(f)||isNaN(g)||isNaN(v)){alert("Bitte gültige Zahlen eingeben");return}if(f>=g||g>=v){alert("Die Werte müssen aufsteigend sein: Kritisch < Warnung < OK");return}h.mutate({deadlineCriticalDays:r,deadlineWarningDays:i,deadlineOkDays:o})},m=(f,g)=>{f(g),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(Vs,{className:"w-5 h-5"})}),s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(Mn,{className:"w-6 h-6"}),s.jsx("h1",{className:"text-2xl font-bold",children:"Fristenschwellen"})]})]}),s.jsxs(X,{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(wn,{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(Q,{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(ms,{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(Q,{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(As,{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(Q,{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(I,{onClick:p,disabled:!d||h.isPending,children:h.isPending?"Speichere...":"Speichern"})]})]})]})}const WC=[{value:"PLESK",label:"Plesk"},{value:"CPANEL",label:"cPanel"},{value:"DIRECTADMIN",label:"DirectAdmin"}],_x=[{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 GC(){const e=Yt(),t=pe(),[n,r]=b.useState(!1),[a,i]=b.useState(null),[l,o]=b.useState(vd),[c,d]=b.useState(!1),[u,h]=b.useState(null),[p,m]=b.useState(!1),[f,g]=b.useState({}),[v,j]=b.useState(null),{data:x,isLoading:y}=ue({queryKey:["email-provider-configs"],queryFn:()=>xn.getConfigs()}),N=G({mutationFn:S=>xn.createConfig(S),onSuccess:()=>{t.invalidateQueries({queryKey:["email-provider-configs"]}),E()}}),D=G({mutationFn:({id:S,data:_})=>xn.updateConfig(S,_),onSuccess:()=>{t.invalidateQueries({queryKey:["email-provider-configs"]}),E()}}),P=G({mutationFn:S=>xn.deleteConfig(S),onSuccess:()=>{t.invalidateQueries({queryKey:["email-provider-configs"]})}}),F=(x==null?void 0:x.data)||[],w=()=>{o(vd),i(null),d(!1),h(null),r(!0)},C=S=>{o({name:S.name,type:S.type,apiUrl:S.apiUrl,apiKey:S.apiKey||"",username:S.username||"",password:"",domain:S.domain,defaultForwardEmail:S.defaultForwardEmail||"",imapEncryption:S.imapEncryption??"SSL",smtpEncryption:S.smtpEncryption??"SSL",allowSelfSignedCerts:S.allowSelfSignedCerts??!1,isActive:S.isActive,isDefault:S.isDefault}),i(S.id),d(!1),h(null),r(!0)},E=()=>{r(!1),i(null),o(vd),d(!1),h(null)},K=async S=>{var _,U,Z;j(S.id),g(W=>({...W,[S.id]:null}));try{const W=await xn.testConnection({id:S.id}),fe={success:((_=W.data)==null?void 0:_.success)||!1,message:(U=W.data)==null?void 0:U.message,error:(Z=W.data)==null?void 0:Z.error};g(le=>({...le,[S.id]:fe}))}catch(W){g(fe=>({...fe,[S.id]:{success:!1,error:W instanceof Error?W.message:"Unbekannter Fehler beim Testen"}}))}finally{j(null)}},O=async()=>{var S,_,U;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 xn.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:((S=Z.data)==null?void 0:S.success)||!1,message:(_=Z.data)==null?void 0:_.message,error:(U=Z.data)==null?void 0:U.error})}catch(Z){h({success:!1,error:Z instanceof Error?Z.message:"Unbekannter Fehler beim Verbindungstest"})}finally{m(!1)}},B=S=>{S.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(_)},A=(S,_)=>{confirm(`Möchten Sie den Provider "${_}" wirklich löschen?`)&&P.mutate(S)},M=S=>S.error?S.error:S.message?S.message:"Verbindung fehlgeschlagen";return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-4 mb-6",children:[s.jsxs(I,{variant:"ghost",onClick:()=>e("/settings"),children:[s.jsx(Vs,{className:"w-4 h-4 mr-2"}),"Zurück"]}),s.jsx("h1",{className:"text-2xl font-bold",children:"Email-Provisionierung"})]}),s.jsxs(X,{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(I,{onClick:w,children:[s.jsx(Ue,{className:"w-4 h-4 mr-2"}),"Provider hinzufügen"]})]}),y?s.jsx("div",{className:"text-center py-8",children:"Laden..."}):F.length===0?s.jsx(X,{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:F.map(S=>{const _=f[S.id],U=v===S.id;return s.jsx(X,{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:S.name}),s.jsx("span",{className:"px-2 py-1 text-xs rounded bg-blue-100 text-blue-800",children:S.type}),S.isDefault&&s.jsx("span",{className:"px-2 py-1 text-xs rounded bg-green-100 text-green-800",children:"Standard"}),!S.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:S.apiUrl})]}),s.jsxs("div",{children:[s.jsx("dt",{className:"text-gray-500",children:"Domain"}),s.jsx("dd",{children:S.domain})]}),s.jsxs("div",{children:[s.jsx("dt",{className:"text-gray-500",children:"Benutzer"}),s.jsx("dd",{children:S.username||"-"})]}),s.jsxs("div",{children:[s.jsx("dt",{className:"text-gray-500",children:"Standard-Weiterleitung"}),s.jsx("dd",{className:"truncate",children:S.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(pr,{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(hx,{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(I,{variant:"ghost",size:"sm",onClick:()=>K(S),disabled:U,title:"Verbindung testen",children:U?s.jsx("span",{className:"w-4 h-4 border-2 border-gray-400 border-t-transparent rounded-full animate-spin"}):s.jsx(ka,{className:"w-4 h-4 text-blue-500"})}),s.jsx(I,{variant:"ghost",size:"sm",onClick:()=>C(S),children:s.jsx(Xe,{className:"w-4 h-4"})}),s.jsx(I,{variant:"ghost",size:"sm",onClick:()=>A(S.id,S.name),children:s.jsx(je,{className:"w-4 h-4 text-red-500"})})]})]})},S.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(Zt,{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(Zt,{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(Q,{label:"Name *",value:l.name,onChange:S=>o({...l,name:S.target.value}),placeholder:"z.B. Plesk Hauptserver",required:!0}),s.jsx(Le,{label:"Provider-Typ *",value:l.type,onChange:S=>o({...l,type:S.target.value}),options:WC}),s.jsx(Q,{label:"API-URL *",value:l.apiUrl,onChange:S=>o({...l,apiUrl:S.target.value}),placeholder:"https://server.de:8443",required:!0}),s.jsx(Q,{label:"API-Key",value:l.apiKey,onChange:S=>o({...l,apiKey:S.target.value}),placeholder:"Optional - alternativ zu Benutzername/Passwort"}),s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[s.jsx(Q,{label:"Benutzername",value:l.username,onChange:S=>o({...l,username:S.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:S=>o({...l,password:S.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(Mt,{className:"w-4 h-4"}):s.jsx(Ae,{className:"w-4 h-4"})})]})]})]}),s.jsx(Q,{label:"Domain *",value:l.domain,onChange:S=>o({...l,domain:S.target.value}),placeholder:"stressfrei-wechseln.de",required:!0}),s.jsx(Q,{label:"Standard-Weiterleitungsadresse",value:l.defaultForwardEmail,onChange:S=>o({...l,defaultForwardEmail:S.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:S=>o({...l,imapEncryption:S.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:_x.map(S=>s.jsxs("option",{value:S.value,children:[S.label," - ",S.description]},S.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:S=>o({...l,smtpEncryption:S.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:_x.map(S=>s.jsxs("option",{value:S.value,children:[S.label," - ",S.description]},S.value))})]})]}),s.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:l.allowSelfSignedCerts,onChange:S=>o({...l,allowSelfSignedCerts:S.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:S=>o({...l,isActive:S.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:S=>o({...l,isDefault:S.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(I,{type:"button",variant:"secondary",onClick:O,disabled:p,className:"w-full",children:p?"Teste Verbindung...":s.jsxs(s.Fragment,{children:[s.jsx(ka,{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(pr,{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(hx,{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(I,{type:"button",variant:"secondary",onClick:E,children:"Abbrechen"}),s.jsx(I,{type:"submit",disabled:N.isPending||D.isPending,children:N.isPending||D.isPending?"Speichern...":"Speichern"})]})]})]})})})]})}function ZC(){const[e,t]=b.useState(null),[n,r]=b.useState(null),[a,i]=b.useState(!1),[l,o]=b.useState(""),[c,d]=b.useState(null),u=b.useRef(null),h=pe(),{logout:p}=Qe(),{data:m,isLoading:f}=ue({queryKey:["backups"],queryFn:()=>jr.list()}),g=(m==null?void 0:m.data)||[],v=G({mutationFn:()=>jr.create(),onSuccess:()=>{h.invalidateQueries({queryKey:["backups"]})}}),j=G({mutationFn:C=>jr.restore(C),onSuccess:()=>{h.invalidateQueries({queryKey:["backups"]}),t(null)}}),x=G({mutationFn:C=>jr.delete(C),onSuccess:()=>{h.invalidateQueries({queryKey:["backups"]}),r(null)}}),y=G({mutationFn:C=>jr.upload(C),onSuccess:()=>{h.invalidateQueries({queryKey:["backups"]}),d(null),u.current&&(u.current.value="")},onError:C=>{d(C.message||"Upload fehlgeschlagen")}}),N=G({mutationFn:()=>jr.factoryReset(),onSuccess:()=>{i(!1),o(""),p()}}),D=C=>{var K;const E=(K=C.target.files)==null?void 0:K[0];if(E){if(!E.name.endsWith(".zip")){d("Nur ZIP-Dateien sind erlaubt");return}d(null),y.mutate(E)}},P=async C=>{const E=localStorage.getItem("token"),K=jr.getDownloadUrl(C);try{const O=await fetch(K,{headers:{Authorization:`Bearer ${E}`}});if(!O.ok)throw new Error("Download fehlgeschlagen");const B=await O.blob(),A=window.URL.createObjectURL(B),M=document.createElement("a");M.href=A,M.download=`opencrm-backup-${C}.zip`,document.body.appendChild(M),M.click(),document.body.removeChild(M),window.URL.revokeObjectURL(A)}catch(O){console.error("Download error:",O)}},F=C=>new Date(C).toLocaleString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit"}),w=C=>C<1024?`${C} B`:C<1024*1024?`${(C/1024).toFixed(1)} KB`:`${(C/(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(I,{variant:"secondary",onClick:()=>{var C;return(C=u.current)==null?void 0:C.click()},disabled:y.isPending,children:y.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(I,{onClick:()=>v.mutate(),disabled:v.isPending,children:v.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(Ps,{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"})}):g.length===0?s.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-gray-500",children:[s.jsx(ux,{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:g.map(C=>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:C.name}),s.jsxs("span",{className:"text-sm text-gray-500 flex items-center gap-1",children:[s.jsx(Mn,{className:"w-4 h-4"}),F(C.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(_e,{className:"w-4 h-4"}),C.totalRecords.toLocaleString("de-DE")," Datensätze"]}),s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(ux,{className:"w-4 h-4"}),w(C.sizeBytes)]}),C.hasUploads&&s.jsxs("span",{className:"flex items-center gap-1 text-green-600",children:[s.jsx(M2,{className:"w-4 h-4"}),"Dokumente (",w(C.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 (",C.tables.filter(E=>E.count>0).length," mit Daten)"]}),s.jsx("div",{className:"mt-2 flex flex-wrap gap-1",children:C.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(I,{variant:"secondary",size:"sm",onClick:()=>P(C.name),title:"Als ZIP herunterladen",children:s.jsx(S2,{className:"w-4 h-4"})}),s.jsxs(I,{variant:"secondary",size:"sm",onClick:()=>t(C.name),disabled:j.isPending,children:[s.jsx(Vu,{className:"w-4 h-4 mr-1"}),"Wiederherstellen"]}),s.jsx(I,{variant:"danger",size:"sm",onClick:()=>r(C.name),disabled:x.isPending,children:s.jsx(je,{className:"w-4 h-4"})})]})]})},C.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(I,{variant:"secondary",onClick:()=>t(null),disabled:j.isPending,children:"Abbrechen"}),s.jsx(I,{variant:"primary",onClick:()=>j.mutate(e),disabled:j.isPending,children:j.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(I,{variant:"secondary",onClick:()=>r(null),disabled:x.isPending,children:"Abbrechen"}),s.jsx(I,{variant:"danger",onClick:()=>x.mutate(n),disabled:x.isPending,children:x.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(ms,{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(I,{variant:"danger",onClick:()=>i(!0),children:[s.jsx(K2,{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(ms,{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:C=>o(C.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(I,{variant:"secondary",onClick:()=>{i(!1),o("")},disabled:N.isPending,children:"Abbrechen"}),s.jsx(I,{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 JC(){var x;const[e,t]=b.useState(""),[n,r]=b.useState(1),[a,i]=b.useState(!1),[l,o]=b.useState(null),c=pe(),{refreshUser:d}=Qe(),{data:u,isLoading:h}=ue({queryKey:["users",e,n],queryFn:()=>Ii.getAll({search:e||void 0,page:n,limit:20})}),{data:p}=ue({queryKey:["roles"],queryFn:()=>Ii.getRoles()}),m=G({mutationFn:Ii.delete,onSuccess:()=>{c.invalidateQueries({queryKey:["users"]})},onError:y=>{alert((y==null?void 0:y.message)||"Fehler beim Löschen des Benutzers")}}),f=y=>{var N;return(N=y.roles)==null?void 0:N.some(D=>D.name==="Admin")},g=((x=u==null?void 0:u.data)==null?void 0:x.filter(y=>y.isActive&&f(y)).length)||0,v=y=>{o(y),i(!0)},j=()=>{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(I,{variant:"ghost",size:"sm",children:s.jsx(Vs,{className:"w-4 h-4"})})}),s.jsx("h1",{className:"text-2xl font-bold flex-1",children:"Benutzer"}),s.jsxs(I,{onClick:()=>i(!0),children:[s.jsx(Ue,{className:"w-4 h-4 mr-2"}),"Neuer Benutzer"]})]}),s.jsx(X,{className:"mb-6",children:s.jsxs("div",{className:"flex gap-4",children:[s.jsx("div",{className:"flex-1",children:s.jsx(Q,{placeholder:"Suchen...",value:e,onChange:y=>t(y.target.value)})}),s.jsx(I,{variant:"secondary",children:s.jsx(Pl,{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(Al,{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(X,{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(y=>{var N;return s.jsxs("tr",{className:"border-b hover:bg-gray-50",children:[s.jsxs("td",{className:"py-3 px-4",children:[y.firstName," ",y.lastName]}),s.jsx("td",{className:"py-3 px-4",children:y.email}),s.jsx("td",{className:"py-3 px-4",children:s.jsx("div",{className:"flex gap-1 flex-wrap",children:(N=y.roles)==null?void 0:N.filter(D=>D.name!=="Developer").map(D=>s.jsx(ge,{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(ge,{variant:y.isActive?"success":"danger",children:y.isActive?"Aktiv":"Inaktiv"}),y.hasDeveloperAccess&&s.jsxs(ge,{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(I,{variant:"ghost",size:"sm",onClick:()=>v(y),children:s.jsx(Xe,{className:"w-4 h-4"})}),(()=>{const D=f(y)&&y.isActive&&g<=1;return s.jsx(I,{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(y.id)},children:s.jsx(je,{className:`w-4 h-4 ${D?"text-gray-300":"text-red-500"}`})})})()]})})]},y.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(I,{variant:"secondary",size:"sm",onClick:()=>r(y=>Math.max(1,y-1)),disabled:n===1,children:"Zurück"}),s.jsx(I,{variant:"secondary",size:"sm",onClick:()=>r(y=>y+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(XC,{isOpen:a,onClose:j,user:l,roles:(p==null?void 0:p.data)||[],onUserUpdated:d})]})}function XC({isOpen:e,onClose:t,user:n,roles:r,onUserUpdated:a}){const i=pe(),[l,o]=b.useState(null),[c,d]=b.useState({email:"",password:"",firstName:"",lastName:"",roleIds:[],isActive:!0,hasDeveloperAccess:!1});b.useEffect(()=>{var g;e&&(o(null),d(n?{email:n.email,password:"",firstName:n.firstName,lastName:n.lastName,roleIds:((g=n.roles)==null?void 0:g.filter(v=>v.name!=="Developer").map(v=>v.id))||[],isActive:n.isActive??!0,hasDeveloperAccess:n.hasDeveloperAccess??!1}:{email:"",password:"",firstName:"",lastName:"",roleIds:[],isActive:!0,hasDeveloperAccess:!1}))},[e,n]);const u=G({mutationFn:Ii.create,onSuccess:()=>{i.invalidateQueries({queryKey:["users"]}),t()},onError:g=>{o((g==null?void 0:g.message)||"Fehler beim Erstellen des Benutzers")}}),h=G({mutationFn:g=>Ii.update(n.id,g),onSuccess:async()=>{i.invalidateQueries({queryKey:["users"]}),await a(),t()},onError:g=>{o((g==null?void 0:g.message)||"Fehler beim Aktualisieren des Benutzers")}}),p=g=>{if(g.preventDefault(),n){const v={email:c.email,firstName:c.firstName,lastName:c.lastName,roleIds:c.roleIds,isActive:c.isActive,hasDeveloperAccess:c.hasDeveloperAccess};c.password&&(v.password=c.password),h.mutate(v)}else u.mutate({email:c.email,password:c.password,firstName:c.firstName,lastName:c.lastName,roleIds:c.roleIds,hasDeveloperAccess:c.hasDeveloperAccess})},m=g=>{d(v=>({...v,roleIds:v.roleIds.includes(g)?v.roleIds.filter(j=>j!==g):[...v.roleIds,g]}))},f=u.isPending||h.isPending;return s.jsx(He,{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(ms,{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(Q,{label:"Vorname *",value:c.firstName,onChange:g=>d({...c,firstName:g.target.value}),required:!0}),s.jsx(Q,{label:"Nachname *",value:c.lastName,onChange:g=>d({...c,lastName:g.target.value}),required:!0})]}),s.jsx(Q,{label:"E-Mail *",type:"email",value:c.email,onChange:g=>d({...c,email:g.target.value}),required:!0}),s.jsx(Q,{label:n?"Neues Passwort (leer = unverändert)":"Passwort *",type:"password",value:c.password,onChange:g=>d({...c,password:g.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(g=>g.name!=="Developer").map(g=>s.jsxs("label",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"checkbox",checked:c.roleIds.includes(g.id),onChange:()=>m(g.id),className:"rounded"}),s.jsx("span",{children:g.name}),g.description&&s.jsxs("span",{className:"text-sm text-gray-500",children:["(",g.description,")"]})]},g.id)),s.jsxs("label",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"checkbox",checked:c.hasDeveloperAccess,onChange:g=>d({...c,hasDeveloperAccess:g.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(ms,{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:g=>d({...c,isActive:g.target.checked}),className:"rounded"}),"Aktiv"]})}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx(I,{type:"button",variant:"secondary",onClick:t,children:"Abbrechen"}),s.jsx(I,{type:"submit",disabled:f,children:f?"Speichern...":"Speichern"})]})]})})}function YC(){const{hasPermission:e,developerMode:t,setDeveloperMode:n}=Qe(),r=[{to:"/settings/users",icon:q2,title:"Benutzer",description:"Verwalten Sie Benutzerkonten, Rollen und Berechtigungen.",show:e("users:read")},{to:"/settings/platforms",icon:U2,title:"Vertriebsplattformen",description:"Verwalten Sie die Plattformen, über die Verträge abgeschlossen werden.",show:e("platforms:read")},{to:"/settings/cancellation-periods",icon:Mn,title:"Kündigungsfristen",description:"Konfigurieren Sie die verfügbaren Kündigungsfristen für Verträge.",show:e("platforms:read")},{to:"/settings/contract-durations",icon:bv,title:"Vertragslaufzeiten",description:"Konfigurieren Sie die verfügbaren Laufzeiten für Verträge.",show:e("platforms:read")},{to:"/settings/providers",icon:k2,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:P2,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(Av,{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(Pt,{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(Pt,{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(Mn,{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(Pt,{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(sn,{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(Pt,{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(Pt,{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(Ae,{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(Pt,{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(X,{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(X,{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 e4({onSelectTable:e}){const t=b.useRef(null),[n,r]=b.useState(1),[a,i]=b.useState({x:0,y:0}),[l,o]=b.useState(!1),[c,d]=b.useState({x:0,y:0}),[u,h]=b.useState({}),[p,m]=b.useState(null),{data:f,isLoading:g}=ue({queryKey:["developer-schema"],queryFn:Si.getSchema}),v=(f==null?void 0:f.data)||[];b.useEffect(()=>{if(v.length>0&&Object.keys(u).length===0){const w=Math.ceil(Math.sqrt(v.length)),C={x:280,y:200},E={};v.forEach((K,O)=>{const B=O%w,A=Math.floor(O/w);E[K.name]={x:50+B*C.x,y:50+A*C.y}}),h(E)}},[v,u]);const j=b.useCallback(w=>{(w.target===w.currentTarget||w.target.tagName==="svg")&&(o(!0),d({x:w.clientX-a.x,y:w.clientY-a.y}))},[a]),x=b.useCallback(w=>{var C;if(l&&!p)i({x:w.clientX-c.x,y:w.clientY-c.y});else if(p){const E=(C=t.current)==null?void 0:C.getBoundingClientRect();E&&h(K=>({...K,[p]:{x:(w.clientX-E.left-a.x)/n-100,y:(w.clientY-E.top-a.y)/n-20}}))}},[l,p,c,a,n]),y=b.useCallback(()=>{o(!1),m(null)},[]),N=w=>{r(C=>Math.min(2,Math.max(.3,C+w)))},D=()=>{r(1),i({x:0,y:0})},P=b.useCallback(()=>{const w=[];return v.forEach(C=>{const E=u[C.name];E&&C.foreignKeys.forEach(K=>{const O=u[K.targetTable];if(!O)return;const B=v.find(M=>M.name===K.targetTable),A=B==null?void 0:B.relations.find(M=>M.targetTable===C.name);w.push({from:{table:C.name,x:E.x+100,y:E.y+60},to:{table:K.targetTable,x:O.x+100,y:O.y+60},type:(A==null?void 0:A.type)||"one",label:K.field})})}),w},[v,u]);if(g)return s.jsx("div",{className:"flex items-center justify-center h-full",children:"Laden..."});const F=P();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(I,{variant:"ghost",size:"sm",onClick:()=>N(.1),title:"Vergrößern",children:s.jsx(Q2,{className:"w-4 h-4"})}),s.jsx(I,{variant:"ghost",size:"sm",onClick:()=>N(-.1),title:"Verkleinern",children:s.jsx(H2,{className:"w-4 h-4"})}),s.jsx(I,{variant:"ghost",size:"sm",onClick:D,title:"Zurücksetzen",children:s.jsx(O2,{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(z2,{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:j,onMouseMove:x,onMouseUp:y,onMouseLeave:y,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"})})]}),F.map((w,C)=>{const E=w.to.x-w.from.x,K=w.to.y-w.from.y,O=w.from.x+E/2,B=w.from.y+K/2,A=w.from.x+E*.25,M=w.from.y,S=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 ${A} ${M}, ${S} ${_}, ${w.to.x} ${w.to.y}`,fill:"none",stroke:"#9ca3af",strokeWidth:"2",markerEnd:"url(#arrowhead)"}),s.jsx("text",{x:O,y:B-8,fontSize:"10",fill:"#6b7280",textAnchor:"middle",className:"select-none",children:w.type==="many"?"1:n":"1:1"})]},C)}),v.map(w=>{const C=u[w.name];if(!C)return null;const E=200,K=32,O=20,B=[...new Set([w.primaryKey,...w.foreignKeys.map(M=>M.field)])],A=K+Math.min(B.length,5)*O+8;return s.jsxs("g",{transform:`translate(${C.x}, ${C.y})`,style:{cursor:"move"},onMouseDown:M=>{M.stopPropagation(),m(w.name)},children:[s.jsx("rect",{x:"3",y:"3",width:E,height:A,rx:"6",fill:"rgba(0,0,0,0.1)"}),s.jsx("rect",{x:"0",y:"0",width:E,height:A,rx:"6",fill:"white",stroke:"#e5e7eb",strokeWidth:"1"}),s.jsx("rect",{x:"0",y:"0",width:E,height:K,rx:"6",fill:"#3b82f6",className:"cursor-pointer",onClick:()=>e==null?void 0:e(w.name)}),s.jsx("rect",{x:"0",y:K-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,S)=>{const _=M===w.primaryKey||w.primaryKey.includes(M),U=w.foreignKeys.some(Z=>Z.field===M);return s.jsx("g",{transform:`translate(8, ${K+4+S*O})`,children:s.jsxs("text",{x:"0",y:"14",fontSize:"11",fill:_?"#dc2626":U?"#2563eb":"#374151",fontFamily:"monospace",className:"select-none",children:[_&&"🔑 ",U&&!_&&"🔗 ",M]})},M)}),B.length>5&&s.jsxs("text",{x:E/2,y:A-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 t4(){var F;const[e,t]=b.useState(null),[n,r]=b.useState(1),[a,i]=b.useState(null),[l,o]=b.useState(!1),c=pe(),{data:d,isLoading:u,error:h}=ue({queryKey:["developer-schema"],queryFn:Si.getSchema});console.log("Schema data:",d),console.log("Schema error:",h);const{data:p,isLoading:m}=ue({queryKey:["developer-table",e,n],queryFn:()=>Si.getTableData(e,n),enabled:!!e}),f=G({mutationFn:({tableName:w,id:C,data:E})=>Si.updateRow(w,C,E),onSuccess:()=>{c.invalidateQueries({queryKey:["developer-table",e]}),i(null)},onError:w=>{var C,E;alert(((E=(C=w.response)==null?void 0:C.data)==null?void 0:E.error)||"Fehler beim Speichern")}}),g=G({mutationFn:({tableName:w,id:C})=>Si.deleteRow(w,C),onSuccess:()=>{c.invalidateQueries({queryKey:["developer-table",e]})},onError:w=>{var C,E;alert(((E=(C=w.response)==null?void 0:C.data)==null?void 0:E.error)||"Fehler beim Löschen")}}),v=(d==null?void 0:d.data)||[],j=v.find(w=>w.name===e),x=(w,C)=>C.primaryKey.includes(",")?C.primaryKey.split(",").map(E=>w[E]).join("-"):String(w[C.primaryKey]),y=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?")&&g.mutate({tableName:e,id:w})};if(u)return s.jsx("div",{className:"text-center py-8",children:"Laden..."});const P=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(I,{onClick:()=>o(!0),children:[s.jsx(dx,{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(X,{title:"Tabellen",className:"lg:col-span-1",children:s.jsx("div",{className:"space-y-1 max-h-[600px] overflow-y-auto",children:v.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(B2,{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&&j?s.jsxs(s.Fragment,{children:[s.jsxs(X,{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)"}),j.foreignKeys.length>0?s.jsx("div",{className:"space-y-1",children:j.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(jv,{className:"w-4 h-4 text-gray-400"}),s.jsx(ge,{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)"}),j.relations.length>0?s.jsx("div",{className:"space-y-1",children:j.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(ge,{variant:w.type==="many"?"warning":"default",children:w.type==="many"?"1:n":"1:1"}),s.jsx(ge,{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:j.primaryKey})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-gray-500",children:"Readonly:"})," ",s.jsx("span",{className:"font-mono text-red-600",children:j.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:j.requiredFields.join(", ")||"-"})]})]})})]}),s.jsx(X,{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,j.readonlyFields.includes(w)&&s.jsx("span",{className:"ml-1 text-red-400 text-xs",children:"*"}),j.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:[(F=p==null?void 0:p.data)==null?void 0:F.map(w=>{const C=x(w,j);return s.jsxs("tr",{className:"border-b hover:bg-gray-50",children:[Object.entries(w).map(([E,K])=>s.jsx("td",{className:"py-2 px-3 font-mono text-xs max-w-[200px] truncate",children:y(K)},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(I,{variant:"ghost",size:"sm",onClick:()=>i({id:C,data:{...w}}),children:s.jsx(Xe,{className:"w-4 h-4"})}),s.jsx(I,{variant:"ghost",size:"sm",onClick:()=>D(C),children:s.jsx(je,{className:"w-4 h-4 text-red-500"})})]})})]},C)}),(!(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(I,{variant:"secondary",size:"sm",onClick:()=>r(w=>Math.max(1,w-1)),disabled:n===1,children:s.jsx(D2,{className:"w-4 h-4"})}),s.jsx(I,{variant:"secondary",size:"sm",onClick:()=>r(w=>w+1),disabled:n>=p.pagination.totalPages,children:s.jsx(Pt,{className:"w-4 h-4"})})]})]})]})})]}):s.jsx(X,{children:s.jsx("div",{className:"text-center py-8 text-gray-500",children:"Wähle eine Tabelle aus der Liste aus"})})})]}),s.jsx(He,{isOpen:!!a,onClose:()=>i(null),title:`${e} bearbeiten`,children:a&&j&&s.jsxs("div",{className:"space-y-4 max-h-[60vh] overflow-y-auto",children:[Object.entries(a.data).map(([w,C])=>{const E=j.readonlyFields.includes(w),K=j.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)"}),K&&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:y(C)}):typeof C=="boolean"?s.jsxs("select",{value:String(a.data[w]),onChange:O=>i({...a,data:{...a.data,[w]:O.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 C=="number"?"number":"text",value:a.data[w]??"",onChange:O=>i({...a,data:{...a.data,[w]:typeof C=="number"?O.target.value?Number(O.target.value):null:O.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(I,{variant:"secondary",onClick:()=>i(null),children:[s.jsx(Zt,{className:"w-4 h-4 mr-2"}),"Abbrechen"]}),s.jsxs(I,{onClick:N,disabled:f.isPending,children:[s.jsx(Dv,{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(dx,{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(Zt,{className:"w-5 h-5"})})]}),s.jsx("div",{className:"flex-1 overflow-hidden",children:s.jsx(e4,{onSelectTable:P})})]})]})]})}function s4({children:e}){const{isAuthenticated:t,isLoading:n}=Qe();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(ga,{to:"/login",replace:!0})}function n4({children:e}){const{hasPermission:t,developerMode:n}=Qe();return!t("developer:access")||!n?s.jsx(ga,{to:"/",replace:!0}):s.jsx(s.Fragment,{children:e})}function r4(){const{isAuthenticated:e,isLoading:t}=Qe();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(j2,{}),s.jsxs(dw,{children:[s.jsx(Oe,{path:"/login",element:e?s.jsx(ga,{to:"/",replace:!0}):s.jsx(J2,{})}),s.jsxs(Oe,{path:"/",element:s.jsx(s4,{children:s.jsx(Z2,{})}),children:[s.jsx(Oe,{index:!0,element:s.jsx(X2,{})}),s.jsx(Oe,{path:"customers",element:s.jsx(ek,{})}),s.jsx(Oe,{path:"customers/new",element:s.jsx(Tx,{})}),s.jsx(Oe,{path:"customers/:id",element:s.jsx(ok,{})}),s.jsx(Oe,{path:"customers/:id/edit",element:s.jsx(Tx,{})}),s.jsx(Oe,{path:"contracts",element:s.jsx(Qk,{})}),s.jsx(Oe,{path:"contracts/cockpit",element:s.jsx(kC,{})}),s.jsx(Oe,{path:"contracts/new",element:s.jsx(zx,{})}),s.jsx(Oe,{path:"contracts/:id",element:s.jsx(pC,{})}),s.jsx(Oe,{path:"contracts/:id/edit",element:s.jsx(zx,{})}),s.jsx(Oe,{path:"tasks",element:s.jsx(EC,{})}),s.jsx(Oe,{path:"settings",element:s.jsx(YC,{})}),s.jsx(Oe,{path:"settings/users",element:s.jsx(JC,{})}),s.jsx(Oe,{path:"settings/platforms",element:s.jsx(PC,{})}),s.jsx(Oe,{path:"settings/cancellation-periods",element:s.jsx(TC,{})}),s.jsx(Oe,{path:"settings/contract-durations",element:s.jsx(IC,{})}),s.jsx(Oe,{path:"settings/providers",element:s.jsx(LC,{})}),s.jsx(Oe,{path:"settings/contract-categories",element:s.jsx(UC,{})}),s.jsx(Oe,{path:"settings/view",element:s.jsx(VC,{})}),s.jsx(Oe,{path:"settings/portal",element:s.jsx(QC,{})}),s.jsx(Oe,{path:"settings/deadlines",element:s.jsx(HC,{})}),s.jsx(Oe,{path:"settings/email-providers",element:s.jsx(GC,{})}),s.jsx(Oe,{path:"settings/database-backup",element:s.jsx(ZC,{})}),s.jsx(Oe,{path:"users",element:s.jsx(ga,{to:"/settings/users",replace:!0})}),s.jsx(Oe,{path:"platforms",element:s.jsx(ga,{to:"/settings/platforms",replace:!0})}),s.jsx(Oe,{path:"developer/database",element:s.jsx(n4,{children:s.jsx(t4,{})})})]}),s.jsx(Oe,{path:"*",element:s.jsx(ga,{to:"/",replace:!0})})]})]})}const a4=new Gw({defaultOptions:{queries:{retry:1,staleTime:0,gcTime:0,refetchOnMount:"always"}}});jd.createRoot(document.getElementById("root")).render(s.jsx(At.StrictMode,{children:s.jsx(Zw,{client:a4,children:s.jsx(vw,{children:s.jsx(v2,{children:s.jsxs(y2,{children:[s.jsx(r4,{}),s.jsx(U1,{position:"top-right",toastOptions:{duration:4e3,style:{background:"#363636",color:"#fff"},success:{iconTheme:{primary:"#10b981",secondary:"#fff"}},error:{iconTheme:{primary:"#ef4444",secondary:"#fff"}}}})]})})})})}));