var Fv=Object.defineProperty;var zv=(e,t,n)=>t in e?Fv(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var de=(e,t,n)=>zv(e,typeof t!="symbol"?t+"":t,n);function Uv(e,t){for(var n=0;nr[s]})}}}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 s of document.querySelectorAll('link[rel="modulepreload"]'))r(s);new MutationObserver(s=>{for(const i of s)if(i.type==="childList")for(const o of i.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&r(o)}).observe(document,{childList:!0,subtree:!0});function n(s){const i={};return s.integrity&&(i.integrity=s.integrity),s.referrerPolicy&&(i.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?i.credentials="include":s.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(s){if(s.ep)return;s.ep=!0;const i=n(s);fetch(s.href,i)}})();function Bv(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Oh={exports:{}},Ga={},Dh={exports:{}},ce={};/** * @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 no=Symbol.for("react.element"),Wv=Symbol.for("react.portal"),Hv=Symbol.for("react.fragment"),Qv=Symbol.for("react.strict_mode"),Vv=Symbol.for("react.profiler"),qv=Symbol.for("react.provider"),Gv=Symbol.for("react.context"),Yv=Symbol.for("react.forward_ref"),Kv=Symbol.for("react.suspense"),Xv=Symbol.for("react.memo"),Jv=Symbol.for("react.lazy"),ff=Symbol.iterator;function Zv(e){return e===null||typeof e!="object"?null:(e=ff&&e[ff]||e["@@iterator"],typeof e=="function"?e:null)}var Lh={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Mh=Object.assign,Ah={};function $s(e,t,n){this.props=e,this.context=t,this.refs=Ah,this.updater=n||Lh}$s.prototype.isReactComponent={};$s.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")};$s.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function $h(){}$h.prototype=$s.prototype;function Ou(e,t,n){this.props=e,this.context=t,this.refs=Ah,this.updater=n||Lh}var Du=Ou.prototype=new $h;Du.constructor=Ou;Mh(Du,$s.prototype);Du.isPureReactComponent=!0;var pf=Array.isArray,Fh=Object.prototype.hasOwnProperty,Lu={current:null},zh={key:!0,ref:!0,__self:!0,__source:!0};function Uh(e,t,n){var r,s={},i=null,o=null;if(t!=null)for(r in t.ref!==void 0&&(o=t.ref),t.key!==void 0&&(i=""+t.key),t)Fh.call(t,r)&&!zh.hasOwnProperty(r)&&(s[r]=t[r]);var a=arguments.length-2;if(a===1)s.children=n;else if(1>>1,z=F[E];if(0>>1;Es(G,V))Xs(ie,G)?(F[E]=ie,F[X]=V,E=X):(F[E]=G,F[U]=V,E=U);else if(Xs(ie,V))F[E]=ie,F[X]=V,E=X;else break e}}return Y}function s(F,Y){var V=F.sortIndex-Y.sortIndex;return V!==0?V:F.id-Y.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;e.unstable_now=function(){return i.now()}}else{var o=Date,a=o.now();e.unstable_now=function(){return o.now()-a}}var l=[],c=[],d=1,f=null,p=3,v=!1,g=!1,y=!1,x=typeof setTimeout=="function"?setTimeout:null,m=typeof clearTimeout=="function"?clearTimeout:null,h=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function w(F){for(var Y=n(c);Y!==null;){if(Y.callback===null)r(c);else if(Y.startTime<=F)r(c),Y.sortIndex=Y.expirationTime,t(l,Y);else break;Y=n(c)}}function C(F){if(y=!1,w(F),!g)if(n(l)!==null)g=!0,L(T);else{var Y=n(c);Y!==null&&Z(C,Y.startTime-F)}}function T(F,Y){g=!1,y&&(y=!1,m(P),P=-1),v=!0;var V=p;try{for(w(Y),f=n(l);f!==null&&(!(f.expirationTime>Y)||F&&!Q());){var E=f.callback;if(typeof E=="function"){f.callback=null,p=f.priorityLevel;var z=E(f.expirationTime<=Y);Y=e.unstable_now(),typeof z=="function"?f.callback=z:f===n(l)&&r(l),w(Y)}else r(l);f=n(l)}if(f!==null)var W=!0;else{var U=n(c);U!==null&&Z(C,U.startTime-Y),W=!1}return W}finally{f=null,p=V,v=!1}}var b=!1,N=null,P=-1,I=5,O=-1;function Q(){return!(e.unstable_now()-OF||125E?(F.sortIndex=V,t(c,F),n(l)===null&&F===n(c)&&(y?(m(P),P=-1):y=!0,Z(C,V-E))):(F.sortIndex=z,t(l,F),g||v||(g=!0,L(T))),F},e.unstable_shouldYield=Q,e.unstable_wrapCallback=function(F){var Y=p;return function(){var V=p;p=Y;try{return F.apply(this,arguments)}finally{p=V}}}})(Vh);Qh.exports=Vh;var dw=Qh.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 fw=S,qt=dw;function A(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"),pc=Object.prototype.hasOwnProperty,pw=/^[: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]*$/,mf={},gf={};function hw(e){return pc.call(gf,e)?!0:pc.call(mf,e)?!1:pw.test(e)?gf[e]=!0:(mf[e]=!0,!1)}function mw(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 gw(e,t,n,r){if(t===null||typeof t>"u"||mw(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 jt(e,t,n,r,s,i,o){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=s,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=i,this.removeEmptyString=o}var ut={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){ut[e]=new jt(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];ut[t]=new jt(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){ut[e]=new jt(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){ut[e]=new jt(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){ut[e]=new jt(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){ut[e]=new jt(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){ut[e]=new jt(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){ut[e]=new jt(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){ut[e]=new jt(e,5,!1,e.toLowerCase(),null,!1,!1)});var Au=/[\-:]([a-z])/g;function $u(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(Au,$u);ut[t]=new jt(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(Au,$u);ut[t]=new jt(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(Au,$u);ut[t]=new jt(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){ut[e]=new jt(e,1,!1,e.toLowerCase(),null,!1,!1)});ut.xlinkHref=new jt("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){ut[e]=new jt(e,1,!1,e.toLowerCase(),null,!0,!0)});function Fu(e,t,n,r){var s=ut.hasOwnProperty(t)?ut[t]:null;(s!==null?s.type!==0:r||!(2a||s[o]!==i[a]){var l=` `+s[o].replace(" at new "," at ");return e.displayName&&l.includes("")&&(l=l.replace("",e.displayName)),l}while(1<=o&&0<=a);break}}}finally{_l=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?ui(e):""}function yw(e){switch(e.tag){case 5:return ui(e.type);case 16:return ui("Lazy");case 13:return ui("Suspense");case 19:return ui("SuspenseList");case 0:case 2:case 15:return e=Tl(e.type,!1),e;case 11:return e=Tl(e.type.render,!1),e;case 1:return e=Tl(e.type,!0),e;default:return""}}function yc(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 ls:return"Fragment";case as:return"Portal";case hc:return"Profiler";case zu:return"StrictMode";case mc:return"Suspense";case gc:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case Yh:return(e.displayName||"Context")+".Consumer";case Gh:return(e._context.displayName||"Context")+".Provider";case Uu:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case Bu:return t=e.displayName||null,t!==null?t:yc(e.type)||"Memo";case Jn:t=e._payload,e=e._init;try{return yc(e(t))}catch{}}return null}function vw(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 yc(t);case 8:return t===zu?"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 Xh(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function ww(e){var t=Xh(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 s=n.get,i=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return s.call(this)},set:function(o){r=""+o,i.call(this,o)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(o){r=""+o},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function xo(e){e._valueTracker||(e._valueTracker=ww(e))}function Jh(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=Xh(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function la(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 vc(e,t){var n=t.checked;return Le({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function vf(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 Zh(e,t){t=t.checked,t!=null&&Fu(e,"checked",t,!1)}function wc(e,t){Zh(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")?xc(e,t.type,n):t.hasOwnProperty("defaultValue")&&xc(e,t.type,hr(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function wf(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 xc(e,t,n){(t!=="number"||la(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var di=Array.isArray;function xs(e,t,n,r){if(e=e.options,t){t={};for(var s=0;s"+t.valueOf().toString()+"",t=So.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Pi(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var yi={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},xw=["Webkit","ms","Moz","O"];Object.keys(yi).forEach(function(e){xw.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),yi[t]=yi[e]})});function rm(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||yi.hasOwnProperty(e)&&yi[e]?(""+t).trim():t+"px"}function sm(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,s=rm(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,s):e[n]=s}}var Sw=Le({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 bc(e,t){if(t){if(Sw[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(A(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(A(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(A(61))}if(t.style!=null&&typeof t.style!="object")throw Error(A(62))}}function Cc(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 Ec=null;function Wu(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var Nc=null,Ss=null,ks=null;function kf(e){if(e=io(e)){if(typeof Nc!="function")throw Error(A(280));var t=e.stateNode;t&&(t=Za(t),Nc(e.stateNode,e.type,t))}}function im(e){Ss?ks?ks.push(e):ks=[e]:Ss=e}function om(){if(Ss){var e=Ss,t=ks;if(ks=Ss=null,kf(e),t)for(e=0;e>>=0,e===0?32:31-(Rw(e)/Ow|0)|0}var ko=64,bo=4194304;function fi(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 fa(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,s=e.suspendedLanes,i=e.pingedLanes,o=n&268435455;if(o!==0){var a=o&~s;a!==0?r=fi(a):(i&=o,i!==0&&(r=fi(i)))}else o=n&~s,o!==0?r=fi(o):i!==0&&(r=fi(i));if(r===0)return 0;if(t!==0&&t!==r&&!(t&s)&&(s=r&-r,i=t&-t,s>=i||s===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 ro(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-vn(t),e[t]=n}function Aw(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=wi),If=" ",Rf=!1;function Nm(e,t){switch(e){case"keyup":return dx.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function _m(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var cs=!1;function px(e,t){switch(e){case"compositionend":return _m(t);case"keypress":return t.which!==32?null:(Rf=!0,If);case"textInput":return e=t.data,e===If&&Rf?null:e;default:return null}}function hx(e,t){if(cs)return e==="compositionend"||!Xu&&Nm(e,t)?(e=Cm(),Go=Gu=nr=null,cs=!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=Mf(n)}}function Im(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?Im(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function Rm(){for(var e=window,t=la();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=la(e.document)}return t}function Ju(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 bx(e){var t=Rm(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&Im(n.ownerDocument.documentElement,n)){if(r!==null&&Ju(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 s=n.textContent.length,i=Math.min(r.start,s);r=r.end===void 0?i:Math.min(r.end,s),!e.extend&&i>r&&(s=r,r=i,i=s),s=Af(n,i);var o=Af(n,r);s&&o&&(e.rangeCount!==1||e.anchorNode!==s.node||e.anchorOffset!==s.offset||e.focusNode!==o.node||e.focusOffset!==o.offset)&&(t=t.createRange(),t.setStart(s.node,s.offset),e.removeAllRanges(),i>r?(e.addRange(t),e.extend(o.node,o.offset)):(t.setEnd(o.node,o.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,us=null,Rc=null,Si=null,Oc=!1;function $f(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;Oc||us==null||us!==la(r)||(r=us,"selectionStart"in r&&Ju(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}),Si&&Mi(Si,r)||(Si=r,r=ma(Rc,"onSelect"),0ps||(e.current=Fc[ps],Fc[ps]=null,ps--)}function _e(e,t){ps++,Fc[ps]=e.current,e.current=t}var mr={},vt=vr(mr),At=vr(!1),$r=mr;function Ps(e,t){var n=e.type.contextTypes;if(!n)return mr;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var s={},i;for(i in n)s[i]=t[i];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=s),s}function $t(e){return e=e.childContextTypes,e!=null}function ya(){je(At),je(vt)}function Qf(e,t,n){if(vt.current!==mr)throw Error(A(168));_e(vt,t),_e(At,n)}function Um(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var s in r)if(!(s in t))throw Error(A(108,vw(e)||"Unknown",s));return Le({},n,r)}function va(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||mr,$r=vt.current,_e(vt,e),_e(At,At.current),!0}function Vf(e,t,n){var r=e.stateNode;if(!r)throw Error(A(169));n?(e=Um(e,t,$r),r.__reactInternalMemoizedMergedChildContext=e,je(At),je(vt),_e(vt,e)):je(At),_e(At,n)}var Mn=null,el=!1,Bl=!1;function Bm(e){Mn===null?Mn=[e]:Mn.push(e)}function Lx(e){el=!0,Bm(e)}function wr(){if(!Bl&&Mn!==null){Bl=!0;var e=0,t=ke;try{var n=Mn;for(ke=1;e>=o,s-=o,An=1<<32-vn(t)+s|n<P?(I=N,N=null):I=N.sibling;var O=p(m,N,w[P],C);if(O===null){N===null&&(N=I);break}e&&N&&O.alternate===null&&t(m,N),h=i(O,h,P),b===null?T=O:b.sibling=O,b=O,N=I}if(P===w.length)return n(m,N),Pe&&Nr(m,P),T;if(N===null){for(;PP?(I=N,N=null):I=N.sibling;var Q=p(m,N,O.value,C);if(Q===null){N===null&&(N=I);break}e&&N&&Q.alternate===null&&t(m,N),h=i(Q,h,P),b===null?T=Q:b.sibling=Q,b=Q,N=I}if(O.done)return n(m,N),Pe&&Nr(m,P),T;if(N===null){for(;!O.done;P++,O=w.next())O=f(m,O.value,C),O!==null&&(h=i(O,h,P),b===null?T=O:b.sibling=O,b=O);return Pe&&Nr(m,P),T}for(N=r(m,N);!O.done;P++,O=w.next())O=v(N,m,P,O.value,C),O!==null&&(e&&O.alternate!==null&&N.delete(O.key===null?P:O.key),h=i(O,h,P),b===null?T=O:b.sibling=O,b=O);return e&&N.forEach(function(ue){return t(m,ue)}),Pe&&Nr(m,P),T}function x(m,h,w,C){if(typeof w=="object"&&w!==null&&w.type===ls&&w.key===null&&(w=w.props.children),typeof w=="object"&&w!==null){switch(w.$$typeof){case wo:e:{for(var T=w.key,b=h;b!==null;){if(b.key===T){if(T=w.type,T===ls){if(b.tag===7){n(m,b.sibling),h=s(b,w.props.children),h.return=m,m=h;break e}}else if(b.elementType===T||typeof T=="object"&&T!==null&&T.$$typeof===Jn&&Yf(T)===b.type){n(m,b.sibling),h=s(b,w.props),h.ref=ti(m,b,w),h.return=m,m=h;break e}n(m,b);break}else t(m,b);b=b.sibling}w.type===ls?(h=Mr(w.props.children,m.mode,C,w.key),h.return=m,m=h):(C=na(w.type,w.key,w.props,null,m.mode,C),C.ref=ti(m,h,w),C.return=m,m=C)}return o(m);case as:e:{for(b=w.key;h!==null;){if(h.key===b)if(h.tag===4&&h.stateNode.containerInfo===w.containerInfo&&h.stateNode.implementation===w.implementation){n(m,h.sibling),h=s(h,w.children||[]),h.return=m,m=h;break e}else{n(m,h);break}else t(m,h);h=h.sibling}h=Kl(w,m.mode,C),h.return=m,m=h}return o(m);case Jn:return b=w._init,x(m,h,b(w._payload),C)}if(di(w))return g(m,h,w,C);if(Ks(w))return y(m,h,w,C);Po(m,w)}return typeof w=="string"&&w!==""||typeof w=="number"?(w=""+w,h!==null&&h.tag===6?(n(m,h.sibling),h=s(h,w),h.return=m,m=h):(n(m,h),h=Yl(w,m.mode,C),h.return=m,m=h),o(m)):n(m,h)}return x}var Rs=Vm(!0),qm=Vm(!1),Sa=vr(null),ka=null,gs=null,nd=null;function rd(){nd=gs=ka=null}function sd(e){var t=Sa.current;je(Sa),e._currentValue=t}function Bc(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 Cs(e,t){ka=e,nd=gs=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(Mt=!0),e.firstContext=null)}function sn(e){var t=e._currentValue;if(nd!==e)if(e={context:e,memoizedValue:t,next:null},gs===null){if(ka===null)throw Error(A(308));gs=e,ka.dependencies={lanes:0,firstContext:e}}else gs=gs.next=e;return t}var Rr=null;function id(e){Rr===null?Rr=[e]:Rr.push(e)}function Gm(e,t,n,r){var s=t.interleaved;return s===null?(n.next=n,id(t)):(n.next=s.next,s.next=n),t.interleaved=n,Wn(e,r)}function Wn(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var Zn=!1;function od(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Ym(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 Fn(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function cr(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,ge&2){var s=r.pending;return s===null?t.next=t:(t.next=s.next,s.next=t),r.pending=t,Wn(e,n)}return s=r.interleaved,s===null?(t.next=t,id(r)):(t.next=s.next,s.next=t),r.interleaved=t,Wn(e,n)}function Ko(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,Qu(e,n)}}function Kf(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var s=null,i=null;if(n=n.firstBaseUpdate,n!==null){do{var o={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};i===null?s=i=o:i=i.next=o,n=n.next}while(n!==null);i===null?s=i=t:i=i.next=t}else s=i=t;n={baseState:r.baseState,firstBaseUpdate:s,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 ba(e,t,n,r){var s=e.updateQueue;Zn=!1;var i=s.firstBaseUpdate,o=s.lastBaseUpdate,a=s.shared.pending;if(a!==null){s.shared.pending=null;var l=a,c=l.next;l.next=null,o===null?i=c:o.next=c,o=l;var d=e.alternate;d!==null&&(d=d.updateQueue,a=d.lastBaseUpdate,a!==o&&(a===null?d.firstBaseUpdate=c:a.next=c,d.lastBaseUpdate=l))}if(i!==null){var f=s.baseState;o=0,d=c=l=null,a=i;do{var p=a.lane,v=a.eventTime;if((r&p)===p){d!==null&&(d=d.next={eventTime:v,lane:0,tag:a.tag,payload:a.payload,callback:a.callback,next:null});e:{var g=e,y=a;switch(p=t,v=n,y.tag){case 1:if(g=y.payload,typeof g=="function"){f=g.call(v,f,p);break e}f=g;break e;case 3:g.flags=g.flags&-65537|128;case 0:if(g=y.payload,p=typeof g=="function"?g.call(v,f,p):g,p==null)break e;f=Le({},f,p);break e;case 2:Zn=!0}}a.callback!==null&&a.lane!==0&&(e.flags|=64,p=s.effects,p===null?s.effects=[a]:p.push(a))}else v={eventTime:v,lane:p,tag:a.tag,payload:a.payload,callback:a.callback,next:null},d===null?(c=d=v,l=f):d=d.next=v,o|=p;if(a=a.next,a===null){if(a=s.shared.pending,a===null)break;p=a,a=p.next,p.next=null,s.lastBaseUpdate=p,s.shared.pending=null}}while(!0);if(d===null&&(l=f),s.baseState=l,s.firstBaseUpdate=c,s.lastBaseUpdate=d,t=s.shared.interleaved,t!==null){s=t;do o|=s.lane,s=s.next;while(s!==t)}else i===null&&(s.shared.lanes=0);Ur|=o,e.lanes=o,e.memoizedState=f}}function Xf(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var r=Hl.transition;Hl.transition={};try{e(!1),t()}finally{ke=n,Hl.transition=r}}function fg(){return on().memoizedState}function Fx(e,t,n){var r=dr(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},pg(e))hg(t,n);else if(n=Gm(e,t,n,r),n!==null){var s=_t();wn(n,e,r,s),mg(n,t,r)}}function zx(e,t,n){var r=dr(e),s={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(pg(e))hg(t,s);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=t.lastRenderedReducer,i!==null))try{var o=t.lastRenderedState,a=i(o,n);if(s.hasEagerState=!0,s.eagerState=a,Sn(a,o)){var l=t.interleaved;l===null?(s.next=s,id(t)):(s.next=l.next,l.next=s),t.interleaved=s;return}}catch{}finally{}n=Gm(e,t,s,r),n!==null&&(s=_t(),wn(n,e,r,s),mg(n,t,r))}}function pg(e){var t=e.alternate;return e===De||t!==null&&t===De}function hg(e,t){ki=Ea=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function mg(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Qu(e,n)}}var Na={readContext:sn,useCallback:ht,useContext:ht,useEffect:ht,useImperativeHandle:ht,useInsertionEffect:ht,useLayoutEffect:ht,useMemo:ht,useReducer:ht,useRef:ht,useState:ht,useDebugValue:ht,useDeferredValue:ht,useTransition:ht,useMutableSource:ht,useSyncExternalStore:ht,useId:ht,unstable_isNewReconciler:!1},Ux={readContext:sn,useCallback:function(e,t){return _n().memoizedState=[e,t===void 0?null:t],e},useContext:sn,useEffect:Zf,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,Jo(4194308,4,ag.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Jo(4194308,4,e,t)},useInsertionEffect:function(e,t){return Jo(4,2,e,t)},useMemo:function(e,t){var n=_n();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=_n();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=Fx.bind(null,De,e),[r.memoizedState,e]},useRef:function(e){var t=_n();return e={current:e},t.memoizedState=e},useState:Jf,useDebugValue:hd,useDeferredValue:function(e){return _n().memoizedState=e},useTransition:function(){var e=Jf(!1),t=e[0];return e=$x.bind(null,e[1]),_n().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=De,s=_n();if(Pe){if(n===void 0)throw Error(A(407));n=n()}else{if(n=t(),it===null)throw Error(A(349));zr&30||Zm(r,t,n)}s.memoizedState=n;var i={value:n,getSnapshot:t};return s.queue=i,Zf(tg.bind(null,r,i,e),[e]),r.flags|=2048,Hi(9,eg.bind(null,r,i,n,t),void 0,null),n},useId:function(){var e=_n(),t=it.identifierPrefix;if(Pe){var n=$n,r=An;n=(r&~(1<<32-vn(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=Bi++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=o.createElement(n,{is:r.is}):(e=o.createElement(n),n==="select"&&(o=e,r.multiple?o.multiple=!0:r.size&&(o.size=r.size))):e=o.createElementNS(e,n),e[Tn]=t,e[Fi]=r,Eg(e,t,!1,!1),t.stateNode=e;e:{switch(o=Cc(n,r),n){case"dialog":Te("cancel",e),Te("close",e),s=r;break;case"iframe":case"object":case"embed":Te("load",e),s=r;break;case"video":case"audio":for(s=0;sLs&&(t.flags|=128,r=!0,ni(i,!1),t.lanes=4194304)}else{if(!r)if(e=Ca(o),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),ni(i,!0),i.tail===null&&i.tailMode==="hidden"&&!o.alternate&&!Pe)return mt(t),null}else 2*We()-i.renderingStartTime>Ls&&n!==1073741824&&(t.flags|=128,r=!0,ni(i,!1),t.lanes=4194304);i.isBackwards?(o.sibling=t.child,t.child=o):(n=i.last,n!==null?n.sibling=o:t.child=o,i.last=o)}return i.tail!==null?(t=i.tail,i.rendering=t,i.tail=t.sibling,i.renderingStartTime=We(),t.sibling=null,n=Oe.current,_e(Oe,r?n&1|2:n&1),t):(mt(t),null);case 22:case 23:return xd(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?Ht&1073741824&&(mt(t),t.subtreeFlags&6&&(t.flags|=8192)):mt(t),null;case 24:return null;case 25:return null}throw Error(A(156,t.tag))}function Yx(e,t){switch(ed(t),t.tag){case 1:return $t(t.type)&&ya(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Os(),je(At),je(vt),cd(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return ld(t),null;case 13:if(je(Oe),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(A(340));Is()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return je(Oe),null;case 4:return Os(),null;case 10:return sd(t.type._context),null;case 22:case 23:return xd(),null;case 24:return null;default:return null}}var Ro=!1,gt=!1,Kx=typeof WeakSet=="function"?WeakSet:Set,H=null;function ys(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){Ae(e,t,r)}else n.current=null}function Xc(e,t,n){try{n()}catch(r){Ae(e,t,r)}}var up=!1;function Xx(e,t){if(Dc=pa,e=Rm(),Ju(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 s=r.anchorOffset,i=r.focusNode;r=r.focusOffset;try{n.nodeType,i.nodeType}catch{n=null;break e}var o=0,a=-1,l=-1,c=0,d=0,f=e,p=null;t:for(;;){for(var v;f!==n||s!==0&&f.nodeType!==3||(a=o+s),f!==i||r!==0&&f.nodeType!==3||(l=o+r),f.nodeType===3&&(o+=f.nodeValue.length),(v=f.firstChild)!==null;)p=f,f=v;for(;;){if(f===e)break t;if(p===n&&++c===s&&(a=o),p===i&&++d===r&&(l=o),(v=f.nextSibling)!==null)break;f=p,p=f.parentNode}f=v}n=a===-1||l===-1?null:{start:a,end:l}}else n=null}n=n||{start:0,end:0}}else n=null;for(Lc={focusedElem:e,selectionRange:n},pa=!1,H=t;H!==null;)if(t=H,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,H=e;else for(;H!==null;){t=H;try{var g=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(g!==null){var y=g.memoizedProps,x=g.memoizedState,m=t.stateNode,h=m.getSnapshotBeforeUpdate(t.elementType===t.type?y:fn(t.type,y),x);m.__reactInternalSnapshotBeforeUpdate=h}break;case 3:var w=t.stateNode.containerInfo;w.nodeType===1?w.textContent="":w.nodeType===9&&w.documentElement&&w.removeChild(w.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(A(163))}}catch(C){Ae(t,t.return,C)}if(e=t.sibling,e!==null){e.return=t.return,H=e;break}H=t.return}return g=up,up=!1,g}function bi(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var s=r=r.next;do{if((s.tag&e)===e){var i=s.destroy;s.destroy=void 0,i!==void 0&&Xc(t,n,i)}s=s.next}while(s!==r)}}function rl(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 Jc(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 Tg(e){var t=e.alternate;t!==null&&(e.alternate=null,Tg(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Tn],delete t[Fi],delete t[$c],delete t[Ox],delete t[Dx])),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 jg(e){return e.tag===5||e.tag===3||e.tag===4}function dp(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||jg(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 Zc(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=ga));else if(r!==4&&(e=e.child,e!==null))for(Zc(e,t,n),e=e.sibling;e!==null;)Zc(e,t,n),e=e.sibling}function eu(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(eu(e,t,n),e=e.sibling;e!==null;)eu(e,t,n),e=e.sibling}var lt=null,pn=!1;function Kn(e,t,n){for(n=n.child;n!==null;)Pg(e,t,n),n=n.sibling}function Pg(e,t,n){if(In&&typeof In.onCommitFiberUnmount=="function")try{In.onCommitFiberUnmount(Ya,n)}catch{}switch(n.tag){case 5:gt||ys(n,t);case 6:var r=lt,s=pn;lt=null,Kn(e,t,n),lt=r,pn=s,lt!==null&&(pn?(e=lt,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):lt.removeChild(n.stateNode));break;case 18:lt!==null&&(pn?(e=lt,n=n.stateNode,e.nodeType===8?Ul(e.parentNode,n):e.nodeType===1&&Ul(e,n),Di(e)):Ul(lt,n.stateNode));break;case 4:r=lt,s=pn,lt=n.stateNode.containerInfo,pn=!0,Kn(e,t,n),lt=r,pn=s;break;case 0:case 11:case 14:case 15:if(!gt&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){s=r=r.next;do{var i=s,o=i.destroy;i=i.tag,o!==void 0&&(i&2||i&4)&&Xc(n,t,o),s=s.next}while(s!==r)}Kn(e,t,n);break;case 1:if(!gt&&(ys(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(a){Ae(n,t,a)}Kn(e,t,n);break;case 21:Kn(e,t,n);break;case 22:n.mode&1?(gt=(r=gt)||n.memoizedState!==null,Kn(e,t,n),gt=r):Kn(e,t,n);break;default:Kn(e,t,n)}}function fp(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new Kx),t.forEach(function(r){var s=o0.bind(null,e,r);n.has(r)||(n.add(r),r.then(s,s))})}}function un(e,t){var n=t.deletions;if(n!==null)for(var r=0;rs&&(s=o),r&=~i}if(r=s,r=We()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*Zx(r/1960))-r,10e?16:e,rr===null)var r=!1;else{if(e=rr,rr=null,ja=0,ge&6)throw Error(A(331));var s=ge;for(ge|=4,H=e.current;H!==null;){var i=H,o=i.child;if(H.flags&16){var a=i.deletions;if(a!==null){for(var l=0;lWe()-vd?Lr(e,0):yd|=n),Ft(e,t)}function $g(e,t){t===0&&(e.mode&1?(t=bo,bo<<=1,!(bo&130023424)&&(bo=4194304)):t=1);var n=_t();e=Wn(e,t),e!==null&&(ro(e,t,n),Ft(e,n))}function i0(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),$g(e,n)}function o0(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,s=e.memoizedState;s!==null&&(n=s.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(A(314))}r!==null&&r.delete(t),$g(e,n)}var Fg;Fg=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||At.current)Mt=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return Mt=!1,qx(e,t,n);Mt=!!(e.flags&131072)}else Mt=!1,Pe&&t.flags&1048576&&Wm(t,xa,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;Zo(e,t),e=t.pendingProps;var s=Ps(t,vt.current);Cs(t,n),s=dd(null,t,r,e,s,n);var i=fd();return t.flags|=1,typeof s=="object"&&s!==null&&typeof s.render=="function"&&s.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,$t(r)?(i=!0,va(t)):i=!1,t.memoizedState=s.state!==null&&s.state!==void 0?s.state:null,od(t),s.updater=nl,t.stateNode=s,s._reactInternals=t,Hc(t,r,e,n),t=qc(null,t,r,!0,i,n)):(t.tag=0,Pe&&i&&Zu(t),Ct(null,t,s,n),t=t.child),t;case 16:r=t.elementType;e:{switch(Zo(e,t),e=t.pendingProps,s=r._init,r=s(r._payload),t.type=r,s=t.tag=l0(r),e=fn(r,e),s){case 0:t=Vc(null,t,r,e,n);break e;case 1:t=ap(null,t,r,e,n);break e;case 11:t=ip(null,t,r,e,n);break e;case 14:t=op(null,t,r,fn(r.type,e),n);break e}throw Error(A(306,r,""))}return t;case 0:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:fn(r,s),Vc(e,t,r,s,n);case 1:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:fn(r,s),ap(e,t,r,s,n);case 3:e:{if(kg(t),e===null)throw Error(A(387));r=t.pendingProps,i=t.memoizedState,s=i.element,Ym(e,t),ba(t,r,null,n);var o=t.memoizedState;if(r=o.element,i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:o.cache,pendingSuspenseBoundaries:o.pendingSuspenseBoundaries,transitions:o.transitions},t.updateQueue.baseState=i,t.memoizedState=i,t.flags&256){s=Ds(Error(A(423)),t),t=lp(e,t,r,n,s);break e}else if(r!==s){s=Ds(Error(A(424)),t),t=lp(e,t,r,n,s);break e}else for(Qt=lr(t.stateNode.containerInfo.firstChild),Vt=t,Pe=!0,hn=null,n=qm(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(Is(),r===s){t=Hn(e,t,n);break e}Ct(e,t,r,n)}t=t.child}return t;case 5:return Km(t),e===null&&Uc(t),r=t.type,s=t.pendingProps,i=e!==null?e.memoizedProps:null,o=s.children,Mc(r,s)?o=null:i!==null&&Mc(r,i)&&(t.flags|=32),Sg(e,t),Ct(e,t,o,n),t.child;case 6:return e===null&&Uc(t),null;case 13:return bg(e,t,n);case 4:return ad(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=Rs(t,null,r,n):Ct(e,t,r,n),t.child;case 11:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:fn(r,s),ip(e,t,r,s,n);case 7:return Ct(e,t,t.pendingProps,n),t.child;case 8:return Ct(e,t,t.pendingProps.children,n),t.child;case 12:return Ct(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,s=t.pendingProps,i=t.memoizedProps,o=s.value,_e(Sa,r._currentValue),r._currentValue=o,i!==null)if(Sn(i.value,o)){if(i.children===s.children&&!At.current){t=Hn(e,t,n);break e}}else for(i=t.child,i!==null&&(i.return=t);i!==null;){var a=i.dependencies;if(a!==null){o=i.child;for(var l=a.firstContext;l!==null;){if(l.context===r){if(i.tag===1){l=Fn(-1,n&-n),l.tag=2;var c=i.updateQueue;if(c!==null){c=c.shared;var d=c.pending;d===null?l.next=l:(l.next=d.next,d.next=l),c.pending=l}}i.lanes|=n,l=i.alternate,l!==null&&(l.lanes|=n),Bc(i.return,n,t),a.lanes|=n;break}l=l.next}}else if(i.tag===10)o=i.type===t.type?null:i.child;else if(i.tag===18){if(o=i.return,o===null)throw Error(A(341));o.lanes|=n,a=o.alternate,a!==null&&(a.lanes|=n),Bc(o,n,t),o=i.sibling}else o=i.child;if(o!==null)o.return=i;else for(o=i;o!==null;){if(o===t){o=null;break}if(i=o.sibling,i!==null){i.return=o.return,o=i;break}o=o.return}i=o}Ct(e,t,s.children,n),t=t.child}return t;case 9:return s=t.type,r=t.pendingProps.children,Cs(t,n),s=sn(s),r=r(s),t.flags|=1,Ct(e,t,r,n),t.child;case 14:return r=t.type,s=fn(r,t.pendingProps),s=fn(r.type,s),op(e,t,r,s,n);case 15:return wg(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:fn(r,s),Zo(e,t),t.tag=1,$t(r)?(e=!0,va(t)):e=!1,Cs(t,n),gg(t,r,s),Hc(t,r,s,n),qc(null,t,r,!0,e,n);case 19:return Cg(e,t,n);case 22:return xg(e,t,n)}throw Error(A(156,t.tag))};function zg(e,t){return pm(e,t)}function a0(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 nn(e,t,n,r){return new a0(e,t,n,r)}function kd(e){return e=e.prototype,!(!e||!e.isReactComponent)}function l0(e){if(typeof e=="function")return kd(e)?1:0;if(e!=null){if(e=e.$$typeof,e===Uu)return 11;if(e===Bu)return 14}return 2}function fr(e,t){var n=e.alternate;return n===null?(n=nn(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 na(e,t,n,r,s,i){var o=2;if(r=e,typeof e=="function")kd(e)&&(o=1);else if(typeof e=="string")o=5;else e:switch(e){case ls:return Mr(n.children,s,i,t);case zu:o=8,s|=8;break;case hc:return e=nn(12,n,t,s|2),e.elementType=hc,e.lanes=i,e;case mc:return e=nn(13,n,t,s),e.elementType=mc,e.lanes=i,e;case gc:return e=nn(19,n,t,s),e.elementType=gc,e.lanes=i,e;case Kh:return il(n,s,i,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case Gh:o=10;break e;case Yh:o=9;break e;case Uu:o=11;break e;case Bu:o=14;break e;case Jn:o=16,r=null;break e}throw Error(A(130,e==null?e:typeof e,""))}return t=nn(o,n,t,s),t.elementType=e,t.type=r,t.lanes=i,t}function Mr(e,t,n,r){return e=nn(7,e,r,t),e.lanes=n,e}function il(e,t,n,r){return e=nn(22,e,r,t),e.elementType=Kh,e.lanes=n,e.stateNode={isHidden:!1},e}function Yl(e,t,n){return e=nn(6,e,null,t),e.lanes=n,e}function Kl(e,t,n){return t=nn(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function c0(e,t,n,r,s){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=Pl(0),this.expirationTimes=Pl(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Pl(0),this.identifierPrefix=r,this.onRecoverableError=s,this.mutableSourceEagerHydrationData=null}function bd(e,t,n,r,s,i,o,a,l){return e=new c0(e,t,n,a,l),t===1?(t=1,i===!0&&(t|=8)):t=0,i=nn(3,null,null,t),e.current=i,i.stateNode=e,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},od(i),e}function u0(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(Hg)}catch(e){console.error(e)}}Hg(),Hh.exports=Yt;var m0=Hh.exports,xp=m0;fc.createRoot=xp.createRoot,fc.hydrateRoot=xp.hydrateRoot;/** * @remix-run/router v1.23.0 * * Copyright (c) Remix Software Inc. * * This source code is licensed under the MIT license found in the * LICENSE.md file in the root directory of this source tree. * * @license MIT */function Vi(){return Vi=Object.assign?Object.assign.bind():function(e){for(var t=1;t"u")throw new Error(t)}function Qg(e,t){if(!e){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function y0(){return Math.random().toString(36).substr(2,8)}function kp(e,t){return{usr:e.state,key:e.key,idx:t}}function iu(e,t,n,r){return n===void 0&&(n=null),Vi({pathname:typeof e=="string"?e:e.pathname,search:"",hash:""},typeof t=="string"?Us(t):t,{state:n,key:t&&t.key||r||y0()})}function Ra(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 Us(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 v0(e,t,n,r){r===void 0&&(r={});let{window:s=document.defaultView,v5Compat:i=!1}=r,o=s.history,a=sr.Pop,l=null,c=d();c==null&&(c=0,o.replaceState(Vi({},o.state,{idx:c}),""));function d(){return(o.state||{idx:null}).idx}function f(){a=sr.Pop;let x=d(),m=x==null?null:x-c;c=x,l&&l({action:a,location:y.location,delta:m})}function p(x,m){a=sr.Push;let h=iu(y.location,x,m);c=d()+1;let w=kp(h,c),C=y.createHref(h);try{o.pushState(w,"",C)}catch(T){if(T instanceof DOMException&&T.name==="DataCloneError")throw T;s.location.assign(C)}i&&l&&l({action:a,location:y.location,delta:1})}function v(x,m){a=sr.Replace;let h=iu(y.location,x,m);c=d();let w=kp(h,c),C=y.createHref(h);o.replaceState(w,"",C),i&&l&&l({action:a,location:y.location,delta:0})}function g(x){let m=s.location.origin!=="null"?s.location.origin:s.location.href,h=typeof x=="string"?x:Ra(x);return h=h.replace(/ $/,"%20"),He(m,"No window.location.(origin|href) available to create URL for href: "+h),new URL(h,m)}let y={get action(){return a},get location(){return e(s,o)},listen(x){if(l)throw new Error("A history only accepts one active listener");return s.addEventListener(Sp,f),l=x,()=>{s.removeEventListener(Sp,f),l=null}},createHref(x){return t(s,x)},createURL:g,encodeLocation(x){let m=g(x);return{pathname:m.pathname,search:m.search,hash:m.hash}},push:p,replace:v,go(x){return o.go(x)}};return y}var bp;(function(e){e.data="data",e.deferred="deferred",e.redirect="redirect",e.error="error"})(bp||(bp={}));function w0(e,t,n){return n===void 0&&(n="/"),x0(e,t,n)}function x0(e,t,n,r){let s=typeof t=="string"?Us(t):t,i=_d(s.pathname||"/",n);if(i==null)return null;let o=Vg(e);S0(o);let a=null;for(let l=0;a==null&&l{let l={relativePath:a===void 0?i.path||"":a,caseSensitive:i.caseSensitive===!0,childrenIndex:o,route:i};l.relativePath.startsWith("/")&&(He(l.relativePath.startsWith(r),'Absolute route path "'+l.relativePath+'" nested under path '+('"'+r+'" is not valid. An absolute child route path ')+"must start with the combined path of all its parent routes."),l.relativePath=l.relativePath.slice(r.length));let c=pr([r,l.relativePath]),d=n.concat(l);i.children&&i.children.length>0&&(He(i.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+c+'".')),Vg(i.children,t,d,c)),!(i.path==null&&!i.index)&&t.push({path:c,score:T0(c,i.index),routesMeta:d})};return e.forEach((i,o)=>{var a;if(i.path===""||!((a=i.path)!=null&&a.includes("?")))s(i,o);else for(let l of qg(i.path))s(i,o,l)}),t}function qg(e){let t=e.split("/");if(t.length===0)return[];let[n,...r]=t,s=n.endsWith("?"),i=n.replace(/\?$/,"");if(r.length===0)return s?[i,""]:[i];let o=qg(r.join("/")),a=[];return a.push(...o.map(l=>l===""?i:[i,l].join("/"))),s&&a.push(...o),a.map(l=>e.startsWith("/")&&l===""?"/":l)}function S0(e){e.sort((t,n)=>t.score!==n.score?n.score-t.score:j0(t.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}const k0=/^:[\w-]+$/,b0=3,C0=2,E0=1,N0=10,_0=-2,Cp=e=>e==="*";function T0(e,t){let n=e.split("/"),r=n.length;return n.some(Cp)&&(r+=_0),t&&(r+=C0),n.filter(s=>!Cp(s)).reduce((s,i)=>s+(k0.test(i)?b0:i===""?E0:N0),r)}function j0(e,t){return e.length===t.length&&e.slice(0,-1).every((r,s)=>r===t[s])?e[e.length-1]-t[t.length-1]:0}function P0(e,t,n){let{routesMeta:r}=e,s={},i="/",o=[];for(let a=0;a{let{paramName:p,isOptional:v}=d;if(p==="*"){let y=a[f]||"";o=i.slice(0,i.length-y.length).replace(/(.)\/+$/,"$1")}const g=a[f];return v&&!g?c[p]=void 0:c[p]=(g||"").replace(/%2F/g,"/"),c},{}),pathname:i,pathnameBase:o,pattern:e}}function R0(e,t,n){t===void 0&&(t=!1),n===void 0&&(n=!0),Qg(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=[],s="^"+e.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(o,a,l)=>(r.push({paramName:a,isOptional:l!=null}),l?"/?([^\\/]+)?":"/([^\\/]+)"));return e.endsWith("*")?(r.push({paramName:"*"}),s+=e==="*"||e==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):n?s+="\\/*$":e!==""&&e!=="/"&&(s+="(?:(?=\\/|$))"),[new RegExp(s,t?void 0:"i"),r]}function O0(e){try{return e.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return Qg(!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 _d(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)||"/"}function D0(e,t){t===void 0&&(t="/");let{pathname:n,search:r="",hash:s=""}=typeof e=="string"?Us(e):e;return{pathname:n?n.startsWith("/")?n:L0(n,t):t,search:$0(r),hash:F0(s)}}function L0(e,t){let n=t.replace(/\/+$/,"").split("/");return e.split("/").forEach(s=>{s===".."?n.length>1&&n.pop():s!=="."&&n.push(s)}),n.length>1?n.join("/"):"/"}function Xl(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 M0(e){return e.filter((t,n)=>n===0||t.route.path&&t.route.path.length>0)}function Td(e,t){let n=M0(e);return t?n.map((r,s)=>s===n.length-1?r.pathname:r.pathnameBase):n.map(r=>r.pathnameBase)}function jd(e,t,n,r){r===void 0&&(r=!1);let s;typeof e=="string"?s=Us(e):(s=Vi({},e),He(!s.pathname||!s.pathname.includes("?"),Xl("?","pathname","search",s)),He(!s.pathname||!s.pathname.includes("#"),Xl("#","pathname","hash",s)),He(!s.search||!s.search.includes("#"),Xl("#","search","hash",s)));let i=e===""||s.pathname==="",o=i?"/":s.pathname,a;if(o==null)a=n;else{let f=t.length-1;if(!r&&o.startsWith("..")){let p=o.split("/");for(;p[0]==="..";)p.shift(),f-=1;s.pathname=p.join("/")}a=f>=0?t[f]:"/"}let l=D0(s,a),c=o&&o!=="/"&&o.endsWith("/"),d=(i||o===".")&&n.endsWith("/");return!l.pathname.endsWith("/")&&(c||d)&&(l.pathname+="/"),l}const pr=e=>e.join("/").replace(/\/\/+/g,"/"),A0=e=>e.replace(/\/+$/,"").replace(/^\/*/,"/"),$0=e=>!e||e==="?"?"":e.startsWith("?")?e:"?"+e,F0=e=>!e||e==="#"?"":e.startsWith("#")?e:"#"+e;function z0(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.internal=="boolean"&&"data"in e}const Gg=["post","put","patch","delete"];new Set(Gg);const U0=["get",...Gg];new Set(U0);/** * React Router v6.30.1 * * Copyright (c) Remix Software Inc. * * This source code is licensed under the MIT license found in the * LICENSE.md file in the root directory of this source tree. * * @license MIT */function qi(){return qi=Object.assign?Object.assign.bind():function(e){for(var t=1;t{a.current=!0}),S.useCallback(function(c,d){if(d===void 0&&(d={}),!a.current)return;if(typeof c=="number"){r.go(c);return}let f=jd(c,JSON.parse(o),i,d.relative==="path");e==null&&t!=="/"&&(f.pathname=f.pathname==="/"?t:pr([t,f.pathname])),(d.replace?r.replace:r.push)(f,d.state,d)},[t,r,o,i,e])}function Xg(e,t){let{relative:n}=t===void 0?{}:t,{future:r}=S.useContext(xr),{matches:s}=S.useContext(Sr),{pathname:i}=Ws(),o=JSON.stringify(Td(s,r.v7_relativeSplatPath));return S.useMemo(()=>jd(e,JSON.parse(o),i,n==="path"),[e,o,i,n])}function Q0(e,t){return V0(e,t)}function V0(e,t,n,r){Bs()||He(!1);let{navigator:s}=S.useContext(xr),{matches:i}=S.useContext(Sr),o=i[i.length-1],a=o?o.params:{};o&&o.pathname;let l=o?o.pathnameBase:"/";o&&o.route;let c=Ws(),d;if(t){var f;let x=typeof t=="string"?Us(t):t;l==="/"||(f=x.pathname)!=null&&f.startsWith(l)||He(!1),d=x}else d=c;let p=d.pathname||"/",v=p;if(l!=="/"){let x=l.replace(/^\//,"").split("/");v="/"+p.replace(/^\//,"").split("/").slice(x.length).join("/")}let g=w0(e,{pathname:v}),y=X0(g&&g.map(x=>Object.assign({},x,{params:Object.assign({},a,x.params),pathname:pr([l,s.encodeLocation?s.encodeLocation(x.pathname).pathname:x.pathname]),pathnameBase:x.pathnameBase==="/"?l:pr([l,s.encodeLocation?s.encodeLocation(x.pathnameBase).pathname:x.pathnameBase])})),i,n,r);return t&&y?S.createElement(ul.Provider,{value:{location:qi({pathname:"/",search:"",hash:"",state:null,key:"default"},d),navigationType:sr.Pop}},y):y}function q0(){let e=tS(),t=z0(e)?e.status+" "+e.statusText:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null,s={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return S.createElement(S.Fragment,null,S.createElement("h2",null,"Unexpected Application Error!"),S.createElement("h3",{style:{fontStyle:"italic"}},t),n?S.createElement("pre",{style:s},n):null,null)}const G0=S.createElement(q0,null);class Y0 extends S.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?S.createElement(Sr.Provider,{value:this.props.routeContext},S.createElement(Yg.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function K0(e){let{routeContext:t,match:n,children:r}=e,s=S.useContext(Pd);return s&&s.static&&s.staticContext&&(n.route.errorElement||n.route.ErrorBoundary)&&(s.staticContext._deepestRenderedBoundaryId=n.route.id),S.createElement(Sr.Provider,{value:t},r)}function X0(e,t,n,r){var s;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 o=e,a=(s=n)==null?void 0:s.errors;if(a!=null){let d=o.findIndex(f=>f.route.id&&(a==null?void 0:a[f.route.id])!==void 0);d>=0||He(!1),o=o.slice(0,Math.min(o.length,d+1))}let l=!1,c=-1;if(n&&r&&r.v7_partialHydration)for(let d=0;d=0?o=o.slice(0,c+1):o=[o[0]];break}}}return o.reduceRight((d,f,p)=>{let v,g=!1,y=null,x=null;n&&(v=a&&f.route.id?a[f.route.id]:void 0,y=f.route.errorElement||G0,l&&(c<0&&p===0?(rS("route-fallback"),g=!0,x=null):c===p&&(g=!0,x=f.route.hydrateFallbackElement||null)));let m=t.concat(o.slice(0,p+1)),h=()=>{let w;return v?w=y:g?w=x:f.route.Component?w=S.createElement(f.route.Component,null):f.route.element?w=f.route.element:w=d,S.createElement(K0,{match:f,routeContext:{outlet:d,matches:m,isDataRoute:n!=null},children:w})};return n&&(f.route.ErrorBoundary||f.route.errorElement||p===0)?S.createElement(Y0,{location:n.location,revalidation:n.revalidation,component:y,error:v,children:h(),routeContext:{outlet:null,matches:m,isDataRoute:!0}}):h()},null)}var Jg=function(e){return e.UseBlocker="useBlocker",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e}(Jg||{}),Zg=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}(Zg||{});function J0(e){let t=S.useContext(Pd);return t||He(!1),t}function Z0(e){let t=S.useContext(B0);return t||He(!1),t}function eS(e){let t=S.useContext(Sr);return t||He(!1),t}function ey(e){let t=eS(),n=t.matches[t.matches.length-1];return n.route.id||He(!1),n.route.id}function tS(){var e;let t=S.useContext(Yg),n=Z0(),r=ey();return t!==void 0?t:(e=n.errors)==null?void 0:e[r]}function nS(){let{router:e}=J0(Jg.UseNavigateStable),t=ey(Zg.UseNavigateStable),n=S.useRef(!1);return Kg(()=>{n.current=!0}),S.useCallback(function(s,i){i===void 0&&(i={}),n.current&&(typeof s=="number"?e.navigate(s):e.navigate(s,qi({fromRouteId:t},i)))},[e,t])}const Ep={};function rS(e,t,n){Ep[e]||(Ep[e]=!0)}function sS(e,t){e==null||e.v7_startTransition,e==null||e.v7_relativeSplatPath}function ty(e){let{to:t,replace:n,state:r,relative:s}=e;Bs()||He(!1);let{future:i,static:o}=S.useContext(xr),{matches:a}=S.useContext(Sr),{pathname:l}=Ws(),c=kr(),d=jd(t,Td(a,i.v7_relativeSplatPath),l,s==="path"),f=JSON.stringify(d);return S.useEffect(()=>c(JSON.parse(f),{replace:n,state:r,relative:s}),[c,f,s,n,r]),null}function Tr(e){He(!1)}function iS(e){let{basename:t="/",children:n=null,location:r,navigationType:s=sr.Pop,navigator:i,static:o=!1,future:a}=e;Bs()&&He(!1);let l=t.replace(/^\/*/,"/"),c=S.useMemo(()=>({basename:l,navigator:i,static:o,future:qi({v7_relativeSplatPath:!1},a)}),[l,a,i,o]);typeof r=="string"&&(r=Us(r));let{pathname:d="/",search:f="",hash:p="",state:v=null,key:g="default"}=r,y=S.useMemo(()=>{let x=_d(d,l);return x==null?null:{location:{pathname:x,search:f,hash:p,state:v,key:g},navigationType:s}},[l,d,f,p,v,g,s]);return y==null?null:S.createElement(xr.Provider,{value:c},S.createElement(ul.Provider,{children:n,value:y}))}function oS(e){let{children:t,location:n}=e;return Q0(ou(t),n)}new Promise(()=>{});function ou(e,t){t===void 0&&(t=[]);let n=[];return S.Children.forEach(e,(r,s)=>{if(!S.isValidElement(r))return;let i=[...t,s];if(r.type===S.Fragment){n.push.apply(n,ou(r.props.children,i));return}r.type!==Tr&&He(!1),!r.props.index||!r.props.children||He(!1);let o={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&&(o.children=ou(r.props.children,i)),n.push(o)}),n}/** * React Router DOM v6.30.1 * * Copyright (c) Remix Software Inc. * * This source code is licensed under the MIT license found in the * LICENSE.md file in the root directory of this source tree. * * @license MIT */function au(){return au=Object.assign?Object.assign.bind():function(e){for(var t=1;t=0)&&(n[s]=e[s]);return n}function lS(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function cS(e,t){return e.button===0&&(!t||t==="_self")&&!lS(e)}function lu(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(s=>[n,s]):[[n,r]])},[]))}function uS(e,t){let n=lu(e);return t&&t.forEach((r,s)=>{n.has(s)||t.getAll(s).forEach(i=>{n.append(s,i)})}),n}const dS=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","viewTransition"],fS="6";try{window.__reactRouterVersion=fS}catch{}const pS="startTransition",Np=sw[pS];function hS(e){let{basename:t,children:n,future:r,window:s}=e,i=S.useRef();i.current==null&&(i.current=g0({window:s,v5Compat:!0}));let o=i.current,[a,l]=S.useState({action:o.action,location:o.location}),{v7_startTransition:c}=r||{},d=S.useCallback(f=>{c&&Np?Np(()=>l(f)):l(f)},[l,c]);return S.useLayoutEffect(()=>o.listen(d),[o,d]),S.useEffect(()=>sS(r),[r]),S.createElement(iS,{basename:t,children:n,location:a.location,navigationType:a.action,navigator:o,future:r})}const mS=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",gS=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,ny=S.forwardRef(function(t,n){let{onClick:r,relative:s,reloadDocument:i,replace:o,state:a,target:l,to:c,preventScrollReset:d,viewTransition:f}=t,p=aS(t,dS),{basename:v}=S.useContext(xr),g,y=!1;if(typeof c=="string"&&gS.test(c)&&(g=c,mS))try{let w=new URL(window.location.href),C=c.startsWith("//")?new URL(w.protocol+c):new URL(c),T=_d(C.pathname,v);C.origin===w.origin&&T!=null?c=T+C.search+C.hash:y=!0}catch{}let x=W0(c,{relative:s}),m=yS(c,{replace:o,state:a,target:l,preventScrollReset:d,relative:s,viewTransition:f});function h(w){r&&r(w),w.defaultPrevented||m(w)}return S.createElement("a",au({},p,{href:g||x,onClick:y||i?r:h,ref:n,target:l}))});var _p;(function(e){e.UseScrollRestoration="useScrollRestoration",e.UseSubmit="useSubmit",e.UseSubmitFetcher="useSubmitFetcher",e.UseFetcher="useFetcher",e.useViewTransitionState="useViewTransitionState"})(_p||(_p={}));var Tp;(function(e){e.UseFetcher="useFetcher",e.UseFetchers="useFetchers",e.UseScrollRestoration="useScrollRestoration"})(Tp||(Tp={}));function yS(e,t){let{target:n,replace:r,state:s,preventScrollReset:i,relative:o,viewTransition:a}=t===void 0?{}:t,l=kr(),c=Ws(),d=Xg(e,{relative:o});return S.useCallback(f=>{if(cS(f,n)){f.preventDefault();let p=r!==void 0?r:Ra(c)===Ra(d);l(e,{replace:p,state:s,preventScrollReset:i,relative:o,viewTransition:a})}},[c,l,d,r,s,n,e,i,o,a])}function vS(e){let t=S.useRef(lu(e)),n=S.useRef(!1),r=Ws(),s=S.useMemo(()=>uS(r.search,n.current?null:t.current),[r.search]),i=kr(),o=S.useCallback((a,l)=>{const c=lu(typeof a=="function"?a(s):a);n.current=!0,i("?"+c,l)},[i,s]);return[s,o]}var ry={exports:{}},sy={};/** * @license React * use-sync-external-store-with-selector.production.js * * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */var ao=S;function wS(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var xS=typeof Object.is=="function"?Object.is:wS,SS=ao.useSyncExternalStore,kS=ao.useRef,bS=ao.useEffect,CS=ao.useMemo,ES=ao.useDebugValue;sy.useSyncExternalStoreWithSelector=function(e,t,n,r,s){var i=kS(null);if(i.current===null){var o={hasValue:!1,value:null};i.current=o}else o=i.current;i=CS(function(){function l(v){if(!c){if(c=!0,d=v,v=r(v),s!==void 0&&o.hasValue){var g=o.value;if(s(g,v))return f=g}return f=v}if(g=f,xS(d,v))return g;var y=r(v);return s!==void 0&&s(g,y)?(d=v,g):(d=v,f=y)}var c=!1,d,f,p=n===void 0?null:n;return[function(){return l(t())},p===null?void 0:function(){return l(p())}]},[t,n,r,s]);var a=SS(e,i[0],i[1]);return bS(function(){o.hasValue=!0,o.value=a},[a]),ES(a),a};ry.exports=sy;var NS=ry.exports;function _S(e){e()}function TS(){let e=null,t=null;return{clear(){e=null,t=null},notify(){_S(()=>{let n=e;for(;n;)n.callback(),n=n.next})},get(){const n=[];let r=e;for(;r;)n.push(r),r=r.next;return n},subscribe(n){let r=!0;const s=t={callback:n,next:null,prev:t};return s.prev?s.prev.next=s:e=s,function(){!r||e===null||(r=!1,s.next?s.next.prev=s.prev:t=s.prev,s.prev?s.prev.next=s.next:e=s.next)}}}}var jp={notify(){},get:()=>[]};function jS(e,t){let n,r=jp,s=0,i=!1;function o(y){d();const x=r.subscribe(y);let m=!1;return()=>{m||(m=!0,x(),f())}}function a(){r.notify()}function l(){g.onStateChange&&g.onStateChange()}function c(){return i}function d(){s++,n||(n=e.subscribe(l),r=TS())}function f(){s--,n&&s===0&&(n(),n=void 0,r.clear(),r=jp)}function p(){i||(i=!0,d())}function v(){i&&(i=!1,f())}const g={addNestedSub:o,notifyNestedSubs:a,handleChangeWrapper:l,isSubscribed:c,trySubscribe:p,tryUnsubscribe:v,getListeners:()=>r};return g}var PS=()=>typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",IS=PS(),RS=()=>typeof navigator<"u"&&navigator.product==="ReactNative",OS=RS(),DS=()=>IS||OS?S.useLayoutEffect:S.useEffect,LS=DS(),Jl=Symbol.for("react-redux-context"),Zl=typeof globalThis<"u"?globalThis:{};function MS(){if(!S.createContext)return{};const e=Zl[Jl]??(Zl[Jl]=new Map);let t=e.get(S.createContext);return t||(t=S.createContext(null),e.set(S.createContext,t)),t}var gr=MS();function AS(e){const{children:t,context:n,serverState:r,store:s}=e,i=S.useMemo(()=>{const l=jS(s);return{store:s,subscription:l,getServerState:r?()=>r:void 0}},[s,r]),o=S.useMemo(()=>s.getState(),[s]);LS(()=>{const{subscription:l}=i;return l.onStateChange=l.notifyNestedSubs,l.trySubscribe(),o!==s.getState()&&l.notifyNestedSubs(),()=>{l.tryUnsubscribe(),l.onStateChange=void 0}},[i,o]);const a=n||gr;return S.createElement(a.Provider,{value:i},t)}var $S=AS;function Id(e=gr){return function(){return S.useContext(e)}}var iy=Id();function oy(e=gr){const t=e===gr?iy:Id(e),n=()=>{const{store:r}=t();return r};return Object.assign(n,{withTypes:()=>n}),n}var FS=oy();function zS(e=gr){const t=e===gr?FS:oy(e),n=()=>t().dispatch;return Object.assign(n,{withTypes:()=>n}),n}var US=zS(),BS=(e,t)=>e===t;function WS(e=gr){const t=e===gr?iy:Id(e),n=(r,s={})=>{const{equalityFn:i=BS}=typeof s=="function"?{equalityFn:s}:s,o=t(),{store:a,subscription:l,getServerState:c}=o;S.useRef(!0);const d=S.useCallback({[r.name](p){return r(p)}}[r.name],[r]),f=NS.useSyncExternalStoreWithSelector(l.addNestedSub,a.getState,c||a.getState,d,i);return S.useDebugValue(f),f};return Object.assign(n,{withTypes:()=>n}),n}var HS=WS();function at(e){return`Minified Redux error #${e}; visit https://redux.js.org/Errors?code=${e} for the full message or use the non-minified dev environment for full errors. `}var QS=typeof Symbol=="function"&&Symbol.observable||"@@observable",Pp=QS,ec=()=>Math.random().toString(36).substring(7).split("").join("."),VS={INIT:`@@redux/INIT${ec()}`,REPLACE:`@@redux/REPLACE${ec()}`,PROBE_UNKNOWN_ACTION:()=>`@@redux/PROBE_UNKNOWN_ACTION${ec()}`},Oa=VS;function Rd(e){if(typeof e!="object"||e===null)return!1;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t||Object.getPrototypeOf(e)===null}function ay(e,t,n){if(typeof e!="function")throw new Error(at(2));if(typeof t=="function"&&typeof n=="function"||typeof n=="function"&&typeof arguments[3]=="function")throw new Error(at(0));if(typeof t=="function"&&typeof n>"u"&&(n=t,t=void 0),typeof n<"u"){if(typeof n!="function")throw new Error(at(1));return n(ay)(e,t)}let r=e,s=t,i=new Map,o=i,a=0,l=!1;function c(){o===i&&(o=new Map,i.forEach((x,m)=>{o.set(m,x)}))}function d(){if(l)throw new Error(at(3));return s}function f(x){if(typeof x!="function")throw new Error(at(4));if(l)throw new Error(at(5));let m=!0;c();const h=a++;return o.set(h,x),function(){if(m){if(l)throw new Error(at(6));m=!1,c(),o.delete(h),i=null}}}function p(x){if(!Rd(x))throw new Error(at(7));if(typeof x.type>"u")throw new Error(at(8));if(typeof x.type!="string")throw new Error(at(17));if(l)throw new Error(at(9));try{l=!0,s=r(s,x)}finally{l=!1}return(i=o).forEach(h=>{h()}),x}function v(x){if(typeof x!="function")throw new Error(at(10));r=x,p({type:Oa.REPLACE})}function g(){const x=f;return{subscribe(m){if(typeof m!="object"||m===null)throw new Error(at(11));function h(){const C=m;C.next&&C.next(d())}return h(),{unsubscribe:x(h)}},[Pp](){return this}}}return p({type:Oa.INIT}),{dispatch:p,subscribe:f,getState:d,replaceReducer:v,[Pp]:g}}function qS(e){Object.keys(e).forEach(t=>{const n=e[t];if(typeof n(void 0,{type:Oa.INIT})>"u")throw new Error(at(12));if(typeof n(void 0,{type:Oa.PROBE_UNKNOWN_ACTION()})>"u")throw new Error(at(13))})}function GS(e){const t=Object.keys(e),n={};for(let i=0;i"u")throw a&&a.type,new Error(at(14));c[f]=g,l=l||g!==v}return l=l||r.length!==Object.keys(o).length,l?c:o}}function Da(...e){return e.length===0?t=>t:e.length===1?e[0]:e.reduce((t,n)=>(...r)=>t(n(...r)))}function YS(...e){return t=>(n,r)=>{const s=t(n,r);let i=()=>{throw new Error(at(15))};const o={getState:s.getState,dispatch:(l,...c)=>i(l,...c)},a=e.map(l=>l(o));return i=Da(...a)(s.dispatch),{...s,dispatch:i}}}function KS(e){return Rd(e)&&"type"in e&&typeof e.type=="string"}var ly=Symbol.for("immer-nothing"),Ip=Symbol.for("immer-draftable"),Gt=Symbol.for("immer-state");function yn(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var Gi=Object.getPrototypeOf;function Wr(e){return!!e&&!!e[Gt]}function Qn(e){var t;return e?cy(e)||Array.isArray(e)||!!e[Ip]||!!((t=e.constructor)!=null&&t[Ip])||lo(e)||fl(e):!1}var XS=Object.prototype.constructor.toString(),Rp=new WeakMap;function cy(e){if(!e||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);if(t===null||t===Object.prototype)return!0;const n=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;if(n===Object)return!0;if(typeof n!="function")return!1;let r=Rp.get(n);return r===void 0&&(r=Function.toString.call(n),Rp.set(n,r)),r===XS}function La(e,t,n=!0){dl(e)===0?(n?Reflect.ownKeys(e):Object.keys(e)).forEach(s=>{t(s,e[s],e)}):e.forEach((r,s)=>t(s,r,e))}function dl(e){const t=e[Gt];return t?t.type_:Array.isArray(e)?1:lo(e)?2:fl(e)?3:0}function cu(e,t){return dl(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function uy(e,t,n){const r=dl(e);r===2?e.set(t,n):r===3?e.add(n):e[t]=n}function JS(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function lo(e){return e instanceof Map}function fl(e){return e instanceof Set}function jr(e){return e.copy_||e.base_}function uu(e,t){if(lo(e))return new Map(e);if(fl(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);const n=cy(e);if(t===!0||t==="class_only"&&!n){const r=Object.getOwnPropertyDescriptors(e);delete r[Gt];let s=Reflect.ownKeys(r);for(let i=0;i1&&Object.defineProperties(e,{set:Lo,add:Lo,clear:Lo,delete:Lo}),Object.freeze(e),t&&Object.values(e).forEach(n=>Od(n,!0))),e}function ZS(){yn(2)}var Lo={value:ZS};function pl(e){return e===null||typeof e!="object"?!0:Object.isFrozen(e)}var e1={};function Hr(e){const t=e1[e];return t||yn(0,e),t}var Yi;function dy(){return Yi}function t1(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function Op(e,t){t&&(Hr("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function du(e){fu(e),e.drafts_.forEach(n1),e.drafts_=null}function fu(e){e===Yi&&(Yi=e.parent_)}function Dp(e){return Yi=t1(Yi,e)}function n1(e){const t=e[Gt];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function Lp(e,t){t.unfinalizedDrafts_=t.drafts_.length;const n=t.drafts_[0];return e!==void 0&&e!==n?(n[Gt].modified_&&(du(t),yn(4)),Qn(e)&&(e=Ma(t,e),t.parent_||Aa(t,e)),t.patches_&&Hr("Patches").generateReplacementPatches_(n[Gt].base_,e,t.patches_,t.inversePatches_)):e=Ma(t,n,[]),du(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==ly?e:void 0}function Ma(e,t,n){if(pl(t))return t;const r=e.immer_.shouldUseStrictIteration(),s=t[Gt];if(!s)return La(t,(i,o)=>Mp(e,s,t,i,o,n),r),t;if(s.scope_!==e)return t;if(!s.modified_)return Aa(e,s.base_,!0),s.base_;if(!s.finalized_){s.finalized_=!0,s.scope_.unfinalizedDrafts_--;const i=s.copy_;let o=i,a=!1;s.type_===3&&(o=new Set(i),i.clear(),a=!0),La(o,(l,c)=>Mp(e,s,i,l,c,n,a),r),Aa(e,i,!1),n&&e.patches_&&Hr("Patches").generatePatches_(s,n,e.patches_,e.inversePatches_)}return s.copy_}function Mp(e,t,n,r,s,i,o){if(s==null||typeof s!="object"&&!o)return;const a=pl(s);if(!(a&&!o)){if(Wr(s)){const l=i&&t&&t.type_!==3&&!cu(t.assigned_,r)?i.concat(r):void 0,c=Ma(e,s,l);if(uy(n,r,c),Wr(c))e.canAutoFreeze_=!1;else return}else o&&n.add(s);if(Qn(s)&&!a){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1||t&&t.base_&&t.base_[r]===s&&a)return;Ma(e,s),(!t||!t.scope_.parent_)&&typeof r!="symbol"&&(lo(n)?n.has(r):Object.prototype.propertyIsEnumerable.call(n,r))&&Aa(e,s)}}}function Aa(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&Od(t,n)}function r1(e,t){const n=Array.isArray(e),r={type_:n?1:0,scope_:t?t.scope_:dy(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1};let s=r,i=Dd;n&&(s=[r],i=Ki);const{revoke:o,proxy:a}=Proxy.revocable(s,i);return r.draft_=a,r.revoke_=o,a}var Dd={get(e,t){if(t===Gt)return e;const n=jr(e);if(!cu(n,t))return s1(e,n,t);const r=n[t];return e.finalized_||!Qn(r)?r:r===tc(e.base_,t)?(nc(e),e.copy_[t]=hu(r,e)):r},has(e,t){return t in jr(e)},ownKeys(e){return Reflect.ownKeys(jr(e))},set(e,t,n){const r=fy(jr(e),t);if(r!=null&&r.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){const s=tc(jr(e),t),i=s==null?void 0:s[Gt];if(i&&i.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if(JS(n,s)&&(n!==void 0||cu(e.base_,t)))return!0;nc(e),pu(e)}return e.copy_[t]===n&&(n!==void 0||t in e.copy_)||Number.isNaN(n)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=n,e.assigned_[t]=!0),!0},deleteProperty(e,t){return tc(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,nc(e),pu(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){const n=jr(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:r.enumerable,value:n[t]}},defineProperty(){yn(11)},getPrototypeOf(e){return Gi(e.base_)},setPrototypeOf(){yn(12)}},Ki={};La(Dd,(e,t)=>{Ki[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});Ki.deleteProperty=function(e,t){return Ki.set.call(this,e,t,void 0)};Ki.set=function(e,t,n){return Dd.set.call(this,e[0],t,n,e[0])};function tc(e,t){const n=e[Gt];return(n?jr(n):e)[t]}function s1(e,t,n){var s;const r=fy(t,n);return r?"value"in r?r.value:(s=r.get)==null?void 0:s.call(e.draft_):void 0}function fy(e,t){if(!(t in e))return;let n=Gi(e);for(;n;){const r=Object.getOwnPropertyDescriptor(n,t);if(r)return r;n=Gi(n)}}function pu(e){e.modified_||(e.modified_=!0,e.parent_&&pu(e.parent_))}function nc(e){e.copy_||(e.copy_=uu(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var i1=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.useStrictIteration_=!0,this.produce=(t,n,r)=>{if(typeof t=="function"&&typeof n!="function"){const i=n;n=t;const o=this;return function(l=i,...c){return o.produce(l,d=>n.call(this,d,...c))}}typeof n!="function"&&yn(6),r!==void 0&&typeof r!="function"&&yn(7);let s;if(Qn(t)){const i=Dp(this),o=hu(t,void 0);let a=!0;try{s=n(o),a=!1}finally{a?du(i):fu(i)}return Op(i,r),Lp(s,i)}else if(!t||typeof t!="object"){if(s=n(t),s===void 0&&(s=t),s===ly&&(s=void 0),this.autoFreeze_&&Od(s,!0),r){const i=[],o=[];Hr("Patches").generateReplacementPatches_(t,s,i,o),r(i,o)}return s}else yn(1,t)},this.produceWithPatches=(t,n)=>{if(typeof t=="function")return(o,...a)=>this.produceWithPatches(o,l=>t(l,...a));let r,s;return[this.produce(t,n,(o,a)=>{r=o,s=a}),r,s]},typeof(e==null?void 0:e.autoFreeze)=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof(e==null?void 0:e.useStrictShallowCopy)=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy),typeof(e==null?void 0:e.useStrictIteration)=="boolean"&&this.setUseStrictIteration(e.useStrictIteration)}createDraft(e){Qn(e)||yn(8),Wr(e)&&(e=o1(e));const t=Dp(this),n=hu(e,void 0);return n[Gt].isManual_=!0,fu(t),n}finishDraft(e,t){const n=e&&e[Gt];(!n||!n.isManual_)&&yn(9);const{scope_:r}=n;return Op(r,t),Lp(void 0,r)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}setUseStrictIteration(e){this.useStrictIteration_=e}shouldUseStrictIteration(){return this.useStrictIteration_}applyPatches(e,t){let n;for(n=t.length-1;n>=0;n--){const s=t[n];if(s.path.length===0&&s.op==="replace"){e=s.value;break}}n>-1&&(t=t.slice(n+1));const r=Hr("Patches").applyPatches_;return Wr(e)?r(e,t):this.produce(e,s=>r(s,t))}};function hu(e,t){const n=lo(e)?Hr("MapSet").proxyMap_(e,t):fl(e)?Hr("MapSet").proxySet_(e,t):r1(e,t);return(t?t.scope_:dy()).drafts_.push(n),n}function o1(e){return Wr(e)||yn(10,e),py(e)}function py(e){if(!Qn(e)||pl(e))return e;const t=e[Gt];let n,r=!0;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=uu(e,t.scope_.immer_.useStrictShallowCopy_),r=t.scope_.immer_.shouldUseStrictIteration()}else n=uu(e,!0);return La(n,(s,i)=>{uy(n,s,py(i))},r),t&&(t.finalized_=!1),n}var a1=new i1,hy=a1.produce;function my(e){return({dispatch:n,getState:r})=>s=>i=>typeof i=="function"?i(n,r,e):s(i)}var l1=my(),c1=my,u1=typeof window<"u"&&window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__?window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__:function(){if(arguments.length!==0)return typeof arguments[0]=="object"?Da:Da.apply(null,arguments)};function Ap(e,t){function n(...r){if(t){let s=t(...r);if(!s)throw new Error(zn(0));return{type:e,payload:s.payload,..."meta"in s&&{meta:s.meta},..."error"in s&&{error:s.error}}}return{type:e,payload:r[0]}}return n.toString=()=>`${e}`,n.type=e,n.match=r=>KS(r)&&r.type===e,n}var gy=class hi extends Array{constructor(...t){super(...t),Object.setPrototypeOf(this,hi.prototype)}static get[Symbol.species](){return hi}concat(...t){return super.concat.apply(this,t)}prepend(...t){return t.length===1&&Array.isArray(t[0])?new hi(...t[0].concat(this)):new hi(...t.concat(this))}};function $p(e){return Qn(e)?hy(e,()=>{}):e}function Mo(e,t,n){return e.has(t)?e.get(t):e.set(t,n(t)).get(t)}function d1(e){return typeof e=="boolean"}var f1=()=>function(t){const{thunk:n=!0,immutableCheck:r=!0,serializableCheck:s=!0,actionCreatorCheck:i=!0}=t??{};let o=new gy;return n&&(d1(n)?o.push(l1):o.push(c1(n.extraArgument))),o},p1="RTK_autoBatch",Fp=e=>t=>{setTimeout(t,e)},h1=(e={type:"raf"})=>t=>(...n)=>{const r=t(...n);let s=!0,i=!1,o=!1;const a=new Set,l=e.type==="tick"?queueMicrotask:e.type==="raf"?typeof window<"u"&&window.requestAnimationFrame?window.requestAnimationFrame:Fp(10):e.type==="callback"?e.queueNotification:Fp(e.timeout),c=()=>{o=!1,i&&(i=!1,a.forEach(d=>d()))};return Object.assign({},r,{subscribe(d){const f=()=>s&&d(),p=r.subscribe(f);return a.add(d),()=>{p(),a.delete(d)}},dispatch(d){var f;try{return s=!((f=d==null?void 0:d.meta)!=null&&f[p1]),i=!s,i&&(o||(o=!0,l(c))),r.dispatch(d)}finally{s=!0}}})},m1=e=>function(n){const{autoBatch:r=!0}=n??{};let s=new gy(e);return r&&s.push(h1(typeof r=="object"?r:void 0)),s};function g1(e){const t=f1(),{reducer:n=void 0,middleware:r,devTools:s=!0,preloadedState:i=void 0,enhancers:o=void 0}=e||{};let a;if(typeof n=="function")a=n;else if(Rd(n))a=GS(n);else throw new Error(zn(1));let l;typeof r=="function"?l=r(t):l=t();let c=Da;s&&(c=u1({trace:!1,...typeof s=="object"&&s}));const d=YS(...l),f=m1(d);let p=typeof o=="function"?o(f):f();const v=c(...p);return ay(a,i,v)}function yy(e){const t={},n=[];let r;const s={addCase(i,o){const a=typeof i=="string"?i:i.type;if(!a)throw new Error(zn(28));if(a in t)throw new Error(zn(29));return t[a]=o,s},addAsyncThunk(i,o){return o.pending&&(t[i.pending.type]=o.pending),o.rejected&&(t[i.rejected.type]=o.rejected),o.fulfilled&&(t[i.fulfilled.type]=o.fulfilled),o.settled&&n.push({matcher:i.settled,reducer:o.settled}),s},addMatcher(i,o){return n.push({matcher:i,reducer:o}),s},addDefaultCase(i){return r=i,s}};return e(s),[t,n,r]}function y1(e){return typeof e=="function"}function v1(e,t){let[n,r,s]=yy(t),i;if(y1(e))i=()=>$p(e());else{const a=$p(e);i=()=>a}function o(a=i(),l){let c=[n[l.type],...r.filter(({matcher:d})=>d(l)).map(({reducer:d})=>d)];return c.filter(d=>!!d).length===0&&(c=[s]),c.reduce((d,f)=>{if(f)if(Wr(d)){const v=f(d,l);return v===void 0?d:v}else{if(Qn(d))return hy(d,p=>f(p,l));{const p=f(d,l);if(p===void 0){if(d===null)return d;throw Error("A case reducer on a non-draftable value must not return undefined")}return p}}return d},a)}return o.getInitialState=i,o}var w1=Symbol.for("rtk-slice-createasyncthunk");function x1(e,t){return`${e}/${t}`}function S1({creators:e}={}){var n;const t=(n=e==null?void 0:e.asyncThunk)==null?void 0:n[w1];return function(s){const{name:i,reducerPath:o=i}=s;if(!i)throw new Error(zn(11));const a=(typeof s.reducers=="function"?s.reducers(b1()):s.reducers)||{},l=Object.keys(a),c={sliceCaseReducersByName:{},sliceCaseReducersByType:{},actionCreators:{},sliceMatchers:[]},d={addCase(C,T){const b=typeof C=="string"?C:C.type;if(!b)throw new Error(zn(12));if(b in c.sliceCaseReducersByType)throw new Error(zn(13));return c.sliceCaseReducersByType[b]=T,d},addMatcher(C,T){return c.sliceMatchers.push({matcher:C,reducer:T}),d},exposeAction(C,T){return c.actionCreators[C]=T,d},exposeCaseReducer(C,T){return c.sliceCaseReducersByName[C]=T,d}};l.forEach(C=>{const T=a[C],b={reducerName:C,type:x1(i,C),createNotation:typeof s.reducers=="function"};E1(T)?_1(b,T,d,t):C1(b,T,d)});function f(){const[C={},T=[],b=void 0]=typeof s.extraReducers=="function"?yy(s.extraReducers):[s.extraReducers],N={...C,...c.sliceCaseReducersByType};return v1(s.initialState,P=>{for(let I in N)P.addCase(I,N[I]);for(let I of c.sliceMatchers)P.addMatcher(I.matcher,I.reducer);for(let I of T)P.addMatcher(I.matcher,I.reducer);b&&P.addDefaultCase(b)})}const p=C=>C,v=new Map,g=new WeakMap;let y;function x(C,T){return y||(y=f()),y(C,T)}function m(){return y||(y=f()),y.getInitialState()}function h(C,T=!1){function b(P){let I=P[C];return typeof I>"u"&&T&&(I=Mo(g,b,m)),I}function N(P=p){const I=Mo(v,T,()=>new WeakMap);return Mo(I,P,()=>{const O={};for(const[Q,ue]of Object.entries(s.selectors??{}))O[Q]=k1(ue,P,()=>Mo(g,P,m),T);return O})}return{reducerPath:C,getSelectors:N,get selectors(){return N(b)},selectSlice:b}}const w={name:i,reducer:x,actions:c.actionCreators,caseReducers:c.sliceCaseReducersByName,getInitialState:m,...h(o),injectInto(C,{reducerPath:T,...b}={}){const N=T??o;return C.inject({reducerPath:N,reducer:x},b),{...w,...h(N,!0)}}};return w}}function k1(e,t,n,r){function s(i,...o){let a=t(i);return typeof a>"u"&&r&&(a=n()),e(a,...o)}return s.unwrapped=e,s}var hl=S1();function b1(){function e(t,n){return{_reducerDefinitionType:"asyncThunk",payloadCreator:t,...n}}return e.withTypes=()=>e,{reducer(t){return Object.assign({[t.name](...n){return t(...n)}}[t.name],{_reducerDefinitionType:"reducer"})},preparedReducer(t,n){return{_reducerDefinitionType:"reducerWithPrepare",prepare:t,reducer:n}},asyncThunk:e}}function C1({type:e,reducerName:t,createNotation:n},r,s){let i,o;if("reducer"in r){if(n&&!N1(r))throw new Error(zn(17));i=r.reducer,o=r.prepare}else i=r;s.addCase(e,i).exposeCaseReducer(t,i).exposeAction(t,o?Ap(e,o):Ap(e))}function E1(e){return e._reducerDefinitionType==="asyncThunk"}function N1(e){return e._reducerDefinitionType==="reducerWithPrepare"}function _1({type:e,reducerName:t},n,r,s){if(!s)throw new Error(zn(18));const{payloadCreator:i,fulfilled:o,pending:a,rejected:l,settled:c,options:d}=n,f=s(e,i,d);r.exposeAction(t,f),o&&r.addCase(f.fulfilled,o),a&&r.addCase(f.pending,a),l&&r.addCase(f.rejected,l),c&&r.addMatcher(f.settled,c),r.exposeCaseReducer(t,{fulfilled:o||Ao,pending:a||Ao,rejected:l||Ao,settled:c||Ao})}function Ao(){}function zn(e){return`Minified Redux Toolkit error #${e}; visit https://redux-toolkit.js.org/Errors?code=${e} for the full message or use the non-minified dev environment for full errors. `}const T1={isAuthenticated:localStorage.getItem("isAuthenticated")==="true",userId:null,username:localStorage.getItem("username")||null,loading:!1},vy=hl({name:"auth",initialState:T1,reducers:{setAuth:(e,t)=>{e.isAuthenticated=!0,e.userId=t.payload.userId,e.username=t.payload.username,localStorage.setItem("isAuthenticated","true"),localStorage.setItem("username",t.payload.username)},clearAuth:e=>{e.isAuthenticated=!1,e.userId=null,e.username=null,localStorage.removeItem("isAuthenticated"),localStorage.removeItem("username")}}}),{setAuth:Ld,clearAuth:Xi}=vy.actions,j1=vy.reducer,P1={notes:[],allNotes:[],archivedNotes:[],selectedDate:null,selectedTag:null,searchQuery:"",loading:!1,editingNoteId:null,offlineMode:!1,pendingSyncCount:0},wy=hl({name:"notes",initialState:P1,reducers:{setNotes:(e,t)=>{e.notes=t.payload},setAllNotes:(e,t)=>{e.allNotes=t.payload},addNote:(e,t)=>{e.notes.unshift(t.payload),e.allNotes.unshift(t.payload)},updateNote:(e,t)=>{const n=e.notes.findIndex(s=>s.id===t.payload.id);n!==-1&&(e.notes[n]=t.payload);const r=e.allNotes.findIndex(s=>s.id===t.payload.id);r!==-1&&(e.allNotes[r]=t.payload)},deleteNote:(e,t)=>{e.notes=e.notes.filter(n=>n.id!==t.payload),e.allNotes=e.allNotes.filter(n=>n.id!==t.payload)},setSelectedDate:(e,t)=>{e.selectedDate=t.payload},setSelectedTag:(e,t)=>{e.selectedTag=t.payload},setSearchQuery:(e,t)=>{e.searchQuery=t.payload},setEditingNote:(e,t)=>{e.editingNoteId=t.payload},setOfflineMode:(e,t)=>{e.offlineMode=t.payload},setPendingSyncCount:(e,t)=>{e.pendingSyncCount=t.payload},updateNoteSyncStatus:(e,t)=>{const n=e.notes.findIndex(s=>s.id===t.payload.id);n!==-1&&(e.notes[n].syncStatus=t.payload.syncStatus);const r=e.allNotes.findIndex(s=>s.id===t.payload.id);r!==-1&&(e.allNotes[r].syncStatus=t.payload.syncStatus)}}}),{setNotes:I1,setAllNotes:R1,addNote:rc,updateNote:Be,deleteNote:V_,setSelectedDate:mu,setSelectedTag:$a,setSearchQuery:gu,setEditingNote:q_,setOfflineMode:Ns,setPendingSyncCount:Md,updateNoteSyncStatus:G_}=wy.actions,O1=wy.reducer,D1=()=>{const e=localStorage.getItem("theme");return e==="dark"||e==="light"?e:window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"},L1={theme:D1(),accentColor:localStorage.getItem("accentColor")||"#007bff",notifications:[],isMobileSidebarOpen:!1,isPreviewMode:!1,syncStatus:"idle"},xy=hl({name:"ui",initialState:L1,reducers:{toggleTheme:e=>{e.theme=e.theme==="light"?"dark":"light",localStorage.setItem("theme",e.theme)},setTheme:(e,t)=>{e.theme=t.payload,localStorage.setItem("theme",e.theme)},setAccentColor:(e,t)=>{e.accentColor=t.payload,localStorage.setItem("accentColor",t.payload)},addNotification:(e,t)=>{const n=t.payload.id||`notification-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,{id:r,...s}=t.payload;e.notifications.push({...s,id:n})},removeNotification:(e,t)=>{e.notifications=e.notifications.filter(n=>n.id!==t.payload)},toggleMobileSidebar:e=>{e.isMobileSidebarOpen=!e.isMobileSidebarOpen},closeMobileSidebar:e=>{e.isMobileSidebarOpen=!1},togglePreviewMode:e=>{e.isPreviewMode=!e.isPreviewMode},setSyncStatus:(e,t)=>{e.syncStatus=t.payload}}}),{toggleTheme:M1,setTheme:A1,setAccentColor:Fa,addNotification:_s,removeNotification:Sy,toggleMobileSidebar:Y_,closeMobileSidebar:K_,togglePreviewMode:$1,setSyncStatus:ss}=xy.actions,F1=xy.reducer,z1={user:null,aiSettings:null,aiEnabled:!1,loading:!1},ky=hl({name:"profile",initialState:z1,reducers:{setUser:(e,t)=>{e.user=t.payload},setAiSettings:(e,t)=>{e.aiSettings=t.payload,e.aiEnabled=t.payload.ai_enabled===1},setLoading:(e,t)=>{e.loading=t.payload}}}),{setUser:Ad,setAiSettings:$d,setLoading:X_}=ky.actions,U1=ky.reducer,te=g1({reducer:{auth:j1,notes:O1,ui:F1,profile:U1}}),wt=()=>US(),oe=HS;function by(e,t){return function(){return e.apply(t,arguments)}}const{toString:B1}=Object.prototype,{getPrototypeOf:Fd}=Object,{iterator:ml,toStringTag:Cy}=Symbol,gl=(e=>t=>{const n=B1.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),kn=e=>(e=e.toLowerCase(),t=>gl(t)===e),yl=e=>t=>typeof t===e,{isArray:Hs}=Array,Ms=yl("undefined");function co(e){return e!==null&&!Ms(e)&&e.constructor!==null&&!Ms(e.constructor)&&zt(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const Ey=kn("ArrayBuffer");function W1(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&Ey(e.buffer),t}const H1=yl("string"),zt=yl("function"),Ny=yl("number"),uo=e=>e!==null&&typeof e=="object",Q1=e=>e===!0||e===!1,ra=e=>{if(gl(e)!=="object")return!1;const t=Fd(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Cy in e)&&!(ml in e)},V1=e=>{if(!uo(e)||co(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},q1=kn("Date"),G1=kn("File"),Y1=kn("Blob"),K1=kn("FileList"),X1=e=>uo(e)&&zt(e.pipe),J1=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||zt(e.append)&&((t=gl(e))==="formdata"||t==="object"&&zt(e.toString)&&e.toString()==="[object FormData]"))},Z1=kn("URLSearchParams"),[ek,tk,nk,rk]=["ReadableStream","Request","Response","Headers"].map(kn),sk=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function fo(e,t,{allOwnKeys:n=!1}={}){if(e===null||typeof e>"u")return;let r,s;if(typeof e!="object"&&(e=[e]),Hs(e))for(r=0,s=e.length;r0;)if(s=n[r],t===s.toLowerCase())return s;return null}const Dr=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,Ty=e=>!Ms(e)&&e!==Dr;function yu(){const{caseless:e,skipUndefined:t}=Ty(this)&&this||{},n={},r=(s,i)=>{const o=e&&_y(n,i)||i;ra(n[o])&&ra(s)?n[o]=yu(n[o],s):ra(s)?n[o]=yu({},s):Hs(s)?n[o]=s.slice():(!t||!Ms(s))&&(n[o]=s)};for(let s=0,i=arguments.length;s(fo(t,(s,i)=>{n&&zt(s)?e[i]=by(s,n):e[i]=s},{allOwnKeys:r}),e),ok=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),ak=(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)},lk=(e,t,n,r)=>{let s,i,o;const a={};if(t=t||{},e==null)return t;do{for(s=Object.getOwnPropertyNames(e),i=s.length;i-- >0;)o=s[i],(!r||r(o,e,t))&&!a[o]&&(t[o]=e[o],a[o]=!0);e=n!==!1&&Fd(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},ck=(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},uk=e=>{if(!e)return null;if(Hs(e))return e;let t=e.length;if(!Ny(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},dk=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&Fd(Uint8Array)),fk=(e,t)=>{const r=(e&&e[ml]).call(e);let s;for(;(s=r.next())&&!s.done;){const i=s.value;t.call(e,i[0],i[1])}},pk=(e,t)=>{let n;const r=[];for(;(n=e.exec(t))!==null;)r.push(n);return r},hk=kn("HTMLFormElement"),mk=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,s){return r.toUpperCase()+s}),zp=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),gk=kn("RegExp"),jy=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),r={};fo(n,(s,i)=>{let o;(o=t(s,i,e))!==!1&&(r[i]=o||s)}),Object.defineProperties(e,r)},yk=e=>{jy(e,(t,n)=>{if(zt(e)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const r=e[n];if(zt(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+"'")})}})},vk=(e,t)=>{const n={},r=s=>{s.forEach(i=>{n[i]=!0})};return Hs(e)?r(e):r(String(e).split(t)),n},wk=()=>{},xk=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function Sk(e){return!!(e&&zt(e.append)&&e[Cy]==="FormData"&&e[ml])}const kk=e=>{const t=new Array(10),n=(r,s)=>{if(uo(r)){if(t.indexOf(r)>=0)return;if(co(r))return r;if(!("toJSON"in r)){t[s]=r;const i=Hs(r)?[]:{};return fo(r,(o,a)=>{const l=n(o,s+1);!Ms(l)&&(i[a]=l)}),t[s]=void 0,i}}return r};return n(e,0)},bk=kn("AsyncFunction"),Ck=e=>e&&(uo(e)||zt(e))&&zt(e.then)&&zt(e.catch),Py=((e,t)=>e?setImmediate:t?((n,r)=>(Dr.addEventListener("message",({source:s,data:i})=>{s===Dr&&i===n&&r.length&&r.shift()()},!1),s=>{r.push(s),Dr.postMessage(n,"*")}))(`axios@${Math.random()}`,[]):n=>setTimeout(n))(typeof setImmediate=="function",zt(Dr.postMessage)),Ek=typeof queueMicrotask<"u"?queueMicrotask.bind(Dr):typeof process<"u"&&process.nextTick||Py,Nk=e=>e!=null&&zt(e[ml]),_={isArray:Hs,isArrayBuffer:Ey,isBuffer:co,isFormData:J1,isArrayBufferView:W1,isString:H1,isNumber:Ny,isBoolean:Q1,isObject:uo,isPlainObject:ra,isEmptyObject:V1,isReadableStream:ek,isRequest:tk,isResponse:nk,isHeaders:rk,isUndefined:Ms,isDate:q1,isFile:G1,isBlob:Y1,isRegExp:gk,isFunction:zt,isStream:X1,isURLSearchParams:Z1,isTypedArray:dk,isFileList:K1,forEach:fo,merge:yu,extend:ik,trim:sk,stripBOM:ok,inherits:ak,toFlatObject:lk,kindOf:gl,kindOfTest:kn,endsWith:ck,toArray:uk,forEachEntry:fk,matchAll:pk,isHTMLForm:hk,hasOwnProperty:zp,hasOwnProp:zp,reduceDescriptors:jy,freezeMethods:yk,toObjectSet:vk,toCamelCase:mk,noop:wk,toFiniteNumber:xk,findKey:_y,global:Dr,isContextDefined:Ty,isSpecCompliantForm:Sk,toJSONObject:kk,isAsyncFn:bk,isThenable:Ck,setImmediate:Py,asap:Ek,isIterable:Nk};function re(e,t,n,r,s){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),s&&(this.response=s,this.status=s.status?s.status:null)}_.inherits(re,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:_.toJSONObject(this.config),code:this.code,status:this.status}}});const Iy=re.prototype,Ry={};["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=>{Ry[e]={value:e}});Object.defineProperties(re,Ry);Object.defineProperty(Iy,"isAxiosError",{value:!0});re.from=(e,t,n,r,s,i)=>{const o=Object.create(Iy);_.toFlatObject(e,o,function(d){return d!==Error.prototype},c=>c!=="isAxiosError");const a=e&&e.message?e.message:"Error",l=t==null&&e?e.code:t;return re.call(o,a,l,n,r,s),e&&o.cause==null&&Object.defineProperty(o,"cause",{value:e,configurable:!0}),o.name=e&&e.name||"Error",i&&Object.assign(o,i),o};const _k=null;function vu(e){return _.isPlainObject(e)||_.isArray(e)}function Oy(e){return _.endsWith(e,"[]")?e.slice(0,-2):e}function Up(e,t,n){return e?e.concat(t).map(function(s,i){return s=Oy(s),!n&&i?"["+s+"]":s}).join(n?".":""):t}function Tk(e){return _.isArray(e)&&!e.some(vu)}const jk=_.toFlatObject(_,{},null,function(t){return/^is[A-Z]/.test(t)});function vl(e,t,n){if(!_.isObject(e))throw new TypeError("target must be an object");t=t||new FormData,n=_.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(y,x){return!_.isUndefined(x[y])});const r=n.metaTokens,s=n.visitor||d,i=n.dots,o=n.indexes,l=(n.Blob||typeof Blob<"u"&&Blob)&&_.isSpecCompliantForm(t);if(!_.isFunction(s))throw new TypeError("visitor must be a function");function c(g){if(g===null)return"";if(_.isDate(g))return g.toISOString();if(_.isBoolean(g))return g.toString();if(!l&&_.isBlob(g))throw new re("Blob is not supported. Use a Buffer instead.");return _.isArrayBuffer(g)||_.isTypedArray(g)?l&&typeof Blob=="function"?new Blob([g]):Buffer.from(g):g}function d(g,y,x){let m=g;if(g&&!x&&typeof g=="object"){if(_.endsWith(y,"{}"))y=r?y:y.slice(0,-2),g=JSON.stringify(g);else if(_.isArray(g)&&Tk(g)||(_.isFileList(g)||_.endsWith(y,"[]"))&&(m=_.toArray(g)))return y=Oy(y),m.forEach(function(w,C){!(_.isUndefined(w)||w===null)&&t.append(o===!0?Up([y],C,i):o===null?y:y+"[]",c(w))}),!1}return vu(g)?!0:(t.append(Up(x,y,i),c(g)),!1)}const f=[],p=Object.assign(jk,{defaultVisitor:d,convertValue:c,isVisitable:vu});function v(g,y){if(!_.isUndefined(g)){if(f.indexOf(g)!==-1)throw Error("Circular reference detected in "+y.join("."));f.push(g),_.forEach(g,function(m,h){(!(_.isUndefined(m)||m===null)&&s.call(t,m,_.isString(h)?h.trim():h,y,p))===!0&&v(m,y?y.concat(h):[h])}),f.pop()}}if(!_.isObject(e))throw new TypeError("data must be an object");return v(e),t}function Bp(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(r){return t[r]})}function zd(e,t){this._pairs=[],e&&vl(e,this,t)}const Dy=zd.prototype;Dy.append=function(t,n){this._pairs.push([t,n])};Dy.toString=function(t){const n=t?function(r){return t.call(this,r,Bp)}:Bp;return this._pairs.map(function(s){return n(s[0])+"="+n(s[1])},"").join("&")};function Pk(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function Ly(e,t,n){if(!t)return e;const r=n&&n.encode||Pk;_.isFunction(n)&&(n={serialize:n});const s=n&&n.serialize;let i;if(s?i=s(t,n):i=_.isURLSearchParams(t)?t.toString():new zd(t,n).toString(r),i){const o=e.indexOf("#");o!==-1&&(e=e.slice(0,o)),e+=(e.indexOf("?")===-1?"?":"&")+i}return e}class Wp{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){_.forEach(this.handlers,function(r){r!==null&&t(r)})}}const My={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Ik=typeof URLSearchParams<"u"?URLSearchParams:zd,Rk=typeof FormData<"u"?FormData:null,Ok=typeof Blob<"u"?Blob:null,Dk={isBrowser:!0,classes:{URLSearchParams:Ik,FormData:Rk,Blob:Ok},protocols:["http","https","file","blob","url","data"]},Ud=typeof window<"u"&&typeof document<"u",wu=typeof navigator=="object"&&navigator||void 0,Lk=Ud&&(!wu||["ReactNative","NativeScript","NS"].indexOf(wu.product)<0),Mk=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",Ak=Ud&&window.location.href||"http://localhost",$k=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:Ud,hasStandardBrowserEnv:Lk,hasStandardBrowserWebWorkerEnv:Mk,navigator:wu,origin:Ak},Symbol.toStringTag,{value:"Module"})),yt={...$k,...Dk};function Fk(e,t){return vl(e,new yt.classes.URLSearchParams,{visitor:function(n,r,s,i){return yt.isNode&&_.isBuffer(n)?(this.append(r,n.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)},...t})}function zk(e){return _.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function Uk(e){const t={},n=Object.keys(e);let r;const s=n.length;let i;for(r=0;r=n.length;return o=!o&&_.isArray(s)?s.length:o,l?(_.hasOwnProp(s,o)?s[o]=[s[o],r]:s[o]=r,!a):((!s[o]||!_.isObject(s[o]))&&(s[o]=[]),t(n,r,s[o],i)&&_.isArray(s[o])&&(s[o]=Uk(s[o])),!a)}if(_.isFormData(e)&&_.isFunction(e.entries)){const n={};return _.forEachEntry(e,(r,s)=>{t(zk(r),s,n,0)}),n}return null}function Bk(e,t,n){if(_.isString(e))try{return(t||JSON.parse)(e),_.trim(e)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(e)}const po={transitional:My,adapter:["xhr","http","fetch"],transformRequest:[function(t,n){const r=n.getContentType()||"",s=r.indexOf("application/json")>-1,i=_.isObject(t);if(i&&_.isHTMLForm(t)&&(t=new FormData(t)),_.isFormData(t))return s?JSON.stringify(Ay(t)):t;if(_.isArrayBuffer(t)||_.isBuffer(t)||_.isStream(t)||_.isFile(t)||_.isBlob(t)||_.isReadableStream(t))return t;if(_.isArrayBufferView(t))return t.buffer;if(_.isURLSearchParams(t))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let a;if(i){if(r.indexOf("application/x-www-form-urlencoded")>-1)return Fk(t,this.formSerializer).toString();if((a=_.isFileList(t))||r.indexOf("multipart/form-data")>-1){const l=this.env&&this.env.FormData;return vl(a?{"files[]":t}:t,l&&new l,this.formSerializer)}}return i||s?(n.setContentType("application/json",!1),Bk(t)):t}],transformResponse:[function(t){const n=this.transitional||po.transitional,r=n&&n.forcedJSONParsing,s=this.responseType==="json";if(_.isResponse(t)||_.isReadableStream(t))return t;if(t&&_.isString(t)&&(r&&!this.responseType||s)){const o=!(n&&n.silentJSONParsing)&&s;try{return JSON.parse(t,this.parseReviver)}catch(a){if(o)throw a.name==="SyntaxError"?re.from(a,re.ERR_BAD_RESPONSE,this,null,this.response):a}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:yt.classes.FormData,Blob:yt.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};_.forEach(["delete","get","head","post","put","patch"],e=>{po.headers[e]={}});const Wk=_.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"]),Hk=e=>{const t={};let n,r,s;return e&&e.split(` `).forEach(function(o){s=o.indexOf(":"),n=o.substring(0,s).trim().toLowerCase(),r=o.substring(s+1).trim(),!(!n||t[n]&&Wk[n])&&(n==="set-cookie"?t[n]?t[n].push(r):t[n]=[r]:t[n]=t[n]?t[n]+", "+r:r)}),t},Hp=Symbol("internals");function si(e){return e&&String(e).trim().toLowerCase()}function sa(e){return e===!1||e==null?e:_.isArray(e)?e.map(sa):String(e)}function Qk(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 Vk=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function sc(e,t,n,r,s){if(_.isFunction(r))return r.call(this,t,n);if(s&&(t=n),!!_.isString(t)){if(_.isString(r))return t.indexOf(r)!==-1;if(_.isRegExp(r))return r.test(t)}}function qk(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,n,r)=>n.toUpperCase()+r)}function Gk(e,t){const n=_.toCamelCase(" "+t);["get","set","has"].forEach(r=>{Object.defineProperty(e,r+n,{value:function(s,i,o){return this[r].call(this,t,s,i,o)},configurable:!0})})}let Ut=class{constructor(t){t&&this.set(t)}set(t,n,r){const s=this;function i(a,l,c){const d=si(l);if(!d)throw new Error("header name must be a non-empty string");const f=_.findKey(s,d);(!f||s[f]===void 0||c===!0||c===void 0&&s[f]!==!1)&&(s[f||l]=sa(a))}const o=(a,l)=>_.forEach(a,(c,d)=>i(c,d,l));if(_.isPlainObject(t)||t instanceof this.constructor)o(t,n);else if(_.isString(t)&&(t=t.trim())&&!Vk(t))o(Hk(t),n);else if(_.isObject(t)&&_.isIterable(t)){let a={},l,c;for(const d of t){if(!_.isArray(d))throw TypeError("Object iterator must return a key-value pair");a[c=d[0]]=(l=a[c])?_.isArray(l)?[...l,d[1]]:[l,d[1]]:d[1]}o(a,n)}else t!=null&&i(n,t,r);return this}get(t,n){if(t=si(t),t){const r=_.findKey(this,t);if(r){const s=this[r];if(!n)return s;if(n===!0)return Qk(s);if(_.isFunction(n))return n.call(this,s,r);if(_.isRegExp(n))return n.exec(s);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,n){if(t=si(t),t){const r=_.findKey(this,t);return!!(r&&this[r]!==void 0&&(!n||sc(this,this[r],r,n)))}return!1}delete(t,n){const r=this;let s=!1;function i(o){if(o=si(o),o){const a=_.findKey(r,o);a&&(!n||sc(r,r[a],a,n))&&(delete r[a],s=!0)}}return _.isArray(t)?t.forEach(i):i(t),s}clear(t){const n=Object.keys(this);let r=n.length,s=!1;for(;r--;){const i=n[r];(!t||sc(this,this[i],i,t,!0))&&(delete this[i],s=!0)}return s}normalize(t){const n=this,r={};return _.forEach(this,(s,i)=>{const o=_.findKey(r,i);if(o){n[o]=sa(s),delete n[i];return}const a=t?qk(i):String(i).trim();a!==i&&delete n[i],n[a]=sa(s),r[a]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){const n=Object.create(null);return _.forEach(this,(r,s)=>{r!=null&&r!==!1&&(n[s]=t&&_.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(s=>r.set(s)),r}static accessor(t){const r=(this[Hp]=this[Hp]={accessors:{}}).accessors,s=this.prototype;function i(o){const a=si(o);r[a]||(Gk(s,o),r[a]=!0)}return _.isArray(t)?t.forEach(i):i(t),this}};Ut.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);_.reduceDescriptors(Ut.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}});_.freezeMethods(Ut);function ic(e,t){const n=this||po,r=t||n,s=Ut.from(r.headers);let i=r.data;return _.forEach(e,function(a){i=a.call(n,i,s.normalize(),t?t.status:void 0)}),s.normalize(),i}function $y(e){return!!(e&&e.__CANCEL__)}function Qs(e,t,n){re.call(this,e??"canceled",re.ERR_CANCELED,t,n),this.name="CanceledError"}_.inherits(Qs,re,{__CANCEL__:!0});function Fy(e,t,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new re("Request failed with status code "+n.status,[re.ERR_BAD_REQUEST,re.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function Yk(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function Kk(e,t){e=e||10;const n=new Array(e),r=new Array(e);let s=0,i=0,o;return t=t!==void 0?t:1e3,function(l){const c=Date.now(),d=r[i];o||(o=c),n[s]=l,r[s]=c;let f=i,p=0;for(;f!==s;)p+=n[f++],f=f%e;if(s=(s+1)%e,s===i&&(i=(i+1)%e),c-o{n=d,s=null,i&&(clearTimeout(i),i=null),e(...c)};return[(...c)=>{const d=Date.now(),f=d-n;f>=r?o(c,d):(s=c,i||(i=setTimeout(()=>{i=null,o(s)},r-f)))},()=>s&&o(s)]}const za=(e,t,n=3)=>{let r=0;const s=Kk(50,250);return Xk(i=>{const o=i.loaded,a=i.lengthComputable?i.total:void 0,l=o-r,c=s(l),d=o<=a;r=o;const f={loaded:o,total:a,progress:a?o/a:void 0,bytes:l,rate:c||void 0,estimated:c&&a&&d?(a-o)/c:void 0,event:i,lengthComputable:a!=null,[t?"download":"upload"]:!0};e(f)},n)},Qp=(e,t)=>{const n=e!=null;return[r=>t[0]({lengthComputable:n,total:e,loaded:r}),t[1]]},Vp=e=>(...t)=>_.asap(()=>e(...t)),Jk=yt.hasStandardBrowserEnv?((e,t)=>n=>(n=new URL(n,yt.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new URL(yt.origin),yt.navigator&&/(msie|trident)/i.test(yt.navigator.userAgent)):()=>!0,Zk=yt.hasStandardBrowserEnv?{write(e,t,n,r,s,i,o){if(typeof document>"u")return;const a=[`${e}=${encodeURIComponent(t)}`];_.isNumber(n)&&a.push(`expires=${new Date(n).toUTCString()}`),_.isString(r)&&a.push(`path=${r}`),_.isString(s)&&a.push(`domain=${s}`),i===!0&&a.push("secure"),_.isString(o)&&a.push(`SameSite=${o}`),document.cookie=a.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 eb(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function tb(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function zy(e,t,n){let r=!eb(t);return e&&(r||n==!1)?tb(e,t):t}const qp=e=>e instanceof Ut?{...e}:e;function Qr(e,t){t=t||{};const n={};function r(c,d,f,p){return _.isPlainObject(c)&&_.isPlainObject(d)?_.merge.call({caseless:p},c,d):_.isPlainObject(d)?_.merge({},d):_.isArray(d)?d.slice():d}function s(c,d,f,p){if(_.isUndefined(d)){if(!_.isUndefined(c))return r(void 0,c,f,p)}else return r(c,d,f,p)}function i(c,d){if(!_.isUndefined(d))return r(void 0,d)}function o(c,d){if(_.isUndefined(d)){if(!_.isUndefined(c))return r(void 0,c)}else return r(void 0,d)}function a(c,d,f){if(f in t)return r(c,d);if(f in e)return r(void 0,c)}const l={url:i,method:i,data:i,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,withXSRFToken:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:a,headers:(c,d,f)=>s(qp(c),qp(d),f,!0)};return _.forEach(Object.keys({...e,...t}),function(d){const f=l[d]||s,p=f(e[d],t[d],d);_.isUndefined(p)&&f!==a||(n[d]=p)}),n}const Uy=e=>{const t=Qr({},e);let{data:n,withXSRFToken:r,xsrfHeaderName:s,xsrfCookieName:i,headers:o,auth:a}=t;if(t.headers=o=Ut.from(o),t.url=Ly(zy(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),a&&o.set("Authorization","Basic "+btoa((a.username||"")+":"+(a.password?unescape(encodeURIComponent(a.password)):""))),_.isFormData(n)){if(yt.hasStandardBrowserEnv||yt.hasStandardBrowserWebWorkerEnv)o.setContentType(void 0);else if(_.isFunction(n.getHeaders)){const l=n.getHeaders(),c=["content-type","content-length"];Object.entries(l).forEach(([d,f])=>{c.includes(d.toLowerCase())&&o.set(d,f)})}}if(yt.hasStandardBrowserEnv&&(r&&_.isFunction(r)&&(r=r(t)),r||r!==!1&&Jk(t.url))){const l=s&&i&&Zk.read(i);l&&o.set(s,l)}return t},nb=typeof XMLHttpRequest<"u",rb=nb&&function(e){return new Promise(function(n,r){const s=Uy(e);let i=s.data;const o=Ut.from(s.headers).normalize();let{responseType:a,onUploadProgress:l,onDownloadProgress:c}=s,d,f,p,v,g;function y(){v&&v(),g&&g(),s.cancelToken&&s.cancelToken.unsubscribe(d),s.signal&&s.signal.removeEventListener("abort",d)}let x=new XMLHttpRequest;x.open(s.method.toUpperCase(),s.url,!0),x.timeout=s.timeout;function m(){if(!x)return;const w=Ut.from("getAllResponseHeaders"in x&&x.getAllResponseHeaders()),T={data:!a||a==="text"||a==="json"?x.responseText:x.response,status:x.status,statusText:x.statusText,headers:w,config:e,request:x};Fy(function(N){n(N),y()},function(N){r(N),y()},T),x=null}"onloadend"in x?x.onloadend=m:x.onreadystatechange=function(){!x||x.readyState!==4||x.status===0&&!(x.responseURL&&x.responseURL.indexOf("file:")===0)||setTimeout(m)},x.onabort=function(){x&&(r(new re("Request aborted",re.ECONNABORTED,e,x)),x=null)},x.onerror=function(C){const T=C&&C.message?C.message:"Network Error",b=new re(T,re.ERR_NETWORK,e,x);b.event=C||null,r(b),x=null},x.ontimeout=function(){let C=s.timeout?"timeout of "+s.timeout+"ms exceeded":"timeout exceeded";const T=s.transitional||My;s.timeoutErrorMessage&&(C=s.timeoutErrorMessage),r(new re(C,T.clarifyTimeoutError?re.ETIMEDOUT:re.ECONNABORTED,e,x)),x=null},i===void 0&&o.setContentType(null),"setRequestHeader"in x&&_.forEach(o.toJSON(),function(C,T){x.setRequestHeader(T,C)}),_.isUndefined(s.withCredentials)||(x.withCredentials=!!s.withCredentials),a&&a!=="json"&&(x.responseType=s.responseType),c&&([p,g]=za(c,!0),x.addEventListener("progress",p)),l&&x.upload&&([f,v]=za(l),x.upload.addEventListener("progress",f),x.upload.addEventListener("loadend",v)),(s.cancelToken||s.signal)&&(d=w=>{x&&(r(!w||w.type?new Qs(null,e,x):w),x.abort(),x=null)},s.cancelToken&&s.cancelToken.subscribe(d),s.signal&&(s.signal.aborted?d():s.signal.addEventListener("abort",d)));const h=Yk(s.url);if(h&&yt.protocols.indexOf(h)===-1){r(new re("Unsupported protocol "+h+":",re.ERR_BAD_REQUEST,e));return}x.send(i||null)})},sb=(e,t)=>{const{length:n}=e=e?e.filter(Boolean):[];if(t||n){let r=new AbortController,s;const i=function(c){if(!s){s=!0,a();const d=c instanceof Error?c:this.reason;r.abort(d instanceof re?d:new Qs(d instanceof Error?d.message:d))}};let o=t&&setTimeout(()=>{o=null,i(new re(`timeout ${t} of ms exceeded`,re.ETIMEDOUT))},t);const a=()=>{e&&(o&&clearTimeout(o),o=null,e.forEach(c=>{c.unsubscribe?c.unsubscribe(i):c.removeEventListener("abort",i)}),e=null)};e.forEach(c=>c.addEventListener("abort",i));const{signal:l}=r;return l.unsubscribe=()=>_.asap(a),l}},ib=function*(e,t){let n=e.byteLength;if(n{const s=ob(e,t);let i=0,o,a=l=>{o||(o=!0,r&&r(l))};return new ReadableStream({async pull(l){try{const{done:c,value:d}=await s.next();if(c){a(),l.close();return}let f=d.byteLength;if(n){let p=i+=f;n(p)}l.enqueue(new Uint8Array(d))}catch(c){throw a(c),c}},cancel(l){return a(l),s.return()}},{highWaterMark:2})},Yp=64*1024,{isFunction:$o}=_,lb=(({Request:e,Response:t})=>({Request:e,Response:t}))(_.global),{ReadableStream:Kp,TextEncoder:Xp}=_.global,Jp=(e,...t)=>{try{return!!e(...t)}catch{return!1}},cb=e=>{e=_.merge.call({skipUndefined:!0},lb,e);const{fetch:t,Request:n,Response:r}=e,s=t?$o(t):typeof fetch=="function",i=$o(n),o=$o(r);if(!s)return!1;const a=s&&$o(Kp),l=s&&(typeof Xp=="function"?(g=>y=>g.encode(y))(new Xp):async g=>new Uint8Array(await new n(g).arrayBuffer())),c=i&&a&&Jp(()=>{let g=!1;const y=new n(yt.origin,{body:new Kp,method:"POST",get duplex(){return g=!0,"half"}}).headers.has("Content-Type");return g&&!y}),d=o&&a&&Jp(()=>_.isReadableStream(new r("").body)),f={stream:d&&(g=>g.body)};s&&["text","arrayBuffer","blob","formData","stream"].forEach(g=>{!f[g]&&(f[g]=(y,x)=>{let m=y&&y[g];if(m)return m.call(y);throw new re(`Response type '${g}' is not supported`,re.ERR_NOT_SUPPORT,x)})});const p=async g=>{if(g==null)return 0;if(_.isBlob(g))return g.size;if(_.isSpecCompliantForm(g))return(await new n(yt.origin,{method:"POST",body:g}).arrayBuffer()).byteLength;if(_.isArrayBufferView(g)||_.isArrayBuffer(g))return g.byteLength;if(_.isURLSearchParams(g)&&(g=g+""),_.isString(g))return(await l(g)).byteLength},v=async(g,y)=>{const x=_.toFiniteNumber(g.getContentLength());return x??p(y)};return async g=>{let{url:y,method:x,data:m,signal:h,cancelToken:w,timeout:C,onDownloadProgress:T,onUploadProgress:b,responseType:N,headers:P,withCredentials:I="same-origin",fetchOptions:O}=Uy(g),Q=t||fetch;N=N?(N+"").toLowerCase():"text";let ue=sb([h,w&&w.toAbortSignal()],C),ne=null;const J=ue&&ue.unsubscribe&&(()=>{ue.unsubscribe()});let $;try{if(b&&c&&x!=="get"&&x!=="head"&&($=await v(P,m))!==0){let E=new n(y,{method:"POST",body:m,duplex:"half"}),z;if(_.isFormData(m)&&(z=E.headers.get("content-type"))&&P.setContentType(z),E.body){const[W,U]=Qp($,za(Vp(b)));m=Gp(E.body,Yp,W,U)}}_.isString(I)||(I=I?"include":"omit");const L=i&&"credentials"in n.prototype,Z={...O,signal:ue,method:x.toUpperCase(),headers:P.normalize().toJSON(),body:m,duplex:"half",credentials:L?I:void 0};ne=i&&new n(y,Z);let F=await(i?Q(ne,O):Q(y,Z));const Y=d&&(N==="stream"||N==="response");if(d&&(T||Y&&J)){const E={};["status","statusText","headers"].forEach(G=>{E[G]=F[G]});const z=_.toFiniteNumber(F.headers.get("content-length")),[W,U]=T&&Qp(z,za(Vp(T),!0))||[];F=new r(Gp(F.body,Yp,W,()=>{U&&U(),J&&J()}),E)}N=N||"text";let V=await f[_.findKey(f,N)||"text"](F,g);return!Y&&J&&J(),await new Promise((E,z)=>{Fy(E,z,{data:V,headers:Ut.from(F.headers),status:F.status,statusText:F.statusText,config:g,request:ne})})}catch(L){throw J&&J(),L&&L.name==="TypeError"&&/Load failed|fetch/i.test(L.message)?Object.assign(new re("Network Error",re.ERR_NETWORK,g,ne),{cause:L.cause||L}):re.from(L,L&&L.code,g,ne)}}},ub=new Map,By=e=>{let t=e&&e.env||{};const{fetch:n,Request:r,Response:s}=t,i=[r,s,n];let o=i.length,a=o,l,c,d=ub;for(;a--;)l=i[a],c=d.get(l),c===void 0&&d.set(l,c=a?new Map:cb(t)),d=c;return c};By();const Bd={http:_k,xhr:rb,fetch:{get:By}};_.forEach(Bd,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const Zp=e=>`- ${e}`,db=e=>_.isFunction(e)||e===null||e===!1;function fb(e,t){e=_.isArray(e)?e:[e];const{length:n}=e;let r,s;const i={};for(let o=0;o`adapter ${l} `+(c===!1?"is not supported by the environment":"is not available in the build"));let a=n?o.length>1?`since : `+o.map(Zp).join(` `):" "+Zp(o[0]):"as no adapter specified";throw new re("There is no suitable adapter to dispatch the request "+a,"ERR_NOT_SUPPORT")}return s}const Wy={getAdapter:fb,adapters:Bd};function oc(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Qs(null,e)}function eh(e){return oc(e),e.headers=Ut.from(e.headers),e.data=ic.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),Wy.getAdapter(e.adapter||po.adapter,e)(e).then(function(r){return oc(e),r.data=ic.call(e,e.transformResponse,r),r.headers=Ut.from(r.headers),r},function(r){return $y(r)||(oc(e),r&&r.response&&(r.response.data=ic.call(e,e.transformResponse,r.response),r.response.headers=Ut.from(r.response.headers))),Promise.reject(r)})}const Hy="1.13.1",wl={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{wl[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const th={};wl.transitional=function(t,n,r){function s(i,o){return"[Axios v"+Hy+"] Transitional option '"+i+"'"+o+(r?". "+r:"")}return(i,o,a)=>{if(t===!1)throw new re(s(o," has been removed"+(n?" in "+n:"")),re.ERR_DEPRECATED);return n&&!th[o]&&(th[o]=!0,console.warn(s(o," has been deprecated since v"+n+" and will be removed in the near future"))),t?t(i,o,a):!0}};wl.spelling=function(t){return(n,r)=>(console.warn(`${r} is likely a misspelling of ${t}`),!0)};function pb(e,t,n){if(typeof e!="object")throw new re("options must be an object",re.ERR_BAD_OPTION_VALUE);const r=Object.keys(e);let s=r.length;for(;s-- >0;){const i=r[s],o=t[i];if(o){const a=e[i],l=a===void 0||o(a,i,e);if(l!==!0)throw new re("option "+i+" must be "+l,re.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new re("Unknown option "+i,re.ERR_BAD_OPTION)}}const ia={assertOptions:pb,validators:wl},En=ia.validators;let Ar=class{constructor(t){this.defaults=t||{},this.interceptors={request:new Wp,response:new Wp}}async request(t,n){try{return await this._request(t,n)}catch(r){if(r instanceof Error){let s={};Error.captureStackTrace?Error.captureStackTrace(s):s=new Error;const i=s.stack?s.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=Qr(this.defaults,n);const{transitional:r,paramsSerializer:s,headers:i}=n;r!==void 0&&ia.assertOptions(r,{silentJSONParsing:En.transitional(En.boolean),forcedJSONParsing:En.transitional(En.boolean),clarifyTimeoutError:En.transitional(En.boolean)},!1),s!=null&&(_.isFunction(s)?n.paramsSerializer={serialize:s}:ia.assertOptions(s,{encode:En.function,serialize:En.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),ia.assertOptions(n,{baseUrl:En.spelling("baseURL"),withXsrfToken:En.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let o=i&&_.merge(i.common,i[n.method]);i&&_.forEach(["delete","get","head","post","put","patch","common"],g=>{delete i[g]}),n.headers=Ut.concat(o,i);const a=[];let l=!0;this.interceptors.request.forEach(function(y){typeof y.runWhen=="function"&&y.runWhen(n)===!1||(l=l&&y.synchronous,a.unshift(y.fulfilled,y.rejected))});const c=[];this.interceptors.response.forEach(function(y){c.push(y.fulfilled,y.rejected)});let d,f=0,p;if(!l){const g=[eh.bind(this),void 0];for(g.unshift(...a),g.push(...c),p=g.length,d=Promise.resolve(n);f{if(!r._listeners)return;let i=r._listeners.length;for(;i-- >0;)r._listeners[i](s);r._listeners=null}),this.promise.then=s=>{let i;const o=new Promise(a=>{r.subscribe(a),i=a}).then(s);return o.cancel=function(){r.unsubscribe(i)},o},t(function(i,o,a){r.reason||(r.reason=new Qs(i,o,a),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 Qy(function(s){t=s}),cancel:t}}};function mb(e){return function(n){return e.apply(null,n)}}function gb(e){return _.isObject(e)&&e.isAxiosError===!0}const xu={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(xu).forEach(([e,t])=>{xu[t]=e});function Vy(e){const t=new Ar(e),n=by(Ar.prototype.request,t);return _.extend(n,Ar.prototype,t,{allOwnKeys:!0}),_.extend(n,t,null,{allOwnKeys:!0}),n.create=function(s){return Vy(Qr(e,s))},n}const Ve=Vy(po);Ve.Axios=Ar;Ve.CanceledError=Qs;Ve.CancelToken=hb;Ve.isCancel=$y;Ve.VERSION=Hy;Ve.toFormData=vl;Ve.AxiosError=re;Ve.Cancel=Ve.CanceledError;Ve.all=function(t){return Promise.all(t)};Ve.spread=mb;Ve.isAxiosError=gb;Ve.mergeConfig=Qr;Ve.AxiosHeaders=Ut;Ve.formToJSON=e=>Ay(_.isHTMLForm(e)?new FormData(e):e);Ve.getAdapter=Wy.getAdapter;Ve.HttpStatusCode=xu;Ve.default=Ve;const{Axios:eT,AxiosError:tT,CanceledError:nT,isCancel:rT,CancelToken:sT,VERSION:iT,all:oT,Cancel:aT,isAxiosError:lT,spread:cT,toFormData:uT,AxiosHeaders:dT,HttpStatusCode:fT,formToJSON:pT,getAdapter:hT,mergeConfig:mT}=Ve,yb="notesDB",vb=1;class wb{constructor(){de(this,"db",null);de(this,"initPromise",null)}async init(){return this.db?this.db:this.initPromise?this.initPromise:(this.initPromise=new Promise((t,n)=>{const r=indexedDB.open(yb,vb);r.onerror=()=>{n(r.error)},r.onsuccess=()=>{this.db=r.result,this.initPromise=null,t(this.db)},r.onupgradeneeded=s=>{const i=s.target.result;if(!i.objectStoreNames.contains("notes")){const o=i.createObjectStore("notes",{keyPath:"id"});o.createIndex("user_id","user_id",{unique:!1}),o.createIndex("created_at","created_at",{unique:!1}),o.createIndex("syncStatus","syncStatus",{unique:!1})}if(!i.objectStoreNames.contains("syncQueue")){const o=i.createObjectStore("syncQueue",{keyPath:"id"});o.createIndex("timestamp","timestamp",{unique:!1}),o.createIndex("noteId","noteId",{unique:!1})}}}),this.initPromise)}async getStore(t,n="readonly"){if(await this.init(),!this.db)throw new Error("Database not initialized");return this.db.transaction([t],n).objectStore(t)}async getAllNotes(){const t=await this.getStore("notes");return new Promise((n,r)=>{const s=t.getAll();s.onsuccess=()=>n(s.result),s.onerror=()=>r(s.error)})}async getNotesByUserId(t){const n=await this.getStore("notes");return new Promise((r,s)=>{const i=n.index("user_id").getAll(t);i.onsuccess=()=>r(i.result),i.onerror=()=>s(i.error)})}async getNote(t){const n=await this.getStore("notes");return new Promise((r,s)=>{const i=n.get(t);i.onsuccess=()=>r(i.result),i.onerror=()=>s(i.error)})}async saveNote(t){const n=await this.getStore("notes","readwrite");return new Promise((r,s)=>{const i=n.put(t);i.onsuccess=()=>r(),i.onerror=()=>s(i.error)})}async saveNotes(t){if(t.length===0)return;if(await this.init(),!this.db)throw new Error("Database not initialized");const r=this.db.transaction(["notes"],"readwrite").objectStore("notes");return new Promise((s,i)=>{let o=0;for(const a of t){const l=r.put(a);l.onerror=()=>i(l.error),l.onsuccess=()=>{o++,o===t.length&&s()}}})}async deleteNote(t){const n=await this.getStore("notes","readwrite");return new Promise((r,s)=>{const i=n.delete(t);i.onsuccess=()=>r(),i.onerror=()=>s(i.error)})}async clearAllNotes(){const t=await this.getStore("notes","readwrite");return new Promise((n,r)=>{const s=t.clear();s.onsuccess=()=>n(),s.onerror=()=>r(s.error)})}async addToSyncQueue(t){const n=await this.getStore("syncQueue","readwrite"),r=`sync-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,s={...t,id:r};return new Promise((i,o)=>{const a=n.add(s);a.onsuccess=()=>i(r),a.onerror=()=>o(a.error)})}async getSyncQueue(){const t=await this.getStore("syncQueue");return new Promise((n,r)=>{const s=t.index("timestamp").getAll();s.onsuccess=()=>n(s.result),s.onerror=()=>r(s.error)})}async getSyncQueueItem(t){const n=await this.getStore("syncQueue");return new Promise((r,s)=>{const i=n.get(t);i.onsuccess=()=>r(i.result),i.onerror=()=>s(i.error)})}async removeFromSyncQueue(t){const n=await this.getStore("syncQueue","readwrite");return new Promise((r,s)=>{const i=n.delete(t);i.onsuccess=()=>r(),i.onerror=()=>s(i.error)})}async updateSyncQueueItem(t,n){const r=await this.getSyncQueueItem(t);if(!r)throw new Error("Sync queue item not found");const s=await this.getStore("syncQueue","readwrite");return new Promise((i,o)=>{const a=s.put({...r,...n});a.onsuccess=()=>i(),a.onerror=()=>o(a.error)})}async clearSyncQueue(){const t=await this.getStore("syncQueue","readwrite");return new Promise((n,r)=>{const s=t.clear();s.onsuccess=()=>n(),s.onerror=()=>r(s.error)})}async clearAll(){await Promise.all([this.clearAllNotes(),this.clearSyncQueue()])}async getPendingSyncCount(){return(await this.getSyncQueue()).length}async isNoteSynced(t){const n=await this.getNote(t);return(n==null?void 0:n.syncStatus)==="synced"}async getDataVersion(){const n=(await this.getAllNotes()).filter(i=>i.is_archived===0);if(n.length===0)return{last_updated_at:null,last_created_at:null,total_notes:0};let r=null,s=null;for(const i of n)i.updated_at&&(!r||i.updated_at>r)&&(r=i.updated_at),i.created_at&&(!s||i.created_at>s)&&(s=i.created_at);return{last_updated_at:r,last_created_at:s,total_notes:n.length}}async getDataVersionByUserId(t){const r=(await this.getNotesByUserId(t)).filter(o=>o.is_archived===0);if(r.length===0)return{last_updated_at:null,last_created_at:null,total_notes:0};let s=null,i=null;for(const o of r)o.updated_at&&(!s||o.updated_at>s)&&(s=o.updated_at),o.created_at&&(!i||o.created_at>i)&&(i=o.created_at);return{last_updated_at:s,last_created_at:i,total_notes:r.length}}}const D=new wb,K=Ve.create({baseURL:"/api",withCredentials:!0,headers:{"Content-Type":"application/json"}});K.interceptors.request.use(e=>{var t;return console.log("API Request:",(t=e.method)==null?void 0:t.toUpperCase(),e.url),e},e=>Promise.reject(e));K.interceptors.response.use(e=>(console.log("API Response:",e.status,e.config.url),e),e=>{var t,n,r,s;if(console.error("API Error:",{url:(t=e.config)==null?void 0:t.url,status:(n=e.response)==null?void 0:n.status,message:e.message,data:(r=e.response)==null?void 0:r.data}),((s=e.response)==null?void 0:s.status)===401){const i=["/login","/register","/notes/archived/all","/user/delete-account"],o=["/auth/status"],a=i.some(c=>{var d,f;return(f=(d=e.config)==null?void 0:d.url)==null?void 0:f.includes(c)}),l=o.some(c=>{var d,f;return(f=(d=e.config)==null?void 0:d.url)==null?void 0:f.includes(c)});!a&&!l&&(D.clearAll().catch(c=>{console.error("Ошибка очистки IndexedDB при 401:",c)}),localStorage.removeItem("isAuthenticated"),window.location.href="/")}return e.response||console.error("Network error - server might be down or proxy not working"),Promise.reject(e)});const Vr={login:async(e,t)=>{const{data:n}=await K.post("/login",{username:e,password:t});return n},register:async(e,t,n)=>{const{data:r}=await K.post("/register",{username:e,password:t,confirmPassword:n});return r},checkStatus:async()=>{const{data:e}=await K.get("/auth/status");return e},logout:async()=>{await K.post("/logout")}},qn=()=>{const e=wt();return{showNotification:S.useCallback((n,r="info")=>{const s=`notification-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;e(_s({message:n,type:r,id:s})),setTimeout(()=>{e(Sy(s))},4e3)},[e])}},Ni=/^[a-z0-9]+(-[a-z0-9]+)*$/,xl=(e,t,n,r="")=>{const s=e.split(":");if(e.slice(0,1)==="@"){if(s.length<2||s.length>3)return null;r=s.shift().slice(1)}if(s.length>3||!s.length)return null;if(s.length>1){const a=s.pop(),l=s.pop(),c={provider:s.length>0?s[0]:r,prefix:l,name:a};return t&&!oa(c)?null:c}const i=s[0],o=i.split("-");if(o.length>1){const a={provider:r,prefix:o.shift(),name:o.join("-")};return t&&!oa(a)?null:a}if(n&&r===""){const a={provider:r,prefix:"",name:i};return t&&!oa(a,n)?null:a}return null},oa=(e,t)=>e?!!((e.provider===""||e.provider.match(Ni))&&(t&&e.prefix===""||e.prefix.match(Ni))&&e.name.match(Ni)):!1,qy=Object.freeze({left:0,top:0,width:16,height:16}),Ua=Object.freeze({rotate:0,vFlip:!1,hFlip:!1}),Wd=Object.freeze({...qy,...Ua}),Su=Object.freeze({...Wd,body:"",hidden:!1});function xb(e,t){const n={};!e.hFlip!=!t.hFlip&&(n.hFlip=!0),!e.vFlip!=!t.vFlip&&(n.vFlip=!0);const r=((e.rotate||0)+(t.rotate||0))%4;return r&&(n.rotate=r),n}function nh(e,t){const n=xb(e,t);for(const r in Su)r in Ua?r in e&&!(r in n)&&(n[r]=Ua[r]):r in t?n[r]=t[r]:r in e&&(n[r]=e[r]);return n}function Sb(e,t){const n=e.icons,r=e.aliases||Object.create(null),s=Object.create(null);function i(o){if(n[o])return s[o]=[];if(!(o in s)){s[o]=null;const a=r[o]&&r[o].parent,l=a&&i(a);l&&(s[o]=[a].concat(l))}return s[o]}return Object.keys(n).concat(Object.keys(r)).forEach(i),s}function kb(e,t,n){const r=e.icons,s=e.aliases||Object.create(null);let i={};function o(a){i=nh(r[a]||s[a],i)}return o(t),n.forEach(o),nh(e,i)}function Gy(e,t){const n=[];if(typeof e!="object"||typeof e.icons!="object")return n;e.not_found instanceof Array&&e.not_found.forEach(s=>{t(s,null),n.push(s)});const r=Sb(e);for(const s in r){const i=r[s];i&&(t(s,kb(e,s,i)),n.push(s))}return n}const bb={provider:"",aliases:{},not_found:{},...qy};function ac(e,t){for(const n in t)if(n in e&&typeof e[n]!=typeof t[n])return!1;return!0}function Yy(e){if(typeof e!="object"||e===null)return null;const t=e;if(typeof t.prefix!="string"||!e.icons||typeof e.icons!="object"||!ac(e,bb))return null;const n=t.icons;for(const s in n){const i=n[s];if(!s.match(Ni)||typeof i.body!="string"||!ac(i,Su))return null}const r=t.aliases||Object.create(null);for(const s in r){const i=r[s],o=i.parent;if(!s.match(Ni)||typeof o!="string"||!n[o]&&!r[o]||!ac(i,Su))return null}return t}const rh=Object.create(null);function Cb(e,t){return{provider:e,prefix:t,icons:Object.create(null),missing:new Set}}function qr(e,t){const n=rh[e]||(rh[e]=Object.create(null));return n[t]||(n[t]=Cb(e,t))}function Hd(e,t){return Yy(t)?Gy(t,(n,r)=>{r?e.icons[n]=r:e.missing.add(n)}):[]}function Eb(e,t,n){try{if(typeof n.body=="string")return e.icons[t]={...n},!0}catch{}return!1}let Ji=!1;function Ky(e){return typeof e=="boolean"&&(Ji=e),Ji}function Nb(e){const t=typeof e=="string"?xl(e,!0,Ji):e;if(t){const n=qr(t.provider,t.prefix),r=t.name;return n.icons[r]||(n.missing.has(r)?null:void 0)}}function _b(e,t){const n=xl(e,!0,Ji);if(!n)return!1;const r=qr(n.provider,n.prefix);return Eb(r,n.name,t)}function Tb(e,t){if(typeof e!="object")return!1;if(typeof t!="string"&&(t=e.provider||""),Ji&&!t&&!e.prefix){let s=!1;return Yy(e)&&(e.prefix="",Gy(e,(i,o)=>{o&&_b(i,o)&&(s=!0)})),s}const n=e.prefix;if(!oa({provider:t,prefix:n,name:"a"}))return!1;const r=qr(t,n);return!!Hd(r,e)}const Xy=Object.freeze({width:null,height:null}),Jy=Object.freeze({...Xy,...Ua}),jb=/(-?[0-9.]*[0-9]+[0-9.]*)/g,Pb=/^-?[0-9.]*[0-9]+[0-9.]*$/g;function sh(e,t,n){if(t===1)return e;if(n=n||100,typeof e=="number")return Math.ceil(e*t*n)/n;if(typeof e!="string")return e;const r=e.split(jb);if(r===null||!r.length)return e;const s=[];let i=r.shift(),o=Pb.test(i);for(;;){if(o){const a=parseFloat(i);isNaN(a)?s.push(i):s.push(Math.ceil(a*t*n)/n)}else s.push(i);if(i=r.shift(),i===void 0)return s.join("");o=!o}}const Ib=e=>e==="unset"||e==="undefined"||e==="none";function Rb(e,t){const n={...Wd,...e},r={...Jy,...t},s={left:n.left,top:n.top,width:n.width,height:n.height};let i=n.body;[n,r].forEach(g=>{const y=[],x=g.hFlip,m=g.vFlip;let h=g.rotate;x?m?h+=2:(y.push("translate("+(s.width+s.left).toString()+" "+(0-s.top).toString()+")"),y.push("scale(-1 1)"),s.top=s.left=0):m&&(y.push("translate("+(0-s.left).toString()+" "+(s.height+s.top).toString()+")"),y.push("scale(1 -1)"),s.top=s.left=0);let w;switch(h<0&&(h-=Math.floor(h/4)*4),h=h%4,h){case 1:w=s.height/2+s.top,y.unshift("rotate(90 "+w.toString()+" "+w.toString()+")");break;case 2:y.unshift("rotate(180 "+(s.width/2+s.left).toString()+" "+(s.height/2+s.top).toString()+")");break;case 3:w=s.width/2+s.left,y.unshift("rotate(-90 "+w.toString()+" "+w.toString()+")");break}h%2===1&&(s.left!==s.top&&(w=s.left,s.left=s.top,s.top=w),s.width!==s.height&&(w=s.width,s.width=s.height,s.height=w)),y.length&&(i=''+i+"")});const o=r.width,a=r.height,l=s.width,c=s.height;let d,f;o===null?(f=a===null?"1em":a==="auto"?c:a,d=sh(f,l/c)):(d=o==="auto"?l:o,f=a===null?sh(d,c/l):a==="auto"?c:a);const p={},v=(g,y)=>{Ib(y)||(p[g]=y.toString())};return v("width",d),v("height",f),p.viewBox=s.left.toString()+" "+s.top.toString()+" "+l.toString()+" "+c.toString(),{attributes:p,body:i}}const Ob=/\sid="(\S+)"/g,Db="IconifyId"+Date.now().toString(16)+(Math.random()*16777216|0).toString(16);let Lb=0;function Mb(e,t=Db){const n=[];let r;for(;r=Ob.exec(e);)n.push(r[1]);if(!n.length)return e;const s="suffix"+(Math.random()*16777216|Date.now()).toString(16);return n.forEach(i=>{const o=typeof t=="function"?t(i):t+(Lb++).toString(),a=i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");e=e.replace(new RegExp('([#;"])('+a+')([")]|\\.[a-z])',"g"),"$1"+o+s+"$3")}),e=e.replace(new RegExp(s,"g"),""),e}const ku=Object.create(null);function Ab(e,t){ku[e]=t}function bu(e){return ku[e]||ku[""]}function Qd(e){let t;if(typeof e.resources=="string")t=[e.resources];else if(t=e.resources,!(t instanceof Array)||!t.length)return null;return{resources:t,path:e.path||"/",maxURL:e.maxURL||500,rotate:e.rotate||750,timeout:e.timeout||5e3,random:e.random===!0,index:e.index||0,dataAfterTimeout:e.dataAfterTimeout!==!1}}const Vd=Object.create(null),ii=["https://api.simplesvg.com","https://api.unisvg.com"],aa=[];for(;ii.length>0;)ii.length===1||Math.random()>.5?aa.push(ii.shift()):aa.push(ii.pop());Vd[""]=Qd({resources:["https://api.iconify.design"].concat(aa)});function $b(e,t){const n=Qd(t);return n===null?!1:(Vd[e]=n,!0)}function qd(e){return Vd[e]}const Fb=()=>{let e;try{if(e=fetch,typeof e=="function")return e}catch{}};let ih=Fb();function zb(e,t){const n=qd(e);if(!n)return 0;let r;if(!n.maxURL)r=0;else{let s=0;n.resources.forEach(o=>{s=Math.max(s,o.length)});const i=t+".json?icons=";r=n.maxURL-s-n.path.length-i.length}return r}function Ub(e){return e===404}const Bb=(e,t,n)=>{const r=[],s=zb(e,t),i="icons";let o={type:i,provider:e,prefix:t,icons:[]},a=0;return n.forEach((l,c)=>{a+=l.length+1,a>=s&&c>0&&(r.push(o),o={type:i,provider:e,prefix:t,icons:[]},a=l.length),o.icons.push(l)}),r.push(o),r};function Wb(e){if(typeof e=="string"){const t=qd(e);if(t)return t.path}return"/"}const Hb=(e,t,n)=>{if(!ih){n("abort",424);return}let r=Wb(t.provider);switch(t.type){case"icons":{const i=t.prefix,a=t.icons.join(","),l=new URLSearchParams({icons:a});r+=i+".json?"+l.toString();break}case"custom":{const i=t.uri;r+=i.slice(0,1)==="/"?i.slice(1):i;break}default:n("abort",400);return}let s=503;ih(e+r).then(i=>{const o=i.status;if(o!==200){setTimeout(()=>{n(Ub(o)?"abort":"next",o)});return}return s=501,i.json()}).then(i=>{if(typeof i!="object"||i===null){setTimeout(()=>{i===404?n("abort",i):n("next",s)});return}setTimeout(()=>{n("success",i)})}).catch(()=>{n("next",s)})},Qb={prepare:Bb,send:Hb};function Vb(e){const t={loaded:[],missing:[],pending:[]},n=Object.create(null);e.sort((s,i)=>s.provider!==i.provider?s.provider.localeCompare(i.provider):s.prefix!==i.prefix?s.prefix.localeCompare(i.prefix):s.name.localeCompare(i.name));let r={provider:"",prefix:"",name:""};return e.forEach(s=>{if(r.name===s.name&&r.prefix===s.prefix&&r.provider===s.provider)return;r=s;const i=s.provider,o=s.prefix,a=s.name,l=n[i]||(n[i]=Object.create(null)),c=l[o]||(l[o]=qr(i,o));let d;a in c.icons?d=t.loaded:o===""||c.missing.has(a)?d=t.missing:d=t.pending;const f={provider:i,prefix:o,name:a};d.push(f)}),t}function Zy(e,t){e.forEach(n=>{const r=n.loaderCallbacks;r&&(n.loaderCallbacks=r.filter(s=>s.id!==t))})}function qb(e){e.pendingCallbacksFlag||(e.pendingCallbacksFlag=!0,setTimeout(()=>{e.pendingCallbacksFlag=!1;const t=e.loaderCallbacks?e.loaderCallbacks.slice(0):[];if(!t.length)return;let n=!1;const r=e.provider,s=e.prefix;t.forEach(i=>{const o=i.icons,a=o.pending.length;o.pending=o.pending.filter(l=>{if(l.prefix!==s)return!0;const c=l.name;if(e.icons[c])o.loaded.push({provider:r,prefix:s,name:c});else if(e.missing.has(c))o.missing.push({provider:r,prefix:s,name:c});else return n=!0,!0;return!1}),o.pending.length!==a&&(n||Zy([e],i.id),i.callback(o.loaded.slice(0),o.missing.slice(0),o.pending.slice(0),i.abort))})}))}let Gb=0;function Yb(e,t,n){const r=Gb++,s=Zy.bind(null,n,r);if(!t.pending.length)return s;const i={id:r,icons:t,callback:e,abort:s};return n.forEach(o=>{(o.loaderCallbacks||(o.loaderCallbacks=[])).push(i)}),s}function Kb(e,t=!0,n=!1){const r=[];return e.forEach(s=>{const i=typeof s=="string"?xl(s,t,n):s;i&&r.push(i)}),r}var Xb={resources:[],index:0,timeout:2e3,rotate:750,random:!1,dataAfterTimeout:!1};function Jb(e,t,n,r){const s=e.resources.length,i=e.random?Math.floor(Math.random()*s):e.index;let o;if(e.random){let b=e.resources.slice(0);for(o=[];b.length>1;){const N=Math.floor(Math.random()*b.length);o.push(b[N]),b=b.slice(0,N).concat(b.slice(N+1))}o=o.concat(b)}else o=e.resources.slice(i).concat(e.resources.slice(0,i));const a=Date.now();let l="pending",c=0,d,f=null,p=[],v=[];typeof r=="function"&&v.push(r);function g(){f&&(clearTimeout(f),f=null)}function y(){l==="pending"&&(l="aborted"),g(),p.forEach(b=>{b.status==="pending"&&(b.status="aborted")}),p=[]}function x(b,N){N&&(v=[]),typeof b=="function"&&v.push(b)}function m(){return{startTime:a,payload:t,status:l,queriesSent:c,queriesPending:p.length,subscribe:x,abort:y}}function h(){l="failed",v.forEach(b=>{b(void 0,d)})}function w(){p.forEach(b=>{b.status==="pending"&&(b.status="aborted")}),p=[]}function C(b,N,P){const I=N!=="success";switch(p=p.filter(O=>O!==b),l){case"pending":break;case"failed":if(I||!e.dataAfterTimeout)return;break;default:return}if(N==="abort"){d=P,h();return}if(I){d=P,p.length||(o.length?T():h());return}if(g(),w(),!e.random){const O=e.resources.indexOf(b.resource);O!==-1&&O!==e.index&&(e.index=O)}l="completed",v.forEach(O=>{O(P)})}function T(){if(l!=="pending")return;g();const b=o.shift();if(b===void 0){if(p.length){f=setTimeout(()=>{g(),l==="pending"&&(w(),h())},e.timeout);return}h();return}const N={status:"pending",resource:b,callback:(P,I)=>{C(N,P,I)}};p.push(N),c++,f=setTimeout(T,e.rotate),n(b,t,N.callback)}return setTimeout(T),m}function ev(e){const t={...Xb,...e};let n=[];function r(){n=n.filter(a=>a().status==="pending")}function s(a,l,c){const d=Jb(t,a,l,(f,p)=>{r(),c&&c(f,p)});return n.push(d),d}function i(a){return n.find(l=>a(l))||null}return{query:s,find:i,setIndex:a=>{t.index=a},getIndex:()=>t.index,cleanup:r}}function oh(){}const lc=Object.create(null);function Zb(e){if(!lc[e]){const t=qd(e);if(!t)return;const n=ev(t),r={config:t,redundancy:n};lc[e]=r}return lc[e]}function eC(e,t,n){let r,s;if(typeof e=="string"){const i=bu(e);if(!i)return n(void 0,424),oh;s=i.send;const o=Zb(e);o&&(r=o.redundancy)}else{const i=Qd(e);if(i){r=ev(i);const o=e.resources?e.resources[0]:"",a=bu(o);a&&(s=a.send)}}return!r||!s?(n(void 0,424),oh):r.query(t,s,n)().abort}const ah="iconify2",Zi="iconify",tv=Zi+"-count",lh=Zi+"-version",nv=36e5,tC=168;function Cu(e,t){try{return e.getItem(t)}catch{}}function Gd(e,t,n){try{return e.setItem(t,n),!0}catch{}}function ch(e,t){try{e.removeItem(t)}catch{}}function Eu(e,t){return Gd(e,tv,t.toString())}function Nu(e){return parseInt(Cu(e,tv))||0}const Sl={local:!0,session:!0},rv={local:new Set,session:new Set};let Yd=!1;function nC(e){Yd=e}let Fo=typeof window>"u"?{}:window;function sv(e){const t=e+"Storage";try{if(Fo&&Fo[t]&&typeof Fo[t].length=="number")return Fo[t]}catch{}Sl[e]=!1}function iv(e,t){const n=sv(e);if(!n)return;const r=Cu(n,lh);if(r!==ah){if(r){const a=Nu(n);for(let l=0;l{const l=Zi+a.toString(),c=Cu(n,l);if(typeof c=="string"){try{const d=JSON.parse(c);if(typeof d=="object"&&typeof d.cached=="number"&&d.cached>s&&typeof d.provider=="string"&&typeof d.data=="object"&&typeof d.data.prefix=="string"&&t(d,a))return!0}catch{}ch(n,l)}};let o=Nu(n);for(let a=o-1;a>=0;a--)i(a)||(a===o-1?(o--,Eu(n,o)):rv[e].add(a))}function ov(){if(!Yd){nC(!0);for(const e in Sl)iv(e,t=>{const n=t.data,r=t.provider,s=n.prefix,i=qr(r,s);if(!Hd(i,n).length)return!1;const o=n.lastModified||-1;return i.lastModifiedCached=i.lastModifiedCached?Math.min(i.lastModifiedCached,o):o,!0})}}function rC(e,t){const n=e.lastModifiedCached;if(n&&n>=t)return n===t;if(e.lastModifiedCached=t,n)for(const r in Sl)iv(r,s=>{const i=s.data;return s.provider!==e.provider||i.prefix!==e.prefix||i.lastModified===t});return!0}function sC(e,t){Yd||ov();function n(r){let s;if(!Sl[r]||!(s=sv(r)))return;const i=rv[r];let o;if(i.size)i.delete(o=Array.from(i).shift());else if(o=Nu(s),!Eu(s,o+1))return;const a={cached:Math.floor(Date.now()/nv),provider:e.provider,data:t};return Gd(s,Zi+o.toString(),JSON.stringify(a))}t.lastModified&&!rC(e,t.lastModified)||Object.keys(t.icons).length&&(t.not_found&&(t=Object.assign({},t),delete t.not_found),n("local")||n("session"))}function uh(){}function iC(e){e.iconsLoaderFlag||(e.iconsLoaderFlag=!0,setTimeout(()=>{e.iconsLoaderFlag=!1,qb(e)}))}function oC(e,t){e.iconsToLoad?e.iconsToLoad=e.iconsToLoad.concat(t).sort():e.iconsToLoad=t,e.iconsQueueFlag||(e.iconsQueueFlag=!0,setTimeout(()=>{e.iconsQueueFlag=!1;const{provider:n,prefix:r}=e,s=e.iconsToLoad;delete e.iconsToLoad;let i;if(!s||!(i=bu(n)))return;i.prepare(n,r,s).forEach(a=>{eC(n,a,l=>{if(typeof l!="object")a.icons.forEach(c=>{e.missing.add(c)});else try{const c=Hd(e,l);if(!c.length)return;const d=e.pendingIcons;d&&c.forEach(f=>{d.delete(f)}),sC(e,l)}catch(c){console.error(c)}iC(e)})})}))}const aC=(e,t)=>{const n=Kb(e,!0,Ky()),r=Vb(n);if(!r.pending.length){let l=!0;return t&&setTimeout(()=>{l&&t(r.loaded,r.missing,r.pending,uh)}),()=>{l=!1}}const s=Object.create(null),i=[];let o,a;return r.pending.forEach(l=>{const{provider:c,prefix:d}=l;if(d===a&&c===o)return;o=c,a=d,i.push(qr(c,d));const f=s[c]||(s[c]=Object.create(null));f[d]||(f[d]=[])}),r.pending.forEach(l=>{const{provider:c,prefix:d,name:f}=l,p=qr(c,d),v=p.pendingIcons||(p.pendingIcons=new Set);v.has(f)||(v.add(f),s[c][d].push(f))}),i.forEach(l=>{const{provider:c,prefix:d}=l;s[c][d].length&&oC(l,s[c][d])}),t?Yb(t,r,i):uh};function lC(e,t){const n={...e};for(const r in t){const s=t[r],i=typeof s;r in Xy?(s===null||s&&(i==="string"||i==="number"))&&(n[r]=s):i===typeof n[r]&&(n[r]=r==="rotate"?s%4:s)}return n}const cC=/[\s,]+/;function uC(e,t){t.split(cC).forEach(n=>{switch(n.trim()){case"horizontal":e.hFlip=!0;break;case"vertical":e.vFlip=!0;break}})}function dC(e,t=0){const n=e.replace(/^-?[0-9.]*/,"");function r(s){for(;s<0;)s+=4;return s%4}if(n===""){const s=parseInt(e);return isNaN(s)?0:r(s)}else if(n!==e){let s=0;switch(n){case"%":s=25;break;case"deg":s=90}if(s){let i=parseFloat(e.slice(0,e.length-n.length));return isNaN(i)?0:(i=i/s,i%1===0?r(i):0)}}return t}function fC(e,t){let n=e.indexOf("xlink:")===-1?"":' xmlns:xlink="http://www.w3.org/1999/xlink"';for(const r in t)n+=" "+r+'="'+t[r]+'"';return'"+e+""}function pC(e){return e.replace(/"/g,"'").replace(/%/g,"%25").replace(/#/g,"%23").replace(//g,"%3E").replace(/\s+/g," ")}function hC(e){return"data:image/svg+xml,"+pC(e)}function mC(e){return'url("'+hC(e)+'")'}let _i;function gC(){try{_i=window.trustedTypes.createPolicy("iconify",{createHTML:e=>e})}catch{_i=null}}function yC(e){return _i===void 0&&gC(),_i?_i.createHTML(e):e}const av={...Jy,inline:!1},vC={xmlns:"http://www.w3.org/2000/svg",xmlnsXlink:"http://www.w3.org/1999/xlink","aria-hidden":!0,role:"img"},wC={display:"inline-block"},_u={backgroundColor:"currentColor"},lv={backgroundColor:"transparent"},dh={Image:"var(--svg)",Repeat:"no-repeat",Size:"100% 100%"},fh={WebkitMask:_u,mask:_u,background:lv};for(const e in fh){const t=fh[e];for(const n in dh)t[e+n]=dh[n]}const xC={...av,inline:!0};function ph(e){return e+(e.match(/^[-0-9.]+$/)?"px":"")}const SC=(e,t,n,r)=>{const s=n?xC:av,i=lC(s,t),o=t.mode||"svg",a={},l=t.style||{},c={...o==="svg"?vC:{},ref:r};for(let m in t){const h=t[m];if(h!==void 0)switch(m){case"icon":case"style":case"children":case"onLoad":case"mode":case"_ref":case"_inline":break;case"inline":case"hFlip":case"vFlip":i[m]=h===!0||h==="true"||h===1;break;case"flip":typeof h=="string"&&uC(i,h);break;case"color":a.color=h;break;case"rotate":typeof h=="string"?i[m]=dC(h):typeof h=="number"&&(i[m]=h);break;case"ariaHidden":case"aria-hidden":h!==!0&&h!=="true"&&delete c["aria-hidden"];break;default:s[m]===void 0&&(c[m]=h)}}const d=Rb(e,i),f=d.attributes;if(i.inline&&(a.verticalAlign="-0.125em"),o==="svg"){c.style={...a,...l},Object.assign(c,f);let m=0,h=t.id;return typeof h=="string"&&(h=h.replace(/-/g,"_")),c.dangerouslySetInnerHTML={__html:yC(Mb(d.body,h?()=>h+"ID"+m++:"iconifyReact"))},xn.createElement("svg",c)}const{body:p,width:v,height:g}=e,y=o==="mask"||(o==="bg"?!1:p.indexOf("currentColor")!==-1),x=fC(p,{...f,width:v+"",height:g+""});return c.style={...a,"--svg":mC(x),width:ph(f.width),height:ph(f.height),...wC,...y?_u:lv,...l},xn.createElement("span",c)};Ky(!0);Ab("",Qb);if(typeof document<"u"&&typeof window<"u"){ov();const e=window;if(e.IconifyPreload!==void 0){const t=e.IconifyPreload,n="Invalid IconifyPreload syntax.";typeof t=="object"&&t!==null&&(t instanceof Array?t:[t]).forEach(r=>{try{(typeof r!="object"||r===null||r instanceof Array||typeof r.icons!="object"||typeof r.prefix!="string"||!Tb(r))&&console.error(n)}catch{console.error(n)}})}if(e.IconifyProviders!==void 0){const t=e.IconifyProviders;if(typeof t=="object"&&t!==null)for(let n in t){const r="IconifyProviders["+n+"] is invalid.";try{const s=t[n];if(typeof s!="object"||!s||s.resources===void 0)continue;$b(n,s)||console.error(r)}catch{console.error(r)}}}}class cv extends xn.Component{constructor(t){super(t),this.state={icon:null}}_abortLoading(){this._loading&&(this._loading.abort(),this._loading=null)}_setData(t){this.state.icon!==t&&this.setState({icon:t})}_checkIcon(t){const n=this.state,r=this.props.icon;if(typeof r=="object"&&r!==null&&typeof r.body=="string"){this._icon="",this._abortLoading(),(t||n.icon===null)&&this._setData({data:r});return}let s;if(typeof r!="string"||(s=xl(r,!1,!0))===null){this._abortLoading(),this._setData(null);return}const i=Nb(s);if(!i){(!this._loading||this._loading.name!==r)&&(this._abortLoading(),this._icon="",this._setData(null),i!==null&&(this._loading={name:r,abort:aC([s],this._checkIcon.bind(this,!1))}));return}if(this._icon!==r||n.icon===null){this._abortLoading(),this._icon=r;const o=["iconify"];s.prefix!==""&&o.push("iconify--"+s.prefix),s.provider!==""&&o.push("iconify--"+s.provider),this._setData({data:i,classes:o}),this.props.onLoad&&this.props.onLoad(r)}}componentDidMount(){this._checkIcon(!1)}componentDidUpdate(t){t.icon!==this.props.icon&&this._checkIcon(!0)}componentWillUnmount(){this._abortLoading()}render(){const t=this.props,n=this.state.icon;if(n===null)return t.children?t.children:xn.createElement("span",{});let r=t;return n.classes&&(r={...t,className:(typeof t.className=="string"?t.className+" ":"")+n.classes.join(" ")}),SC({...Wd,...n.data},r,t._inline,t._ref)}}const M=xn.forwardRef(function(t,n){const r={...t,_ref:n,_inline:!1};return xn.createElement(cv,r)});xn.forwardRef(function(t,n){const r={...t,_ref:n,_inline:!0};return xn.createElement(cv,r)});const kC=e=>{const t=e.replace("#",""),n=parseInt(t.substring(0,2),16),r=parseInt(t.substring(2,4),16),s=parseInt(t.substring(4,6),16);return`${n}, ${r}, ${s}`},eo=e=>{document.documentElement.style.setProperty("--accent-color",e);const t=kC(e);document.documentElement.style.setProperty("--accent-color-rgb",t)},Kd=()=>{const e=oe(r=>r.ui.theme),t=oe(r=>r.ui.accentColor),n=wt();return S.useEffect(()=>{document.documentElement.setAttribute("data-theme",e),eo(t);const r=document.querySelector('meta[name="theme-color"]');r&&r.setAttribute("content",e==="dark"?"#1a1a1a":t)},[e,t]),S.useEffect(()=>{const r=window.matchMedia("(prefers-color-scheme: dark)"),s=i=>{localStorage.getItem("theme")||n(A1(i.matches?"dark":"light"))};return r.addEventListener("change",s),()=>r.removeEventListener("change",s)},[n]),{theme:e,accentColor:t,toggleTheme:()=>n(M1())}},ho=()=>{const{theme:e,toggleTheme:t}=Kd();return u.jsx("button",{id:"theme-toggle-btn",className:"theme-toggle-btn",onClick:t,title:"Переключить тему",children:u.jsx(M,{icon:e==="dark"?"mdi:weather-sunny":"mdi:weather-night"})})},bC=()=>{const[e,t]=S.useState(""),[n,r]=S.useState(""),[s,i]=S.useState(!1),o=kr(),a=wt(),{showNotification:l}=qn(),c=oe(v=>v.auth.isAuthenticated),d=oe(v=>v.auth.userId),[f]=vS();S.useEffect(()=>{c&&o("/notes")},[c,o]),S.useEffect(()=>{f.get("error")==="invalid_password"&&l("Неверный пароль!","error")},[f,l]);const p=async v=>{var g;if(v.preventDefault(),!e.trim()||!n){l("Логин и пароль обязательны","error");return}i(!0);try{console.log("Attempting login...");const y=await Vr.login(e,n);if(console.log("Login response:",y),y.success){const x=await Vr.checkStatus(),m=x.userId;d&&d!==m&&(console.log(`[Login] User changed from ${d} to ${m}, clearing IndexedDB`),await D.clearAll()),a(Ld({userId:m,username:x.username})),l("Успешный вход!","success"),o("/notes")}else l(y.error||"Ошибка входа","error")}catch(y){console.error("Login error details:",y),console.error("Error response:",y.response),console.error("Error message:",y.message);let x="Ошибка соединения с сервером";y.response?x=((g=y.response.data)==null?void 0:g.error)||`Ошибка ${y.response.status}`:y.request?x="Сервер не отвечает. Проверьте, запущен ли backend на порту 3000":x=y.message||"Ошибка соединения с сервером",l(x,"error")}finally{i(!1)}};return u.jsxs("div",{className:"container",children:[u.jsx("header",{children:u.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[u.jsxs("span",{children:[u.jsx(M,{icon:"mdi:login"})," Вход в систему"]}),u.jsx(ho,{})]})}),u.jsxs("div",{className:"login-form",children:[u.jsxs("form",{id:"loginForm",onSubmit:p,children:[u.jsxs("div",{className:"form-group",children:[u.jsx("label",{htmlFor:"username",children:"Логин:"}),u.jsx("input",{type:"text",id:"username",name:"username",value:e,onChange:v=>t(v.target.value),required:!0,placeholder:"Введите ваш логин"})]}),u.jsxs("div",{className:"form-group",children:[u.jsx("label",{htmlFor:"password",children:"Пароль:"}),u.jsx("input",{type:"password",id:"password",name:"password",value:n,onChange:v=>r(v.target.value),required:!0,placeholder:"Введите пароль"})]}),u.jsx("button",{type:"submit",className:"btnSave",disabled:s,children:s?"Вход...":"Войти"})]}),u.jsxs("p",{className:"auth-link",children:["Нет аккаунта? ",u.jsx(ny,{to:"/register",children:"Зарегистрируйтесь"})]})]})]})},CC=()=>{const[e,t]=S.useState(""),[n,r]=S.useState(""),[s,i]=S.useState(""),[o,a]=S.useState(!1),l=kr(),c=wt(),{showNotification:d}=qn(),f=oe(v=>v.auth.isAuthenticated);S.useEffect(()=>{f&&l("/notes")},[f,l]);const p=async v=>{var g;if(v.preventDefault(),!e.trim()||!n||!s){d("Все поля обязательны","error");return}if(e.length<3){d("Логин должен быть не менее 3 символов","error");return}if(n.length<6){d("Пароль должен быть не менее 6 символов","error");return}if(n!==s){d("Пароли не совпадают","error");return}a(!0);try{console.log("Attempting registration...");const y=await Vr.register(e,n,s);if(console.log("Register response:",y),y.success){const x=await Vr.checkStatus(),m=x.userId;await D.clearAll(),c(Ld({userId:m,username:x.username})),d("Регистрация успешна!","success"),l("/notes")}else d(y.error||"Ошибка регистрации","error")}catch(y){console.error("Register error details:",y),console.error("Error response:",y.response),console.error("Error message:",y.message);let x="Ошибка соединения с сервером";y.response?x=((g=y.response.data)==null?void 0:g.error)||`Ошибка ${y.response.status}`:y.request?x="Сервер не отвечает. Проверьте, запущен ли backend на порту 3000":x=y.message||"Ошибка соединения с сервером",d(x,"error")}finally{a(!1)}};return u.jsxs("div",{className:"container",children:[u.jsx("header",{children:u.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[u.jsxs("span",{children:[u.jsx(M,{icon:"mdi:account-plus"})," Регистрация"]}),u.jsx(ho,{})]})}),u.jsxs("div",{className:"login-form",children:[u.jsxs("form",{id:"registerForm",onSubmit:p,children:[u.jsxs("div",{className:"form-group",children:[u.jsx("label",{htmlFor:"username",children:"Логин:"}),u.jsx("input",{type:"text",id:"username",name:"username",value:e,onChange:v=>t(v.target.value),required:!0,placeholder:"Введите ваш логин (мин. 3 символа)"})]}),u.jsxs("div",{className:"form-group",children:[u.jsx("label",{htmlFor:"password",children:"Пароль:"}),u.jsx("input",{type:"password",id:"password",name:"password",value:n,onChange:v=>r(v.target.value),required:!0,placeholder:"Введите пароль (мин. 6 символов)"})]}),u.jsxs("div",{className:"form-group",children:[u.jsx("label",{htmlFor:"confirmPassword",children:"Подтвердите пароль:"}),u.jsx("input",{type:"password",id:"confirmPassword",name:"confirmPassword",value:s,onChange:v=>i(v.target.value),required:!0,placeholder:"Подтвердите пароль"})]}),u.jsx("button",{type:"submit",className:"btnSave",disabled:o,children:o?"Регистрация...":"Зарегистрироваться"})]}),u.jsxs("p",{className:"auth-link",children:["Уже есть аккаунт? ",u.jsx(ny,{to:"/",children:"Войдите"})]})]})]})},Et={getProfile:async()=>{const{data:e}=await K.get("/user");return e},updateProfile:async e=>{const{data:t}=await K.put("/user/profile",e);return t},uploadAvatar:async e=>{const t=new FormData;t.append("avatar",e);const{data:n}=await K.post("/user/avatar",t,{headers:{"Content-Type":"multipart/form-data"}});return n},deleteAvatar:async()=>{await K.delete("/user/avatar")},deleteAccount:async e=>{const{data:t}=await K.delete("/user/delete-account",{data:{password:e}});return t},getAiSettings:async()=>{const{data:e}=await K.get("/user/ai-settings");return e},updateAiSettings:async e=>{const{data:t}=await K.put("/user/ai-settings",e);return t}};function zo(){return`temp-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}function Er(e){return typeof e=="string"&&e.startsWith("temp-")}async function Tu(){var e,t,n,r;if(!navigator.onLine)return!1;try{const s=new AbortController,i=setTimeout(()=>s.abort(),2e3),o=await fetch("/api/auth/status",{method:"GET",signal:s.signal,cache:"no-cache",credentials:"include"});return clearTimeout(i),o.ok}catch(s){const i=s.name==="AbortError";return(s.message==="Failed to fetch"||((e=s.message)==null?void 0:e.includes("NetworkError"))||((t=s.message)==null?void 0:t.includes("ERR_INTERNET_DISCONNECTED"))||((n=s.message)==null?void 0:n.includes("ERR_NETWORK"))||((r=s.message)==null?void 0:r.includes("network request failed")))&&!i?!1:i?(navigator.onLine,!1):navigator.onLine}}function hh(e){return new Promise((t,n)=>{const r=new FileReader;r.onload=()=>{typeof r.result=="string"?t(r.result):n(new Error("Failed to convert file to base64"))},r.onerror=n,r.readAsDataURL(e)})}function mh(e,t){const n=atob(e.split(",")[1]||e),r=new Array(n.length);for(let i=0;ia.timestamp-l.timestamp);for(const a of o){try{let l=a.noteId;i.has(a.noteId)&&(l=i.get(a.noteId),console.log(`[SyncService] Mapped temp ID ${a.noteId} to server ID ${l}`));const c={...a,noteId:l};await this.processSyncItem(c,i),await D.removeFromSyncQueue(a.id),r++,await this.updatePendingCount()}catch(l){console.error("[SyncService] Error processing item:",a,l),s++;const c={...a,retries:a.retries+1,lastError:l instanceof Error?l.message:"Unknown error"};if(c.retriessetTimeout(l,100))}if(console.log(`[SyncService] Sync complete. Success: ${r}, Errors: ${s}`),r>0){try{console.log("[SyncService] Performing full data sync...");const{data:a}=await K.get("/notes"),l=a.map(p=>({...p,syncStatus:"synced"})),c=te.getState().auth.userId,d=c?await D.getNotesByUserId(c):await D.getAllNotes(),f=new Set(l.map(p=>p.id));for(const p of d)typeof p.id=="string"&&p.id.startsWith("temp-")||f.has(p.id)||(console.log(`[SyncService] Removing deleted note from IndexedDB: ${p.id}`),await D.deleteNote(p.id));await D.saveNotes(l),console.log("[SyncService] Full data sync completed")}catch(a){console.error("[SyncService] Error during full data sync:",a)}te.dispatch(_s({message:`Синхронизировано заметок: ${r}`,type:"success"}))}s>0&&s===o.length?te.dispatch(ss("error")):te.dispatch(ss("idle")),await this.updatePendingCount(),this.notifyListeners()}catch(n){console.error("[SyncService] Fatal sync error:",n),te.dispatch(ss("error")),te.dispatch(_s({message:"Ошибка синхронизации",type:"error"}))}finally{this.isSyncing=!1}}async processSyncItem(t,n){switch(console.log(`[SyncService] Processing ${t.type} for note ${t.noteId}`),t.type){case"create":await this.syncCreate(t,n);break;case"update":await this.syncUpdate(t,n);break;case"delete":await this.syncDelete(t);break;case"uploadImage":await this.syncUploadImage(t);break;case"uploadFile":await this.syncUploadFile(t);break;default:console.warn(`[SyncService] Unknown sync type: ${t.type}`)}}async syncCreate(t,n){const r=await D.getNote(t.noteId);if(!r)throw new Error("Note not found in local database");const{data:s}=await K.post("/notes",{content:r.content,date:r.date,time:r.time});n&&typeof t.noteId=="string"&&n.set(t.noteId,s.id);const i={...s,images:await this.updateImageReferences(r,s),files:await this.updateFileReferences(r,s),syncStatus:"synced"};await D.deleteNote(t.noteId),await D.saveNote(i),te.dispatch(Be(i)),await this.syncAttachments(r,s.id)}async syncUpdate(t,n){if(typeof t.noteId=="string"&&t.noteId.startsWith("temp-")&&!(n!=null&&n.has(t.noteId))){await this.syncCreate(t,n);return}const r=await D.getNote(t.noteId);if(!r){console.warn(`[SyncService] Note ${t.noteId} not found, skipping update`);return}t.data.hasOwnProperty("is_pinned")?await K.put(`/notes/${t.noteId}/pin`):t.data.hasOwnProperty("is_archived")?t.data.is_archived===1?await K.put(`/notes/${t.noteId}/archive`):await K.put(`/notes/${t.noteId}/unarchive`):await K.put(`/notes/${t.noteId}`,{content:r.content,skipTimestamp:t.data.skipTimestamp});const s={...r,syncStatus:"synced"};await D.saveNote(s),te.dispatch(Be(s))}async syncDelete(t){if(typeof t.noteId=="string"&&t.noteId.startsWith("temp-")){await D.deleteNote(t.noteId);return}await K.delete(`/notes/${t.noteId}`),await D.deleteNote(t.noteId)}async syncUploadImage(t){const n=await D.getNote(t.noteId);if(!n)throw new Error("Note not found");const r=t.data.imageId,s=n.images.find(f=>f.id===r);if(!s||!s.base64Data){console.warn("[SyncService] Temp image not found or no base64 data");return}const i=mh(s.base64Data,s.mime_type),o=new File([i],s.original_name,{type:s.mime_type}),a=new FormData;a.append("images",o);const{data:l}=await K.post(`/notes/${t.noteId}/images`,a,{headers:{"Content-Type":"multipart/form-data"}}),c=n.images.map(f=>f.id===r?l[0]:f),d={...n,images:c,syncStatus:"synced"};await D.saveNote(d),te.dispatch(Be(d))}async syncUploadFile(t){const n=await D.getNote(t.noteId);if(!n)throw new Error("Note not found");const r=t.data.fileId,s=n.files.find(f=>f.id===r);if(!s||!s.base64Data){console.warn("[SyncService] Temp file not found or no base64 data");return}const i=mh(s.base64Data,s.mime_type),o=new File([i],s.original_name,{type:s.mime_type}),a=new FormData;a.append("files",o);const{data:l}=await K.post(`/notes/${t.noteId}/files`,a,{headers:{"Content-Type":"multipart/form-data"}}),c=n.files.map(f=>f.id===r?l[0]:f),d={...n,files:c,syncStatus:"synced"};await D.saveNote(d),te.dispatch(Be(d))}async updateImageReferences(t,n){return t.images.some(s=>s.base64Data),t.images}async updateFileReferences(t,n){return t.files.some(s=>s.base64Data),t.files}async syncAttachments(t,n){if(t.images.some(s=>s.base64Data)||t.files.some(s=>s.base64Data)){for(const s of t.images)s.base64Data&&await D.addToSyncQueue({type:"uploadImage",noteId:n,data:{imageId:s.id},timestamp:Date.now(),retries:0});for(const s of t.files)s.base64Data&&await D.addToSyncQueue({type:"uploadFile",noteId:n,data:{fileId:s.id},timestamp:Date.now(),retries:0})}}scheduleRetry(){this.syncTimer&&clearTimeout(this.syncTimer),this.syncTimer=setTimeout(()=>{console.log("[SyncService] Retrying sync..."),this.startSync()},_C)}async updatePendingCount(){const t=await D.getPendingSyncCount();te.dispatch(Md(t))}onSyncComplete(t){this.listeners.push(t)}notifyListeners(){this.listeners.forEach(t=>t())}stop(){this.syncTimer&&(clearTimeout(this.syncTimer),this.syncTimer=null),this.listeners=[]}}const Ba=new TC,jC=({onFilterChange:e,onToggleSidebar:t})=>{const n=kr(),r=wt(),s=oe(v=>v.profile.user),i=oe(v=>v.notes.selectedDate),o=oe(v=>v.notes.selectedTag),a=oe(v=>v.notes.searchQuery),l=oe(v=>v.notes.offlineMode),c=oe(v=>v.notes.pendingSyncCount),d=oe(v=>v.ui.syncStatus);S.useEffect(()=>{f()},[]),S.useEffect(()=>{const v=!!(i||o||a);e==null||e(v)},[i,o,a,e]);const f=async()=>{try{const v=await Et.getProfile();r(Ad(v));const g=v.accent_color||"#007bff";r(Fa(g)),eo(g),(v.colored_icons!==void 0?v.colored_icons===1:!0)?document.body.classList.add("colored-icons"):document.body.classList.remove("colored-icons");try{const x=await Et.getAiSettings();r($d(x))}catch(x){console.error("Ошибка загрузки AI настроек:",x)}}catch(v){console.error("Ошибка загрузки информации о пользователе:",v)}},p=async()=>{r(ss("syncing")),await Ba.startSync()};return u.jsxs(u.Fragment,{children:[t&&u.jsx("button",{className:"mobile-menu-btn",onClick:t,children:u.jsx(M,{icon:"mdi:menu"})}),u.jsxs("header",{className:"notes-header",children:[u.jsx("div",{className:"notes-header-left",children:u.jsxs("span",{children:[u.jsx(M,{icon:"mdi:note-text"})," Мои заметки"]})}),u.jsxs("div",{className:"user-info",children:[l?u.jsx("div",{className:"offline-indicator",title:"Работаем в offline режиме",children:u.jsx(M,{icon:"mdi:wifi-off",style:{color:"#ff9800"}})}):c>0?u.jsx("button",{className:"sync-indicator",title:`Синхронизировать ${c} заметок`,onClick:p,disabled:d==="syncing",children:d==="syncing"?u.jsx(M,{icon:"mdi:loading",className:"spinning"}):u.jsxs(u.Fragment,{children:[u.jsx(M,{icon:"mdi:cloud-upload",style:{color:"#007bff"}}),u.jsx("span",{className:"sync-badge",children:c})]})}):d==="syncing"?u.jsx("div",{className:"sync-indicator",children:u.jsx(M,{icon:"mdi:loading",className:"spinning",style:{color:"#007bff"}})}):null,s!=null&&s.avatar?u.jsx("div",{className:"user-avatar-mini",style:{display:"block"},title:"Перейти в профиль",onClick:()=>n("/profile"),children:u.jsx("img",{src:s.avatar,alt:"Аватар",loading:"lazy"})}):u.jsx("div",{className:"user-avatar-mini user-avatar-placeholder-mini",style:{display:"flex"},title:"Перейти в профиль",onClick:()=>n("/profile"),children:u.jsx(M,{icon:"mdi:account"})}),u.jsx(ho,{}),u.jsx("button",{className:"settings-icon-btn",title:"Настройки",onClick:()=>n("/settings"),children:u.jsx(M,{icon:"mdi:cog"})})]})]})]})};function Wa(e){"@babel/helpers - typeof";return Wa=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Wa(e)}function an(e){if(e===null||e===!0||e===!1)return NaN;var t=Number(e);return isNaN(t)?t:t<0?Math.ceil(t):Math.floor(t)}function Ne(e,t){if(t.length1?"s":"")+" required, but only "+t.length+" present")}function Qe(e){Ne(1,arguments);var t=Object.prototype.toString.call(e);return e instanceof Date||Wa(e)==="object"&&t==="[object Date]"?new Date(e.getTime()):typeof e=="number"||t==="[object Number]"?new Date(e):((typeof e=="string"||t==="[object String]")&&typeof console<"u"&&(console.warn("Starting with v2.0.0-beta.1 date-fns doesn't accept strings as date arguments. Please use `parseISO` to parse strings. See: https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#string-arguments"),console.warn(new Error().stack)),new Date(NaN))}function uv(e,t){Ne(2,arguments);var n=Qe(e),r=an(t);if(isNaN(r))return new Date(NaN);if(!r)return n;var s=n.getDate(),i=new Date(n.getTime());i.setMonth(n.getMonth()+r+1,0);var o=i.getDate();return s>=o?i:(n.setFullYear(i.getFullYear(),i.getMonth(),s),n)}function PC(e,t){Ne(2,arguments);var n=Qe(e).getTime(),r=an(t);return new Date(n+r)}var IC={};function Vs(){return IC}function RC(e,t){var n,r,s,i,o,a,l,c;Ne(1,arguments);var d=Vs(),f=an((n=(r=(s=(i=t==null?void 0:t.weekStartsOn)!==null&&i!==void 0?i:t==null||(o=t.locale)===null||o===void 0||(a=o.options)===null||a===void 0?void 0:a.weekStartsOn)!==null&&s!==void 0?s:d.weekStartsOn)!==null&&r!==void 0?r:(l=d.locale)===null||l===void 0||(c=l.options)===null||c===void 0?void 0:c.weekStartsOn)!==null&&n!==void 0?n:0);if(!(f>=0&&f<=6))throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");var p=Qe(e),v=p.getDay(),g=(v=0&&f<=6))throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");var p=Qe(e),v=p.getDay(),g=(v=s.getTime()?n+1:t.getTime()>=o.getTime()?n:n-1}function HC(e){Ne(1,arguments);var t=pv(e),n=new Date(0);n.setUTCFullYear(t,0,4),n.setUTCHours(0,0,0,0);var r=Ha(n);return r}var QC=6048e5;function VC(e){Ne(1,arguments);var t=Qe(e),n=Ha(t).getTime()-HC(t).getTime();return Math.round(n/QC)+1}function As(e,t){var n,r,s,i,o,a,l,c;Ne(1,arguments);var d=Vs(),f=an((n=(r=(s=(i=t==null?void 0:t.weekStartsOn)!==null&&i!==void 0?i:t==null||(o=t.locale)===null||o===void 0||(a=o.options)===null||a===void 0?void 0:a.weekStartsOn)!==null&&s!==void 0?s:d.weekStartsOn)!==null&&r!==void 0?r:(l=d.locale)===null||l===void 0||(c=l.options)===null||c===void 0?void 0:c.weekStartsOn)!==null&&n!==void 0?n:0);if(!(f>=0&&f<=6))throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");var p=Qe(e),v=p.getUTCDay(),g=(v=1&&v<=7))throw new RangeError("firstWeekContainsDate must be between 1 and 7 inclusively");var g=new Date(0);g.setUTCFullYear(f+1,0,v),g.setUTCHours(0,0,0,0);var y=As(g,t),x=new Date(0);x.setUTCFullYear(f,0,v),x.setUTCHours(0,0,0,0);var m=As(x,t);return d.getTime()>=y.getTime()?f+1:d.getTime()>=m.getTime()?f:f-1}function qC(e,t){var n,r,s,i,o,a,l,c;Ne(1,arguments);var d=Vs(),f=an((n=(r=(s=(i=t==null?void 0:t.firstWeekContainsDate)!==null&&i!==void 0?i:t==null||(o=t.locale)===null||o===void 0||(a=o.options)===null||a===void 0?void 0:a.firstWeekContainsDate)!==null&&s!==void 0?s:d.firstWeekContainsDate)!==null&&r!==void 0?r:(l=d.locale)===null||l===void 0||(c=l.options)===null||c===void 0?void 0:c.firstWeekContainsDate)!==null&&n!==void 0?n:1),p=hv(e,t),v=new Date(0);v.setUTCFullYear(p,0,f),v.setUTCHours(0,0,0,0);var g=As(v,t);return g}var GC=6048e5;function YC(e,t){Ne(1,arguments);var n=Qe(e),r=As(n,t).getTime()-qC(n,t).getTime();return Math.round(r/GC)+1}function Se(e,t){for(var n=e<0?"-":"",r=Math.abs(e).toString();r.length0?r:1-r;return Se(n==="yy"?s%100:s,n.length)},M:function(t,n){var r=t.getUTCMonth();return n==="M"?String(r+1):Se(r+1,2)},d:function(t,n){return Se(t.getUTCDate(),n.length)},a:function(t,n){var r=t.getUTCHours()/12>=1?"pm":"am";switch(n){case"a":case"aa":return r.toUpperCase();case"aaa":return r;case"aaaaa":return r[0];case"aaaa":default:return r==="am"?"a.m.":"p.m."}},h:function(t,n){return Se(t.getUTCHours()%12||12,n.length)},H:function(t,n){return Se(t.getUTCHours(),n.length)},m:function(t,n){return Se(t.getUTCMinutes(),n.length)},s:function(t,n){return Se(t.getUTCSeconds(),n.length)},S:function(t,n){var r=n.length,s=t.getUTCMilliseconds(),i=Math.floor(s*Math.pow(10,r-3));return Se(i,n.length)}},rs={midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},KC={G:function(t,n,r){var s=t.getUTCFullYear()>0?1:0;switch(n){case"G":case"GG":case"GGG":return r.era(s,{width:"abbreviated"});case"GGGGG":return r.era(s,{width:"narrow"});case"GGGG":default:return r.era(s,{width:"wide"})}},y:function(t,n,r){if(n==="yo"){var s=t.getUTCFullYear(),i=s>0?s:1-s;return r.ordinalNumber(i,{unit:"year"})}return Xn.y(t,n)},Y:function(t,n,r,s){var i=hv(t,s),o=i>0?i:1-i;if(n==="YY"){var a=o%100;return Se(a,2)}return n==="Yo"?r.ordinalNumber(o,{unit:"year"}):Se(o,n.length)},R:function(t,n){var r=pv(t);return Se(r,n.length)},u:function(t,n){var r=t.getUTCFullYear();return Se(r,n.length)},Q:function(t,n,r){var s=Math.ceil((t.getUTCMonth()+1)/3);switch(n){case"Q":return String(s);case"QQ":return Se(s,2);case"Qo":return r.ordinalNumber(s,{unit:"quarter"});case"QQQ":return r.quarter(s,{width:"abbreviated",context:"formatting"});case"QQQQQ":return r.quarter(s,{width:"narrow",context:"formatting"});case"QQQQ":default:return r.quarter(s,{width:"wide",context:"formatting"})}},q:function(t,n,r){var s=Math.ceil((t.getUTCMonth()+1)/3);switch(n){case"q":return String(s);case"qq":return Se(s,2);case"qo":return r.ordinalNumber(s,{unit:"quarter"});case"qqq":return r.quarter(s,{width:"abbreviated",context:"standalone"});case"qqqqq":return r.quarter(s,{width:"narrow",context:"standalone"});case"qqqq":default:return r.quarter(s,{width:"wide",context:"standalone"})}},M:function(t,n,r){var s=t.getUTCMonth();switch(n){case"M":case"MM":return Xn.M(t,n);case"Mo":return r.ordinalNumber(s+1,{unit:"month"});case"MMM":return r.month(s,{width:"abbreviated",context:"formatting"});case"MMMMM":return r.month(s,{width:"narrow",context:"formatting"});case"MMMM":default:return r.month(s,{width:"wide",context:"formatting"})}},L:function(t,n,r){var s=t.getUTCMonth();switch(n){case"L":return String(s+1);case"LL":return Se(s+1,2);case"Lo":return r.ordinalNumber(s+1,{unit:"month"});case"LLL":return r.month(s,{width:"abbreviated",context:"standalone"});case"LLLLL":return r.month(s,{width:"narrow",context:"standalone"});case"LLLL":default:return r.month(s,{width:"wide",context:"standalone"})}},w:function(t,n,r,s){var i=YC(t,s);return n==="wo"?r.ordinalNumber(i,{unit:"week"}):Se(i,n.length)},I:function(t,n,r){var s=VC(t);return n==="Io"?r.ordinalNumber(s,{unit:"week"}):Se(s,n.length)},d:function(t,n,r){return n==="do"?r.ordinalNumber(t.getUTCDate(),{unit:"date"}):Xn.d(t,n)},D:function(t,n,r){var s=WC(t);return n==="Do"?r.ordinalNumber(s,{unit:"dayOfYear"}):Se(s,n.length)},E:function(t,n,r){var s=t.getUTCDay();switch(n){case"E":case"EE":case"EEE":return r.day(s,{width:"abbreviated",context:"formatting"});case"EEEEE":return r.day(s,{width:"narrow",context:"formatting"});case"EEEEEE":return r.day(s,{width:"short",context:"formatting"});case"EEEE":default:return r.day(s,{width:"wide",context:"formatting"})}},e:function(t,n,r,s){var i=t.getUTCDay(),o=(i-s.weekStartsOn+8)%7||7;switch(n){case"e":return String(o);case"ee":return Se(o,2);case"eo":return r.ordinalNumber(o,{unit:"day"});case"eee":return r.day(i,{width:"abbreviated",context:"formatting"});case"eeeee":return r.day(i,{width:"narrow",context:"formatting"});case"eeeeee":return r.day(i,{width:"short",context:"formatting"});case"eeee":default:return r.day(i,{width:"wide",context:"formatting"})}},c:function(t,n,r,s){var i=t.getUTCDay(),o=(i-s.weekStartsOn+8)%7||7;switch(n){case"c":return String(o);case"cc":return Se(o,n.length);case"co":return r.ordinalNumber(o,{unit:"day"});case"ccc":return r.day(i,{width:"abbreviated",context:"standalone"});case"ccccc":return r.day(i,{width:"narrow",context:"standalone"});case"cccccc":return r.day(i,{width:"short",context:"standalone"});case"cccc":default:return r.day(i,{width:"wide",context:"standalone"})}},i:function(t,n,r){var s=t.getUTCDay(),i=s===0?7:s;switch(n){case"i":return String(i);case"ii":return Se(i,n.length);case"io":return r.ordinalNumber(i,{unit:"day"});case"iii":return r.day(s,{width:"abbreviated",context:"formatting"});case"iiiii":return r.day(s,{width:"narrow",context:"formatting"});case"iiiiii":return r.day(s,{width:"short",context:"formatting"});case"iiii":default:return r.day(s,{width:"wide",context:"formatting"})}},a:function(t,n,r){var s=t.getUTCHours(),i=s/12>=1?"pm":"am";switch(n){case"a":case"aa":return r.dayPeriod(i,{width:"abbreviated",context:"formatting"});case"aaa":return r.dayPeriod(i,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return r.dayPeriod(i,{width:"narrow",context:"formatting"});case"aaaa":default:return r.dayPeriod(i,{width:"wide",context:"formatting"})}},b:function(t,n,r){var s=t.getUTCHours(),i;switch(s===12?i=rs.noon:s===0?i=rs.midnight:i=s/12>=1?"pm":"am",n){case"b":case"bb":return r.dayPeriod(i,{width:"abbreviated",context:"formatting"});case"bbb":return r.dayPeriod(i,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return r.dayPeriod(i,{width:"narrow",context:"formatting"});case"bbbb":default:return r.dayPeriod(i,{width:"wide",context:"formatting"})}},B:function(t,n,r){var s=t.getUTCHours(),i;switch(s>=17?i=rs.evening:s>=12?i=rs.afternoon:s>=4?i=rs.morning:i=rs.night,n){case"B":case"BB":case"BBB":return r.dayPeriod(i,{width:"abbreviated",context:"formatting"});case"BBBBB":return r.dayPeriod(i,{width:"narrow",context:"formatting"});case"BBBB":default:return r.dayPeriod(i,{width:"wide",context:"formatting"})}},h:function(t,n,r){if(n==="ho"){var s=t.getUTCHours()%12;return s===0&&(s=12),r.ordinalNumber(s,{unit:"hour"})}return Xn.h(t,n)},H:function(t,n,r){return n==="Ho"?r.ordinalNumber(t.getUTCHours(),{unit:"hour"}):Xn.H(t,n)},K:function(t,n,r){var s=t.getUTCHours()%12;return n==="Ko"?r.ordinalNumber(s,{unit:"hour"}):Se(s,n.length)},k:function(t,n,r){var s=t.getUTCHours();return s===0&&(s=24),n==="ko"?r.ordinalNumber(s,{unit:"hour"}):Se(s,n.length)},m:function(t,n,r){return n==="mo"?r.ordinalNumber(t.getUTCMinutes(),{unit:"minute"}):Xn.m(t,n)},s:function(t,n,r){return n==="so"?r.ordinalNumber(t.getUTCSeconds(),{unit:"second"}):Xn.s(t,n)},S:function(t,n){return Xn.S(t,n)},X:function(t,n,r,s){var i=s._originalDate||t,o=i.getTimezoneOffset();if(o===0)return"Z";switch(n){case"X":return wh(o);case"XXXX":case"XX":return Pr(o);case"XXXXX":case"XXX":default:return Pr(o,":")}},x:function(t,n,r,s){var i=s._originalDate||t,o=i.getTimezoneOffset();switch(n){case"x":return wh(o);case"xxxx":case"xx":return Pr(o);case"xxxxx":case"xxx":default:return Pr(o,":")}},O:function(t,n,r,s){var i=s._originalDate||t,o=i.getTimezoneOffset();switch(n){case"O":case"OO":case"OOO":return"GMT"+vh(o,":");case"OOOO":default:return"GMT"+Pr(o,":")}},z:function(t,n,r,s){var i=s._originalDate||t,o=i.getTimezoneOffset();switch(n){case"z":case"zz":case"zzz":return"GMT"+vh(o,":");case"zzzz":default:return"GMT"+Pr(o,":")}},t:function(t,n,r,s){var i=s._originalDate||t,o=Math.floor(i.getTime()/1e3);return Se(o,n.length)},T:function(t,n,r,s){var i=s._originalDate||t,o=i.getTime();return Se(o,n.length)}};function vh(e,t){var n=e>0?"-":"+",r=Math.abs(e),s=Math.floor(r/60),i=r%60;if(i===0)return n+String(s);var o=t;return n+String(s)+o+Se(i,2)}function wh(e,t){if(e%60===0){var n=e>0?"-":"+";return n+Se(Math.abs(e)/60,2)}return Pr(e,t)}function Pr(e,t){var n=t||"",r=e>0?"-":"+",s=Math.abs(e),i=Se(Math.floor(s/60),2),o=Se(s%60,2);return r+i+n+o}var xh=function(t,n){switch(t){case"P":return n.date({width:"short"});case"PP":return n.date({width:"medium"});case"PPP":return n.date({width:"long"});case"PPPP":default:return n.date({width:"full"})}},mv=function(t,n){switch(t){case"p":return n.time({width:"short"});case"pp":return n.time({width:"medium"});case"ppp":return n.time({width:"long"});case"pppp":default:return n.time({width:"full"})}},XC=function(t,n){var r=t.match(/(P+)(p+)?/)||[],s=r[1],i=r[2];if(!i)return xh(t,n);var o;switch(s){case"P":o=n.dateTime({width:"short"});break;case"PP":o=n.dateTime({width:"medium"});break;case"PPP":o=n.dateTime({width:"long"});break;case"PPPP":default:o=n.dateTime({width:"full"});break}return o.replace("{{date}}",xh(s,n)).replace("{{time}}",mv(i,n))},JC={p:mv,P:XC},ZC=["D","DD"],eE=["YY","YYYY"];function tE(e){return ZC.indexOf(e)!==-1}function nE(e){return eE.indexOf(e)!==-1}function Sh(e,t,n){if(e==="YYYY")throw new RangeError("Use `yyyy` instead of `YYYY` (in `".concat(t,"`) for formatting years to the input `").concat(n,"`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));if(e==="YY")throw new RangeError("Use `yy` instead of `YY` (in `".concat(t,"`) for formatting years to the input `").concat(n,"`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));if(e==="D")throw new RangeError("Use `d` instead of `D` (in `".concat(t,"`) for formatting days of the month to the input `").concat(n,"`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));if(e==="DD")throw new RangeError("Use `dd` instead of `DD` (in `".concat(t,"`) for formatting days of the month to the input `").concat(n,"`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"))}var rE={lessThanXSeconds:{one:"less than a second",other:"less than {{count}} seconds"},xSeconds:{one:"1 second",other:"{{count}} seconds"},halfAMinute:"half a minute",lessThanXMinutes:{one:"less than a minute",other:"less than {{count}} minutes"},xMinutes:{one:"1 minute",other:"{{count}} minutes"},aboutXHours:{one:"about 1 hour",other:"about {{count}} hours"},xHours:{one:"1 hour",other:"{{count}} hours"},xDays:{one:"1 day",other:"{{count}} days"},aboutXWeeks:{one:"about 1 week",other:"about {{count}} weeks"},xWeeks:{one:"1 week",other:"{{count}} weeks"},aboutXMonths:{one:"about 1 month",other:"about {{count}} months"},xMonths:{one:"1 month",other:"{{count}} months"},aboutXYears:{one:"about 1 year",other:"about {{count}} years"},xYears:{one:"1 year",other:"{{count}} years"},overXYears:{one:"over 1 year",other:"over {{count}} years"},almostXYears:{one:"almost 1 year",other:"almost {{count}} years"}},sE=function(t,n,r){var s,i=rE[t];return typeof i=="string"?s=i:n===1?s=i.one:s=i.other.replace("{{count}}",n.toString()),r!=null&&r.addSuffix?r.comparison&&r.comparison>0?"in "+s:s+" ago":s};function Ts(e){return function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},n=t.width?String(t.width):e.defaultWidth,r=e.formats[n]||e.formats[e.defaultWidth];return r}}var iE={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},oE={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},aE={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},lE={date:Ts({formats:iE,defaultWidth:"full"}),time:Ts({formats:oE,defaultWidth:"full"}),dateTime:Ts({formats:aE,defaultWidth:"full"})},cE={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},uE=function(t,n,r,s){return cE[t]};function jn(e){return function(t,n){var r=n!=null&&n.context?String(n.context):"standalone",s;if(r==="formatting"&&e.formattingValues){var i=e.defaultFormattingWidth||e.defaultWidth,o=n!=null&&n.width?String(n.width):i;s=e.formattingValues[o]||e.formattingValues[i]}else{var a=e.defaultWidth,l=n!=null&&n.width?String(n.width):e.defaultWidth;s=e.values[l]||e.values[a]}var c=e.argumentCallback?e.argumentCallback(t):t;return s[c]}}var dE={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},fE={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},pE={narrow:["J","F","M","A","M","J","J","A","S","O","N","D"],abbreviated:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wide:["January","February","March","April","May","June","July","August","September","October","November","December"]},hE={narrow:["S","M","T","W","T","F","S"],short:["Su","Mo","Tu","We","Th","Fr","Sa"],abbreviated:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],wide:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},mE={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"}},gE={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"}},yE=function(t,n){var r=Number(t),s=r%100;if(s>20||s<10)switch(s%10){case 1:return r+"st";case 2:return r+"nd";case 3:return r+"rd"}return r+"th"},vE={ordinalNumber:yE,era:jn({values:dE,defaultWidth:"wide"}),quarter:jn({values:fE,defaultWidth:"wide",argumentCallback:function(t){return t-1}}),month:jn({values:pE,defaultWidth:"wide"}),day:jn({values:hE,defaultWidth:"wide"}),dayPeriod:jn({values:mE,defaultWidth:"wide",formattingValues:gE,defaultFormattingWidth:"wide"})};function Pn(e){return function(t){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},r=n.width,s=r&&e.matchPatterns[r]||e.matchPatterns[e.defaultMatchWidth],i=t.match(s);if(!i)return null;var o=i[0],a=r&&e.parsePatterns[r]||e.parsePatterns[e.defaultParseWidth],l=Array.isArray(a)?xE(a,function(f){return f.test(o)}):wE(a,function(f){return f.test(o)}),c;c=e.valueCallback?e.valueCallback(l):l,c=n.valueCallback?n.valueCallback(c):c;var d=t.slice(o.length);return{value:c,rest:d}}}function wE(e,t){for(var n in e)if(e.hasOwnProperty(n)&&t(e[n]))return n}function xE(e,t){for(var n=0;n1&&arguments[1]!==void 0?arguments[1]:{},r=t.match(e.matchPattern);if(!r)return null;var s=r[0],i=t.match(e.parsePattern);if(!i)return null;var o=e.valueCallback?e.valueCallback(i[0]):i[0];o=n.valueCallback?n.valueCallback(o):o;var a=t.slice(s.length);return{value:o,rest:a}}}var SE=/^(\d+)(th|st|nd|rd)?/i,kE=/\d+/i,bE={narrow:/^(b|a)/i,abbreviated:/^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,wide:/^(before christ|before common era|anno domini|common era)/i},CE={any:[/^b/i,/^(a|c)/i]},EE={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},NE={any:[/1/i,/2/i,/3/i,/4/i]},_E={narrow:/^[jfmasond]/i,abbreviated:/^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,wide:/^(january|february|march|april|may|june|july|august|september|october|november|december)/i},TE={narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^f/i,/^mar/i,/^ap/i,/^may/i,/^jun/i,/^jul/i,/^au/i,/^s/i,/^o/i,/^n/i,/^d/i]},jE={narrow:/^[smtwf]/i,short:/^(su|mo|tu|we|th|fr|sa)/i,abbreviated:/^(sun|mon|tue|wed|thu|fri|sat)/i,wide:/^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i},PE={narrow:[/^s/i,/^m/i,/^t/i,/^w/i,/^t/i,/^f/i,/^s/i],any:[/^su/i,/^m/i,/^tu/i,/^w/i,/^th/i,/^f/i,/^sa/i]},IE={narrow:/^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,any:/^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i},RE={any:{am:/^a/i,pm:/^p/i,midnight:/^mi/i,noon:/^no/i,morning:/morning/i,afternoon:/afternoon/i,evening:/evening/i,night:/night/i}},OE={ordinalNumber:gv({matchPattern:SE,parsePattern:kE,valueCallback:function(t){return parseInt(t,10)}}),era:Pn({matchPatterns:bE,defaultMatchWidth:"wide",parsePatterns:CE,defaultParseWidth:"any"}),quarter:Pn({matchPatterns:EE,defaultMatchWidth:"wide",parsePatterns:NE,defaultParseWidth:"any",valueCallback:function(t){return t+1}}),month:Pn({matchPatterns:_E,defaultMatchWidth:"wide",parsePatterns:TE,defaultParseWidth:"any"}),day:Pn({matchPatterns:jE,defaultMatchWidth:"wide",parsePatterns:PE,defaultParseWidth:"any"}),dayPeriod:Pn({matchPatterns:IE,defaultMatchWidth:"any",parsePatterns:RE,defaultParseWidth:"any"})},DE={code:"en-US",formatDistance:sE,formatLong:lE,formatRelative:uE,localize:vE,match:OE,options:{weekStartsOn:0,firstWeekContainsDate:1}},LE=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,ME=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,AE=/^'([^]*?)'?$/,$E=/''/g,FE=/[a-zA-Z]/;function mi(e,t,n){var r,s,i,o,a,l,c,d,f,p,v,g,y,x,m,h,w,C;Ne(2,arguments);var T=String(t),b=Vs(),N=(r=(s=n==null?void 0:n.locale)!==null&&s!==void 0?s:b.locale)!==null&&r!==void 0?r:DE,P=an((i=(o=(a=(l=n==null?void 0:n.firstWeekContainsDate)!==null&&l!==void 0?l:n==null||(c=n.locale)===null||c===void 0||(d=c.options)===null||d===void 0?void 0:d.firstWeekContainsDate)!==null&&a!==void 0?a:b.firstWeekContainsDate)!==null&&o!==void 0?o:(f=b.locale)===null||f===void 0||(p=f.options)===null||p===void 0?void 0:p.firstWeekContainsDate)!==null&&i!==void 0?i:1);if(!(P>=1&&P<=7))throw new RangeError("firstWeekContainsDate must be between 1 and 7 inclusively");var I=an((v=(g=(y=(x=n==null?void 0:n.weekStartsOn)!==null&&x!==void 0?x:n==null||(m=n.locale)===null||m===void 0||(h=m.options)===null||h===void 0?void 0:h.weekStartsOn)!==null&&y!==void 0?y:b.weekStartsOn)!==null&&g!==void 0?g:(w=b.locale)===null||w===void 0||(C=w.options)===null||C===void 0?void 0:C.weekStartsOn)!==null&&v!==void 0?v:0);if(!(I>=0&&I<=6))throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");if(!N.localize)throw new RangeError("locale must contain localize property");if(!N.formatLong)throw new RangeError("locale must contain formatLong property");var O=Qe(e);if(!MC(O))throw new RangeError("Invalid time value");var Q=OC(O),ue=UC(O,Q),ne={firstWeekContainsDate:P,weekStartsOn:I,locale:N,_originalDate:O},J=T.match(ME).map(function($){var L=$[0];if(L==="p"||L==="P"){var Z=JC[L];return Z($,N.formatLong)}return $}).join("").match(LE).map(function($){if($==="''")return"'";var L=$[0];if(L==="'")return zE($);var Z=KC[L];if(Z)return!(n!=null&&n.useAdditionalWeekYearTokens)&&nE($)&&Sh($,t,String(e)),!(n!=null&&n.useAdditionalDayOfYearTokens)&&tE($)&&Sh($,t,String(e)),Z(ue,$,N.localize,ne);if(L.match(FE))throw new RangeError("Format string contains an unescaped latin alphabet character `"+L+"`");return $}).join("");return J}function zE(e){var t=e.match(AE);return t?t[1].replace($E,"'"):e}function UE(e,t){Ne(2,arguments);var n=Qe(e),r=Qe(t);return n.getFullYear()===r.getFullYear()&&n.getMonth()===r.getMonth()}function BE(e,t){var n;Ne(1,arguments);var r=an((n=void 0)!==null&&n!==void 0?n:2);if(r!==2&&r!==1&&r!==0)throw new RangeError("additionalDigits must be 0, 1 or 2");if(!(typeof e=="string"||Object.prototype.toString.call(e)==="[object String]"))return new Date(NaN);var s=VE(e),i;if(s.date){var o=qE(s.date,r);i=GE(o.restDateString,o.year)}if(!i||isNaN(i.getTime()))return new Date(NaN);var a=i.getTime(),l=0,c;if(s.time&&(l=YE(s.time),isNaN(l)))return new Date(NaN);if(s.timezone){if(c=KE(s.timezone),isNaN(c))return new Date(NaN)}else{var d=new Date(a+l),f=new Date(0);return f.setFullYear(d.getUTCFullYear(),d.getUTCMonth(),d.getUTCDate()),f.setHours(d.getUTCHours(),d.getUTCMinutes(),d.getUTCSeconds(),d.getUTCMilliseconds()),f}return new Date(a+l+c)}var Uo={dateTimeDelimiter:/[T ]/,timeZoneDelimiter:/[Z ]/i,timezone:/([Z+-].*)$/},WE=/^-?(?:(\d{3})|(\d{2})(?:-?(\d{2}))?|W(\d{2})(?:-?(\d{1}))?|)$/,HE=/^(\d{2}(?:[.,]\d*)?)(?::?(\d{2}(?:[.,]\d*)?))?(?::?(\d{2}(?:[.,]\d*)?))?$/,QE=/^([+-])(\d{2})(?::?(\d{2}))?$/;function VE(e){var t={},n=e.split(Uo.dateTimeDelimiter),r;if(n.length>2)return t;if(/:/.test(n[0])?r=n[0]:(t.date=n[0],r=n[1],Uo.timeZoneDelimiter.test(t.date)&&(t.date=e.split(Uo.timeZoneDelimiter)[0],r=e.substr(t.date.length,e.length))),r){var s=Uo.timezone.exec(r);s?(t.time=r.replace(s[1],""),t.timezone=s[1]):t.time=r}return t}function qE(e,t){var n=new RegExp("^(?:(\\d{4}|[+-]\\d{"+(4+t)+"})|(\\d{2}|[+-]\\d{"+(2+t)+"})$)"),r=e.match(n);if(!r)return{year:NaN,restDateString:""};var s=r[1]?parseInt(r[1]):null,i=r[2]?parseInt(r[2]):null;return{year:i===null?s:i*100,restDateString:e.slice((r[1]||r[2]).length)}}function GE(e,t){if(t===null)return new Date(NaN);var n=e.match(WE);if(!n)return new Date(NaN);var r=!!n[4],s=oi(n[1]),i=oi(n[2])-1,o=oi(n[3]),a=oi(n[4]),l=oi(n[5])-1;if(r)return tN(t,a,l)?XE(t,a,l):new Date(NaN);var c=new Date(0);return!ZE(t,i,o)||!eN(t,s)?new Date(NaN):(c.setUTCFullYear(t,i,Math.max(s,o)),c)}function oi(e){return e?parseInt(e):1}function YE(e){var t=e.match(HE);if(!t)return NaN;var n=cc(t[1]),r=cc(t[2]),s=cc(t[3]);return nN(n,r,s)?n*fv+r*dv+s*1e3:NaN}function cc(e){return e&&parseFloat(e.replace(",","."))||0}function KE(e){if(e==="Z")return 0;var t=e.match(QE);if(!t)return 0;var n=t[1]==="+"?-1:1,r=parseInt(t[2]),s=t[3]&&parseInt(t[3])||0;return rN(r,s)?n*(r*fv+s*dv):NaN}function XE(e,t,n){var r=new Date(0);r.setUTCFullYear(e,0,4);var s=r.getUTCDay()||7,i=(t-1)*7+n+1-s;return r.setUTCDate(r.getUTCDate()+i),r}var JE=[31,null,31,30,31,30,31,31,30,31,30,31];function yv(e){return e%400===0||e%4===0&&e%100!==0}function ZE(e,t,n){return t>=0&&t<=11&&n>=1&&n<=(JE[t]||(yv(e)?29:28))}function eN(e,t){return t>=1&&t<=(yv(e)?366:365)}function tN(e,t,n){return t>=1&&t<=53&&n>=0&&n<=6}function nN(e,t,n){return e===24?t===0&&n===0:n>=0&&n<60&&t>=0&&t<60&&e>=0&&e<25}function rN(e,t){return t>=0&&t<=59}function sN(e,t){Ne(2,arguments);var n=an(t);return uv(e,-n)}function kh(e,t,n){Ne(2,arguments);var r=As(e,n),s=As(t,n);return r.getTime()===s.getTime()}function ai(e,t){if(e.one!==void 0&&t===1)return e.one;var n=t%10,r=t%100;return n===1&&r!==11?e.singularNominative.replace("{{count}}",String(t)):n>=2&&n<=4&&(r<10||r>20)?e.singularGenitive.replace("{{count}}",String(t)):e.pluralGenitive.replace("{{count}}",String(t))}function kt(e){return function(t,n){return n!=null&&n.addSuffix?n.comparison&&n.comparison>0?e.future?ai(e.future,t):"через "+ai(e.regular,t):e.past?ai(e.past,t):ai(e.regular,t)+" назад":ai(e.regular,t)}}var iN={lessThanXSeconds:kt({regular:{one:"меньше секунды",singularNominative:"меньше {{count}} секунды",singularGenitive:"меньше {{count}} секунд",pluralGenitive:"меньше {{count}} секунд"},future:{one:"меньше, чем через секунду",singularNominative:"меньше, чем через {{count}} секунду",singularGenitive:"меньше, чем через {{count}} секунды",pluralGenitive:"меньше, чем через {{count}} секунд"}}),xSeconds:kt({regular:{singularNominative:"{{count}} секунда",singularGenitive:"{{count}} секунды",pluralGenitive:"{{count}} секунд"},past:{singularNominative:"{{count}} секунду назад",singularGenitive:"{{count}} секунды назад",pluralGenitive:"{{count}} секунд назад"},future:{singularNominative:"через {{count}} секунду",singularGenitive:"через {{count}} секунды",pluralGenitive:"через {{count}} секунд"}}),halfAMinute:function(t,n){return n!=null&&n.addSuffix?n.comparison&&n.comparison>0?"через полминуты":"полминуты назад":"полминуты"},lessThanXMinutes:kt({regular:{one:"меньше минуты",singularNominative:"меньше {{count}} минуты",singularGenitive:"меньше {{count}} минут",pluralGenitive:"меньше {{count}} минут"},future:{one:"меньше, чем через минуту",singularNominative:"меньше, чем через {{count}} минуту",singularGenitive:"меньше, чем через {{count}} минуты",pluralGenitive:"меньше, чем через {{count}} минут"}}),xMinutes:kt({regular:{singularNominative:"{{count}} минута",singularGenitive:"{{count}} минуты",pluralGenitive:"{{count}} минут"},past:{singularNominative:"{{count}} минуту назад",singularGenitive:"{{count}} минуты назад",pluralGenitive:"{{count}} минут назад"},future:{singularNominative:"через {{count}} минуту",singularGenitive:"через {{count}} минуты",pluralGenitive:"через {{count}} минут"}}),aboutXHours:kt({regular:{singularNominative:"около {{count}} часа",singularGenitive:"около {{count}} часов",pluralGenitive:"около {{count}} часов"},future:{singularNominative:"приблизительно через {{count}} час",singularGenitive:"приблизительно через {{count}} часа",pluralGenitive:"приблизительно через {{count}} часов"}}),xHours:kt({regular:{singularNominative:"{{count}} час",singularGenitive:"{{count}} часа",pluralGenitive:"{{count}} часов"}}),xDays:kt({regular:{singularNominative:"{{count}} день",singularGenitive:"{{count}} дня",pluralGenitive:"{{count}} дней"}}),aboutXWeeks:kt({regular:{singularNominative:"около {{count}} недели",singularGenitive:"около {{count}} недель",pluralGenitive:"около {{count}} недель"},future:{singularNominative:"приблизительно через {{count}} неделю",singularGenitive:"приблизительно через {{count}} недели",pluralGenitive:"приблизительно через {{count}} недель"}}),xWeeks:kt({regular:{singularNominative:"{{count}} неделя",singularGenitive:"{{count}} недели",pluralGenitive:"{{count}} недель"}}),aboutXMonths:kt({regular:{singularNominative:"около {{count}} месяца",singularGenitive:"около {{count}} месяцев",pluralGenitive:"около {{count}} месяцев"},future:{singularNominative:"приблизительно через {{count}} месяц",singularGenitive:"приблизительно через {{count}} месяца",pluralGenitive:"приблизительно через {{count}} месяцев"}}),xMonths:kt({regular:{singularNominative:"{{count}} месяц",singularGenitive:"{{count}} месяца",pluralGenitive:"{{count}} месяцев"}}),aboutXYears:kt({regular:{singularNominative:"около {{count}} года",singularGenitive:"около {{count}} лет",pluralGenitive:"около {{count}} лет"},future:{singularNominative:"приблизительно через {{count}} год",singularGenitive:"приблизительно через {{count}} года",pluralGenitive:"приблизительно через {{count}} лет"}}),xYears:kt({regular:{singularNominative:"{{count}} год",singularGenitive:"{{count}} года",pluralGenitive:"{{count}} лет"}}),overXYears:kt({regular:{singularNominative:"больше {{count}} года",singularGenitive:"больше {{count}} лет",pluralGenitive:"больше {{count}} лет"},future:{singularNominative:"больше, чем через {{count}} год",singularGenitive:"больше, чем через {{count}} года",pluralGenitive:"больше, чем через {{count}} лет"}}),almostXYears:kt({regular:{singularNominative:"почти {{count}} год",singularGenitive:"почти {{count}} года",pluralGenitive:"почти {{count}} лет"},future:{singularNominative:"почти через {{count}} год",singularGenitive:"почти через {{count}} года",pluralGenitive:"почти через {{count}} лет"}})},oN=function(t,n,r){return iN[t](n,r)},aN={full:"EEEE, d MMMM y 'г.'",long:"d MMMM y 'г.'",medium:"d MMM y 'г.'",short:"dd.MM.y"},lN={full:"H:mm:ss zzzz",long:"H:mm:ss z",medium:"H:mm:ss",short:"H:mm"},cN={any:"{{date}}, {{time}}"},uN={date:Ts({formats:aN,defaultWidth:"full"}),time:Ts({formats:lN,defaultWidth:"full"}),dateTime:Ts({formats:cN,defaultWidth:"any"})},Xd=["воскресенье","понедельник","вторник","среду","четверг","пятницу","субботу"];function dN(e){var t=Xd[e];switch(e){case 0:return"'в прошлое "+t+" в' p";case 1:case 2:case 4:return"'в прошлый "+t+" в' p";case 3:case 5:case 6:return"'в прошлую "+t+" в' p"}}function bh(e){var t=Xd[e];return e===2?"'во "+t+" в' p":"'в "+t+" в' p"}function fN(e){var t=Xd[e];switch(e){case 0:return"'в следующее "+t+" в' p";case 1:case 2:case 4:return"'в следующий "+t+" в' p";case 3:case 5:case 6:return"'в следующую "+t+" в' p"}}var pN={lastWeek:function(t,n,r){var s=t.getUTCDay();return kh(t,n,r)?bh(s):dN(s)},yesterday:"'вчера в' p",today:"'сегодня в' p",tomorrow:"'завтра в' p",nextWeek:function(t,n,r){var s=t.getUTCDay();return kh(t,n,r)?bh(s):fN(s)},other:"P"},hN=function(t,n,r,s){var i=pN[t];return typeof i=="function"?i(n,r,s):i},mN={narrow:["до н.э.","н.э."],abbreviated:["до н. э.","н. э."],wide:["до нашей эры","нашей эры"]},gN={narrow:["1","2","3","4"],abbreviated:["1-й кв.","2-й кв.","3-й кв.","4-й кв."],wide:["1-й квартал","2-й квартал","3-й квартал","4-й квартал"]},yN={narrow:["Я","Ф","М","А","М","И","И","А","С","О","Н","Д"],abbreviated:["янв.","фев.","март","апр.","май","июнь","июль","авг.","сент.","окт.","нояб.","дек."],wide:["январь","февраль","март","апрель","май","июнь","июль","август","сентябрь","октябрь","ноябрь","декабрь"]},vN={narrow:["Я","Ф","М","А","М","И","И","А","С","О","Н","Д"],abbreviated:["янв.","фев.","мар.","апр.","мая","июн.","июл.","авг.","сент.","окт.","нояб.","дек."],wide:["января","февраля","марта","апреля","мая","июня","июля","августа","сентября","октября","ноября","декабря"]},wN={narrow:["В","П","В","С","Ч","П","С"],short:["вс","пн","вт","ср","чт","пт","сб"],abbreviated:["вск","пнд","втр","срд","чтв","птн","суб"],wide:["воскресенье","понедельник","вторник","среда","четверг","пятница","суббота"]},xN={narrow:{am:"ДП",pm:"ПП",midnight:"полн.",noon:"полд.",morning:"утро",afternoon:"день",evening:"веч.",night:"ночь"},abbreviated:{am:"ДП",pm:"ПП",midnight:"полн.",noon:"полд.",morning:"утро",afternoon:"день",evening:"веч.",night:"ночь"},wide:{am:"ДП",pm:"ПП",midnight:"полночь",noon:"полдень",morning:"утро",afternoon:"день",evening:"вечер",night:"ночь"}},SN={narrow:{am:"ДП",pm:"ПП",midnight:"полн.",noon:"полд.",morning:"утра",afternoon:"дня",evening:"веч.",night:"ночи"},abbreviated:{am:"ДП",pm:"ПП",midnight:"полн.",noon:"полд.",morning:"утра",afternoon:"дня",evening:"веч.",night:"ночи"},wide:{am:"ДП",pm:"ПП",midnight:"полночь",noon:"полдень",morning:"утра",afternoon:"дня",evening:"вечера",night:"ночи"}},kN=function(t,n){var r=Number(t),s=n==null?void 0:n.unit,i;return s==="date"?i="-е":s==="week"||s==="minute"||s==="second"?i="-я":i="-й",r+i},bN={ordinalNumber:kN,era:jn({values:mN,defaultWidth:"wide"}),quarter:jn({values:gN,defaultWidth:"wide",argumentCallback:function(t){return t-1}}),month:jn({values:yN,defaultWidth:"wide",formattingValues:vN,defaultFormattingWidth:"wide"}),day:jn({values:wN,defaultWidth:"wide"}),dayPeriod:jn({values:xN,defaultWidth:"any",formattingValues:SN,defaultFormattingWidth:"wide"})},CN=/^(\d+)(-?(е|я|й|ое|ье|ая|ья|ый|ой|ий|ый))?/i,EN=/\d+/i,NN={narrow:/^((до )?н\.?\s?э\.?)/i,abbreviated:/^((до )?н\.?\s?э\.?)/i,wide:/^(до нашей эры|нашей эры|наша эра)/i},_N={any:[/^д/i,/^н/i]},TN={narrow:/^[1234]/i,abbreviated:/^[1234](-?[ыои]?й?)? кв.?/i,wide:/^[1234](-?[ыои]?й?)? квартал/i},jN={any:[/1/i,/2/i,/3/i,/4/i]},PN={narrow:/^[яфмаисонд]/i,abbreviated:/^(янв|фев|март?|апр|ма[йя]|июн[ья]?|июл[ья]?|авг|сент?|окт|нояб?|дек)\.?/i,wide:/^(январ[ья]|феврал[ья]|марта?|апрел[ья]|ма[йя]|июн[ья]|июл[ья]|августа?|сентябр[ья]|октябр[ья]|октябр[ья]|ноябр[ья]|декабр[ья])/i},IN={narrow:[/^я/i,/^ф/i,/^м/i,/^а/i,/^м/i,/^и/i,/^и/i,/^а/i,/^с/i,/^о/i,/^н/i,/^я/i],any:[/^я/i,/^ф/i,/^мар/i,/^ап/i,/^ма[йя]/i,/^июн/i,/^июл/i,/^ав/i,/^с/i,/^о/i,/^н/i,/^д/i]},RN={narrow:/^[впсч]/i,short:/^(вс|во|пн|по|вт|ср|чт|че|пт|пя|сб|су)\.?/i,abbreviated:/^(вск|вос|пнд|пон|втр|вто|срд|сре|чтв|чет|птн|пят|суб).?/i,wide:/^(воскресень[ея]|понедельника?|вторника?|сред[аы]|четверга?|пятниц[аы]|суббот[аы])/i},ON={narrow:[/^в/i,/^п/i,/^в/i,/^с/i,/^ч/i,/^п/i,/^с/i],any:[/^в[ос]/i,/^п[он]/i,/^в/i,/^ср/i,/^ч/i,/^п[ят]/i,/^с[уб]/i]},DN={narrow:/^([дп]п|полн\.?|полд\.?|утр[оа]|день|дня|веч\.?|ноч[ьи])/i,abbreviated:/^([дп]п|полн\.?|полд\.?|утр[оа]|день|дня|веч\.?|ноч[ьи])/i,wide:/^([дп]п|полночь|полдень|утр[оа]|день|дня|вечера?|ноч[ьи])/i},LN={any:{am:/^дп/i,pm:/^пп/i,midnight:/^полн/i,noon:/^полд/i,morning:/^у/i,afternoon:/^д[ен]/i,evening:/^в/i,night:/^н/i}},MN={ordinalNumber:gv({matchPattern:CN,parsePattern:EN,valueCallback:function(t){return parseInt(t,10)}}),era:Pn({matchPatterns:NN,defaultMatchWidth:"wide",parsePatterns:_N,defaultParseWidth:"any"}),quarter:Pn({matchPatterns:TN,defaultMatchWidth:"wide",parsePatterns:jN,defaultParseWidth:"any",valueCallback:function(t){return t+1}}),month:Pn({matchPatterns:PN,defaultMatchWidth:"wide",parsePatterns:IN,defaultParseWidth:"any"}),day:Pn({matchPatterns:RN,defaultMatchWidth:"wide",parsePatterns:ON,defaultParseWidth:"any"}),dayPeriod:Pn({matchPatterns:DN,defaultMatchWidth:"wide",parsePatterns:LN,defaultParseWidth:"any"})},vv={code:"ru",formatDistance:oN,formatLong:uN,formatRelative:hN,localize:bN,match:MN,options:{weekStartsOn:1,firstWeekContainsDate:1}};const ju=e=>BE(e.replace(" ","T")+"Z"),Ch=e=>{const t=String(e.getDate()).padStart(2,"0"),n=String(e.getMonth()+1).padStart(2,"0"),r=e.getFullYear(),s=String(e.getHours()).padStart(2,"0"),i=String(e.getMinutes()).padStart(2,"0");return`${t}.${n}.${r} ${s}:${i}`.substring(0,16)},AN=e=>mi(e,"dd.MM.yyyy",{locale:vv}),Eh=e=>{const t=ju(e);return AN(t)},wv=({notes:e=[]})=>{const[t,n]=S.useState(new Date),r=oe(m=>m.notes.selectedDate),s=wt(),i=FC(t),o=AC(t),a=RC(i,{weekStartsOn:1}),l=zC(o,{weekStartsOn:1}),c=$C({start:a,end:l}),d=new Set,f=new Set;e.forEach(m=>{m.created_at&&d.add(Eh(m.created_at)),m.updated_at&&m.created_at!==m.updated_at&&f.add(Eh(m.updated_at))});const p=m=>{const h=mi(m,"dd.MM.yyyy");s(mu(r===h?null:h))},v=()=>{n(sN(t,1))},g=()=>{n(uv(t,1))},y=mi(t,"MMMM yyyy",{locale:vv}),x=y.charAt(0).toUpperCase()+y.slice(1);return u.jsxs("div",{className:"mini-calendar",children:[u.jsxs("div",{className:"calendar-header",children:[u.jsx("button",{className:"calendar-nav",onClick:v,children:"‹"}),u.jsx("span",{className:"calendar-month-year",children:x}),u.jsx("button",{className:"calendar-nav",onClick:g,children:"›"})]}),u.jsxs("div",{className:"calendar-weekdays",children:[u.jsx("div",{className:"calendar-weekday",children:"Пн"}),u.jsx("div",{className:"calendar-weekday",children:"Вт"}),u.jsx("div",{className:"calendar-weekday",children:"Ср"}),u.jsx("div",{className:"calendar-weekday",children:"Чт"}),u.jsx("div",{className:"calendar-weekday",children:"Пт"}),u.jsx("div",{className:"calendar-weekday",children:"Сб"}),u.jsx("div",{className:"calendar-weekday",children:"Вс"})]}),u.jsx("div",{className:"calendar-days",children:c.map((m,h)=>{const w=mi(m,"dd.MM.yyyy"),C=UE(m,t),T=r===w,b=d.has(w),N=f.has(w),P=DC(m,new Date);return u.jsx("div",{className:`calendar-day ${C?"":"other-month"} ${b?"has-notes":""} ${N?"has-edited-notes":""} ${T?"selected":""} ${P?"today":""}`,"data-date":w,onClick:()=>p(m),children:mi(m,"d")},h)})})]})},xv=()=>{const[e,t]=S.useState(""),n=wt(),r=S.useRef(null);S.useEffect(()=>(r.current&&clearTimeout(r.current),r.current=setTimeout(()=>{n(gu(e))},300),()=>{r.current&&clearTimeout(r.current)}),[e,n]);const s=()=>{t(""),n(gu(""))};return u.jsxs("div",{className:"search-section",children:[u.jsx("div",{className:"search-header",children:u.jsxs("span",{className:"search-title",children:[u.jsx(M,{icon:"mdi:magnify"})," Поиск"]})}),u.jsxs("div",{className:"search-container",children:[u.jsx("input",{type:"text",className:"search-input",placeholder:"Поиск по заметкам...",value:e,onChange:i=>t(i.target.value)}),e&&u.jsx("button",{className:"clear-search-btn",onClick:s,title:"Очистить поиск",children:"✕"})]})]})};function Jd(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Xr=Jd();function Sv(e){Xr=e}var Ti={exec:()=>null};function ye(e,t=""){let n=typeof e=="string"?e:e.source,r={replace:(s,i)=>{let o=typeof i=="string"?i:i.source;return o=o.replace(Nt.caret,"$1"),n=n.replace(s,o),r},getRegex:()=>new RegExp(n,t)};return r}var Nt={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceTabs:/^\t+/,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] /,listReplaceTask:/^\[[ xX]\] +/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,unescapeTest:/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>new RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}#`),htmlBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}<(?:[a-z].*>|!--)`,"i")},$N=/^(?:[ \t]*(?:\n|$))+/,FN=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,zN=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,mo=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,UN=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Zd=/(?:[*+-]|\d{1,9}[.)])/,kv=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,bv=ye(kv).replace(/bull/g,Zd).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),BN=ye(kv).replace(/bull/g,Zd).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),ef=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,WN=/^[^\n]+/,tf=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,HN=ye(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",tf).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),QN=ye(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,Zd).getRegex(),kl="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",nf=/|$))/,VN=ye("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|\\n*|$)|\\n*|$)|)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",nf).replace("tag",kl).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Cv=ye(ef).replace("hr",mo).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",kl).getRegex(),qN=ye(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Cv).getRegex(),rf={blockquote:qN,code:FN,def:HN,fences:zN,heading:UN,hr:mo,html:VN,lheading:bv,list:QN,newline:$N,paragraph:Cv,table:Ti,text:WN},Nh=ye("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",mo).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",kl).getRegex(),GN={...rf,lheading:BN,table:Nh,paragraph:ye(ef).replace("hr",mo).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Nh).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",kl).getRegex()},YN={...rf,html:ye(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+? *(?:\\n{2,}|\\s*$)|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",nf).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:Ti,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:ye(ef).replace("hr",mo).replace("heading",` *#{1,6} *[^ ]`).replace("lheading",bv).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},KN=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,XN=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Ev=/^( {2,}|\\)\n(?!\s*$)/,JN=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\`+)[^`]+\\k(?!`))*?\\]\\((?:\\\\[\\s\\S]|[^\\\\\\(\\)]|\\((?:\\\\[\\s\\S]|[^\\\\\\(\\)])*\\))*\\)")).replace("code",new RegExp("(?`+)[^`]+\\k(?!`)")).replace("html",/<(?! )[^<>]*?>/).getRegex(),Tv=/^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/,r_=ye(Tv,"u").replace(/punct/g,bl).getRegex(),s_=ye(Tv,"u").replace(/punct/g,_v).getRegex(),jv="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",i_=ye(jv,"gu").replace(/notPunctSpace/g,Nv).replace(/punctSpace/g,sf).replace(/punct/g,bl).getRegex(),o_=ye(jv,"gu").replace(/notPunctSpace/g,t_).replace(/punctSpace/g,e_).replace(/punct/g,_v).getRegex(),a_=ye("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,Nv).replace(/punctSpace/g,sf).replace(/punct/g,bl).getRegex(),l_=ye(/\\(punct)/,"gu").replace(/punct/g,bl).getRegex(),c_=ye(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),u_=ye(nf).replace("(?:-->|$)","-->").getRegex(),d_=ye("^comment|^|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^|^").replace("comment",u_).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Qa=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+[^`]*?`+(?!`)|[^\[\]\\`])*?/,f_=ye(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]*(?:\n[ \t]*)?)(title))?\s*\)/).replace("label",Qa).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Pv=ye(/^!?\[(label)\]\[(ref)\]/).replace("label",Qa).replace("ref",tf).getRegex(),Iv=ye(/^!?\[(ref)\](?:\[\])?/).replace("ref",tf).getRegex(),p_=ye("reflink|nolink(?!\\()","g").replace("reflink",Pv).replace("nolink",Iv).getRegex(),_h=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,of={_backpedal:Ti,anyPunctuation:l_,autolink:c_,blockSkip:n_,br:Ev,code:XN,del:Ti,emStrongLDelim:r_,emStrongRDelimAst:i_,emStrongRDelimUnd:a_,escape:KN,link:f_,nolink:Iv,punctuation:ZN,reflink:Pv,reflinkSearch:p_,tag:d_,text:JN,url:Ti},h_={...of,link:ye(/^!?\[(label)\]\((.*?)\)/).replace("label",Qa).getRegex(),reflink:ye(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Qa).getRegex()},Pu={...of,emStrongRDelimAst:o_,emStrongLDelim:s_,url:ye(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",_h).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:ye(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\":">",'"':""","'":"'"},Th=e=>g_[e];function Nn(e,t){if(t){if(Nt.escapeTest.test(e))return e.replace(Nt.escapeReplace,Th)}else if(Nt.escapeTestNoEncode.test(e))return e.replace(Nt.escapeReplaceNoEncode,Th);return e}function jh(e){try{e=encodeURI(e).replace(Nt.percentDecode,"%")}catch{return null}return e}function Ph(e,t){var i;let n=e.replace(Nt.findPipe,(o,a,l)=>{let c=!1,d=a;for(;--d>=0&&l[d]==="\\";)c=!c;return c?"|":" |"}),r=n.split(Nt.splitPipe),s=0;if(r[0].trim()||r.shift(),r.length>0&&!((i=r.at(-1))!=null&&i.trim())&&r.pop(),t)if(r.length>t)r.splice(t);else for(;r.length0?-2:-1}function Ih(e,t,n,r,s){let i=t.href,o=t.title||null,a=e[1].replace(s.other.outputLinkReplace,"$1");r.state.inLink=!0;let l={type:e[0].charAt(0)==="!"?"image":"link",raw:n,href:i,title:o,text:a,tokens:r.inlineTokens(a)};return r.state.inLink=!1,l}function v_(e,t,n){let r=e.match(n.other.indentCodeCompensation);if(r===null)return t;let s=r[1];return t.split(` `).map(i=>{let o=i.match(n.other.beginningSpace);if(o===null)return i;let[a]=o;return a.length>=s.length?i.slice(s.length):i}).join(` `)}var Va=class{constructor(e){de(this,"options");de(this,"rules");de(this,"lexer");this.options=e||Xr}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let n=t[0].replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:t[0],codeBlockStyle:"indented",text:this.options.pedantic?n:ci(n,` `)}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let n=t[0],r=v_(n,t[3]||"",this.rules);return{type:"code",raw:n,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:r}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let n=t[2].trim();if(this.rules.other.endingHash.test(n)){let r=ci(n,"#");(this.options.pedantic||!r||this.rules.other.endingSpaceChar.test(r))&&(n=r.trim())}return{type:"heading",raw:t[0],depth:t[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:ci(t[0],` `)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let n=ci(t[0],` `).split(` `),r="",s="",i=[];for(;n.length>0;){let o=!1,a=[],l;for(l=0;l1,s={type:"list",raw:"",ordered:r,start:r?+n.slice(0,-1):"",loose:!1,items:[]};n=r?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=r?n:"[*+-]");let i=this.rules.other.listItemRegex(n),o=!1;for(;e;){let l=!1,c="",d="";if(!(t=i.exec(e))||this.rules.block.hr.test(e))break;c=t[0],e=e.substring(c.length);let f=t[2].split(` `,1)[0].replace(this.rules.other.listReplaceTabs,m=>" ".repeat(3*m.length)),p=e.split(` `,1)[0],v=!f.trim(),g=0;if(this.options.pedantic?(g=2,d=f.trimStart()):v?g=t[1].length+1:(g=t[2].search(this.rules.other.nonSpaceChar),g=g>4?1:g,d=f.slice(g),g+=t[1].length),v&&this.rules.other.blankLine.test(p)&&(c+=p+` `,e=e.substring(p.length+1),l=!0),!l){let m=this.rules.other.nextBulletRegex(g),h=this.rules.other.hrRegex(g),w=this.rules.other.fencesBeginRegex(g),C=this.rules.other.headingBeginRegex(g),T=this.rules.other.htmlBeginRegex(g);for(;e;){let b=e.split(` `,1)[0],N;if(p=b,this.options.pedantic?(p=p.replace(this.rules.other.listReplaceNesting," "),N=p):N=p.replace(this.rules.other.tabCharGlobal," "),w.test(p)||C.test(p)||T.test(p)||m.test(p)||h.test(p))break;if(N.search(this.rules.other.nonSpaceChar)>=g||!p.trim())d+=` `+N.slice(g);else{if(v||f.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||w.test(f)||C.test(f)||h.test(f))break;d+=` `+p}!v&&!p.trim()&&(v=!0),c+=b+` `,e=e.substring(b.length+1),f=N.slice(g)}}s.loose||(o?s.loose=!0:this.rules.other.doubleBlankLine.test(c)&&(o=!0));let y=null,x;this.options.gfm&&(y=this.rules.other.listIsTask.exec(d),y&&(x=y[0]!=="[ ] ",d=d.replace(this.rules.other.listReplaceTask,""))),s.items.push({type:"list_item",raw:c,task:!!y,checked:x,loose:!1,text:d,tokens:[]}),s.raw+=c}let a=s.items.at(-1);if(a)a.raw=a.raw.trimEnd(),a.text=a.text.trimEnd();else return;s.raw=s.raw.trimEnd();for(let l=0;lf.type==="space"),d=c.length>0&&c.some(f=>this.rules.other.anyLine.test(f.raw));s.loose=d}if(s.loose)for(let l=0;l({text:l,tokens:this.lexer.inline(l),header:!1,align:i.align[c]})));return i}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t)return{type:"heading",raw:t[0],depth:t[2].charAt(0)==="="?1:2,text:t[1],tokens:this.lexer.inline(t[1])}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let n=t[1].charAt(t[1].length-1)===` `?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:n,tokens:this.lexer.inline(n)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let n=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(n)){if(!this.rules.other.endAngleBracket.test(n))return;let i=ci(n.slice(0,-1),"\\");if((n.length-i.length)%2===0)return}else{let i=y_(t[2],"()");if(i===-2)return;if(i>-1){let o=(t[0].indexOf("!")===0?5:4)+t[1].length+i;t[2]=t[2].substring(0,i),t[0]=t[0].substring(0,o).trim(),t[3]=""}}let r=t[2],s="";if(this.options.pedantic){let i=this.rules.other.pedanticHrefTitle.exec(r);i&&(r=i[1],s=i[3])}else s=t[3]?t[3].slice(1,-1):"";return r=r.trim(),this.rules.other.startAngleBracket.test(r)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(n)?r=r.slice(1):r=r.slice(1,-1)),Ih(t,{href:r&&r.replace(this.rules.inline.anyPunctuation,"$1"),title:s&&s.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){let r=(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal," "),s=t[r.toLowerCase()];if(!s){let i=n[0].charAt(0);return{type:"text",raw:i,text:i}}return Ih(n,s,n[0],this.lexer,this.rules)}}emStrong(e,t,n=""){let r=this.rules.inline.emStrongLDelim.exec(e);if(!(!r||r[3]&&n.match(this.rules.other.unicodeAlphaNumeric))&&(!(r[1]||r[2])||!n||this.rules.inline.punctuation.exec(n))){let s=[...r[0]].length-1,i,o,a=s,l=0,c=r[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(c.lastIndex=0,t=t.slice(-1*e.length+s);(r=c.exec(t))!=null;){if(i=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!i)continue;if(o=[...i].length,r[3]||r[4]){a+=o;continue}else if((r[5]||r[6])&&s%3&&!((s+o)%3)){l+=o;continue}if(a-=o,a>0)continue;o=Math.min(o,o+a+l);let d=[...r[0]][0].length,f=e.slice(0,s+r.index+d+o);if(Math.min(s,o)%2){let v=f.slice(1,-1);return{type:"em",raw:f,text:v,tokens:this.lexer.inlineTokens(v)}}let p=f.slice(2,-2);return{type:"strong",raw:f,text:p,tokens:this.lexer.inlineTokens(p)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let n=t[2].replace(this.rules.other.newLineCharGlobal," "),r=this.rules.other.nonSpaceChar.test(n),s=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return r&&s&&(n=n.substring(1,n.length-1)),{type:"codespan",raw:t[0],text:n}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e){let t=this.rules.inline.del.exec(e);if(t)return{type:"del",raw:t[0],text:t[2],tokens:this.lexer.inlineTokens(t[2])}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let n,r;return t[2]==="@"?(n=t[1],r="mailto:"+n):(n=t[1],r=n),{type:"link",raw:t[0],text:n,href:r,tokens:[{type:"text",raw:n,text:n}]}}}url(e){var n;let t;if(t=this.rules.inline.url.exec(e)){let r,s;if(t[2]==="@")r=t[0],s="mailto:"+r;else{let i;do i=t[0],t[0]=((n=this.rules.inline._backpedal.exec(t[0]))==null?void 0:n[0])??"";while(i!==t[0]);r=t[0],t[1]==="www."?s="http://"+t[0]:s=t[0]}return{type:"link",raw:t[0],text:r,href:s,tokens:[{type:"text",raw:r,text:r}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let n=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:n}}}},mn=class Iu{constructor(t){de(this,"tokens");de(this,"options");de(this,"state");de(this,"tokenizer");de(this,"inlineQueue");this.tokens=[],this.tokens.links=Object.create(null),this.options=t||Xr,this.options.tokenizer=this.options.tokenizer||new Va,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let n={other:Nt,block:Bo.normal,inline:li.normal};this.options.pedantic?(n.block=Bo.pedantic,n.inline=li.pedantic):this.options.gfm&&(n.block=Bo.gfm,this.options.breaks?n.inline=li.breaks:n.inline=li.gfm),this.tokenizer.rules=n}static get rules(){return{block:Bo,inline:li}}static lex(t,n){return new Iu(n).lex(t)}static lexInline(t,n){return new Iu(n).inlineTokens(t)}lex(t){t=t.replace(Nt.carriageReturn,` `),this.blockTokens(t,this.tokens);for(let n=0;n(a=c.call({lexer:this},t,n))?(t=t.substring(a.raw.length),n.push(a),!0):!1))continue;if(a=this.tokenizer.space(t)){t=t.substring(a.raw.length);let c=n.at(-1);a.raw.length===1&&c!==void 0?c.raw+=` `:n.push(a);continue}if(a=this.tokenizer.code(t)){t=t.substring(a.raw.length);let c=n.at(-1);(c==null?void 0:c.type)==="paragraph"||(c==null?void 0:c.type)==="text"?(c.raw+=(c.raw.endsWith(` `)?"":` `)+a.raw,c.text+=` `+a.text,this.inlineQueue.at(-1).src=c.text):n.push(a);continue}if(a=this.tokenizer.fences(t)){t=t.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.heading(t)){t=t.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.hr(t)){t=t.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.blockquote(t)){t=t.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.list(t)){t=t.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.html(t)){t=t.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.def(t)){t=t.substring(a.raw.length);let c=n.at(-1);(c==null?void 0:c.type)==="paragraph"||(c==null?void 0:c.type)==="text"?(c.raw+=(c.raw.endsWith(` `)?"":` `)+a.raw,c.text+=` `+a.raw,this.inlineQueue.at(-1).src=c.text):this.tokens.links[a.tag]||(this.tokens.links[a.tag]={href:a.href,title:a.title},n.push(a));continue}if(a=this.tokenizer.table(t)){t=t.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.lheading(t)){t=t.substring(a.raw.length),n.push(a);continue}let l=t;if((o=this.options.extensions)!=null&&o.startBlock){let c=1/0,d=t.slice(1),f;this.options.extensions.startBlock.forEach(p=>{f=p.call({lexer:this},d),typeof f=="number"&&f>=0&&(c=Math.min(c,f))}),c<1/0&&c>=0&&(l=t.substring(0,c+1))}if(this.state.top&&(a=this.tokenizer.paragraph(l))){let c=n.at(-1);r&&(c==null?void 0:c.type)==="paragraph"?(c.raw+=(c.raw.endsWith(` `)?"":` `)+a.raw,c.text+=` `+a.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=c.text):n.push(a),r=l.length!==t.length,t=t.substring(a.raw.length);continue}if(a=this.tokenizer.text(t)){t=t.substring(a.raw.length);let c=n.at(-1);(c==null?void 0:c.type)==="text"?(c.raw+=(c.raw.endsWith(` `)?"":` `)+a.raw,c.text+=` `+a.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=c.text):n.push(a);continue}if(t){let c="Infinite loop on byte: "+t.charCodeAt(0);if(this.options.silent){console.error(c);break}else throw new Error(c)}}return this.state.top=!0,n}inline(t,n=[]){return this.inlineQueue.push({src:t,tokens:n}),n}inlineTokens(t,n=[]){var a,l,c,d,f;let r=t,s=null;if(this.tokens.links){let p=Object.keys(this.tokens.links);if(p.length>0)for(;(s=this.tokenizer.rules.inline.reflinkSearch.exec(r))!=null;)p.includes(s[0].slice(s[0].lastIndexOf("[")+1,-1))&&(r=r.slice(0,s.index)+"["+"a".repeat(s[0].length-2)+"]"+r.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(s=this.tokenizer.rules.inline.anyPunctuation.exec(r))!=null;)r=r.slice(0,s.index)+"++"+r.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);for(;(s=this.tokenizer.rules.inline.blockSkip.exec(r))!=null;)r=r.slice(0,s.index)+"["+"a".repeat(s[0].length-2)+"]"+r.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);r=((l=(a=this.options.hooks)==null?void 0:a.emStrongMask)==null?void 0:l.call({lexer:this},r))??r;let i=!1,o="";for(;t;){i||(o=""),i=!1;let p;if((d=(c=this.options.extensions)==null?void 0:c.inline)!=null&&d.some(g=>(p=g.call({lexer:this},t,n))?(t=t.substring(p.raw.length),n.push(p),!0):!1))continue;if(p=this.tokenizer.escape(t)){t=t.substring(p.raw.length),n.push(p);continue}if(p=this.tokenizer.tag(t)){t=t.substring(p.raw.length),n.push(p);continue}if(p=this.tokenizer.link(t)){t=t.substring(p.raw.length),n.push(p);continue}if(p=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(p.raw.length);let g=n.at(-1);p.type==="text"&&(g==null?void 0:g.type)==="text"?(g.raw+=p.raw,g.text+=p.text):n.push(p);continue}if(p=this.tokenizer.emStrong(t,r,o)){t=t.substring(p.raw.length),n.push(p);continue}if(p=this.tokenizer.codespan(t)){t=t.substring(p.raw.length),n.push(p);continue}if(p=this.tokenizer.br(t)){t=t.substring(p.raw.length),n.push(p);continue}if(p=this.tokenizer.del(t)){t=t.substring(p.raw.length),n.push(p);continue}if(p=this.tokenizer.autolink(t)){t=t.substring(p.raw.length),n.push(p);continue}if(!this.state.inLink&&(p=this.tokenizer.url(t))){t=t.substring(p.raw.length),n.push(p);continue}let v=t;if((f=this.options.extensions)!=null&&f.startInline){let g=1/0,y=t.slice(1),x;this.options.extensions.startInline.forEach(m=>{x=m.call({lexer:this},y),typeof x=="number"&&x>=0&&(g=Math.min(g,x))}),g<1/0&&g>=0&&(v=t.substring(0,g+1))}if(p=this.tokenizer.inlineText(v)){t=t.substring(p.raw.length),p.raw.slice(-1)!=="_"&&(o=p.raw.slice(-1)),i=!0;let g=n.at(-1);(g==null?void 0:g.type)==="text"?(g.raw+=p.raw,g.text+=p.text):n.push(p);continue}if(t){let g="Infinite loop on byte: "+t.charCodeAt(0);if(this.options.silent){console.error(g);break}else throw new Error(g)}}return n}},qa=class{constructor(e){de(this,"options");de(this,"parser");this.options=e||Xr}space(e){return""}code({text:e,lang:t,escaped:n}){var i;let r=(i=(t||"").match(Nt.notSpaceStart))==null?void 0:i[0],s=e.replace(Nt.endingNewline,"")+` `;return r?'
'+(n?s:Nn(s,!0))+`
`:"
"+(n?s:Nn(s,!0))+`
`}blockquote({tokens:e}){return`
${this.parser.parse(e)}
`}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`${this.parser.parseInline(e)} `}hr(e){return`
`}list(e){let t=e.ordered,n=e.start,r="";for(let o=0;o `+r+" `}listitem(e){var n;let t="";if(e.task){let r=this.checkbox({checked:!!e.checked});e.loose?((n=e.tokens[0])==null?void 0:n.type)==="paragraph"?(e.tokens[0].text=r+" "+e.tokens[0].text,e.tokens[0].tokens&&e.tokens[0].tokens.length>0&&e.tokens[0].tokens[0].type==="text"&&(e.tokens[0].tokens[0].text=r+" "+Nn(e.tokens[0].tokens[0].text),e.tokens[0].tokens[0].escaped=!0)):e.tokens.unshift({type:"text",raw:r+" ",text:r+" ",escaped:!0}):t+=r+" "}return t+=this.parser.parse(e.tokens,!!e.loose),`
  • ${t}
  • `}checkbox({checked:e}){return"'}paragraph({tokens:e}){return`

    ${this.parser.parseInline(e)}

    `}table(e){let t="",n="";for(let s=0;s${r}`),` `+t+` `+r+`
    `}tablerow({text:e}){return` ${e} `}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?"th":"td";return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+` `}strong({tokens:e}){return`${this.parser.parseInline(e)}`}em({tokens:e}){return`${this.parser.parseInline(e)}`}codespan({text:e}){return`${Nn(e,!0)}`}br(e){return"
    "}del({tokens:e}){return`${this.parser.parseInline(e)}`}link({href:e,title:t,tokens:n}){let r=this.parser.parseInline(n),s=jh(e);if(s===null)return r;e=s;let i='
    ",i}image({href:e,title:t,text:n,tokens:r}){r&&(n=this.parser.parseInline(r,this.parser.textRenderer));let s=jh(e);if(s===null)return Nn(n);e=s;let i=`${n}{let l=o[a].flat(1/0);n=n.concat(this.walkTokens(l,t))}):o.tokens&&(n=n.concat(this.walkTokens(o.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(n=>{let r={...n};if(r.async=this.defaults.async||r.async||!1,n.extensions&&(n.extensions.forEach(s=>{if(!s.name)throw new Error("extension name required");if("renderer"in s){let i=t.renderers[s.name];i?t.renderers[s.name]=function(...o){let a=s.renderer.apply(this,o);return a===!1&&(a=i.apply(this,o)),a}:t.renderers[s.name]=s.renderer}if("tokenizer"in s){if(!s.level||s.level!=="block"&&s.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let i=t[s.level];i?i.unshift(s.tokenizer):t[s.level]=[s.tokenizer],s.start&&(s.level==="block"?t.startBlock?t.startBlock.push(s.start):t.startBlock=[s.start]:s.level==="inline"&&(t.startInline?t.startInline.push(s.start):t.startInline=[s.start]))}"childTokens"in s&&s.childTokens&&(t.childTokens[s.name]=s.childTokens)}),r.extensions=t),n.renderer){let s=this.defaults.renderer||new qa(this.defaults);for(let i in n.renderer){if(!(i in s))throw new Error(`renderer '${i}' does not exist`);if(["options","parser"].includes(i))continue;let o=i,a=n.renderer[o],l=s[o];s[o]=(...c)=>{let d=a.apply(s,c);return d===!1&&(d=l.apply(s,c)),d||""}}r.renderer=s}if(n.tokenizer){let s=this.defaults.tokenizer||new Va(this.defaults);for(let i in n.tokenizer){if(!(i in s))throw new Error(`tokenizer '${i}' does not exist`);if(["options","rules","lexer"].includes(i))continue;let o=i,a=n.tokenizer[o],l=s[o];s[o]=(...c)=>{let d=a.apply(s,c);return d===!1&&(d=l.apply(s,c)),d}}r.tokenizer=s}if(n.hooks){let s=this.defaults.hooks||new gi;for(let i in n.hooks){if(!(i in s))throw new Error(`hook '${i}' does not exist`);if(["options","block"].includes(i))continue;let o=i,a=n.hooks[o],l=s[o];gi.passThroughHooks.has(i)?s[o]=c=>{if(this.defaults.async&&gi.passThroughHooksRespectAsync.has(i))return(async()=>{let f=await a.call(s,c);return l.call(s,f)})();let d=a.call(s,c);return l.call(s,d)}:s[o]=(...c)=>{if(this.defaults.async)return(async()=>{let f=await a.apply(s,c);return f===!1&&(f=await l.apply(s,c)),f})();let d=a.apply(s,c);return d===!1&&(d=l.apply(s,c)),d}}r.hooks=s}if(n.walkTokens){let s=this.defaults.walkTokens,i=n.walkTokens;r.walkTokens=function(o){let a=[];return a.push(i.call(this,o)),s&&(a=a.concat(s.call(this,o))),a}}this.defaults={...this.defaults,...r}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return mn.lex(e,t??this.defaults)}parser(e,t){return gn.parse(e,t??this.defaults)}parseMarkdown(e){return(t,n)=>{let r={...n},s={...this.defaults,...r},i=this.onError(!!s.silent,!!s.async);if(this.defaults.async===!0&&r.async===!1)return i(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof t>"u"||t===null)return i(new Error("marked(): input parameter is undefined or null"));if(typeof t!="string")return i(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));if(s.hooks&&(s.hooks.options=s,s.hooks.block=e),s.async)return(async()=>{let o=s.hooks?await s.hooks.preprocess(t):t,a=await(s.hooks?await s.hooks.provideLexer():e?mn.lex:mn.lexInline)(o,s),l=s.hooks?await s.hooks.processAllTokens(a):a;s.walkTokens&&await Promise.all(this.walkTokens(l,s.walkTokens));let c=await(s.hooks?await s.hooks.provideParser():e?gn.parse:gn.parseInline)(l,s);return s.hooks?await s.hooks.postprocess(c):c})().catch(i);try{s.hooks&&(t=s.hooks.preprocess(t));let o=(s.hooks?s.hooks.provideLexer():e?mn.lex:mn.lexInline)(t,s);s.hooks&&(o=s.hooks.processAllTokens(o)),s.walkTokens&&this.walkTokens(o,s.walkTokens);let a=(s.hooks?s.hooks.provideParser():e?gn.parse:gn.parseInline)(o,s);return s.hooks&&(a=s.hooks.postprocess(a)),a}catch(o){return i(o)}}}onError(e,t){return n=>{if(n.message+=` Please report this to https://github.com/markedjs/marked.`,e){let r="

    An error occurred:

    "+Nn(n.message+"",!0)+"
    ";return t?Promise.resolve(r):r}if(t)return Promise.reject(n);throw n}}},Gr=new w_;function we(e,t){return Gr.parse(e,t)}we.options=we.setOptions=function(e){return Gr.setOptions(e),we.defaults=Gr.defaults,Sv(we.defaults),we};we.getDefaults=Jd;we.defaults=Xr;we.use=function(...e){return Gr.use(...e),we.defaults=Gr.defaults,Sv(we.defaults),we};we.walkTokens=function(e,t){return Gr.walkTokens(e,t)};we.parseInline=Gr.parseInline;we.Parser=gn;we.parser=gn.parse;we.Renderer=qa;we.TextRenderer=af;we.Lexer=mn;we.lexer=mn.lex;we.Tokenizer=Va;we.Hooks=gi;we.parse=we;we.options;we.setOptions;we.use;we.walkTokens;we.parseInline;gn.parse;mn.lex;const x_={name:"spoiler",level:"inline",start(e){var t;return(t=e.match(/\|\|/))==null?void 0:t.index},tokenizer(e){const n=/^\|\|(.*?)\|\|/.exec(e);if(n)return{type:"spoiler",raw:n[0],text:n[1].trim()}},renderer(e){return`${e.text}`}};function ws(e,t){return e.map(n=>{if(t[n.type])return t[n.type](n);if(n.type==="text")return n.text||"";if(n.type==="strong")return`${ws(n.tokens||[],t)}`;if(n.type==="em")return`${ws(n.tokens||[],t)}`;if(n.type==="codespan")return`${n.text||""}`;if(n.type==="del")return`${ws(n.tokens||[],t)}`;if(n.type==="link"){if(t.link)return t.link(n);const r=n.href||"",s=n.title?` title="${n.title}"`:"",i=n.tokens&&n.tokens.length>0?ws(n.tokens,t):n.text||"";return`
    ${i}`}return n.type==="spoiler"?t.spoiler?t.spoiler(n):`${n.text||""}`:n.text||""}).join("")}const S_={link(e){const t=e.href,n=e.title;let r="";e.tokens&&e.tokens.length>0?r=ws(e.tokens,this):e.text&&(r=e.text);try{if(new URL(t,window.location.href).origin!==window.location.origin)return`${r}`}catch{}return`${r}`},listitem(e){const t=e.task,n=e.checked;let r="";return e.tokens&&e.tokens.length>0?r=ws(e.tokens,this):e.text&&(r=e.text),t?`
  • ${``} ${r}
  • `:`
  • ${r}
  • `}};we.use({extensions:[x_],gfm:!0,breaks:!0,renderer:S_});const lf=e=>we.parse(e),Rv=e=>{const t=/#([а-яё\w]+)/gi,n=[];let r;for(;(r=t.exec(e))!==null;){const s=r.index,i=e.substring(Math.max(0,s-100),s),o=e.substring(s+r[0].length,Math.min(e.length,s+r[0].length+100)),a=i.lastIndexOf("<"),l=i.lastIndexOf(">");if(a>l)continue;const c=Math.max(i.lastIndexOf('"'),i.lastIndexOf("'")),d=i.lastIndexOf("=");if(d>-1&&c>d&&Math.min(o.indexOf('"')!==-1?o.indexOf('"'):1/0,o.indexOf("'")!==-1?o.indexOf("'"):1/0)!==1/0)continue;const f=r[1];n.some(p=>p.toLowerCase()===f.toLowerCase())||n.push(f)}return n},k_=e=>{const t=/#([а-яё\w]+)/gi,n=[];let r;for(;(r=t.exec(e))!==null;)n.push({fullMatch:r[0],tag:r[1],index:r.index});let s=e;for(let i=n.length-1;i>=0;i--){const o=n[i],a=s.substring(0,o.index),l=s.substring(o.index+o.fullMatch.length),c=a.lastIndexOf("<"),d=a.lastIndexOf(">");if(c>d)continue;const f=a.substring(Math.max(0,o.index-100)),p=Math.max(f.lastIndexOf('"'),f.lastIndexOf("'")),v=f.lastIndexOf("=");if(v>-1&&p>v){const y=l.substring(0,Math.min(100,l.length));if(Math.min(y.indexOf('"')!==-1?y.indexOf('"'):1/0,y.indexOf("'")!==-1?y.indexOf("'"):1/0)!==1/0)continue}const g=`${o.fullMatch}`;s=a+g+l}return s},b_=(e,t)=>{if(!t.trim())return e;const n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=new RegExp(`(${n})`,"gi");return e.replace(r,'$1')},Ov=({notes:e=[]})=>{const t=oe(a=>a.notes.selectedTag),n=wt(),s=(()=>{const a={},l={};e.forEach(d=>{Rv(d.content).forEach(p=>{const v=p.toLowerCase();a[v]=(a[v]||0)+1,l[v]||(l[v]=p)})});const c={};return Object.keys(a).forEach(d=>{c[l[d]]=a[d]}),c})(),i=Object.keys(s).sort(),o=(a,l)=>{l.preventDefault();const c=a.toLowerCase();(t==null?void 0:t.toLowerCase())===c?n($a(null)):n($a(c)),l.currentTarget.blur()};return i.length===0?u.jsxs("div",{className:"tags-section",children:[u.jsx("div",{className:"tags-header",children:u.jsxs("span",{className:"tags-title",children:[u.jsx(M,{icon:"mdi:tag"})," Теги"]})}),u.jsx("div",{className:"tags-container",children:u.jsx("div",{style:{fontSize:"10px",color:"#999",textAlign:"center"},children:"Нет тегов"})})]}):u.jsxs("div",{className:"tags-section",children:[u.jsx("div",{className:"tags-header",children:u.jsxs("span",{className:"tags-title",children:[u.jsx(M,{icon:"mdi:tag"})," Теги"]})}),u.jsx("div",{className:"tags-container",children:i.map(a=>{const l=s[a],c=(t==null?void 0:t.toLowerCase())===a.toLowerCase();return u.jsxs("span",{className:`tag ${c?"active":""}`,"data-tag":a,onClick:d=>o(a,d),onTouchEnd:d=>{d.currentTarget.blur()},children:["#",a,u.jsx("span",{className:"tag-count",children:l})]},a)})})]})},C_=({notes:e})=>u.jsxs("div",{className:"container-leftside",children:[u.jsx(wv,{notes:e}),u.jsx(xv,{}),u.jsx(Ov,{notes:e})]}),E_=({isOpen:e,onClose:t})=>{const n=oe(r=>r.notes.allNotes);return u.jsxs(u.Fragment,{children:[u.jsx("div",{className:`mobile-sidebar-overlay ${e?"open":""}`,onClick:t}),u.jsxs("div",{className:`mobile-sidebar ${e?"open":""}`,children:[u.jsx("button",{className:"sidebar-close-btn",onClick:t,children:u.jsx(M,{icon:"mdi:close"})}),u.jsxs("div",{className:"sidebar-content",children:[u.jsx("div",{className:"mobile-calendar-section",children:u.jsx(wv,{notes:n})}),u.jsx("div",{className:"mobile-search-section",children:u.jsx(xv,{})}),u.jsx("div",{className:"mobile-tags-section",children:u.jsx(Ov,{notes:n})})]})]})]})},Dv=({onInsert:e,onImageClick:t,onFileClick:n,onPreviewToggle:r,isPreviewMode:s,onInsertColor:i})=>{const[o,a]=S.useState(!1),l=wt(),c=S.useRef(null),d=S.useRef(null),f=S.useRef(null),p=S.useRef(null),[v,g]=S.useState(!1),[y,x]=S.useState(0),[m,h]=S.useState(0),[w,C]=S.useState(null);S.useEffect(()=>{const I=Q=>{c.current&&!c.current.contains(Q.target)&&f.current&&!f.current.contains(Q.target)&&(a(!1),C(null))},O=()=>{if(d.current&&o){const Q=d.current.getBoundingClientRect();C({top:Q.bottom+window.scrollY+2,left:Q.left+window.scrollX})}};if(o){O();const Q=setTimeout(()=>{document.addEventListener("mousedown",I),window.addEventListener("resize",O),window.addEventListener("scroll",O)},100);return()=>{clearTimeout(Q),document.removeEventListener("mousedown",I),window.removeEventListener("resize",O),window.removeEventListener("scroll",O)}}else C(null)},[o]);const T=I=>{I.target.closest(".btnMarkdown")||p.current&&(g(!0),x(I.pageX-p.current.offsetLeft),h(p.current.scrollLeft))},b=I=>{if(!v||!p.current)return;I.preventDefault();const Q=(I.pageX-p.current.offsetLeft-y)*2;p.current.scrollLeft=m-Q},N=()=>{g(!1)};S.useEffect(()=>(v?(document.addEventListener("mousemove",b),document.addEventListener("mouseup",N)):(document.removeEventListener("mousemove",b),document.removeEventListener("mouseup",N)),()=>{document.removeEventListener("mousemove",b),document.removeEventListener("mouseup",N)}),[v]);const P=[];return u.jsxs("div",{className:"markdown-buttons",ref:p,onMouseDown:T,style:{cursor:v?"grabbing":p.current&&p.current.scrollWidth>p.current.clientWidth?"grab":"default"},children:[P.map(I=>u.jsx("button",{className:"btnMarkdown",onClick:()=>{I.action?I.action():e(I.before,I.after)},title:I.title,children:u.jsx(M,{icon:I.icon})},I.id)),u.jsxs("div",{className:"header-dropdown",ref:c,children:[u.jsxs("button",{ref:d,className:"btnMarkdown",onMouseDown:I=>{I.stopPropagation()},onClick:I=>{I.stopPropagation(),a(!o)},title:"Заголовок",children:[u.jsx(M,{icon:"mdi:format-header-pound"}),u.jsx(M,{icon:"mdi:menu-down",style:{fontSize:"10px",marginLeft:"-2px"}})]}),o&&w&&u.jsx("div",{ref:f,className:"header-dropdown-menu",style:{position:"fixed",top:`${w.top}px`,left:`${w.left}px`},children:[1,2,3,4,5].map(I=>u.jsxs("button",{onClick:O=>{O.stopPropagation(),e("#".repeat(I)+" ",""),a(!1),C(null)},children:["H",I]},I))})]}),u.jsx("button",{className:"btnMarkdown",onClick:()=>e("- ",""),title:"Список",children:u.jsx(M,{icon:"mdi:format-list-bulleted"})}),u.jsx("button",{className:"btnMarkdown",onClick:()=>e("1. ",""),title:"Нумерованный список",children:u.jsx(M,{icon:"mdi:format-list-numbered"})}),u.jsx("button",{className:"btnMarkdown",onClick:()=>e("**","**"),title:"Жирный",children:u.jsx(M,{icon:"mdi:format-bold"})}),u.jsx("button",{className:"btnMarkdown",onClick:()=>e("*","*"),title:"Курсив",children:u.jsx(M,{icon:"mdi:format-italic"})}),u.jsx("button",{className:"btnMarkdown",onClick:()=>e("~~","~~"),title:"Зачеркнутый",children:u.jsx(M,{icon:"mdi:format-strikethrough"})}),u.jsx("button",{className:"btnMarkdown",onClick:()=>i==null?void 0:i(),title:"Цвет текста",children:u.jsx(M,{icon:"mdi:palette"})}),u.jsx("button",{className:"btnMarkdown",onClick:()=>e("||","||"),title:"Скрытый текст",children:u.jsx(M,{icon:"mdi:eye-off"})}),u.jsx("button",{className:"btnMarkdown",onClick:()=>e("> ",""),title:"Цитата",children:u.jsx(M,{icon:"mdi:format-quote-close"})}),u.jsx("button",{className:"btnMarkdown",onClick:()=>e("`","`"),title:"Код",children:u.jsx(M,{icon:"mdi:code-tags"})}),u.jsx("button",{className:"btnMarkdown",onClick:()=>e("[текст ссылки](",")"),title:"Ссылка",children:u.jsx(M,{icon:"mdi:link"})}),u.jsx("button",{className:"btnMarkdown",onClick:()=>e("- [ ] ",""),title:"To-Do список",children:u.jsx(M,{icon:"mdi:checkbox-marked-outline"})}),u.jsx("button",{className:"btnMarkdown",onClick:()=>t==null?void 0:t(),title:"Загрузить изображения",children:u.jsx(M,{icon:"mdi:image-plus"})}),u.jsx("button",{className:"btnMarkdown",onClick:()=>n==null?void 0:n(),title:"Прикрепить файлы",children:u.jsx(M,{icon:"mdi:file-plus"})}),u.jsx("button",{className:`btnMarkdown ${s?"active":""}`,onClick:r||(()=>l($1())),title:"Предпросмотр",children:u.jsx(M,{icon:"mdi:monitor-eye"})})]})},Lv=({textareaRef:e,onFormat:t,visible:n,position:r,onHide:s,onInsertColor:i,activeFormats:o={},hasSelection:a=!1})=>{const l=S.useRef(null),[c,d]=S.useState(!1),[f,p]=S.useState(0),[v,g]=S.useState(0);S.useEffect(()=>{n&&l.current&&setTimeout(()=>{if(!l.current)return;const b=l.current,N=b.getBoundingClientRect(),P=window.innerWidth,I=window.innerHeight,O=10,Q=8,ue=b.querySelector(".floating-toolbar"),ne=ue?ue.scrollWidth:N.width,J=P-O*2,$=N.height,L=r.selectionTop??r.top,Z=r.selectionBottom??r.top+20,F=L-O,Y=I-Z-O;let V;F>=$+Q?V=L-$-Q:Y>=$+Q?V=Z+Q:F>Y?V=Math.max(O,L-$-Q):V=Math.min(I-$-O,Z+Q);let E=r.left-ne/2;ne>J?(b.style.maxWidth=`${J}px`,E=O):(E+ne>P-O&&(E=Math.max(O,P-ne-O)),EI-O&&(V=I-$-O),b.style.top=`${V}px`,b.style.left=`${E}px`},0)},[n,r]);const y=b=>{b.target.closest(".floating-toolbar-btn")||l.current&&(d(!0),p(b.pageX-l.current.offsetLeft),g(l.current.scrollLeft))},x=b=>{if(!c||!l.current)return;b.preventDefault();const P=(b.pageX-l.current.offsetLeft-f)*2;l.current.scrollLeft=v-P},m=()=>{d(!1)};S.useEffect(()=>(c?(document.addEventListener("mousemove",x),document.addEventListener("mouseup",m)):(document.removeEventListener("mousemove",x),document.removeEventListener("mouseup",m)),()=>{document.removeEventListener("mousemove",x),document.removeEventListener("mouseup",m)}),[c]);const h=(b,N)=>{t(b,N),setTimeout(()=>{if(e.current){e.current.focus();const P=e.current.selectionStart,I=e.current.selectionEnd;P!==I&&e.current.setSelectionRange(P,I)}},0)},w=async()=>{const b=e.current;if(!b)return;const N=b.selectionStart,P=b.selectionEnd;if(N===P)return;const I=b.value.substring(N,P);try{await navigator.clipboard.writeText(I)}catch{const Q=document.createElement("textarea");Q.value=I,Q.style.position="fixed",Q.style.left="-999999px",document.body.appendChild(Q),Q.select(),document.execCommand("copy"),document.body.removeChild(Q)}},C=async()=>{var ue;const b=e.current;if(!b)return;const N=b.selectionStart,P=b.selectionEnd;if(N===P)return;const I=b.value.substring(N,P);try{await navigator.clipboard.writeText(I)}catch{const J=document.createElement("textarea");J.value=I,J.style.position="fixed",J.style.left="-999999px",document.body.appendChild(J),J.select(),document.execCommand("copy"),document.body.removeChild(J)}const O=b.value.substring(0,N)+b.value.substring(P),Q=(ue=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value"))==null?void 0:ue.set;if(Q){Q.call(b,O);const ne=new Event("input",{bubbles:!0});b.dispatchEvent(ne)}else{b.value=O;const ne=new Event("input",{bubbles:!0});b.dispatchEvent(ne)}b.setSelectionRange(N,N),b.focus()},T=async()=>{var I;const b=e.current;if(!b)return;const N=b.selectionStart,P=b.selectionEnd;try{const O=await navigator.clipboard.readText(),Q=b.value.substring(0,N)+O+b.value.substring(P),ue=(I=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value"))==null?void 0:I.set;if(ue){ue.call(b,Q);const J=new Event("input",{bubbles:!0});b.dispatchEvent(J)}else{b.value=Q;const J=new Event("input",{bubbles:!0});b.dispatchEvent(J)}const ne=N+O.length;b.setSelectionRange(ne,ne),b.focus()}catch{b.focus(),document.execCommand("paste")}};return!n||!a?null:u.jsx("div",{ref:l,className:"floating-toolbar-wrapper",style:{position:"fixed",top:`${r.top}px`,left:`${r.left}px`,zIndex:1e3,cursor:c?"grabbing":l.current&&l.current.scrollWidth>l.current.clientWidth?"grab":"default"},onMouseDown:b=>{b.preventDefault(),y(b)},onContextMenu:b=>{b.preventDefault()},children:u.jsxs("div",{className:"floating-toolbar",children:[u.jsx("button",{className:"floating-toolbar-btn",onClick:s,title:"Закрыть",children:u.jsx(M,{icon:"mdi:close"})}),a&&u.jsxs(u.Fragment,{children:[u.jsx("button",{className:"floating-toolbar-btn",onClick:w,title:"Копировать",children:u.jsx(M,{icon:"mdi:content-copy"})}),u.jsx("button",{className:"floating-toolbar-btn",onClick:C,title:"Вырезать",children:u.jsx(M,{icon:"mdi:content-cut"})}),u.jsx("button",{className:"floating-toolbar-btn",onClick:T,title:"Вставить",children:u.jsx(M,{icon:"mdi:content-paste"})})]}),a&&u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"floating-toolbar-separator"}),u.jsx("button",{className:`floating-toolbar-btn ${o.bold?"active":""}`,onClick:()=>h("**","**"),title:"Жирный",children:u.jsx(M,{icon:"mdi:format-bold"})}),u.jsx("button",{className:`floating-toolbar-btn ${o.italic?"active":""}`,onClick:()=>h("*","*"),title:"Курсив",children:u.jsx(M,{icon:"mdi:format-italic"})}),u.jsx("button",{className:`floating-toolbar-btn ${o.strikethrough?"active":""}`,onClick:()=>h("~~","~~"),title:"Зачеркнутый",children:u.jsx(M,{icon:"mdi:format-strikethrough"})}),u.jsx("div",{className:"floating-toolbar-separator"}),u.jsx("button",{className:"floating-toolbar-btn",onClick:()=>i==null?void 0:i(),title:"Цвет текста",children:u.jsx(M,{icon:"mdi:palette"})}),u.jsx("button",{className:"floating-toolbar-btn",onClick:()=>h("||","||"),title:"Скрытый текст",children:u.jsx(M,{icon:"mdi:eye-off"})})]})]})})},is={getAll:async()=>{const{data:e}=await K.get("/notes");return e},search:async e=>{const{data:t}=await K.get("/notes/search",{params:e});return t},create:async e=>{const{data:t}=await K.post("/notes",e);return t},update:async(e,t,n)=>{const{data:r}=await K.put(`/notes/${e}`,{content:t,skipTimestamp:n});return r},delete:async e=>{await K.delete(`/notes/${e}`)},pin:async e=>{const{data:t}=await K.put(`/notes/${e}/pin`);return t},archive:async e=>{const{data:t}=await K.put(`/notes/${e}/archive`);return t},unarchive:async e=>{const{data:t}=await K.put(`/notes/${e}/unarchive`);return t},uploadImages:async(e,t)=>{const n=new FormData;t.forEach(s=>n.append("images",s));const{data:r}=await K.post(`/notes/${e}/images`,n,{headers:{"Content-Type":"multipart/form-data"}});return r},uploadFiles:async(e,t)=>{const n=new FormData;t.forEach(s=>n.append("files",s));const{data:r}=await K.post(`/notes/${e}/files`,n,{headers:{"Content-Type":"multipart/form-data"}});return r},deleteImage:async(e,t)=>{await K.delete(`/notes/${e}/images/${t}`)},deleteFile:async(e,t)=>{await K.delete(`/notes/${e}/files/${t}`)},getArchived:async()=>{const{data:e}=await K.get("/notes/archived");return e},deleteArchived:async e=>{await K.delete(`/notes/archived/${e}`)},deleteAllArchived:async e=>{const{data:t}=await K.delete("/notes/archived/all",{data:{password:e}});return t},getDataVersion:async()=>{const{data:e}=await K.get("/notes/version");return e}},N_={getLogs:async e=>{const{data:t}=await K.get("/logs",{params:e});return t}},Mv=e=>{const t=S.useCallback(()=>{document.querySelectorAll(".spoiler").forEach(i=>{if(!i._clickHandler){const o=function(a){this.classList.contains("revealed")||(a.stopPropagation(),this.classList.add("revealed"))};i._clickHandler=o,i.addEventListener("click",o)}}),document.querySelectorAll(".external-link").forEach(i=>{if(!i._externalClickHandler){const o=function(a){(window.matchMedia("(display-mode: standalone)").matches||window.navigator.standalone===!0)&&(a.preventDefault(),window.open(this.href,"_blank","noopener,noreferrer"))};i._externalClickHandler=o,i.addEventListener("click",o)}}),document.querySelectorAll(".note-preview-content input[type='checkbox'], .textNote input[type='checkbox']").forEach(i=>{if(!i._checkboxHandler){const o=async function(){if(this.closest(".note-preview-content"))return;const a=this.closest("[data-note-id]");if(!a)return;const l=parseInt(a.getAttribute("data-note-id")||"0");if(!l)return;const c=a.querySelector(".textNote");if(!c)return;const d=c.getAttribute("data-original-content");if(d)try{const p=Array.from(c.querySelectorAll("input[type='checkbox']")).indexOf(this);if(p===-1)return;const v=d.split(` `);let g=0,y="";for(let x=0;x{const n=new MutationObserver(()=>{t()});return n.observe(document.body,{childList:!0,subtree:!0}),t(),()=>{n.disconnect()}},[t])},cf=({content:e})=>{Mv();const t=lf(e);return u.jsxs("div",{className:"note-preview-container",style:{display:"block"},children:[u.jsx("div",{className:"note-preview-header",children:u.jsx("span",{children:"Предпросмотр:"})}),u.jsx("div",{className:"note-preview-content",dangerouslySetInnerHTML:{__html:t}})]})},Av=({images:e,onChange:t})=>{const n=s=>{t(e.filter((i,o)=>o!==s))},r=()=>{t([])};return e.length===0?null:u.jsxs("div",{className:"image-preview-container",style:{display:"block"},children:[u.jsxs("div",{className:"image-preview-header",children:[u.jsx("span",{children:"Загруженные изображения:"}),u.jsx("button",{type:"button",className:"clear-images-btn",onClick:r,children:"Очистить все"})]}),u.jsx("div",{className:"image-preview-list",children:e.map((s,i)=>u.jsxs("div",{className:"image-preview-item",children:[u.jsx("img",{src:URL.createObjectURL(s),alt:`Preview ${i+1}`,className:"image-preview-thumbnail"}),u.jsx("button",{className:"image-preview-remove",onClick:()=>n(i),title:"Удалить",children:u.jsx(M,{icon:"mdi:close"})})]},i))})]})},$v=({files:e,onChange:t})=>{const n=o=>{t(e.filter((a,l)=>l!==o))},r=()=>{t([])},s=o=>{var l;const a=((l=o.split(".").pop())==null?void 0:l.toLowerCase())||"";return a==="pdf"?"mdi:file-pdf":["doc","docx"].includes(a)?"mdi:file-word":["xls","xlsx"].includes(a)?"mdi:file-excel":a==="txt"?"mdi:file-document":["zip","rar","7z"].includes(a)?"mdi:folder-zip":"mdi:file"},i=o=>(o/1024/1024).toFixed(2)+" MB";return e.length===0?null:u.jsxs("div",{className:"file-preview-container",style:{display:"block"},children:[u.jsxs("div",{className:"file-preview-header",children:[u.jsx("span",{children:"Прикрепленные файлы:"}),u.jsx("button",{type:"button",className:"clear-files-btn",onClick:r,children:"Очистить все"})]}),u.jsx("div",{className:"file-preview-list",children:e.map((o,a)=>u.jsxs("div",{className:"file-preview-item",children:[u.jsx(M,{icon:s(o.name),className:"file-icon"}),u.jsxs("div",{className:"file-info",children:[u.jsx("div",{className:"file-name",children:o.name}),u.jsx("div",{className:"file-size",children:i(o.size)})]}),u.jsx("button",{className:"file-preview-remove",onClick:()=>n(a),title:"Удалить",children:u.jsx(M,{icon:"mdi:close"})})]},a))})]})};let os=null;const __=5e3;async function bt(){const e=Date.now();if(os&&e-os.time<__)return os.status;try{const t=await Tu();return os={time:e,status:t},te.dispatch(Ns(!t)),t}catch{const n=navigator.onLine;return os={time:e,status:n},te.dispatch(Ns(!n)),n}}function Wo(){return te.getState().auth.userId}const Je={getAll:async()=>{const e=await bt(),t=Wo();if(!e)return console.log("[Offline] Loading notes from IndexedDB"),t?await D.getNotesByUserId(t):await D.getAllNotes();try{console.log("[Online] Loading notes from server");const{data:n}=await K.get("/notes"),r=n.map(s=>({...s,syncStatus:"synced"}));if(t){const s=await D.getNotesByUserId(t),i=new Set(r.map(o=>o.id));for(const o of s)typeof o.id=="string"&&o.id.startsWith("temp-")||i.has(o.id)||(console.log(`[OfflineAPI] Removing deleted note from IndexedDB: ${o.id}`),await D.deleteNote(o.id));await D.saveNotes(r)}return r}catch(n){return console.error("Error fetching notes from server, falling back to cache:",n),t?await D.getNotesByUserId(t):await D.getAllNotes()}},search:async e=>{const t=await bt(),n=Wo();if(!t){console.log("[Offline] Searching notes locally");const r=n?await D.getNotesByUserId(n):await D.getAllNotes();return Rh(r,e)}try{console.log("[Online] Searching notes on server");const{data:r}=await K.get("/notes/search",{params:e}),s=r.map(i=>({...i,syncStatus:"synced"}));return n&&await D.saveNotes(s),s}catch(r){console.error("Error searching notes, falling back to local:",r);const s=n?await D.getNotesByUserId(n):await D.getAllNotes();return Rh(s,e)}},create:async e=>{var r,s;const t=await bt(),n=Wo();if(!t){console.log("[Offline] Creating note locally");const i=zo(),o=new Date().toISOString(),a={...e,id:i,user_id:n||0,created_at:o,updated_at:o,is_pinned:0,is_archived:0,images:[],files:[],syncStatus:"pending"};return await D.saveNote(a),await D.addToSyncQueue({type:"create",noteId:i,data:e,timestamp:Date.now(),retries:0}),te.dispatch(rc(a)),await dn(),a}try{console.log("[Online] Creating note on server");const{data:i}=await K.post("/notes",e),o={...i,syncStatus:"synced"};return n&&await D.saveNote(o),te.dispatch(rc(o)),o}catch(i){if(!i.response&&(i.code==="ERR_NETWORK"||i.message==="Network Error"||((r=i.message)==null?void 0:r.includes("ERR_INTERNET_DISCONNECTED"))||((s=i.message)==null?void 0:s.includes("Failed to fetch")))){console.error("Network error creating note, falling back to local:",i),os={time:Date.now(),status:!1},te.dispatch(Ns(!0)),console.log("[Offline] Creating note locally after network error");const a=zo(),l=new Date().toISOString(),c={...e,id:a,user_id:n||0,created_at:l,updated_at:l,is_pinned:0,is_archived:0,images:[],files:[],syncStatus:"pending"};return await D.saveNote(c),await D.addToSyncQueue({type:"create",noteId:a,data:e,timestamp:Date.now(),retries:0}),te.dispatch(rc(c)),await dn(),c}else throw console.error("Error creating note (not a network error):",i),i}},update:async(e,t,n)=>{if(!await bt()){console.log("[Offline] Updating note locally");const s=await D.getNote(e);if(!s)throw new Error("Note not found");const i={...s,content:t,updated_at:new Date().toISOString(),syncStatus:"pending"};return await D.saveNote(i),await D.addToSyncQueue({type:"update",noteId:e,data:{content:t,skipTimestamp:n},timestamp:Date.now(),retries:0}),te.dispatch(Be(i)),await dn(),i}try{if(console.log("[Online] Updating note on server"),Er(e))throw new Error("Cannot update temp note online");const{data:s}=await K.put(`/notes/${e}`,{content:t,skipTimestamp:n}),i={...s,syncStatus:"synced"};return await D.saveNote(i),te.dispatch(Be(i)),i}catch(s){return console.error("Error updating note, falling back to local:",s),Je.update(e,t,n)}},delete:async e=>{if(!await bt()){console.log("[Offline] Queuing note for deletion"),await D.getNote(e)&&await D.addToSyncQueue({type:"delete",noteId:e,data:{},timestamp:Date.now(),retries:0}),await dn();return}try{if(console.log("[Online] Deleting note on server"),Er(e))throw new Error("Cannot delete temp note online");await K.delete(`/notes/${e}`),await D.deleteNote(e)}catch(n){console.error("Error deleting note, falling back to local:",n),await Je.delete(e)}},pin:async e=>{if(!await bt()){const n=await D.getNote(e);if(!n)throw new Error("Note not found");const r={...n,is_pinned:n.is_pinned===0?1:0,pinned_at:n.is_pinned===0?new Date().toISOString():void 0,updated_at:new Date().toISOString(),syncStatus:"pending"};return await D.saveNote(r),await D.addToSyncQueue({type:"update",noteId:e,data:{content:n.content,is_pinned:r.is_pinned},timestamp:Date.now(),retries:0}),te.dispatch(Be(r)),await dn(),r}try{if(Er(e))throw new Error("Cannot pin temp note online");const{data:n}=await K.put(`/notes/${e}/pin`),r=await D.getNote(e);if(!r)throw new Error("Note not found");const s={...r,is_pinned:n.is_pinned,pinned_at:n.is_pinned?new Date().toISOString():void 0,syncStatus:"synced"};return await D.saveNote(s),te.dispatch(Be(s)),s}catch(n){throw console.error("Error pinning note:",n),n}},archive:async e=>{if(!await bt()){const n=await D.getNote(e);if(!n)throw new Error("Note not found");const r={...n,is_archived:1,updated_at:new Date().toISOString(),syncStatus:"pending"};return await D.saveNote(r),await D.addToSyncQueue({type:"update",noteId:e,data:{content:n.content,is_archived:1},timestamp:Date.now(),retries:0}),te.dispatch(Be(r)),await dn(),r}try{if(Er(e))throw new Error("Cannot archive temp note online");await K.put(`/notes/${e}/archive`);const n=await D.getNote(e);if(!n)throw new Error("Note not found");const r={...n,is_archived:1,is_pinned:0,pinned_at:void 0,syncStatus:"synced"};return await D.saveNote(r),te.dispatch(Be(r)),r}catch(n){throw console.error("Error archiving note:",n),n}},unarchive:async e=>{if(!await bt()){const n=await D.getNote(e);if(!n)throw new Error("Note not found");const r={...n,is_archived:0,updated_at:new Date().toISOString(),syncStatus:"pending"};return await D.saveNote(r),await D.addToSyncQueue({type:"update",noteId:e,data:{content:n.content,is_archived:0},timestamp:Date.now(),retries:0}),te.dispatch(Be(r)),await dn(),r}try{if(Er(e))throw new Error("Cannot unarchive temp note online");await K.put(`/notes/${e}/unarchive`);const n=await D.getNote(e);if(!n)throw new Error("Note not found");const r={...n,is_archived:0,syncStatus:"synced"};return await D.saveNote(r),te.dispatch(Be(r)),r}catch(n){throw console.error("Error unarchiving note:",n),n}},uploadImages:async(e,t)=>{if(!await bt()){console.log("[Offline] Converting images to base64");const r=await D.getNote(e);if(!r)throw new Error("Note not found");const s=[];for(const o of t){const a=await hh(o),l={id:zo(),note_id:e,filename:o.name,original_name:o.name,file_path:"",file_size:o.size,mime_type:o.type,created_at:new Date().toISOString(),base64Data:a};s.push(l)}const i={...r,images:[...r.images,...s],syncStatus:"pending"};await D.saveNote(i);for(const o of s)await D.addToSyncQueue({type:"uploadImage",noteId:e,data:{imageId:o.id},timestamp:Date.now(),retries:0});return te.dispatch(Be(i)),await dn(),s}try{if(Er(e))throw new Error("Cannot upload images for temp note online");const r=new FormData;t.forEach(a=>r.append("images",a));const{data:s}=await K.post(`/notes/${e}/images`,r,{headers:{"Content-Type":"multipart/form-data"}}),i=Array.isArray(s)?s:(s==null?void 0:s.images)||[],o=await D.getNote(e);if(o){const a={...o,images:[...o.images||[],...i],syncStatus:"synced"};await D.saveNote(a),te.dispatch(Be(a))}return i}catch(r){throw console.error("Error uploading images:",r),r}},uploadFiles:async(e,t)=>{if(!await bt()){console.log("[Offline] Converting files to base64");const r=await D.getNote(e);if(!r)throw new Error("Note not found");const s=[];for(const o of t){const a=await hh(o),l={id:zo(),note_id:e,filename:o.name,original_name:o.name,file_path:"",file_size:o.size,mime_type:o.type,created_at:new Date().toISOString(),base64Data:a};s.push(l)}const i={...r,files:[...r.files,...s],syncStatus:"pending"};await D.saveNote(i);for(const o of s)await D.addToSyncQueue({type:"uploadFile",noteId:e,data:{fileId:o.id},timestamp:Date.now(),retries:0});return te.dispatch(Be(i)),await dn(),s}try{if(Er(e))throw new Error("Cannot upload files for temp note online");const r=new FormData;t.forEach(a=>r.append("files",a));const{data:s}=await K.post(`/notes/${e}/files`,r,{headers:{"Content-Type":"multipart/form-data"}}),i=Array.isArray(s)?s:(s==null?void 0:s.files)||[],o=await D.getNote(e);if(o){const a={...o,files:[...o.files||[],...i],syncStatus:"synced"};await D.saveNote(a),te.dispatch(Be(a))}return i}catch(r){throw console.error("Error uploading files:",r),r}},deleteImage:async(e,t)=>{if(!await bt()){const r=await D.getNote(e);if(r){const s={...r,images:r.images.filter(i=>i.id!==t),syncStatus:"pending"};await D.saveNote(s),te.dispatch(Be(s)),await dn()}return}try{await K.delete(`/notes/${e}/images/${t}`);const r=await D.getNote(e);if(r){const s={...r,images:r.images.filter(i=>i.id!==t),syncStatus:"synced"};await D.saveNote(s),te.dispatch(Be(s))}}catch(r){throw console.error("Error deleting image:",r),r}},deleteFile:async(e,t)=>{if(!await bt()){const r=await D.getNote(e);if(r){const s={...r,files:r.files.filter(i=>i.id!==t),syncStatus:"pending"};await D.saveNote(s),te.dispatch(Be(s)),await dn()}return}try{await K.delete(`/notes/${e}/files/${t}`);const r=await D.getNote(e);if(r){const s={...r,files:r.files.filter(i=>i.id!==t),syncStatus:"synced"};await D.saveNote(s),te.dispatch(Be(s))}}catch(r){throw console.error("Error deleting file:",r),r}},getArchived:async()=>{const e=await bt(),t=Wo();if(!e)return(t?await D.getNotesByUserId(t):await D.getAllNotes()).filter(r=>r.is_archived===1);try{const{data:n}=await K.get("/notes/archived");return n.map(s=>({...s,syncStatus:"synced"}))}catch(n){return console.error("Error fetching archived notes:",n),(t?await D.getNotesByUserId(t):await D.getAllNotes()).filter(s=>s.is_archived===1)}},deleteArchived:async e=>{if(!await bt()){await Je.delete(e);return}try{await K.delete(`/notes/archived/${e}`),await D.deleteNote(e)}catch(n){throw console.error("Error deleting archived note:",n),n}},deleteAllArchived:async e=>{if(!await bt())throw new Error("Cannot delete all archived in offline mode");try{const{data:n}=await K.delete("/notes/archived/all",{data:{password:e}});return n}catch(n){throw console.error("Error deleting all archived:",n),n}}};function Rh(e,t){let n=e;if(t.q){const r=t.q.toLowerCase();n=n.filter(s=>s.content.toLowerCase().includes(r))}if(t.tag){const r=t.tag.toLowerCase();n=n.filter(s=>T_(s.content).some(o=>o.toLowerCase()===r))}return t.date&&(n=n.filter(r=>r.date===t.date)),n}function T_(e){const t=/#(\w+)/g,n=[];let r;for(;(r=t.exec(e))!==null;)n.push(r[1]);return n}async function dn(){const e=await D.getPendingSyncCount();te.dispatch(Md(e))}const uf={improveText:async e=>{const{data:t}=await K.post("/ai/improve",{text:e});return t.improvedText},mergeNotes:async e=>{const{data:t}=await K.post("/ai/merge",{notes:e});return t.mergedText}},j_=({onSave:e})=>{const[t,n]=S.useState(""),[r,s]=S.useState([]),[i,o]=S.useState([]),[a,l]=S.useState(!1),[c,d]=S.useState(!1),[f,p]=S.useState({top:0,left:0}),[v,g]=S.useState(!1),[y,x]=S.useState({bold:!1,italic:!1,strikethrough:!1}),m=S.useRef(null),h=oe(E=>E.ui.isPreviewMode),{showNotification:w}=qn(),C=oe(E=>E.profile.aiEnabled),T=oe(E=>E.profile.user),b=(T==null?void 0:T.floating_toolbar_enabled)!==void 0?T.floating_toolbar_enabled===1:!0,N=async()=>{if(!t.trim()){w("Введите текст заметки","warning");return}try{const E=new Date,z=E.toLocaleDateString("ru-RU"),W=E.toLocaleTimeString("ru-RU",{hour:"2-digit",minute:"2-digit"}),U=await Je.create({content:t,date:z,time:W});r.length>0&&await Je.uploadImages(U.id,r),i.length>0&&await Je.uploadFiles(U.id,i),w("Заметка сохранена!","success"),n(""),s([]),o([]),e()}catch(E){console.error("Ошибка сохранения заметки:",E),w("Ошибка сохранения заметки","error")}},P=async()=>{if(!t.trim()){w("Введите текст для улучшения","warning");return}l(!0);try{const E=await uf.improveText(t);n(E),w("Текст улучшен!","success")}catch(E){console.error("Ошибка улучшения текста:",E),w("Ошибка улучшения текста","error")}finally{l(!1)}},I=S.useCallback(()=>{const E=m.current;if(!E)return{bold:!1,italic:!1,strikethrough:!1};const z=E.selectionStart,W=E.selectionEnd;if(z===W)return{bold:!1,italic:!1,strikethrough:!1};const U=t.substring(z,W),G={bold:!1,italic:!1,strikethrough:!1},X=10,ie=Math.max(0,z-X),Ie=Math.min(t.length,W+X),fe=t.substring(ie,Ie),se=z-ie,pe=fe.substring(0,se),he=fe.substring(se+U.length),Bt=(It,ln)=>{let ot=0;for(let tt=It.length-1;tt>=0&&It[tt]===ln;tt--)ot++;return ot},Me=(It,ln)=>{let ot=0;for(let tt=0;tt=4;(dt||Re)&&(G.strikethrough=!0);const $e=Bt(pe,"*"),Fe=Me(he,"*"),et=Me(U,"*"),xe=Bt(U,"*"),ft=$e>=2,Pt=Fe>=2,ze=et>=2&&xe>=2;(ft&&Pt||ze&&U.length>=4)&&(G.bold=!0);const Ce=$e===1||$e>=3&&$e%2===1,qe=Fe===1||Fe>=3&&Fe%2===1,Wt=et===1&&xe===1||et>=3&&xe>=3&&et%2===1&&xe%2===1;return Ce&&qe&&!G.bold?G.italic=!0:$e>=3&&Fe>=3?(G.italic=!0,G.bold=!0):(Wt&&U.length>=2||et===1&&xe===1&&U.length>=2&&!U.startsWith("**")&&!U.endsWith("**"))&&(G.italic=!0),G.bold&&($e>=3||Fe>=3||et>=3||xe>=3)&&(G.italic=!0),G},[t]),O=S.useCallback((E,z="")=>{const W=m.current;if(!W)return;const U=W.selectionStart,G=W.selectionEnd,X=t.substring(U,G),ie=E.length,Ie=Math.max(0,U-ie),fe=Math.min(t.length,G+ie),se=t.substring(Ie,fe),pe=U-Ie,he=se.substring(0,pe),Bt=se.substring(pe+X.length),Me=he.endsWith(E),be=Bt.startsWith(z),Ee=X.startsWith(E),dt=X.endsWith(z);let Re=!1;if(E==="*"&&z==="*"){const xe=U>1?t[U-2]:"",ft=G+1=2&&!X.startsWith("**")&&!X.endsWith("**");Re=Pt&&ze||Ce}else E==="**"&&z==="**"||E==="~~"&&z==="~~"?Re=Me&&be||Ee&&dt&&X.length>=4:Re=Me&&be||Ee&&dt&&X.length>=ie*2;let $e,Fe,et;if(Re)if(Me&&be)$e=t.substring(0,U-ie)+X+t.substring(G+ie),Fe=U-ie,et=G-ie;else{const xe=X.substring(ie,X.length-ie);$e=t.substring(0,U)+xe+t.substring(G),Fe=U,et=U+xe.length}else{const xe=/^[-*+]\s|^\d+\.\s|^- \[ \]\s|^>\s/.test(E),ft=X.includes(` `);if(xe&&ft){const Pt=X.split(` `);let ze=[],Ce=1,qe=!0;for(let It=0;It ")?ze.push(On+"> "+ot):ze.push(On+E+ot)}const Wt=ze.join(` `);$e=t.substring(0,U)+Wt+t.substring(G),Fe=U+E.length,et=U+Wt.length}else $e=t.substring(0,U)+E+X+z+t.substring(G),Fe=U+E.length,et=G+E.length}n($e),setTimeout(()=>{W.focus(),W.setSelectionRange(Fe,et);const xe=I();x(xe)},0)},[t,I]),Q=S.useCallback(()=>{const E=document.createElement("input");E.type="color",E.style.display="none",document.body.appendChild(E),E.addEventListener("change",function(){const z=this.value,W=m.current;if(!W)return;const U=W.selectionStart,G=W.selectionEnd,X=t.substring(U,G),ie=t.substring(0,U),Ie=t.substring(G);let fe;X.trim()===""?fe=`Текст`:fe=`${X}`;const se=ie+fe+Ie;n(se),setTimeout(()=>{W.focus();const pe=U+fe.length;W.setSelectionRange(pe,pe)},0),document.body.removeChild(this)}),E.addEventListener("cancel",function(){document.body.removeChild(this)}),E.click()},[t]),ue=E=>{if((E.altKey||E.ctrlKey)&&E.key==="Enter")E.preventDefault(),N();else if(E.key==="Enter"){const z=E.currentTarget,W=z.selectionStart,U=z.value,G=U.split(` `);let X=0,ie="";for(let pe=0;pe=W){ie=G[pe];break}X+=he+1}const Ie=[/^(\s*)- \[ \] /,/^(\s*)- \[x\] /i,/^(\s*)- /,/^(\s*)\* /,/^(\s*)\+ /,/^(\s*)(\d+)\. /,/^(\s*)(\w+)\. /,/^(\s*)1\. /];let fe=null,se=null;for(const pe of Ie){const he=ie.match(pe);if(he){fe=he,pe===Ie[0]||pe===Ie[1]?se="checkbox":pe===Ie[2]||pe===Ie[3]||pe===Ie[4]?se="unordered":pe===Ie[7]?se="numbered":se="ordered";break}}if(fe){E.preventDefault();const pe=fe[1]||"",he=fe[0].slice(pe.length);if(ie.slice(fe[0].length).trim()===""){const Me=U.substring(0,W),be=U.substring(W),Ee=Me.replace(/\n\s*- \[ \] \s*$|\n\s*- \[x\] \s*$|\n\s*[-*+]\s*$|\n\s*\d+\.\s*$|\n\s*\w+\.\s*$/i,` `),dt=Ee+be;n(dt),setTimeout(()=>{const Re=Ee.length;z.setSelectionRange(Re,Re)},0)}else{const Me=U.substring(0,W),be=U.substring(W);let Ee="";if(se==="checkbox")Ee=pe+"- [ ] ";else if(se==="unordered")Ee=pe+he;else if(se==="ordered"){const $e=parseInt(fe[2])+1,Fe=fe[2].replace(/\d+/,$e.toString());Ee=pe+Fe+". "}else se==="numbered"&&(Ee=pe+"1. ");const dt=Me+` `+Ee+be;n(dt),setTimeout(()=>{const Re=W+1+Ee.length;z.setSelectionRange(Re,Re)},0)}}}},ne=S.useCallback(()=>{const E=m.current;if(!E)return null;const z=E.selectionStart,W=E.selectionEnd,U=z!==W,G=E.getBoundingClientRect(),X=window.getComputedStyle(E),ie=parseInt(X.lineHeight)||20,Ie=parseInt(X.paddingTop)||0,fe=parseInt(X.paddingLeft)||0;parseInt(X.fontSize);const se=E.scrollTop,he=E.value.substring(0,z).split(` `),Bt=he.length-1,Me=he[Bt],be=document.createElement("span");be.style.position="absolute",be.style.visibility="hidden",be.style.whiteSpace="pre",be.style.font=X.font,document.body.appendChild(be),be.textContent=Me;const Ee=be.offsetWidth,Re=E.value.substring(0,W).split(` `),$e=Re.length-1,Fe=Re[$e];be.textContent=Fe;const et=be.offsetWidth;document.body.removeChild(be);const xe=G.top+Ie+Bt*ie-se,ft=G.top+Ie+$e*ie-se,Pt=G.left+fe+Ee,ze=G.left+fe+et;if(U){const Ce=Math.min(Pt,ze),qe=Math.max(Pt,ze),Wt=(Ce+qe)/2;return{top:(xe+ft)/2,left:Wt,hasSelection:U,selectionTop:Math.min(xe,ft),selectionBottom:Math.max(xe,ft)+ie,selectionLeft:Ce,selectionRight:qe}}else{const Ce=xe,qe=Pt;return{top:Ce,left:qe,hasSelection:U,selectionTop:Ce,selectionBottom:Ce+ie,selectionLeft:qe,selectionRight:qe}}},[]),J=S.useCallback(()=>{if(h||!b){d(!1);return}const E=t.trim().length>0,z=ne();if(z&&E)if(p({top:z.top,left:z.left}),g(z.hasSelection),d(!0),z.hasSelection){const W=I();x(W)}else x({bold:!1,italic:!1,strikethrough:!1});else d(!1),g(!1),x({bold:!1,italic:!1,strikethrough:!1})},[h,t,ne,I,b]);S.useEffect(()=>{const E=m.current;if(!E||h)return;const z=()=>{setTimeout(J,0)},W=X=>{X.buttons===1&&setTimeout(J,0)},U=()=>{setTimeout(J,0)},G=X=>{const ie=X.target;if(ie===E||E.contains(ie)){const Ie=E.value.trim().length>0,fe=E.selectionStart!==E.selectionEnd;Ie&&fe&&(X.preventDefault(),X.stopPropagation())}};return E.addEventListener("mouseup",z),E.addEventListener("mousemove",W),E.addEventListener("keyup",U),E.addEventListener("contextmenu",G),document.addEventListener("selectionchange",J),document.addEventListener("contextmenu",G,!0),()=>{E.removeEventListener("mouseup",z),E.removeEventListener("mousemove",W),E.removeEventListener("keyup",U),E.removeEventListener("contextmenu",G),document.removeEventListener("selectionchange",J),document.removeEventListener("contextmenu",G,!0)}},[h,J]),S.useEffect(()=>{const E=z=>{const W=m.current,U=z.target,G=document.querySelector(".floating-toolbar");G&&G.contains(U)||W&&!W.contains(U)&&setTimeout(()=>{W.selectionStart===W.selectionEnd&&d(!1)},0)};return document.addEventListener("mousedown",E),()=>{document.removeEventListener("mousedown",E)}},[]),S.useEffect(()=>{if(!c)return;const E=()=>{const W=ne();if(W&&(p({top:W.top,left:W.left}),g(W.hasSelection),W.hasSelection)){const U=I();x(U)}},z=m.current;return z&&(z.addEventListener("scroll",E),window.addEventListener("scroll",E,!0)),()=>{z&&z.removeEventListener("scroll",E),window.removeEventListener("scroll",E,!0)}},[c,ne,I]),xn.useEffect(()=>{const E=m.current;if(!E)return;const z=()=>{E.style.height="auto",E.style.height=E.scrollHeight+"px"};return E.addEventListener("input",z),z(),()=>{E.removeEventListener("input",z)}},[t]);const $=S.useRef(null),L=S.useRef(null),Z=()=>{var E;(E=$.current)==null||E.click()},F=()=>{var E;(E=L.current)==null||E.click()},Y=E=>{const W=Array.from(E.target.files||[]).filter(U=>U.type.startsWith("image/")&&U.size<=10*1024*1024);if(W.length+r.length>10){w("Можно загрузить максимум 10 изображений","warning");return}s([...r,...W]),$.current&&($.current.value="")},V=E=>{const z=Array.from(E.target.files||[]),W=/pdf|doc|docx|xls|xlsx|txt|zip|rar|7z/,U=["application/pdf","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","text/plain","application/zip","application/x-zip-compressed","application/x-rar-compressed","application/x-7z-compressed"],G=z.filter(X=>{var ie;return(U.includes(X.type)||W.test(((ie=X.name.split(".").pop())==null?void 0:ie.toLowerCase())||""))&&X.size<=50*1024*1024});o([...i,...G]),L.current&&(L.current.value="")};return u.jsxs("div",{className:"main",children:[u.jsx(Dv,{onInsert:O,onImageClick:Z,onFileClick:F,onInsertColor:Q}),u.jsx("input",{ref:$,type:"file",id:"imageInput",accept:"image/*",multiple:!0,style:{display:"none"},onChange:Y}),u.jsx("input",{ref:L,type:"file",id:"fileInput",accept:".pdf,.doc,.docx,.xls,.xlsx,.txt,.zip,.rar,.7z",multiple:!0,style:{display:"none"},onChange:V}),!h&&u.jsxs(u.Fragment,{children:[u.jsx("textarea",{ref:m,className:"textInput",id:"noteInput",placeholder:"Ваша заметка...",value:t,onChange:E=>n(E.target.value),onKeyDown:ue,onContextMenu:E=>{const z=m.current;if(z){const W=z.value.trim().length>0,U=z.selectionStart!==z.selectionEnd;W&&U&&E.preventDefault()}}}),b&&u.jsx(Lv,{textareaRef:m,onFormat:O,visible:c,position:f,onHide:()=>d(!1),onInsertColor:Q,activeFormats:y,hasSelection:v})]}),h&&u.jsx(cf,{content:t}),u.jsx(Av,{images:r,onChange:s}),u.jsx($v,{files:i,onChange:o}),u.jsxs("div",{className:"save-button-container",children:[u.jsxs("div",{className:"action-buttons",children:[C&&u.jsxs("button",{className:"btnSave btnAI",onClick:P,disabled:a,title:"Улучшить или создать текст через ИИ",children:[u.jsx(M,{icon:"mdi:robot"}),a?"Обработка...":"Помощь ИИ"]}),u.jsx("button",{className:"btnSave",onClick:N,children:"Сохранить"})]}),u.jsx("span",{className:"save-hint",children:"или нажмите Alt + Enter"})]})]})},to=({isOpen:e,onClose:t,onConfirm:n,title:r,message:s,confirmText:i="OK",cancelText:o="Отмена",confirmType:a="primary"})=>(S.useEffect(()=>{const l=c=>{c.key==="Escape"&&t()};return e&&document.addEventListener("keydown",l),()=>document.removeEventListener("keydown",l)},[e,t]),e?u.jsx("div",{className:"modal",style:{display:"block"},onClick:t,children:u.jsxs("div",{className:"modal-content",onClick:l=>l.stopPropagation(),children:[u.jsxs("div",{className:"modal-header",children:[u.jsx("h3",{children:r}),u.jsx("span",{className:"modal-close",onClick:t,children:"×"})]}),u.jsx("div",{className:"modal-body",children:typeof s=="string"?u.jsx("p",{children:s}):s}),u.jsxs("div",{className:"modal-footer",children:[u.jsx("button",{className:a==="danger"?"btn-danger":"btn-primary",onClick:n,style:{marginRight:"10px"},children:i}),u.jsx("button",{className:"btn-secondary",onClick:t,children:o})]})]})}):null);function uc(e,t,n){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/api")||e.startsWith("/uploads")?e:e.startsWith("/")?`/api${e}`:`/api/notes/${t}/images/${n}`}function P_(e,t,n){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/api")||e.startsWith("/uploads")?e:e.startsWith("/")?`/api${e}`:`/api/notes/${t}/files/${n}`}const I_=({note:e,onDelete:t,onPin:n,onArchive:r,onReload:s,isSelected:i=!1,onSelect:o})=>{const[a,l]=S.useState(!1),[c,d]=S.useState(e.content),[f,p]=S.useState(!1),[v,g]=S.useState([]),[y,x]=S.useState([]),[m,h]=S.useState([]),[w,C]=S.useState([]),[T,b]=S.useState(!1),[N,P]=S.useState(!1),[I,O]=S.useState({top:0,left:0}),[Q,ue]=S.useState(!1),[ne,J]=S.useState({bold:!1,italic:!1,strikethrough:!1}),[$,L]=S.useState(!1),[Z,F]=S.useState(!1),[Y,V]=S.useState(!1),E=S.useRef(null),z=S.useRef(null),W=S.useRef(null),U=S.useRef(null),G=S.useRef(!1),X=oe(k=>k.notes.searchQuery),ie=oe(k=>k.ui.isPreviewMode),Ie=oe(k=>k.profile.aiEnabled),fe=oe(k=>k.profile.user),{showNotification:se}=qn(),pe=wt();Mv({onNoteUpdate:s});const he=(fe==null?void 0:fe.floating_toolbar_enabled)!==void 0?fe.floating_toolbar_enabled===1:!0,Bt=()=>{l(!0),d(e.content),g([]),x([]),h([]),C([]),P(!1),J({bold:!1,italic:!1,strikethrough:!1}),L(!1),G.current=!0},Me=()=>{L(!$),P(!1)},be=async()=>{if(!c.trim()){se("Введите текст заметки","warning");return}try{await Je.update(e.id,c);for(const k of m)await Je.deleteImage(e.id,k);for(const k of w)await Je.deleteFile(e.id,k);v.length>0&&await Je.uploadImages(e.id,v),y.length>0&&await Je.uploadFiles(e.id,y),se("Заметка обновлена!","success"),l(!1),g([]),x([]),h([]),C([]),s()}catch(k){console.error("Ошибка обновления заметки:",k),se("Ошибка обновления заметки","error")}},Ee=()=>{l(!1),d(e.content),g([]),x([]),h([]),C([]),P(!1),J({bold:!1,italic:!1,strikethrough:!1}),L(!1)},dt=k=>{h([...m,k])},Re=k=>{C([...w,k])},$e=k=>{h(m.filter(R=>R!==k))},Fe=k=>{C(w.filter(R=>R!==k))},et=async()=>{if(!c.trim()){se("Введите текст для улучшения","warning");return}b(!0);try{const k=await uf.improveText(c);d(k),se("Текст улучшен!","success")}catch(k){console.error("Ошибка улучшения текста:",k),se("Ошибка улучшения текста","error")}finally{b(!1)}},xe=S.useCallback(()=>{const k=E.current;if(!k)return{bold:!1,italic:!1,strikethrough:!1};const R=k.selectionStart,B=k.selectionEnd;if(R===B)return{bold:!1,italic:!1,strikethrough:!1};const q=c.substring(R,B),ee={bold:!1,italic:!1,strikethrough:!1},le=10,ve=Math.max(0,R-le),nt=Math.min(c.length,B+le),Ue=c.substring(ve,nt),Ke=R-ve,me=Ue.substring(0,Ke),xt=Ue.substring(Ke+q.length),br=(Dn,Cr)=>{let Zt=0;for(let bn=Dn.length-1;bn>=0&&Dn[bn]===Cr;bn--)Zt++;return Zt},Rt=(Dn,Cr)=>{let Zt=0;for(let bn=0;bn=4;(Xt||pt)&&(ee.strikethrough=!0);const Ot=br(me,"*"),Dt=Rt(xt,"*"),Jt=Rt(q,"*"),St=br(q,"*"),Gs=Ot>=2,es=Dt>=2,cn=Jt>=2&&St>=2;(Gs&&es||cn&&q.length>=4)&&(ee.bold=!0);const Yn=Ot===1||Ot>=3&&Ot%2===1,ts=Dt===1||Dt>=3&&Dt%2===1,yo=Jt===1&&St===1||Jt>=3&&St>=3&&Jt%2===1&&St%2===1;return Yn&&ts&&!ee.bold?ee.italic=!0:Ot>=3&&Dt>=3?(ee.italic=!0,ee.bold=!0):(yo&&q.length>=2||Jt===1&&St===1&&q.length>=2&&!q.startsWith("**")&&!q.endsWith("**"))&&(ee.italic=!0),ee.bold&&(Ot>=3||Dt>=3||Jt>=3||St>=3)&&(ee.italic=!0),ee},[c]),ft=S.useCallback((k,R="")=>{const B=E.current;if(!B)return;const q=B.selectionStart,ee=B.selectionEnd,le=c.substring(q,ee),ve=k.length,nt=Math.max(0,q-ve),Ue=Math.min(c.length,ee+ve),Ke=c.substring(nt,Ue),me=q-nt,xt=Ke.substring(0,me),br=Ke.substring(me+le.length),Rt=xt.endsWith(k),Ge=br.startsWith(R),rt=le.startsWith(k),Xt=le.endsWith(R);let pt=!1;if(k==="*"&&R==="*"){const St=q>1?c[q-2]:"",Gs=ee+1=2&&!le.startsWith("**")&&!le.endsWith("**");pt=es&&cn||Yn}else k==="**"&&R==="**"||k==="~~"&&R==="~~"?pt=Rt&&Ge||rt&&Xt&&le.length>=4:pt=Rt&&Ge||rt&&Xt&&le.length>=ve*2;let Ot,Dt,Jt;if(pt)if(Rt&&Ge)Ot=c.substring(0,q-ve)+le+c.substring(ee+ve),Dt=q-ve,Jt=ee-ve;else{const St=le.substring(ve,le.length-ve);Ot=c.substring(0,q)+St+c.substring(ee),Dt=q,Jt=q+St.length}else{const St=/^[-*+]\s|^\d+\.\s|^- \[ \]\s|^>\s/.test(k),Gs=le.includes(` `);if(St&&Gs){const es=le.split(` `);let cn=[],Yn=1,ts=!0;for(let Dn=0;Dn ")?cn.push(Ys+"> "+Zt):cn.push(Ys+k+Zt)}const yo=cn.join(` `);Ot=c.substring(0,q)+yo+c.substring(ee),Dt=q+k.length,Jt=q+yo.length}else Ot=c.substring(0,q)+k+le+R+c.substring(ee),Dt=q+k.length,Jt=ee+k.length}d(Ot),setTimeout(()=>{B.focus(),B.setSelectionRange(Dt,Jt);const St=xe();J(St)},0)},[c,xe]),Pt=S.useCallback(()=>{const k=document.createElement("input");k.type="color",k.style.display="none",document.body.appendChild(k),k.addEventListener("change",function(){const R=this.value,B=E.current;if(!B)return;const q=B.selectionStart,ee=B.selectionEnd,le=c.substring(q,ee),ve=c.substring(0,q),nt=c.substring(ee);let Ue;le.trim()===""?Ue=`Текст`:Ue=`${le}`;const Ke=ve+Ue+nt;d(Ke),setTimeout(()=>{B.focus();const me=q+Ue.length;B.setSelectionRange(me,me)},0),document.body.removeChild(this)}),k.addEventListener("cancel",function(){document.body.removeChild(this)}),k.click()},[c]),ze=S.useCallback(()=>{const k=E.current;if(!k)return null;const R=k.selectionStart,B=k.selectionEnd,q=R!==B,ee=q?Math.floor((R+B)/2):R,ve=k.value.substring(0,ee).split(` `),nt=ve.length-1,Ue=ve[ve.length-1],Ke=k.getBoundingClientRect(),me=window.getComputedStyle(k),xt=parseInt(me.lineHeight)||20,br=parseInt(me.paddingTop)||0,Rt=parseInt(me.paddingLeft)||0;parseInt(me.fontSize);const Ge=document.createElement("span");Ge.style.position="absolute",Ge.style.visibility="hidden",Ge.style.whiteSpace="pre",Ge.style.font=me.font,Ge.textContent=Ue,document.body.appendChild(Ge);const rt=Ge.offsetWidth;document.body.removeChild(Ge);const Xt=Ke.top+br+nt*xt+xt/2,pt=Ke.left+Rt+rt;return{top:Xt,left:pt,hasSelection:q}},[]),Ce=S.useCallback(()=>{if($||!he){P(!1);return}const k=c.trim().length>0,R=ze();if(R&&k)if(O({top:R.top,left:R.left}),ue(R.hasSelection),P(!0),R.hasSelection){const B=xe();J(B)}else J({bold:!1,italic:!1,strikethrough:!1});else P(!1),ue(!1),J({bold:!1,italic:!1,strikethrough:!1})},[$,c,ze,xe,he]),qe=()=>{var k;(k=z.current)==null||k.click()},Wt=()=>{var k;(k=W.current)==null||k.click()},It=k=>{const B=Array.from(k.target.files||[]).filter(q=>q.type.startsWith("image/")&&q.size<=10*1024*1024);if(B.length+v.length>10){se("Можно загрузить максимум 10 изображений","warning");return}g([...v,...B]),z.current&&(z.current.value="")},ln=k=>{const R=Array.from(k.target.files||[]),B=/pdf|doc|docx|xls|xlsx|txt|zip|rar|7z/,q=["application/pdf","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","text/plain","application/zip","application/x-zip-compressed","application/x-rar-compressed","application/x-7z-compressed"],ee=R.filter(le=>{var ve;return(q.includes(le.type)||B.test(((ve=le.name.split(".").pop())==null?void 0:ve.toLowerCase())||""))&&le.size<=50*1024*1024});x([...y,...ee]),W.current&&(W.current.value="")},ot=k=>{if((k.altKey||k.ctrlKey)&&k.key==="Enter")k.preventDefault(),be();else if(k.key==="Escape")k.preventDefault(),Ee();else if(k.key==="Enter"){const R=k.currentTarget,B=R.selectionStart,q=R.value,ee=q.split(` `);let le=0,ve="";for(let me=0;me=B){ve=ee[me];break}le+=xt+1}const nt=[/^(\s*)- \[ \] /,/^(\s*)- \[x\] /i,/^(\s*)- /,/^(\s*)\* /,/^(\s*)\+ /,/^(\s*)(\d+)\. /,/^(\s*)(\w+)\. /,/^(\s*)1\. /];let Ue=null,Ke=null;for(const me of nt){const xt=ve.match(me);if(xt){Ue=xt,me===nt[0]||me===nt[1]?Ke="checkbox":me===nt[2]||me===nt[3]||me===nt[4]?Ke="unordered":me===nt[7]?Ke="numbered":Ke="ordered";break}}if(Ue){k.preventDefault();const me=Ue[1]||"",xt=Ue[0].slice(me.length);if(ve.slice(Ue[0].length).trim()===""){const Rt=q.substring(0,B),Ge=q.substring(B),rt=Rt.replace(/\n\s*- \[ \] \s*$|\n\s*- \[x\] \s*$|\n\s*[-*+]\s*$|\n\s*\d+\.\s*$|\n\s*\w+\.\s*$/i,` `),Xt=rt+Ge;d(Xt),setTimeout(()=>{const pt=rt.length;R.setSelectionRange(pt,pt)},0)}else{const Rt=q.substring(0,B),Ge=q.substring(B);let rt="";if(Ke==="checkbox")rt=me+"- [ ] ";else if(Ke==="unordered")rt=me+xt;else if(Ke==="ordered"){const Ot=parseInt(Ue[2])+1,Dt=Ue[2].replace(/\d+/,Ot.toString());rt=me+Dt+". "}else Ke==="numbered"&&(rt=me+"1. ");const Xt=Rt+` `+rt+Ge;d(Xt),setTimeout(()=>{const pt=B+1+rt.length;R.setSelectionRange(pt,pt)},0)}}}},tt=()=>{p(!0)};S.useEffect(()=>{if(!a)return;const k=E.current;if(!k)return;const R=()=>{k.style.height="auto",k.style.height=k.scrollHeight+"px"};return k.addEventListener("input",R),R(),()=>{k.removeEventListener("input",R)}},[a,c]),S.useEffect(()=>{a&&E.current&&!$&&setTimeout(()=>{const k=E.current;if(k&&(k.focus(),G.current)){const R=k.value.length;k.setSelectionRange(R,R),G.current=!1}},100)},[a,$]),S.useEffect(()=>{if(!a)return;const k=E.current;if(!k||$)return;const R=()=>{setTimeout(Ce,0)},B=le=>{le.buttons===1&&setTimeout(Ce,0)},q=()=>{setTimeout(Ce,0)},ee=le=>{const ve=le.target;if(ve===k||k.contains(ve)){const nt=k.value.trim().length>0,Ue=k.selectionStart!==k.selectionEnd;nt&&Ue&&(le.preventDefault(),le.stopPropagation())}};return k.addEventListener("mouseup",R),k.addEventListener("mousemove",B),k.addEventListener("keyup",q),k.addEventListener("contextmenu",ee),document.addEventListener("selectionchange",Ce),document.addEventListener("contextmenu",ee,!0),()=>{k.removeEventListener("mouseup",R),k.removeEventListener("mousemove",B),k.removeEventListener("keyup",q),k.removeEventListener("contextmenu",ee),document.removeEventListener("selectionchange",Ce),document.removeEventListener("contextmenu",ee,!0)}},[a,ie,Ce]),S.useEffect(()=>{if(!a)return;const k=R=>{const B=E.current,q=R.target,ee=document.querySelector(".floating-toolbar");ee&&ee.contains(q)||B&&!B.contains(q)&&setTimeout(()=>{B.selectionStart===B.selectionEnd&&P(!1)},0)};return document.addEventListener("mousedown",k),()=>{document.removeEventListener("mousedown",k)}},[a]),S.useEffect(()=>{if(!a||!N)return;const k=()=>{const B=ze();if(B&&(O({top:B.top,left:B.left}),ue(B.hasSelection),B.hasSelection)){const q=xe();J(q)}},R=E.current;return R&&(R.addEventListener("scroll",k),window.addEventListener("scroll",k,!0)),()=>{R&&R.removeEventListener("scroll",k),window.removeEventListener("scroll",k,!0)}},[a,N,ze,xe]);const On=()=>{p(!1),r(e.id)},Jr=k=>k?k.length>5&&k.match(/^\d{2}:\d{2}/)?k.substring(0,5):k:k||"",Cl=()=>{if(e.created_at){const k=ju(e.created_at),B=Ch(k).replace(/(\d{2}\.\d{2}\.\d{4} \d{2}:\d{2})\d*.*/,"$1");if(e.updated_at&&e.created_at!==e.updated_at){const q=(fe==null?void 0:fe.show_edit_date)!==void 0?fe.show_edit_date===1:!0,ee=ju(e.updated_at),ve=Ch(ee).replace(/(\d{2}\.\d{2}\.\d{4} \d{2}:\d{2})\d*.*/,"$1");return q?u.jsxs(u.Fragment,{children:[B,u.jsx("span",{className:"date-separator",children:" | "}),u.jsx(M,{icon:"mdi:pencil",style:{fontSize:"12px",margin:"0 2px"}}),ve]}):u.jsxs(u.Fragment,{children:[B,u.jsx(M,{icon:"mdi:pencil",style:{fontSize:"12px",margin:"0 2px"}})]})}else return B}else{const k=Jr(e.time);return`${e.date} ${k}`}},Zr=()=>{let k=e.content;X&&(k=b_(k,X));const R=k_(k);return lf(R)},qs=k=>{var B;const R=((B=k.split(".").pop())==null?void 0:B.toLowerCase())||"";return R==="pdf"?"mdi:file-pdf":["doc","docx"].includes(R)?"mdi:file-word":["xls","xlsx"].includes(R)?"mdi:file-excel":R==="txt"?"mdi:file-document":["zip","rar","7z"].includes(R)?"mdi:folder-zip":"mdi:file"},Gn=k=>(k/1024/1024).toFixed(2)+" MB",go=k=>{const R=document.getElementById("imageModal"),B=document.getElementById("modalImage");R&&B&&(B.setAttribute("src",k),R.style.display="block")},j=(k,R)=>{k.stopPropagation(),pe($a(R.toLowerCase()))},ae=()=>{F(!Z)};return S.useEffect(()=>{if(a){F(!1),V(!1);return}if(!U.current)return;const R=setTimeout(()=>{const B=U.current;if(!B)return;const q=B.classList.contains("collapsed");q&&B.classList.remove("collapsed");const ee=B.scrollHeight;q&&!Z&&B.classList.add("collapsed");const le=ee>300;V(le)},100);return()=>clearTimeout(R)},[e.content,a,Z]),S.useEffect(()=>{F(!1)},[e.id]),u.jsxs(u.Fragment,{children:[u.jsxs("div",{className:`container ${e.is_pinned?"note-pinned":""}`,"data-note-id":e.id,children:[u.jsxs("div",{className:"date",children:[u.jsxs("span",{className:"date-text",children:[u.jsx("input",{type:"checkbox",checked:i,onChange:()=>o&&o(e.id),onClick:k=>k.stopPropagation(),style:{width:"18px",height:"18px",cursor:"pointer",marginRight:"10px",verticalAlign:"middle"}}),Cl(),e.is_pinned?u.jsxs("span",{className:"pin-indicator",children:[u.jsx(M,{icon:"mdi:pin"}),"Закреплено"]}):null,e.syncStatus==="pending"&&u.jsx("span",{className:"sync-indicator",title:"Ожидает синхронизации",children:u.jsx(M,{icon:"mdi:cloud-upload"})}),e.syncStatus==="error"&&u.jsx("span",{className:"sync-error-indicator",title:"Ошибка синхронизации",children:u.jsx(M,{icon:"mdi:cloud-alert"})})]}),u.jsxs("div",{className:"note-actions",children:[u.jsx("div",{className:"notesHeaderBtn",onClick:()=>n(e.id),title:e.is_pinned?"Открепить":"Закрепить",children:u.jsx(M,{icon:e.is_pinned?"mdi:pin-off":"mdi:pin"})}),u.jsx("div",{className:"notesHeaderBtn",onClick:Bt,title:"Редактировать",children:u.jsx(M,{icon:"mdi:pencil"})}),u.jsx("div",{className:"notesHeaderBtn",onClick:tt,title:"В архив",children:u.jsx(M,{icon:"mdi:delete"})})]})]}),a?u.jsxs("div",{className:"note-edit-mode",children:[u.jsx(Dv,{onInsert:ft,onImageClick:qe,onFileClick:Wt,onPreviewToggle:Me,isPreviewMode:$}),u.jsx("input",{ref:z,type:"file",id:"imageInput",accept:"image/*",multiple:!0,style:{display:"none"},onChange:It}),u.jsx("input",{ref:W,type:"file",id:"fileInput",accept:".pdf,.doc,.docx,.xls,.xlsx,.txt,.zip,.rar,.7z",multiple:!0,style:{display:"none"},onChange:ln}),!$&&u.jsxs(u.Fragment,{children:[u.jsx("textarea",{ref:E,className:"textInput",value:c,onChange:k=>d(k.target.value),onKeyDown:ot,style:{minHeight:"100px"},onContextMenu:k=>{const R=E.current;if(R){const B=R.value.trim().length>0,q=R.selectionStart!==R.selectionEnd;B&&q&&k.preventDefault()}}}),he&&u.jsx(Lv,{textareaRef:E,onFormat:ft,visible:N,position:I,onHide:()=>P(!1),onInsertColor:Pt,activeFormats:ne,hasSelection:Q})]}),$&&u.jsx(cf,{content:c}),e.images&&e.images.length>0&&u.jsxs("div",{className:"image-preview-container",style:{display:"block"},children:[u.jsx("div",{className:"image-preview-header",children:u.jsx("span",{children:"Прикрепленные изображения:"})}),u.jsx("div",{className:"image-preview-list",children:e.images.filter(k=>!m.includes(k.id)).map(k=>{const R=uc(k.file_path,Number(e.id),Number(k.id));return u.jsxs("div",{className:"image-preview-item",children:[u.jsx("img",{src:R,alt:k.original_name,className:"image-preview-thumbnail"}),u.jsx("button",{className:"image-preview-remove",onClick:()=>dt(k.id),title:"Удалить",children:u.jsx(M,{icon:"mdi:close"})})]},k.id)})})]}),m.length>0&&u.jsxs("div",{className:"image-preview-container",style:{display:"block",opacity:.5},children:[u.jsx("div",{className:"image-preview-header",children:u.jsx("span",{children:"Изображения для удаления:"})}),u.jsx("div",{className:"image-preview-list",children:e.images.filter(k=>m.includes(k.id)).map(k=>{const R=uc(k.file_path,Number(e.id),Number(k.id));return u.jsxs("div",{className:"image-preview-item",children:[u.jsx("img",{src:R,alt:k.original_name,className:"image-preview-thumbnail",style:{opacity:.5}}),u.jsx("button",{className:"image-preview-remove restore-btn",onClick:()=>$e(k.id),title:"Восстановить",children:u.jsx(M,{icon:"mdi:restore"})})]},k.id)})})]}),e.files&&e.files.length>0&&u.jsxs("div",{className:"file-preview-container",style:{display:"block"},children:[u.jsx("div",{className:"file-preview-header",children:u.jsx("span",{children:"Прикрепленные файлы:"})}),u.jsx("div",{className:"file-preview-list",children:e.files.filter(k=>!w.includes(k.id)).map(k=>u.jsxs("div",{className:"file-preview-item",children:[u.jsx(M,{icon:qs(k.original_name),className:"file-icon"}),u.jsxs("div",{className:"file-info",children:[u.jsx("div",{className:"file-name",children:k.original_name}),u.jsx("div",{className:"file-size",children:Gn(k.file_size)})]}),u.jsx("button",{className:"file-preview-remove",onClick:()=>Re(k.id),title:"Удалить",children:u.jsx(M,{icon:"mdi:close"})})]},k.id))})]}),w.length>0&&u.jsxs("div",{className:"file-preview-container",style:{display:"block",opacity:.5},children:[u.jsx("div",{className:"file-preview-header",children:u.jsx("span",{children:"Файлы для удаления:"})}),u.jsx("div",{className:"file-preview-list",children:e.files.filter(k=>w.includes(k.id)).map(k=>u.jsxs("div",{className:"file-preview-item",children:[u.jsx(M,{icon:qs(k.original_name),className:"file-icon",style:{opacity:.5}}),u.jsxs("div",{className:"file-info",children:[u.jsx("div",{className:"file-name",style:{opacity:.5},children:k.original_name}),u.jsx("div",{className:"file-size",style:{opacity:.5},children:Gn(k.file_size)})]}),u.jsx("button",{className:"file-preview-remove restore-btn",onClick:()=>Fe(k.id),title:"Восстановить",children:u.jsx(M,{icon:"mdi:restore"})})]},k.id))})]}),u.jsx(Av,{images:v,onChange:g}),u.jsx($v,{files:y,onChange:x}),u.jsxs("div",{className:"save-button-container",children:[u.jsxs("div",{className:"action-buttons",children:[Ie&&u.jsxs("button",{className:"btnSave btnAI",onClick:et,disabled:T,title:"Улучшить или создать текст через ИИ",children:[u.jsx(M,{icon:"mdi:robot"}),T?"Обработка...":"Помощь ИИ"]}),u.jsx("button",{className:"btnSave",onClick:be,children:"Сохранить"}),u.jsx("button",{className:"btn-secondary",onClick:Ee,children:"Отмена"})]}),u.jsx("span",{className:"save-hint",children:"Alt + Enter для сохранения, Esc для отмены"})]})]}):u.jsxs(u.Fragment,{children:[u.jsx("div",{ref:U,className:`textNote ${Y&&!Z?"collapsed":""}`,"data-original-content":e.content,dangerouslySetInnerHTML:{__html:Zr()},onClick:k=>{const R=k.target;if(R.classList.contains("tag-in-note")){const B=R.getAttribute("data-tag");B&&j(k,B)}}}),Y&&u.jsxs("button",{className:"show-more-btn",onClick:ae,type:"button",children:[u.jsx(M,{icon:Z?"mdi:chevron-up":"mdi:chevron-down"}),u.jsx("span",{children:Z?"Скрыть":"Раскрыть"})]}),e.images&&e.images.length>0&&u.jsx("div",{className:"note-images-container",children:e.images.map(k=>{const R=uc(k.file_path,Number(e.id),Number(k.id));return u.jsx("div",{className:"note-image-item",children:u.jsx("img",{src:R,alt:k.original_name,className:"note-image lazy","data-src":R,"data-image-id":k.id,loading:"lazy",onClick:()=>go(R)})},k.id)})}),e.files&&e.files.length>0&&u.jsx("div",{className:"note-files-container",children:e.files.map(k=>{const R=P_(k.file_path,Number(e.id),Number(k.id));return u.jsx("div",{className:"note-file-item",children:u.jsxs("a",{href:R,download:k.original_name,className:"note-file-link","data-file-id":k.id,children:[u.jsx(M,{icon:qs(k.original_name),className:"file-icon"}),u.jsxs("div",{className:"file-info",children:[u.jsx("div",{className:"file-name",children:k.original_name}),u.jsx("div",{className:"file-size",children:Gn(k.file_size)})]})]})},k.id)})})]})]}),u.jsx(to,{isOpen:f,onClose:()=>p(!1),onConfirm:On,title:"Подтверждение архивирования",message:"Архивировать эту заметку? Её можно будет восстановить из настроек.",confirmText:"Архивировать",cancelText:"Отмена"})]})},R_=S.forwardRef(({selectedNoteIds:e=[],onNoteSelect:t},n)=>{const r=oe(y=>y.notes.notes),s=oe(y=>y.auth.userId),i=oe(y=>y.notes.searchQuery),o=oe(y=>y.notes.selectedDate),a=oe(y=>y.notes.selectedTag),l=wt(),{showNotification:c}=qn(),d=async()=>{try{const y=await Je.getAll();let x=y;s&&(x=y.filter(h=>h.user_id===s)),l(R1(x));let m;if(i||o||a){if(m=await Je.search({q:i||void 0,date:o||void 0,tag:a||void 0}),s&&(m=m.filter(h=>h.user_id===s)),a){const h=a.toLowerCase();m=m.filter(w=>Rv(w.content).some(T=>T.toLowerCase()===h))}}else m=x;m=m.filter(h=>h.is_archived===0),l(I1(m))}catch(y){console.error("Ошибка загрузки заметок:",y),c("Ошибка загрузки заметок","error")}};S.useEffect(()=>{s&&d()},[s,i,o,a]),S.useImperativeHandle(n,()=>({reloadNotes:d}));const f=async y=>{try{await Je.delete(y),c("Заметка удалена","success"),d()}catch(x){console.error("Ошибка удаления заметки:",x),c("Ошибка удаления заметки","error")}},p=async y=>{try{await Je.pin(y),d()}catch(x){console.error("Ошибка закрепления заметки:",x),c("Ошибка закрепления заметки","error")}},v=async y=>{try{await Je.archive(y),c("Заметка архивирована","success"),d()}catch(x){console.error("Ошибка архивирования заметки:",x),c("Ошибка архивирования заметки","error")}};if(r.length===0){let y="Заметок пока нет. Создайте первую!";return o&&a?y=`Нет заметок за ${o} с тегом #${a}`:o?y=`Нет заметок за выбранную дату (${o})`:a?y=`Нет заметок с тегом #${a}`:i&&(y="Ничего не найдено по запросу"),u.jsx("div",{className:"notes-container",children:u.jsx("p",{className:"empty-message",children:y})})}const g=[...r].sort((y,x)=>{if(y.is_pinned!==x.is_pinned)return x.is_pinned-y.is_pinned;if(y.is_pinned&&x.is_pinned){const w=y.pinned_at?new Date(y.pinned_at).getTime():0;return(x.pinned_at?new Date(x.pinned_at).getTime():0)-w}const m=new Date(y.created_at).getTime();return new Date(x.created_at).getTime()-m});return u.jsx("div",{className:"notes-container",children:g.map(y=>u.jsx(I_,{note:y,onDelete:f,onPin:p,onArchive:v,onReload:d,isSelected:e.includes(y.id),onSelect:t},y.id))})}),O_=()=>{const[e,t]=S.useState(!1),[n,r]=S.useState("");S.useEffect(()=>{const o=a=>{const l=a.target;if(l.classList.contains("note-image")){const c=l.getAttribute("src")||l.getAttribute("data-src");c&&(r(c),t(!0))}};return document.addEventListener("click",o),()=>{document.removeEventListener("click",o)}},[]),S.useEffect(()=>{const o=a=>{a.key==="Escape"&&e&&t(!1)};return document.addEventListener("keydown",o),()=>document.removeEventListener("keydown",o)},[e]);const s=()=>{t(!1)},i=o=>{o.target===o.currentTarget&&s()};return e?u.jsxs("div",{id:"imageModal",className:"image-modal",style:{display:"block"},onClick:i,children:[u.jsx("span",{className:"image-modal-close",onClick:s,children:"×"}),u.jsx("img",{className:"image-modal-content",id:"modalImage",src:n,alt:"Preview"})]}):null},D_=({isOpen:e,onClose:t,selectedNotes:n,onSuccess:r})=>{const[s,i]=S.useState(""),[o,a]=S.useState(!1),[l,c]=S.useState(!1),d=S.useRef(!1),{showNotification:f}=qn();S.useEffect(()=>{e&&n.length>=2?(d.current=!1,v()):(i(""),a(!1),c(!1),d.current=!1)},[e]);const p=()=>{d.current=!0,a(!1),c(!1),i(""),t()},v=async()=>{a(!0),i("");try{const y=n.map(m=>m.content),x=await uf.mergeNotes(y);d.current||i(x)}catch(y){if(d.current)return;console.error("Ошибка объединения заметок:",y),f("Ошибка объединения заметок","error"),p()}finally{d.current||a(!1)}},g=async()=>{if(!s.trim()){f("Нет контента для сохранения","warning");return}c(!0);try{const y=new Date,x=y.toLocaleDateString("ru-RU"),m=y.toLocaleTimeString("ru-RU",{hour:"2-digit",minute:"2-digit"});await Je.create({content:s,date:x,time:m}),f("Объединенная заметка сохранена!","success"),r(),p()}catch(y){console.error("Ошибка сохранения заметки:",y),f("Ошибка сохранения заметки","error")}finally{c(!1)}};return S.useEffect(()=>{const y=x=>{x.key==="Escape"&&p()};return e&&document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[e]),e?u.jsx("div",{className:"modal",style:{display:"block"},onClick:p,children:u.jsxs("div",{className:"modal-content",style:{maxWidth:"800px",maxHeight:"80vh",overflow:"auto"},onClick:y=>y.stopPropagation(),children:[u.jsxs("div",{className:"modal-header",children:[u.jsx("h3",{children:"Объединение заметок"}),u.jsx("span",{className:"modal-close",onClick:p,children:"×"})]}),u.jsx("div",{className:"modal-body",children:o?u.jsxs("div",{style:{textAlign:"center",padding:"40px 20px"},children:[u.jsx("div",{className:"spinner",style:{margin:"0 auto 20px"}}),u.jsx("p",{children:"Объединяю заметки через ИИ..."}),u.jsxs("p",{style:{fontSize:"14px",color:"#666",marginTop:"10px"},children:["Выбрано заметок: ",n.length]})]}):u.jsxs(u.Fragment,{children:[u.jsx("div",{style:{marginBottom:"15px",color:"#666"},children:u.jsxs("p",{children:["Результат объединения ",n.length," ",(n.length===2||n.length>4,"заметок"),":"]})}),u.jsx("div",{style:{border:"1px solid var(--border-color)",borderRadius:"8px",padding:"15px",backgroundColor:"var(--bg-secondary)",maxHeight:"400px",overflow:"auto"},children:u.jsx(cf,{content:s})})]})}),u.jsxs("div",{className:"modal-footer",children:[u.jsx("button",{className:"btn-primary",onClick:g,disabled:o||l||!s,style:{marginRight:"10px"},children:l?"Сохранение...":"Сохранить"}),u.jsx("button",{className:"btn-secondary",onClick:p,disabled:l,children:o?"Отменить":"Отмена"})]})]})}):null},L_=()=>{const e=oe(L=>L.notes.allNotes),t=oe(L=>L.notes.notes),n=S.useRef(null),[r,s]=S.useState(!1),[i,o]=S.useState([]),[a,l]=S.useState(!1),[c,d]=S.useState(!1),[f,p]=S.useState(!1),v=wt(),{theme:g}=Kd(),{showNotification:y}=qn(),x=oe(L=>L.notes.selectedDate),m=oe(L=>L.notes.selectedTag),h=oe(L=>L.notes.searchQuery),w=!!(x||m||h),C=()=>{v(mu(null)),v($a(null)),v(gu(""))},b=(()=>{const L=[];return h&&L.push(`Поиск: "${h}"`),x&&L.push(`Дата: ${x}`),m&&L.push(`Тег: #${m}`),L})(),N=()=>{n.current&&n.current.reloadNotes()},P=()=>{s(!r)},I=()=>{s(!1)},O=L=>{o(Z=>Z.includes(L)?Z.filter(F=>F!==L):[...Z,L])},Q=()=>{i.length<2||l(!0)},ue=()=>{o([]),n.current&&n.current.reloadNotes()},ne=()=>{i.length!==0&&d(!0)},J=async()=>{if(i.length!==0){p(!0);try{await Promise.all(i.map(L=>Je.delete(L))),y(`Удалено заметок: ${i.length}`,"success"),o([]),d(!1),n.current&&n.current.reloadNotes()}catch(L){console.error("Ошибка удаления заметок:",L),y("Ошибка удаления заметок","error")}finally{p(!1)}}},$=t.filter(L=>i.includes(L.id));return u.jsxs(u.Fragment,{children:[u.jsx(E_,{isOpen:r,onClose:I}),u.jsx(C_,{notes:e}),u.jsxs("div",{className:"center",children:[u.jsxs("div",{className:"container",children:[u.jsx(jC,{onToggleSidebar:P}),w&&u.jsxs("div",{className:"filter-indicator",children:[u.jsxs("span",{className:"filter-indicator-text",children:["Фильтр: ",b.join(", ")]})," ",u.jsx("button",{onClick:C,children:"✕"})]}),i.length>0&&u.jsxs("div",{className:"filter-indicator",children:[u.jsxs("span",{className:"filter-indicator-text",children:["Выделено заметок: ",i.length]})," ",u.jsx("button",{onClick:()=>o([]),title:"Снять выделение",children:"✕"})]}),u.jsx(j_,{onSave:N})]}),u.jsx(R_,{ref:n,selectedNoteIds:i,onNoteSelect:O})]}),i.length>0&&u.jsxs("div",{style:{position:"fixed",bottom:"20px",right:"20px",display:"flex",flexDirection:"column",gap:"12px",zIndex:1e3},children:[i.length>=2&&u.jsx("button",{onClick:Q,style:{width:"56px",height:"56px",borderRadius:"50%",backgroundColor:g==="dark"?"#4CAF50":"#2196F3",color:"white",border:"none",cursor:"pointer",boxShadow:g==="dark"?"0 4px 12px rgba(76, 175, 80, 0.4)":"0 4px 12px rgba(33, 150, 243, 0.4)",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"24px",transition:"all 0.3s ease"},onMouseEnter:L=>{L.currentTarget.style.transform="scale(1.1)",L.currentTarget.style.boxShadow=g==="dark"?"0 6px 16px rgba(76, 175, 80, 0.6)":"0 6px 16px rgba(33, 150, 243, 0.6)"},onMouseLeave:L=>{L.currentTarget.style.transform="scale(1)",L.currentTarget.style.boxShadow=g==="dark"?"0 4px 12px rgba(76, 175, 80, 0.4)":"0 4px 12px rgba(33, 150, 243, 0.4)"},title:`Объединить ${i.length} заметок`,children:u.jsx(M,{icon:"mdi:link-variant"})}),u.jsx("button",{onClick:ne,disabled:f,style:{width:"56px",height:"56px",borderRadius:"50%",backgroundColor:g==="dark"?"#F44336":"#E53935",color:"white",border:"none",cursor:f?"not-allowed":"pointer",opacity:f?.6:1,boxShadow:g==="dark"?"0 4px 12px rgba(244, 67, 54, 0.4)":"0 4px 12px rgba(229, 57, 53, 0.4)",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"24px",transition:"all 0.3s ease"},onMouseEnter:L=>{f||(L.currentTarget.style.transform="scale(1.1)",L.currentTarget.style.boxShadow=g==="dark"?"0 6px 16px rgba(244, 67, 54, 0.6)":"0 6px 16px rgba(229, 57, 53, 0.6)")},onMouseLeave:L=>{L.currentTarget.style.transform="scale(1)",L.currentTarget.style.boxShadow=g==="dark"?"0 4px 12px rgba(244, 67, 54, 0.4)":"0 4px 12px rgba(229, 57, 53, 0.4)"},title:`Удалить ${i.length} ${i.length===1?"заметку":i.length>4?"заметок":"заметки"}`,children:u.jsx(M,{icon:"mdi:delete"})})]}),u.jsx(O_,{}),u.jsx(D_,{isOpen:a,onClose:()=>l(!1),selectedNotes:$,onSuccess:ue}),u.jsx(to,{isOpen:c,onClose:()=>d(!1),onConfirm:J,title:"Удаление заметок",message:u.jsxs("p",{children:["Вы уверены, что хотите удалить"," ",u.jsx("strong",{children:i.length})," ",i.length===1?"заметку":i.length>4?"заметок":"заметки","? Это действие нельзя отменить."]}),confirmText:f?"Удаление...":"Удалить",cancelText:"Отмена",confirmType:"danger"})]})},M_=()=>{const e=kr(),t=wt(),{showNotification:n}=qn();oe($=>$.profile.user);const[r,s]=S.useState(""),[i,o]=S.useState(""),[a,l]=S.useState(null),[c,d]=S.useState(!1),[f,p]=S.useState(""),[v,g]=S.useState(""),[y,x]=S.useState(""),[m,h]=S.useState(!1),[w,C]=S.useState(""),[T,b]=S.useState(!1),N=S.useRef(null);S.useEffect(()=>{P()},[]);const P=async()=>{try{const $=await Et.getProfile();t(Ad($)),s($.username||""),o($.email||"");const L=$.accent_color||"#007bff";t(Fa(L)),eo(L),$.avatar?(l($.avatar),d(!0)):(l(null),d(!1));try{const Z=await Et.getAiSettings();t($d(Z))}catch(Z){console.error("Ошибка загрузки AI настроек:",Z)}}catch($){console.error("Ошибка загрузки профиля:",$),n("Ошибка загрузки данных профиля","error")}},I=async $=>{var F,Y,V;const L=(F=$.target.files)==null?void 0:F[0];if(!L)return;if(L.size>5*1024*1024){n("Файл слишком большой. Максимальный размер: 5 МБ","error");return}if(!["image/jpeg","image/jpg","image/png","image/gif"].includes(L.type)){n("Недопустимый формат файла. Используйте JPG, PNG или GIF","error");return}try{const E=await Et.uploadAvatar(L);l(E.avatar+"?t="+Date.now()),d(!0),await P(),n("Аватарка успешно загружена","success")}catch(E){console.error("Ошибка загрузки аватарки:",E),n(((V=(Y=E.response)==null?void 0:Y.data)==null?void 0:V.error)||"Ошибка загрузки аватарки","error")}N.current&&(N.current.value="")},O=async()=>{var $,L;try{await Et.deleteAvatar(),l(null),d(!1),await P(),n("Аватарка успешно удалена","success")}catch(Z){console.error("Ошибка удаления аватарки:",Z),n(((L=($=Z.response)==null?void 0:$.data)==null?void 0:L.error)||"Ошибка удаления аватарки","error")}},Q=async()=>{var $,L;if(!r.trim()){n("Логин не может быть пустым","error");return}if(r.length<3){n("Логин должен быть не менее 3 символов","error");return}if(i&&!J(i)){n("Некорректный email адрес","error");return}try{await Et.updateProfile({username:r.trim(),email:i.trim()||void 0}),await P(),n("Профиль успешно обновлен","success")}catch(Z){console.error("Ошибка обновления профиля:",Z),n(((L=($=Z.response)==null?void 0:$.data)==null?void 0:L.error)||"Ошибка обновления профиля","error")}},ue=async()=>{var $,L;if(!f){n("Введите текущий пароль","error");return}if(!v){n("Введите новый пароль","error");return}if(v.length<6){n("Новый пароль должен быть не менее 6 символов","error");return}if(v!==y){n("Новый пароль и подтверждение не совпадают","error");return}try{await Et.updateProfile({currentPassword:f,newPassword:v}),p(""),g(""),x(""),n("Пароль успешно изменен","success")}catch(Z){console.error("Ошибка изменения пароля:",Z),n(((L=($=Z.response)==null?void 0:$.data)==null?void 0:L.error)||"Ошибка изменения пароля","error")}},ne=async()=>{var $,L;if(!w.trim()){n("Введите пароль","warning");return}b(!0);try{await Et.deleteAccount(w),await D.clearAll(),n("Аккаунт успешно удален","success"),t(Xi()),setTimeout(()=>{e("/")},2e3)}catch(Z){console.error("Ошибка удаления аккаунта:",Z),n(((L=($=Z.response)==null?void 0:$.data)==null?void 0:L.error)||"Ошибка удаления аккаунта","error"),b(!1)}},J=$=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test($);return u.jsxs("div",{className:"container",children:[u.jsxs("header",{className:"notes-header",children:[u.jsxs("span",{children:[u.jsx(M,{icon:"mdi:account"})," Личный кабинет"]}),u.jsxs("div",{className:"user-info",children:[u.jsx(ho,{}),u.jsx("button",{className:"notes-btn",onClick:()=>e("/notes"),title:"К заметкам",children:u.jsx(M,{icon:"mdi:note-text"})}),u.jsx("button",{className:"settings-btn",onClick:()=>e("/settings"),title:"Настройки",children:u.jsx(M,{icon:"mdi:cog"})}),u.jsx("button",{className:"logout-btn",title:"Выйти",onClick:async()=>{try{await Vr.logout()}catch($){console.error("Ошибка выхода:",$)}finally{D.clearAll().catch($=>{console.error("Ошибка очистки IndexedDB при выходе:",$)}),t(Xi()),e("/")}},children:u.jsx(M,{icon:"mdi:logout"})})]})]}),u.jsxs("div",{className:"profile-container",children:[u.jsxs("div",{className:"avatar-section",children:[u.jsx("div",{className:"avatar-wrapper",children:c&&a?u.jsx("img",{src:a,alt:"Аватар",className:"avatar-preview",loading:"lazy"}):u.jsx("div",{className:"avatar-placeholder",children:u.jsx(M,{icon:"mdi:account"})})}),u.jsxs("div",{className:"avatar-buttons",children:[u.jsxs("label",{htmlFor:"avatarInput",className:"btn-upload",children:[u.jsx(M,{icon:"mdi:upload"})," Загрузить аватар"]}),u.jsx("input",{ref:N,type:"file",id:"avatarInput",accept:"image/*",style:{display:"none"},onChange:I}),c&&u.jsxs("button",{className:"btn-delete",onClick:O,children:[u.jsx(M,{icon:"mdi:delete"})," Удалить"]})]}),u.jsx("p",{className:"avatar-hint",children:"Максимальный размер: 5 МБ. Форматы: JPG, PNG, GIF"})]}),u.jsxs("div",{className:"profile-form",children:[u.jsx("h3",{children:"Данные профиля"}),u.jsxs("div",{className:"form-group",children:[u.jsx("label",{htmlFor:"username",children:"Логин"}),u.jsx("input",{type:"text",id:"username",placeholder:"Логин",minLength:3,value:r,onChange:$=>s($.target.value)})]}),u.jsxs("div",{className:"form-group",children:[u.jsx("label",{htmlFor:"email",children:"Email (необязательно)"}),u.jsx("input",{type:"email",id:"email",placeholder:"example@example.com",value:i,onChange:$=>o($.target.value)})]}),u.jsx("button",{className:"btnSave",onClick:Q,children:"Сохранить изменения"}),u.jsx("hr",{className:"separator"}),u.jsx("h3",{children:"Изменить пароль"}),u.jsxs("div",{className:"form-group",children:[u.jsx("label",{htmlFor:"currentPassword",children:"Текущий пароль"}),u.jsx("input",{type:"password",id:"currentPassword",placeholder:"Текущий пароль",value:f,onChange:$=>p($.target.value)})]}),u.jsxs("div",{className:"form-group",children:[u.jsx("label",{htmlFor:"newPassword",children:"Новый пароль"}),u.jsx("input",{type:"password",id:"newPassword",placeholder:"Новый пароль (минимум 6 символов)",minLength:6,value:v,onChange:$=>g($.target.value)})]}),u.jsxs("div",{className:"form-group",children:[u.jsx("label",{htmlFor:"confirmPassword",children:"Подтвердите новый пароль"}),u.jsx("input",{type:"password",id:"confirmPassword",placeholder:"Подтвердите новый пароль",value:y,onChange:$=>x($.target.value)})]}),u.jsx("button",{className:"btnSave",onClick:ue,children:"Изменить пароль"}),u.jsx("hr",{className:"separator"}),u.jsxs("button",{className:"btn-danger",onClick:()=>h(!0),children:[u.jsx(M,{icon:"mdi:account-remove"})," Удалить аккаунт"]}),u.jsx("p",{style:{color:"#666",fontSize:"14px",marginBottom:"15px"},children:"Удаление аккаунта - это необратимое действие. Все ваши заметки, изображения и данные будут удалены навсегда."})]})]}),u.jsx(to,{isOpen:m,onClose:()=>{h(!1),C("")},onConfirm:ne,title:"Удаление аккаунта",message:u.jsxs(u.Fragment,{children:[u.jsx("p",{style:{color:"#dc3545",fontWeight:"bold",marginBottom:"15px"},children:"⚠️ ВНИМАНИЕ: Это действие нельзя отменить!"}),u.jsx("p",{style:{marginBottom:"20px"},children:"Вы действительно хотите удалить свой аккаунт? Все ваши заметки, изображения, настройки и данные будут удалены навсегда."}),u.jsxs("div",{style:{marginBottom:"15px"},children:[u.jsx("label",{htmlFor:"deleteAccountPassword",style:{display:"block",marginBottom:"5px",fontWeight:"bold"},children:"Введите пароль для подтверждения:"}),u.jsx("input",{type:"password",id:"deleteAccountPassword",placeholder:"Пароль от аккаунта",className:"modal-password-input",value:w,onChange:$=>C($.target.value),onKeyPress:$=>{$.key==="Enter"&&!T&&ne()}})]})]}),confirmText:T?"Удаление...":"Удалить аккаунт",cancelText:"Отмена",confirmType:"danger"})]})},A_=()=>{const e=kr(),t=wt(),{showNotification:n}=qn();oe(j=>j.profile.user);const r=oe(j=>j.auth.userId);oe(j=>j.ui.accentColor);const[s,i]=S.useState(()=>{const j=localStorage.getItem("settings_active_tab");return j&&["appearance","ai","archive","logs","offline"].includes(j)?j:"appearance"});S.useEffect(()=>{localStorage.setItem("settings_active_tab",s)},[s]);const[o,a]=S.useState("#007bff"),[l,c]=S.useState(!0),[d,f]=S.useState(!0),[p,v]=S.useState(!0),[g,y]=S.useState(""),[x,m]=S.useState(""),[h,w]=S.useState(""),[C,T]=S.useState(!1),[b,N]=S.useState([]),[P,I]=S.useState(!1),[O,Q]=S.useState([]),[ue,ne]=S.useState(0),[J,$]=S.useState(!0),[L,Z]=S.useState(""),[F,Y]=S.useState(!1),[V,E]=S.useState(!1),[z,W]=S.useState(""),[U,G]=S.useState(!1),[X,ie]=S.useState(!1),[Ie,fe]=S.useState(!1),[se,pe]=S.useState(null),[he,Bt]=S.useState(null),[Me,be]=S.useState(!1),[Ee,dt]=S.useState(!1),Re=50,$e=[{color:"#007bff",title:"Синий"},{color:"#28a745",title:"Зеленый"},{color:"#dc3545",title:"Красный"},{color:"#fd7e14",title:"Оранжевый"},{color:"#6f42c1",title:"Фиолетовый"},{color:"#e83e8c",title:"Розовый"}];S.useEffect(()=>{Fe()},[]),S.useEffect(()=>{s==="archive"?Wt():s==="logs"?tt(!0):s==="ai"?et():s==="offline"&&Zr()},[s]);const Fe=async()=>{try{const j=await Et.getProfile();t(Ad(j));const ae=j.accent_color||"#007bff";a(ae),t(Fa(ae)),eo(ae),c(j.show_edit_date!==void 0?j.show_edit_date===1:!0);const k=j.colored_icons!==void 0?j.colored_icons===1:!0;f(k),ft(k);const R=j.floating_toolbar_enabled!==void 0?j.floating_toolbar_enabled===1:!0;v(R);try{const B=await Et.getAiSettings();t($d(B))}catch(B){console.error("Ошибка загрузки AI настроек:",B)}}catch(j){console.error("Ошибка загрузки информации о пользователе:",j)}},et=async()=>{try{const j=await Et.getAiSettings();y(j.openai_api_key||""),m(j.openai_base_url||""),w(j.openai_model||""),T(j.ai_enabled===1),localStorage.setItem("ai_enabled",j.ai_enabled?"1":"0")}catch(j){console.error("Ошибка загрузки AI настроек:",j)}},xe=async()=>{var j,ae;try{await Et.updateProfile({accent_color:o,show_edit_date:l,colored_icons:d,floating_toolbar_enabled:p}),t(Fa(o)),eo(o),await Fe(),ft(d),n("Настройки внешнего вида успешно обновлены","success")}catch(k){console.error("Ошибка обновления настроек внешнего вида:",k),n(((ae=(j=k.response)==null?void 0:j.data)==null?void 0:ae.error)||"Ошибка обновления","error")}},ft=j=>{j?document.body.classList.add("colored-icons"):document.body.classList.remove("colored-icons")},Pt=async()=>{var j,ae;if(!g.trim()){n("API ключ обязателен","error");return}if(!x.trim()){n("Base URL обязателен","error");return}if(!h.trim()){n("Название модели обязательно","error");return}try{await Et.updateAiSettings({openai_api_key:g,openai_base_url:x,openai_model:h}),n("AI настройки успешно сохранены","success"),qe()}catch(k){console.error("Ошибка сохранения AI настроек:",k),n(((ae=(j=k.response)==null?void 0:j.data)==null?void 0:ae.error)||"Ошибка сохранения","error")}},ze=async j=>{var ae,k;if(j&&!Ce()){n("Сначала заполните все AI настройки","warning");return}try{await Et.updateAiSettings({ai_enabled:j?1:0}),T(j),localStorage.setItem("ai_enabled",j?"1":"0"),n(j?"Помощь ИИ включена":"Помощь ИИ отключена","success")}catch(R){console.error("Ошибка сохранения настройки AI:",R),n(((k=(ae=R.response)==null?void 0:ae.data)==null?void 0:k.error)||"Ошибка сохранения","error"),T(!j)}},Ce=()=>g.trim()&&x.trim()&&h.trim(),qe=()=>{Ce()||T(!1)},Wt=async()=>{I(!0);try{const j=await is.getArchived();N(j)}catch(j){console.error("Ошибка загрузки архивных заметок:",j),n("Ошибка загрузки архивных заметок","error")}finally{I(!1)}},It=async j=>{var ae,k;try{await is.unarchive(Number(j)),await Wt(),n("Заметка восстановлена!","success")}catch(R){console.error("Ошибка восстановления заметки:",R),n(((k=(ae=R.response)==null?void 0:ae.data)==null?void 0:k.error)||"Ошибка восстановления","error")}},ln=async j=>{var ae,k;try{await is.deleteArchived(Number(j)),await Wt(),n("Заметка удалена окончательно","success")}catch(R){console.error("Ошибка удаления заметки:",R),n(((k=(ae=R.response)==null?void 0:ae.data)==null?void 0:k.error)||"Ошибка удаления","error")}},ot=async()=>{var j,ae;if(!z.trim()){n("Введите пароль","warning");return}G(!0);try{await is.deleteAllArchived(z),n("Все архивные заметки удалены","success"),E(!1),W(""),await Wt()}catch(k){console.error("Ошибка:",k),n(((ae=(j=k.response)==null?void 0:j.data)==null?void 0:ae.error)||"Ошибка удаления","error")}finally{G(!1)}},tt=S.useCallback(async(j=!1)=>{Y(!0);try{const ae=j?0:ue,k=await N_.getLogs({action_type:L||void 0,limit:Re,offset:ae});j?(Q(k),ne(k.length)):(Q(R=>[...R,...k]),ne(R=>R+k.length)),$(k.length===Re)}catch(ae){console.error("Ошибка загрузки логов:",ae),n("Ошибка загрузки логов","error")}finally{Y(!1)}},[L,Re,n,ue]),On=j=>{Z(j),ne(0),$(!0)};S.useEffect(()=>{s==="logs"&&tt(!0)},[L,s,tt]);const Jr=j=>({login:"Вход",logout:"Выход",register:"Регистрация",note_create:"Создание заметки",note_update:"Редактирование",note_delete:"Удаление",note_pin:"Закрепление",note_archive:"Архивирование",note_unarchive:"Восстановление",note_delete_permanent:"Окончательное удаление",profile_update:"Обновление профиля",ai_improve:"Улучшение через AI"})[j]||j,Cl=async()=>{fe(!0);try{await D.clearAllNotes(),await D.clearSyncQueue(),n("Локальный кэш IndexedDB успешно очищен","success"),ie(!1),await Zr()}catch(j){console.error("Ошибка очистки IndexedDB:",j),n("Ошибка очистки IndexedDB","error")}finally{fe(!1)}},Zr=async()=>{be(!0);try{try{const j=await is.getDataVersion();pe(j)}catch(j){console.error("Ошибка загрузки версии с сервера:",j),pe(null)}try{const j=r?await D.getDataVersionByUserId(r):await D.getDataVersion();Bt(j)}catch(j){console.error("Ошибка загрузки версии из IndexedDB:",j),Bt(null)}}catch(j){console.error("Ошибка загрузки версий данных:",j)}finally{be(!1)}},qs=async()=>{if(!navigator.onLine){n("Нет подключения к интернету","error");return}dt(!0);try{n("Начинаем принудительную синхронизацию...","info"),await Ba.startSync(),console.log("[ForceSync] Loading all notes from server..."),await Je.getAll(),await Zr(),n("Синхронизация завершена успешно","success")}catch(j){console.error("Ошибка принудительной синхронизации:",j),n("Ошибка при синхронизации","error")}finally{dt(!1)}},Gn=j=>{if(!j)return"Нет данных";try{const ae=new Date(j.replace(" ","T")+"Z");return new Intl.DateTimeFormat("ru-RU",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit",second:"2-digit"}).format(ae)}catch{return j}},go=()=>{if(!se||!he)return{status:"Неизвестно",color:"#999"};if(se.total_notes!==he.total_notes)return{status:"Не синхронизировано",color:"#dc3545"};const j=se.last_updated_at?new Date(se.last_updated_at.replace(" ","T")+"Z").getTime():0,ae=he.last_updated_at?new Date(he.last_updated_at.replace(" ","T")+"Z").getTime():0;return j===0&&ae===0?{status:"Нет данных",color:"#999"}:Math.abs(j-ae)<12e4?{status:"Синхронизировано",color:"#28a745"}:{status:"Не синхронизировано",color:"#dc3545"}};return u.jsxs("div",{className:"container",children:[u.jsxs("header",{className:"notes-header",children:[u.jsxs("span",{children:[u.jsx(M,{icon:"mdi:cog"})," Настройки"]}),u.jsxs("div",{className:"user-info",children:[u.jsx(ho,{}),u.jsx("button",{className:"notes-btn",onClick:()=>e("/notes"),title:"К заметкам",children:u.jsx(M,{icon:"mdi:note-text"})}),u.jsx("button",{className:"profile-btn",onClick:()=>e("/profile"),title:"Профиль",children:u.jsx(M,{icon:"mdi:account"})}),u.jsx("button",{className:"logout-btn",title:"Выйти",onClick:async()=>{try{await Vr.logout()}catch(j){console.error("Ошибка выхода:",j)}finally{D.clearAll().catch(j=>{console.error("Ошибка очистки IndexedDB при выходе:",j)}),t(Xi()),e("/")}},children:u.jsx(M,{icon:"mdi:logout"})})]})]}),u.jsxs("div",{className:"settings-tabs",children:[u.jsxs("button",{className:`settings-tab ${s==="appearance"?"active":""}`,onClick:()=>i("appearance"),children:[u.jsx(M,{icon:"mdi:palette"})," Внешний вид"]}),u.jsxs("button",{className:`settings-tab ${s==="ai"?"active":""}`,onClick:()=>i("ai"),children:[u.jsx(M,{icon:"mdi:robot"})," AI настройки"]}),u.jsxs("button",{className:`settings-tab ${s==="archive"?"active":""}`,onClick:()=>i("archive"),children:[u.jsx(M,{icon:"mdi:archive"})," Архив заметок"]}),u.jsxs("button",{className:`settings-tab ${s==="logs"?"active":""}`,onClick:()=>i("logs"),children:[u.jsx(M,{icon:"mdi:history"})," История действий"]}),u.jsxs("button",{className:`settings-tab ${s==="offline"?"active":""}`,onClick:()=>i("offline"),children:[u.jsx(M,{icon:"mdi:database-off"})," Оффлайн режим"]})]}),u.jsxs("div",{className:"settings-content",children:[s==="appearance"&&u.jsxs("div",{className:"tab-content active",children:[u.jsx("h3",{children:"Внешний вид"}),u.jsxs("div",{className:"form-group",children:[u.jsx("label",{htmlFor:"settings-accentColor",children:"Цветовой акцент"}),u.jsx("div",{className:"accent-color-picker",children:$e.map(j=>u.jsx("div",{className:`color-option ${o===j.color?"selected":""}`,"data-color":j.color,style:{backgroundColor:j.color},title:j.title,onClick:()=>a(j.color)},j.color))})]}),u.jsx("div",{className:"form-group ai-toggle-group",children:u.jsxs("label",{className:"ai-toggle-label",children:[u.jsxs("div",{className:"toggle-label-content",children:[u.jsx("span",{className:"toggle-text-main",children:"Показывать дату редактирования"}),u.jsx("span",{className:"toggle-text-desc",children:l?"Отображать дату последнего редактирования заметки рядом с датой создания":"Показывать только иконку карандаша без даты редактирования"})]}),u.jsxs("div",{className:"toggle-switch-wrapper",children:[u.jsx("input",{type:"checkbox",id:"show-edit-date-toggle",className:"toggle-checkbox",checked:l,onChange:j=>c(j.target.checked)}),u.jsx("span",{className:"toggle-slider"})]})]})}),u.jsx("div",{className:"form-group ai-toggle-group",children:u.jsxs("label",{className:"ai-toggle-label",children:[u.jsxs("div",{className:"toggle-label-content",children:[u.jsx("span",{className:"toggle-text-main",children:"Цветные иконки"}),u.jsx("span",{className:"toggle-text-desc",children:d?"Иконки отображаются разными цветами для лучшей визуальной дифференциации":"Все иконки отображаются в монохромном стиле"})]}),u.jsxs("div",{className:"toggle-switch-wrapper",children:[u.jsx("input",{type:"checkbox",id:"colored-icons-toggle",className:"toggle-checkbox",checked:d,onChange:j=>{f(j.target.checked),ft(j.target.checked)}}),u.jsx("span",{className:"toggle-slider"})]})]})}),u.jsx("div",{className:"form-group ai-toggle-group",children:u.jsxs("label",{className:"ai-toggle-label",children:[u.jsxs("div",{className:"toggle-label-content",children:[u.jsx("span",{className:"toggle-text-main",children:"Плавающая панель редактирования"}),u.jsx("span",{className:"toggle-text-desc",children:p?"Показывать плавающую панель инструментов при выделении текста в редакторе":"Скрывать плавающую панель инструментов при выделении текста"})]}),u.jsxs("div",{className:"toggle-switch-wrapper",children:[u.jsx("input",{type:"checkbox",id:"floating-toolbar-toggle",className:"toggle-checkbox",checked:p,onChange:j=>v(j.target.checked)}),u.jsx("span",{className:"toggle-slider"})]})]})}),u.jsx("button",{className:"btnSave",onClick:xe,children:"Сохранить изменения"})]}),s==="ai"&&u.jsxs("div",{className:"tab-content active",children:[u.jsx("h3",{children:"Настройки AI"}),u.jsx("div",{className:"form-group ai-toggle-group",children:u.jsxs("label",{className:`ai-toggle-label ${Ce()?"":"disabled"}`,children:[u.jsxs("div",{className:"toggle-label-content",children:[u.jsx("span",{className:"toggle-text-main",children:"Включить помощь ИИ"}),u.jsx("span",{className:"toggle-text-desc",children:Ce()?'Показывать кнопку "Помощь ИИ" в редакторах заметок':"Сначала заполните API Key, Base URL и Модель ниже"})]}),u.jsxs("div",{className:"toggle-switch-wrapper",children:[u.jsx("input",{type:"checkbox",id:"ai-enabled-toggle",className:"toggle-checkbox",checked:C,disabled:!Ce(),onChange:j=>ze(j.target.checked)}),u.jsx("span",{className:"toggle-slider"})]})]})}),u.jsxs("div",{className:"form-group",children:[u.jsx("label",{htmlFor:"openai-api-key",children:"OpenAI API Key"}),u.jsx("input",{type:"password",id:"openai-api-key",placeholder:"sk-...",className:"form-input",value:g,onChange:j=>{y(j.target.value),qe()}}),u.jsx("p",{style:{color:"#666",fontSize:"12px",marginTop:"5px"},children:"Введите ваш OpenAI API ключ"})]}),u.jsxs("div",{className:"form-group",children:[u.jsx("label",{htmlFor:"openai-base-url",children:"OpenAI Base URL"}),u.jsx("input",{type:"text",id:"openai-base-url",placeholder:"https://api.openai.com/v1",className:"form-input",value:x,onChange:j=>{m(j.target.value),qe()}}),u.jsx("p",{style:{color:"#666",fontSize:"12px",marginTop:"5px"},children:"URL для API запросов (например, https://api.openai.com/v1)"})]}),u.jsxs("div",{className:"form-group",children:[u.jsx("label",{htmlFor:"openai-model",children:"Модель"}),u.jsx("input",{type:"text",id:"openai-model",placeholder:"gpt-3.5-turbo",className:"form-input",value:h,onChange:j=>{w(j.target.value),qe()}}),u.jsxs("p",{style:{color:"#666",fontSize:"12px",marginTop:"5px"},children:["Название модели (например, gpt-4, deepseek/deepseek-chat).",u.jsxs("a",{href:"https://openrouter.ai/models",target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent-color)"},children:[" ","Список доступных моделей"]})]})]}),u.jsx("button",{className:"btnSave",onClick:Pt,children:"Сохранить AI настройки"})]}),s==="archive"&&u.jsxs("div",{className:"tab-content active",children:[u.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"10px"},children:[u.jsx("h3",{children:"Архивные заметки"}),u.jsxs("button",{className:"btn-danger",style:{fontSize:"14px",padding:"8px 16px"},onClick:()=>E(!0),children:[u.jsx(M,{icon:"mdi:delete-sweep"})," Удалить все"]})]}),u.jsx("p",{style:{color:"#666",fontSize:"14px",marginBottom:"20px"},children:"Архивированные заметки можно восстановить или удалить окончательно"}),u.jsx("div",{className:"archived-notes-list",children:P?u.jsx("p",{style:{textAlign:"center",color:"#999"},children:"Загрузка..."}):b.length===0?u.jsx("p",{style:{textAlign:"center",color:"#999"},children:"Архив пуст"}):b.map(j=>{const ae=new Date(j.created_at.replace(" ","T")+"Z"),k=new Intl.DateTimeFormat("ru-RU",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit"}).format(ae),R=lf(j.content),B=R.substring(0,200)+(R.length>200?"...":"");return u.jsxs("div",{className:"archived-note-item",children:[u.jsxs("div",{className:"archived-note-header",children:[u.jsx("span",{className:"archived-note-date",children:k}),u.jsxs("div",{className:"archived-note-actions",children:[u.jsxs("button",{className:"btn-restore",onClick:()=>It(Number(j.id)),title:"Восстановить",children:[u.jsx(M,{icon:"mdi:restore"})," Восстановить"]}),u.jsxs("button",{className:"btn-delete-permanent",onClick:()=>ln(Number(j.id)),title:"Удалить навсегда",children:[u.jsx(M,{icon:"mdi:delete-forever"})," Удалить"]})]})]}),u.jsx("div",{className:"archived-note-content",dangerouslySetInnerHTML:{__html:B}}),j.images&&j.images.length>0&&u.jsxs("div",{className:"archived-note-images",children:[j.images.length," изображений"]})]},j.id)})})]}),s==="logs"&&u.jsxs("div",{className:"tab-content active",children:[u.jsx("h3",{children:"История действий"}),u.jsxs("div",{className:"logs-filters",children:[u.jsxs("select",{id:"logTypeFilter",className:"log-filter-select",value:L,onChange:j=>On(j.target.value),children:[u.jsx("option",{value:"",children:"Все действия"}),u.jsx("option",{value:"login",children:"Вход"}),u.jsx("option",{value:"logout",children:"Выход"}),u.jsx("option",{value:"register",children:"Регистрация"}),u.jsx("option",{value:"note_create",children:"Создание заметки"}),u.jsx("option",{value:"note_update",children:"Редактирование заметки"}),u.jsx("option",{value:"note_delete",children:"Удаление заметки"}),u.jsx("option",{value:"note_pin",children:"Закрепление"}),u.jsx("option",{value:"note_archive",children:"Архивирование"}),u.jsx("option",{value:"note_unarchive",children:"Восстановление"}),u.jsx("option",{value:"note_delete_permanent",children:"Окончательное удаление"}),u.jsx("option",{value:"profile_update",children:"Обновление профиля"}),u.jsx("option",{value:"ai_improve",children:"Улучшение через AI"})]}),u.jsxs("button",{className:"btnSave",onClick:()=>tt(!0),children:[u.jsx(M,{icon:"mdi:refresh"})," Обновить"]})]}),u.jsx("div",{className:"logs-table-container",children:u.jsxs("table",{className:"logs-table",children:[u.jsx("thead",{children:u.jsxs("tr",{children:[u.jsx("th",{children:"Дата и время"}),u.jsx("th",{children:"Действие"}),u.jsx("th",{children:"Детали"})]})}),u.jsx("tbody",{children:F&&O.length===0?u.jsx("tr",{children:u.jsx("td",{colSpan:3,style:{textAlign:"center"},children:"Загрузка..."})}):O.length===0?u.jsx("tr",{children:u.jsx("td",{colSpan:3,style:{textAlign:"center",color:"#999"},children:"Логов пока нет"})}):O.map(j=>{const ae=new Date(j.created_at.replace(" ","T")+"Z"),k=new Intl.DateTimeFormat("ru-RU",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit",second:"2-digit"}).format(ae);return u.jsxs("tr",{children:[u.jsx("td",{children:k}),u.jsx("td",{children:u.jsx("span",{className:`log-action-badge log-action-${j.action_type}`,children:Jr(j.action_type)})}),u.jsx("td",{children:j.details||"-"})]},j.id)})})]})}),J&&O.length>0&&u.jsx("div",{className:"load-more-container",children:u.jsx("button",{className:"btnSave",onClick:()=>tt(!1),children:"Загрузить еще"})})]}),s==="offline"&&u.jsxs("div",{className:"tab-content active",children:[u.jsx("h3",{children:"Оффлайн режим"}),u.jsxs("div",{style:{backgroundColor:"var(--card-bg)",border:"1px solid var(--border-color)",borderRadius:"8px",padding:"20px",marginBottom:"20px"},children:[u.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"15px"},children:[u.jsxs("h4",{style:{margin:0,fontSize:"16px",fontWeight:"600"},children:[u.jsx(M,{icon:"mdi:database-sync",style:{marginRight:"8px",verticalAlign:"middle"}}),"Версии данных"]}),u.jsx("button",{onClick:Zr,disabled:Me,style:{padding:"6px 12px",fontSize:"12px",border:"1px solid var(--border-color)",borderRadius:"4px",backgroundColor:"transparent",cursor:Me?"not-allowed":"pointer",opacity:Me?.6:1},title:"Обновить",children:u.jsx(M,{icon:Me?"mdi:loading":"mdi:refresh"})})]}),Me?u.jsx("p",{style:{textAlign:"center",color:"#999",margin:"20px 0"},children:"Загрузка..."}):u.jsxs(u.Fragment,{children:[u.jsxs("div",{style:{marginBottom:"15px"},children:[u.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:"5px"},children:[u.jsxs("span",{style:{fontWeight:"600",color:"var(--text-color)"},children:[u.jsx(M,{icon:"mdi:server",style:{marginRight:"6px",verticalAlign:"middle"}}),"Сервер:"]}),u.jsxs("span",{style:{fontSize:"12px",color:"#666"},children:[(se==null?void 0:se.total_notes)||0," заметок"]})]}),u.jsxs("div",{style:{fontSize:"13px",color:"#666",marginLeft:"24px"},children:[u.jsxs("div",{children:["Обновлено:"," ",Gn((se==null?void 0:se.last_updated_at)||null)]}),u.jsxs("div",{children:["Создано:"," ",Gn((se==null?void 0:se.last_created_at)||null)]})]})]}),u.jsxs("div",{style:{marginBottom:"15px"},children:[u.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:"5px"},children:[u.jsxs("span",{style:{fontWeight:"600",color:"var(--text-color)"},children:[u.jsx(M,{icon:"mdi:database",style:{marginRight:"6px",verticalAlign:"middle"}}),"IndexedDB (локально):"]}),u.jsxs("span",{style:{fontSize:"12px",color:"#666"},children:[(he==null?void 0:he.total_notes)||0," заметок"]})]}),u.jsxs("div",{style:{fontSize:"13px",color:"#666",marginLeft:"24px"},children:[u.jsxs("div",{children:["Обновлено:"," ",Gn((he==null?void 0:he.last_updated_at)||null)]}),u.jsxs("div",{children:["Создано:"," ",Gn((he==null?void 0:he.last_created_at)||null)]})]})]}),u.jsx("div",{style:{padding:"10px",backgroundColor:"var(--bg-color)",borderRadius:"6px",border:"1px solid var(--border-color)",marginTop:"15px"},children:u.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[u.jsx("span",{style:{fontWeight:"600",fontSize:"14px"},children:"Статус синхронизации:"}),u.jsx("span",{style:{color:go().color,fontWeight:"600",fontSize:"13px"},children:go().status})]})}),u.jsxs("div",{style:{marginTop:"15px",paddingTop:"15px",borderTop:"1px solid var(--border-color)"},children:[u.jsxs("button",{onClick:qs,disabled:Ee,style:{width:"100%",padding:"10px",fontSize:"14px",fontWeight:"600",border:"1px solid var(--border-color)",borderRadius:"6px",backgroundColor:"var(--accent-color)",color:"#fff",cursor:Ee?"not-allowed":"pointer",opacity:Ee?.6:1,display:"flex",alignItems:"center",justifyContent:"center",gap:"8px"},children:[u.jsx(M,{icon:Ee?"mdi:loading":"mdi:sync",style:{fontSize:"18px"}}),Ee?"Синхронизация...":"Принудительная синхронизация"]}),u.jsx("p",{style:{color:"#666",fontSize:"12px",marginTop:"8px",textAlign:"center"},children:"Запустить немедленную синхронизацию данных с сервером"})]})]})]}),u.jsx("p",{style:{color:"#666",fontSize:"14px",marginBottom:"20px"},children:"Очистка локального кэша IndexedDB. Это удалит все заметки, сохраненные в браузере для оффлайн-режима. Данные на сервере не будут затронуты."}),u.jsxs("button",{className:"btn-danger",onClick:()=>ie(!0),style:{fontSize:"14px",padding:"10px 20px"},children:[u.jsx(M,{icon:"mdi:database-remove"})," Очистить локальный кэш (IndexedDB)"]})]})]}),u.jsx(to,{isOpen:V,onClose:()=>{E(!1),W("")},onConfirm:ot,title:"Подтверждение удаления",message:u.jsxs(u.Fragment,{children:[u.jsx("p",{style:{color:"#dc3545",fontWeight:"bold",marginBottom:"15px"},children:"⚠️ ВНИМАНИЕ: Это действие нельзя отменить!"}),u.jsx("p",{style:{marginBottom:"20px"},children:"Вы действительно хотите удалить ВСЕ архивные заметки? Все заметки и их изображения будут удалены навсегда."}),u.jsxs("div",{style:{marginBottom:"15px"},children:[u.jsx("label",{htmlFor:"deleteAllPassword",style:{display:"block",marginBottom:"5px",fontWeight:"bold"},children:"Введите пароль для подтверждения:"}),u.jsx("input",{type:"password",id:"deleteAllPassword",placeholder:"Пароль от аккаунта",className:"modal-password-input",value:z,onChange:j=>W(j.target.value),onKeyPress:j=>{j.key==="Enter"&&!U&&ot()}})]})]}),confirmText:U?"Удаление...":"Удалить все",cancelText:"Отмена",confirmType:"danger"}),u.jsx(to,{isOpen:X,onClose:()=>{ie(!1)},onConfirm:Cl,title:"Подтверждение очистки IndexedDB",message:u.jsxs(u.Fragment,{children:[u.jsx("p",{style:{color:"#dc3545",fontWeight:"bold",marginBottom:"15px"},children:"⚠️ ВНИМАНИЕ: Это действие нельзя отменить!"}),u.jsxs("p",{style:{marginBottom:"20px"},children:["Вы действительно хотите очистить локальный кэш IndexedDB? Все заметки, сохраненные в браузере для оффлайн-режима, будут удалены.",u.jsx("br",{}),u.jsx("br",{}),u.jsx("strong",{children:"Данные на сервере не будут затронуты."})," После очистки данные будут автоматически загружены с сервера при следующем подключении к интернету."]})]}),confirmText:Ie?"Очистка...":"Очистить",cancelText:"Отмена",confirmType:"danger"})]})},$_=()=>{const e=oe(n=>n.ui.notifications),t=wt();return u.jsx("div",{className:"notification-stack",children:e.map((n,r)=>u.jsx(F_,{notification:n,index:r,onRemove:()=>t(Sy(n.id))},n.id))})},F_=({notification:e,index:t,onRemove:n})=>{const[r,s]=S.useState(!1);S.useEffect(()=>{setTimeout(()=>s(!0),100)},[]),S.useEffect(()=>{const o=setTimeout(()=>{i()},4e3);return()=>clearTimeout(o)},[]);const i=()=>{s(!1),setTimeout(n,300)};return u.jsx("div",{className:`notification notification-${e.type} ${r?"visible":""}`,style:{top:`${20+t*70}px`},onClick:i,children:e.message})},z_=()=>{const[e,t]=S.useState(null),[n,r]=S.useState(!1);S.useEffect(()=>{const o=a=>{if(a.preventDefault(),window.matchMedia("(display-mode: standalone)").matches)return;const l=localStorage.getItem("pwa-install-dismissed");if(l){const c=new Date(l).getTime(),d=new Date().getTime(),f=7*24*60*60*1e3;if(d-cr(!0),2e3)};return window.addEventListener("beforeinstallprompt",o),()=>{window.removeEventListener("beforeinstallprompt",o)}},[]);const s=async()=>{if(!e)return;e.prompt();const{outcome:o}=await e.userChoice;if(o==="accepted"){console.log("Пользователь принял предложение об установке");const a=new Date().toISOString();localStorage.setItem("pwa-install-dismissed",a)}else console.log("Пользователь отклонил предложение об установке");t(null),r(!1)},i=()=>{r(!1);const o=new Date().toISOString();localStorage.setItem("pwa-install-dismissed",o)};return!n||!e?null:u.jsxs("div",{style:{position:"fixed",bottom:"20px",left:"50%",transform:"translateX(-50%)",backgroundColor:"var(--bg-primary)",border:"1px solid var(--border-primary)",borderRadius:"12px",padding:"16px 20px",boxShadow:"0 4px 20px var(--shadow-light)",zIndex:1e3,maxWidth:"90%",width:"400px",display:"flex",alignItems:"center",gap:"12px"},children:[u.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",gap:"4px"},children:[u.jsx("div",{style:{fontWeight:600,fontSize:"14px",color:"var(--text-primary)"},children:"Установить NoteJS?"}),u.jsx("div",{style:{fontSize:"12px",color:"var(--text-primary)",opacity:.7},children:"Установите приложение для быстрого доступа"})]}),u.jsxs("div",{style:{display:"flex",gap:"8px"},children:[u.jsxs("button",{onClick:s,style:{padding:"8px 16px",backgroundColor:"var(--accent-color)",color:"white",border:"none",borderRadius:"8px",cursor:"pointer",fontSize:"14px",fontWeight:500,display:"flex",alignItems:"center",gap:"6px"},children:[u.jsx(M,{icon:"mdi:download",width:"18",height:"18"}),"Установить"]}),u.jsx("button",{onClick:i,style:{padding:"8px",backgroundColor:"transparent",color:"var(--text-primary)",border:"none",borderRadius:"8px",cursor:"pointer",display:"flex",alignItems:"center",opacity:.6},"aria-label":"Закрыть",children:u.jsx(M,{icon:"mdi:close",width:"20",height:"20"})})]})]})},U_=()=>u.jsx("div",{className:"loading-overlay",children:u.jsx("div",{className:"loading-content",children:u.jsx("div",{className:"loading-spinner"})})}),dc=({children:e})=>{const t=oe(o=>o.auth.isAuthenticated),n=oe(o=>o.auth.userId),r=wt(),[s,i]=S.useState(!0);return S.useEffect(()=>{(async()=>{try{const a=await Vr.checkStatus();if(a.authenticated){const l=a.userId;n&&n!==l&&(console.log(`[ProtectedRoute] User changed from ${n} to ${l}, clearing IndexedDB`),await D.clearAll()),r(Ld({userId:l,username:a.username}))}else r(Xi())}catch{r(Xi())}finally{i(!1)}})()},[r,n]),s?u.jsx(U_,{}):t?u.jsx(u.Fragment,{children:e}):u.jsx(ty,{to:"/",replace:!0})},B_=()=>(Kd(),u.jsxs(u.Fragment,{children:[u.jsx($_,{}),u.jsx(z_,{}),u.jsx(hS,{children:u.jsxs(oS,{children:[u.jsx(Tr,{path:"/",element:u.jsx(bC,{})}),u.jsx(Tr,{path:"/register",element:u.jsx(CC,{})}),u.jsx(Tr,{path:"/notes",element:u.jsx(dc,{children:u.jsx(L_,{})})}),u.jsx(Tr,{path:"/profile",element:u.jsx(dc,{children:u.jsx(M_,{})})}),u.jsx(Tr,{path:"/settings",element:u.jsx(dc,{children:u.jsx(A_,{})})}),u.jsx(Tr,{path:"*",element:u.jsx(ty,{to:"/",replace:!0})})]})})]})),W_=()=>u.jsx($S,{store:te,children:u.jsx(B_,{})});async function H_(){try{console.log("[Init] Initializing offline mode..."),await D.init(),console.log("[Init] IndexedDB initialized");let e=navigator.onLine;if(!navigator.onLine)e=!1;else try{e=await Tu()}catch(n){console.warn("[Init] Network status check failed, assuming offline:",n),e=!1}navigator.onLine||(e=!1),te.dispatch(Ns(!e)),console.log(`[Init] Network status: ${e?"online":"offline"}`),gh.onOnline(async()=>{console.log("[Network] Online event detected");const n=await Tu();te.dispatch(Ns(!n)),n&&(te.dispatch(_s({message:"Подключение восстановлено, начинаем синхронизацию...",type:"info"})),await Ba.startSync())}),gh.onOffline(()=>{console.log("[Network] Offline event detected"),te.dispatch(Ns(!0)),te.dispatch(_s({message:"Работаем в offline режиме",type:"warning"}))});const t=await D.getPendingSyncCount();te.dispatch(Md(t)),t>0&&console.log(`[Init] Found ${t} pending sync items`),e&&t>0&&(console.log("[Init] Starting initial sync..."),setTimeout(()=>{Ba.startSync()},2e3)),console.log("[Init] Offline mode initialized successfully")}catch(e){console.error("[Init] Error initializing offline mode:",e)}}H_();fc.createRoot(document.getElementById("root")).render(u.jsx(xn.StrictMode,{children:u.jsx(W_,{})}));