PageSourceSearch

https://smartblog.ai/assets/index-CdHZ8Cp1.js

js smartblog.ai collected 2026-10-05 15:05:24 UTC 1,755,435 bytes, 1,050 lines download raw bytes

vendor: 13,151 bytes, lines 1-19
1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Index-q8qT46dB.js","assets/elevenlabs-CpW4MH00.js","assets/livekit-C6cR2JI6.js","assets/FooterV2-DP0IkI1X.js","assets/FaqV2-KQJxzFbG.js","assets/framer-motion-efzc2Ucs.js","assets/Pricing-DMm2lYTW.js","assets/useReveal-CxBxD5TE.js","assets/HowItWorks-_cuCEH65.js","assets/UseCases-RYWmpFrm.js","assets/Login-DSKS4TJz.js","assets/ResetPassword-BVFrw4My.js","assets/PrivacyPolicy-B4miPBfo.js","assets/LegalPageShell-CwD9Qz3L.js","assets/Terms-Cmmy9S02.js","assets/Offer-D2FrWIDu.js","assets/CookiePolicy-CrZOIHG-.js","assets/DocsWorkerApi-0QAhqdjZ.js","assets/DocsPublicApi-CsIq8G0q.js","assets/ConsultationJoin-Dbs2vVKM.js","assets/NotFound-Bb4y9ocl.js"])))=>i.map(i=>d[i]);
2var pE=Object.defineProperty;var wb=e=>{throw TypeError(e)};var fE=(e,t,s)=>t in e?pE(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var Cu=(e,t,s)=>fE(e,typeof t!="symbol"?t+"":t,s),Bp=(e,t,s)=>t.has(e)||wb("Cannot "+s);var q=(e,t,s)=>(Bp(e,t,"read from private field"),s?s.call(e):t.get(e)),Xe=(e,t,s)=>t.has(e)?wb("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,s),ze=(e,t,s,r)=>(Bp(e,t,"write to private field"),r?r.call(e,s):t.set(e,s),s),jt=(e,t,s)=>(Bp(e,t,"access private method"),s);var Tu=(e,t,s,r)=>({set _(a){ze(e,t,a,s)},get _(){return q(e,t,r)}});import{r as h,g as gE,j as n,R as iv,o as Se}from"./elevenlabs-CpW4MH00.js";import{A as xn,m as de}from"./framer-motion-efzc2Ucs.js";import"./livekit-C6cR2JI6.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))r(a);new MutationObserver(a=>{for(const i of a)if(i.type==="childList")for(const o of i.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&r(o)}).observe(document,{childList:!0,subtree:!0});function s(a){const i={};return a.integrity&&(i.integrity=a.integrity),a.referrerPolicy&&(i.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?i.credentials="include":a.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(a){if(a.ep)return;a.ep=!0;const i=s(a);fetch(a.href,i)}})();var bj={exports:{}},jn={},wj={exports:{}},jj={};/**
3 * @license React
4 * scheduler.production.min.js
5 *
6 * Copyright (c) Facebook, Inc. and its affiliates.
7 *
8 * This source code is licensed under the MIT license found in the
9 * LICENSE file in the root directory of this source tree.
10 */(function(e){function t(R,F){var $=R.length;R.push(F);e:for(;0<$;){var J=$-1>>>1,Y=R[J];if(0<a(Y,F))R[J]=F,R[$]=Y,$=J;else break e}}function s(R){return R.length===0?null:R[0]}function r(R){if(R.length===0)return null;var F=R[0],$=R.pop();if($!==F){R[0]=$;e:for(var J=0,Y=R.length,re=Y>>>1;J<re;){var G=2*(J+1)-1,O=R[G],Z=G+1,A=R[Z];if(0>a(O,$))Z<Y&&0>a(A,O)?(R[J]=A,R[Z]=$,J=Z):(R[J]=O,R[G]=$,J=G);else if(Z<Y&&0>a(A,$))R[J]=A,R[Z]=$,J=Z;else break e}}return F}function a(R,F){var $=R.sortIndex-F.sortIndex;return $!==0?$:R.id-F.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;e.unstable_now=function(){return i.now()}}else{var o=Date,l=o.now();e.unstable_now=function(){return o.now()-l}}var c=[],d=[],u=1,m=null,p=3,f=!1,g=!1,x=!1,b=typeof setTimeout=="function"?setTimeout:null,v=typeof clearTimeout=="function"?clearTimeout:null,y=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(R){for(var F=s(d);F!==null;){if(F.callback===null)r(d);else if(F.startTime<=R)r(d),F.sortIndex=F.expirationTime,t(c,F);else break;F=s(d)}}function j(R){if(x=!1,w(R),!g)if(s(c)!==null)g=!0,V(_);else{var F=s(d);F!==null&&te(j,F.startTime-R)}}function _(R,F){g=!1,x&&(x=!1,v(S),S=-1),f=!0;var $=p;try{for(w(F),m=s(c);m!==null&&(!(m.expirationTime>F)||R&&!B());){var J=m.callback;if(typeof J=="function"){m.callback=null,p=m.priorityLevel;var Y=J(m.expirationTime<=F);F=e.unstable_now(),typeof Y=="function"?m.callback=Y:m===s(c)&&r(c),w(F)}else r(c);m=s(c)}if(m!==null)var re=!0;else{var G=s(d);G!==null&&te(j,G.startTime-F),re=!1}return re}finally{m=null,p=$,f=!1}}var N=!1,k=null,S=-1,T=5,C=-1;function B(){return!(e.unstable_now()-C<T)}function E(){if(k!==null){var R=e.unstable_now();C=R;var F=!0;try{F=k(!0,R)}finally{F?H():(N=!1,k=null)}}else N=!1}var H;if(typeof y=="function")H=function(){y(E)};else if(typeof MessageChannel<"u"){var z=new MessageChannel,ne=z.port2;z.port1.onmessage=E,H=function(){ne.postMessage(null)}}else H=function(){b(E,0)};function V(R){k=R,N||(N=!0,H())}function te(R,F){S=b(function(){R(e.unstable_now())},F)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(R){R.callback=null},e.unstable_continueExecution=function(){g||f||(g=!0,V(_))},e.unstable_forceFrameRate=function(R){0>R||125<R?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):T=0<R?Math.floor(1e3/R):5},e.unstable_getCurrentPriorityLevel=function(){return p},e.unstable_getFirstCallbackNode=function(){return s(c)},e.unstable_next=function(R){switch(p){case 1:case 2:case 3:var F=3;break;default:F=p}var $=p;p=F;try{return R()}finally{p=$}},e.unstable_pauseExecution=function(){},e.unstable_requestPaint=function(){},e.unstable_runWithPriority=function(R,F){switch(R){case 1:case 2:case 3:case 4:case 5:break;default:R=3}var $=p;p=R;try{return F()}finally{p=$}},e.unstable_scheduleCallback=function(R,F,$){var J=e.unstable_now();switch(typeof $=="object"&&$!==null?($=$.delay,$=typeof $=="number"&&0<$?J+$:J):$=J,R){case 1:var Y=-1;break;case 2:Y=250;break;case 5:Y=1073741823;break;case 4:Y=1e4;break;default:Y=5e3}return Y=$+Y,R={id:u++,callback:F,priorityLevel:R,startTime:$,expirationTime:Y,sortIndex:-1},$>J?(R.sortIndex=$,t(d,R),s(c)===null&&R===s(d)&&(x?(v(S),S=-1):x=!0,te(j,$-J))):(R.sortIndex=Y,t(c,R),g||f||(g=!0,V(_))),R},e.unstable_shouldYield=B,e.unstable_wrapCallback=function(R){var F=p;return function(){var $=p;p=F;try{return R.apply(this,arguments)}finally{p=$}}}})(jj);wj.exports=jj;var xE=wj.exports;/**
11 * @license React
12 * react-dom.production.min.js
13 *
14 * Copyright (c) Facebook, Inc. and its affiliates.
15 *
16 * This source code is licensed under the MIT license found in the
17 * LICENSE file in the root directory of this source tree.
18 */var vE=h,vn=xE;function be(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,s=1;s<arguments.length;s++)t+="&args[]="+encodeURIComponent(arguments[s]);return"Minified React error #"+e+"; visit "+t+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var _j=new Set,Xc={};function io(e,t){_l(e,t),_l(e+"Capture",t)}function _l(e,t){for(Xc[e]=t,e=0;e<t.length;e++)_j.add(t[e])}var Yr=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),rg=Object.prototype.hasOwnProperty,yE=/^[: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]*$/,jb={},_b={};function bE(e){return rg.call(_b,e)?!0:rg.call(jb,e)?!1:yE.test(e)?_b[e]=!0:(jb[e]=!0,!1)}function wE(e,t,s,r){if(s!==null&&s.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:s!==null?!s.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function jE(e,t,s,r){if(t===null||typeof t>"u"||wE(e,t,s,r))return!0;if(r)return!1;if(s!==null)switch(s.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 Us(e,t,s,r,a,i,o){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=a,this.mustUseProperty=s,this.propertyName=e,this.type=t,this.sanitizeURL=i,this.removeEmptyString=o}var Ss={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){Ss[e]=new Us(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];Ss[t]=new Us(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){Ss[e]=new Us(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){Ss[e]=new Us(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){Ss[e]=new Us(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){Ss[e]=new Us(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){Ss[e]=new Us(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){Ss[e]=new Us(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){Ss[e]=new Us(e,5,!1,e.toLowerCase(),null,!1,!1)});var ov=/[\-:]([a-z])/g;function lv(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(ov,lv);Ss[t]=new Us(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(ov,lv);Ss[t]=new Us(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(ov,lv);Ss[t]=new Us(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){Ss[e]=new Us(e,1,!1,e.toLowerCase(),null,!1,!1)});Ss.xlinkHref=new Us("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){Ss[e]=new Us(e,1,!1,e.toLowerCase(),null,!0,!0)});function cv(e,t,s,r){var a=Ss.hasOwnProperty(t)?Ss[t]:null;(a!==null?a.type!==0:r||!(2<t.length)||t[0]!=="o"&&t[0]!=="O"||t[1]!=="n"&&t[1]!=="N")&&(jE(t,s,a,r)&&(s=null),r||a===null?bE(t)&&(s===null?e.removeAttribute(t):e.setAttribute(t,""+s)):a.mustUseProperty?e[a.propertyName]=s===null?a.type===3?!1:"":s:(t=a.attributeName,r=a.attributeNamespace,s===null?e.removeAttribute(t):(a=a.type,s=a===3||a===4&&s===!0?"":""+s,r?e.setAttributeNS(r,t,s):e.setAttribute(t,s))))}var sa=vE.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,Pu=Symbol.for("react.element"),Mo=Symbol.for("react.portal"),zo=Symbol.for("react.fragment"),dv=Symbol.for("react.strict_mode"),ag=Symbol.for("react.profiler"),kj=Symbol.for("react.provider"),Nj=Symbol.for("react.context"),uv=Symbol.for("react.forward_ref"),ig=Symbol.for("react.suspense"),og=Symbol.for("react.suspense_list"),hv=Symbol.for("react.memo"),ba=Symbol.for("react.lazy"),Sj=Symbol.for("react.offscreen"),kb=Symbol.iterator;function uc(e){return e===null||typeof e!="object"?null:(e=kb&&e[kb]||e["@@iterator"],typeof e=="function"?e:null)}var qt=Object.assign,Vp;function Nc(e){if(Vp===void 0)try{throw Error()}catch(s){var t=s.stack.trim().match(/\n( *(at )?)/);Vp=t&&t[1]||""}return`
19`+Vp+e}var qp=!1;function Hp(e,t){if(!e||qp)return"";qp=!0;var s=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(t)if(t=function(){throw Error()},Object.defineProperty(t.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(t,[])}catch(d){var r=d}Reflect.construct(e,[],t)}else{try{t.call()}catch(d){r=d}e.call(t.prototype)}else{try{throw Error()}catch(d){r=d}e()}}
vendor: 14,694 bytes, lines 19-22
19catch(d){if(d&&r&&typeof d.stack=="string"){for(var a=d.stack.split(`
20`),i=r.stack.split(`
21`),o=a.length-1,l=i.length-1;1<=o&&0<=l&&a[o]!==i[l];)l--;for(;1<=o&&0<=l;o--,l--)if(a[o]!==i[l]){if(o!==1||l!==1)do if(o--,l--,0>l||a[o]!==i[l]){var c=`
22`+a[o].replace(" at new "," at ");return e.displayName&&c.includes("<anonymous>")&&(c=c.replace("<anonymous>",e.displayName)),c}while(1<=o&&0<=l);break}}}finally{qp=!1,Error.prepareStackTrace=s}return(e=e?e.displayName||e.name:"")?Nc(e):""}function _E(e){switch(e.tag){case 5:return Nc(e.type);case 16:return Nc("Lazy");case 13:return Nc("Suspense");case 19:return Nc("SuspenseList");case 0:case 2:case 15:return e=Hp(e.type,!1),e;case 11:return e=Hp(e.type.render,!1),e;case 1:return e=Hp(e.type,!0),e;default:return""}}function lg(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 zo:return"Fragment";case Mo:return"Portal";case ag:return"Profiler";case dv:return"StrictMode";case ig:return"Suspense";case og:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case Nj:return(e.displayName||"Context")+".Consumer";case kj:return(e._context.displayName||"Context")+".Provider";case uv:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case hv:return t=e.displayName||null,t!==null?t:lg(e.type)||"Memo";case ba:t=e._payload,e=e._init;try{return lg(e(t))}catch{}}return null}function kE(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 lg(t);case 8:return t===dv?"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 ti(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function Cj(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function NE(e){var t=Cj(e)?"checked":"value",s=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof s<"u"&&typeof s.get=="function"&&typeof s.set=="function"){var a=s.get,i=s.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return a.call(this)},set:function(o){r=""+o,i.call(this,o)}}),Object.defineProperty(e,t,{enumerable:s.enumerable}),{getValue:function(){return r},setValue:function(o){r=""+o},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function Eu(e){e._valueTracker||(e._valueTracker=NE(e))}function Tj(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var s=t.getValue(),r="";return e&&(r=Cj(e)?e.checked?"true":"false":e.value),e=r,e!==s?(t.setValue(e),!0):!1}function Eh(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 cg(e,t){var s=t.checked;return qt({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:s??e._wrapperState.initialChecked})}function Nb(e,t){var s=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;s=ti(t.value!=null?t.value:s),e._wrapperState={initialChecked:r,initialValue:s,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function Pj(e,t){t=t.checked,t!=null&&cv(e,"checked",t,!1)}function dg(e,t){Pj(e,t);var s=ti(t.value),r=t.type;if(s!=null)r==="number"?(s===0&&e.value===""||e.value!=s)&&(e.value=""+s):e.value!==""+s&&(e.value=""+s);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?ug(e,t.type,s):t.hasOwnProperty("defaultValue")&&ug(e,t.type,ti(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function Sb(e,t,s){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,s||t===e.value||(e.value=t),e.defaultValue=t}s=e.name,s!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,s!==""&&(e.name=s)}function ug(e,t,s){(t!=="number"||Eh(e.ownerDocument)!==e)&&(s==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+s&&(e.defaultValue=""+s))}var Sc=Array.isArray;function Xo(e,t,s,r){if(e=e.options,t){t={};for(var a=0;a<s.length;a++)t["$"+s[a]]=!0;for(s=0;s<e.length;s++)a=t.hasOwnProperty("$"+e[s].value),e[s].selected!==a&&(e[s].selected=a),a&&r&&(e[s].defaultSelected=!0)}else{for(s=""+ti(s),t=null,a=0;a<e.length;a++){if(e[a].value===s){e[a].selected=!0,r&&(e[a].defaultSelected=!0);return}t!==null||e[a].disabled||(t=e[a])}t!==null&&(t.selected=!0)}}function hg(e,t){if(t.dangerouslySetInnerHTML!=null)throw Error(be(91));return qt({},t,{value:void 0,defaultValue:void 0,children:""+e._wrapperState.initialValue})}function Cb(e,t){var s=t.value;if(s==null){if(s=t.children,t=t.defaultValue,s!=null){if(t!=null)throw Error(be(92));if(Sc(s)){if(1<s.length)throw Error(be(93));s=s[0]}t=s}t==null&&(t=""),s=t}e._wrapperState={initialValue:ti(s)}}function Ej(e,t){var s=ti(t.value),r=ti(t.defaultValue);s!=null&&(s=""+s,s!==e.value&&(e.value=s),t.defaultValue==null&&e.defaultValue!==s&&(e.defaultValue=s)),r!=null&&(e.defaultValue=""+r)}function Tb(e){var t=e.textContent;t===e._wrapperState.initialValue&&t!==""&&t!==null&&(e.value=t)}function Aj(e){switch(e){case"svg":return"http://www.w3.org/2000/svg";case"math":return"http://www.w3.org/1998/Math/MathML";default:return"http://www.w3.org/1999/xhtml"}}function mg(e,t){return e==null||e==="http://www.w3.org/1999/xhtml"?Aj(t):e==="http://www.w3.org/2000/svg"&&t==="foreignObject"?"http://www.w3.org/1999/xhtml":e}var Au,Rj=function(e){return typeof MSApp<"u"&&MSApp.execUnsafeLocalFunction?function(t,s,r,a){MSApp.execUnsafeLocalFunction(function(){return e(t,s,r,a)})}:e}(function(e,t){if(e.namespaceURI!=="http://www.w3.org/2000/svg"||"innerHTML"in e)e.innerHTML=t;else{for(Au=Au||document.createElement("div"),Au.innerHTML="<svg>"+t.valueOf().toString()+"</svg>",t=Au.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function ed(e,t){if(t){var s=e.firstChild;if(s&&s===e.lastChild&&s.nodeType===3){s.nodeValue=t;return}}e.textContent=t}var Mc={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},SE=["Webkit","ms","Moz","O"];Object.keys(Mc).forEach(function(e){SE.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),Mc[t]=Mc[e]})});function $j(e,t,s){return t==null||typeof t=="boolean"||t===""?"":s||typeof t!="number"||t===0||Mc.hasOwnProperty(e)&&Mc[e]?(""+t).trim():t+"px"}function Lj(e,t){e=e.style;for(var s in t)if(t.hasOwnProperty(s)){var r=s.indexOf("--")===0,a=$j(s,t[s],r);s==="float"&&(s="cssFloat"),r?e.setProperty(s,a):e[s]=a}}var CE=qt({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 pg(e,t){if(t){if(CE[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(be(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(be(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(be(61))}if(t.style!=null&&typeof t.style!="object")throw Error(be(62))}}function fg(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 gg=null;function mv(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var xg=null,el=null,tl=null;function Pb(e){if(e=Zd(e)){if(typeof xg!="function")throw Error(be(280));var t=e.stateNode;t&&(t=Dm(t),xg(e.stateNode,e.type,t))}}function Ij(e){el?tl?tl.push(e):tl=[e]:el=e}function Oj(){if(el){var e=el,t=tl;if(tl=el=null,Pb(e),t)for(e=0;e<t.length;e++)Pb(t[e])}}function Dj(e,t){return e(t)}function Mj(){}var Wp=!1;function zj(e,t,s){if(Wp)return e(t,s);Wp=!0;try{return Dj(e,t,s)}finally{Wp=!1,(el!==null||tl!==null)&&(Mj(),Oj())}}function td(e,t){var s=e.stateNode;if(s===null)return null;var r=Dm(s);if(r===null)return null;s=r[t];e:switch(t){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(r=!r.disabled)||(e=e.type,r=!(e==="button"||e==="input"||e==="select"||e==="textarea")),e=!r;break e;default:e=!1}if(e)return null;if(s&&typeof s!="function")throw Error(be(231,t,typeof s));return s}var vg=!1;if(Yr)try{var hc={};Object.defineProperty(hc,"passive",{get:function(){vg=!0}}),window.addEventListener("test",hc,hc),window.removeEventListener("test",hc,hc)}catch{vg=!1}function TE(e,t,s,r,a,i,o,l,c){var d=Array.prototype.slice.call(arguments,3);try{t.apply(s,d)}catch(u){this.onError(u)}}var zc=!1,Ah=null,Rh=!1,yg=null,PE={onError:function(e){zc=!0,Ah=e}};function EE(e,t,s,r,a,i,o,l,c){zc=!1,Ah=null,TE.apply(PE,arguments)}function AE(e,t,s,r,a,i,o,l,c){if(EE.apply(this,arguments),zc){if(zc){var d=Ah;zc=!1,Ah=null}else throw Error(be(198));Rh||(Rh=!0,yg=d)}}function oo(e){var t=e,s=e;if(e.alternate)for(;t.return;)t=t.return;else{e=t;do t=e,t.flags&4098&&(s=t.return),e=t.return;while(e)}return t.tag===3?s:null}function Fj(e){if(e.tag===13){var t=e.memoizedState;if(t===null&&(e=e.alternate,e!==null&&(t=e.memoizedState)),t!==null)return t.dehydrated}return null}function Eb(e){if(oo(e)!==e)throw Error(be(188))}function RE(e){var t=e.alternate;if(!t){if(t=oo(e),t===null)throw Error(be(188));return t!==e?null:e}for(var s=e,r=t;;){var a=s.return;if(a===null)break;var i=a.alternate;if(i===null){if(r=a.return,r!==null){s=r;continue}break}if(a.child===i.child){for(i=a.child;i;){if(i===s)return Eb(a),e;if(i===r)return Eb(a),t;i=i.sibling}throw Error(be(188))}if(s.return!==r.return)s=a,r=i;else{for(var o=!1,l=a.child;l;){if(l===s){o=!0,s=a,r=i;break}if(l===r){o=!0,r=a,s=i;break}l=l.sibling}if(!o){for(l=i.child;l;){if(l===s){o=!0,s=i,r=a;break}if(l===r){o=!0,r=i,s=a;break}l=l.sibling}if(!o)throw Error(be(189))}}if(s.alternate!==r)throw Error(be(190))}if(s.tag!==3)throw Error(be(188));return s.stateNode.current===s?e:t}function Uj(e){return e=RE(e),e!==null?Bj(e):null}function Bj(e){if(e.tag===5||e.tag===6)return e;for(e=e.child;e!==null;){var t=Bj(e);if(t!==null)return t;e=e.sibling}return null}var Vj=vn.unstable_scheduleCallback,Ab=vn.unstable_cancelCallback,$E=vn.unstable_shouldYield,LE=vn.unstable_requestPaint,ts=vn.unstable_now,IE=vn.unstable_getCurrentPriorityLevel,pv=vn.unstable_ImmediatePriority,qj=vn.unstable_UserBlockingPriority,$h=vn.unstable_NormalPriority,OE=vn.unstable_LowPriority,Hj=vn.unstable_IdlePriority,$m=null,_r=null;function DE(e){if(_r&&typeof _r.onCommitFiberRoot=="function")try{_r.onCommitFiberRoot($m,e,void 0,(e.current.flags&128)===128)}catch{}}var Yn=Math.clz32?Math.clz32:FE,ME=Math.log,zE=Math.LN2;function FE(e){return e>>>=0,e===0?32:31-(ME(e)/zE|0)|0}var Ru=64,$u=4194304;function Cc(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 Lh(e,t){var s=e.pendingLanes;if(s===0)return 0;var r=0,a=e.suspendedLanes,i=e.pingedLanes,o=s&268435455;if(o!==0){var l=o&~a;l!==0?r=Cc(l):(i&=o,i!==0&&(r=Cc(i)))}else o=s&~a,o!==0?r=Cc(o):i!==0&&(r=Cc(i));if(r===0)return 0;if(t!==0&&t!==r&&!(t&a)&&(a=r&-r,i=t&-t,a>=i||a===16&&(i&4194240)!==0))return t;if(r&4&&(r|=s&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0<t;)s=31-Yn(t),a=1<<s,r|=e[s],t&=~a;return r}function UE(e,t){switch(e){case 1:case 2:case 4:return t+250;case 8:case 16:case 32:case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t+5e3;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return-1;case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function BE(e,t){for(var s=e.suspendedLanes,r=e.pingedLanes,a=e.expirationTimes,i=e.pendingLanes;0<i;){var o=31-Yn(i),l=1<<o,c=a[o];c===-1?(!(l&s)||l&r)&&(a[o]=UE(l,t)):c<=t&&(e.expiredLanes|=l),i&=~l}}function bg(e){return e=e.pendingLanes&-1073741825,e!==0?e:e&1073741824?1073741824:0}function Wj(){var e=Ru;return Ru<<=1,!(Ru&4194240)&&(Ru=64),e}function Gp(e){for(var t=[],s=0;31>s;s++)t.push(e);return t}function Qd(e,t,s){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-Yn(t),e[t]=s}function VE(e,t){var s=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<s;){var a=31-Yn(s),i=1<<a;t[a]=0,r[a]=-1,e[a]=-1,s&=~i}}function fv(e,t){var s=e.entangledLanes|=t;for(e=e.entanglements;s;){var r=31-Yn(s),a=1<<r;a&t|e[r]&t&&(e[r]|=t),s&=~a}}var At=0;function Gj(e){return e&=-e,1<e?4<e?e&268435455?16:536870912:4:1}
vendor: 5,160 bytes, line 22
22var Yj,gv,Kj,Qj,Jj,wg=!1,Lu=[],Ua=null,Ba=null,Va=null,sd=new Map,nd=new Map,_a=[],qE="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset submit".split(" ");function Rb(e,t){switch(e){case"focusin":case"focusout":Ua=null;break;case"dragenter":case"dragleave":Ba=null;break;case"mouseover":case"mouseout":Va=null;break;case"pointerover":case"pointerout":sd.delete(t.pointerId);break;case"gotpointercapture":case"lostpointercapture":nd.delete(t.pointerId)}}function mc(e,t,s,r,a,i){return e===null||e.nativeEvent!==i?(e={blockedOn:t,domEventName:s,eventSystemFlags:r,nativeEvent:i,targetContainers:[a]},t!==null&&(t=Zd(t),t!==null&&gv(t)),e):(e.eventSystemFlags|=r,t=e.targetContainers,a!==null&&t.indexOf(a)===-1&&t.push(a),e)}function HE(e,t,s,r,a){switch(t){case"focusin":return Ua=mc(Ua,e,t,s,r,a),!0;case"dragenter":return Ba=mc(Ba,e,t,s,r,a),!0;case"mouseover":return Va=mc(Va,e,t,s,r,a),!0;case"pointerover":var i=a.pointerId;return sd.set(i,mc(sd.get(i)||null,e,t,s,r,a)),!0;case"gotpointercapture":return i=a.pointerId,nd.set(i,mc(nd.get(i)||null,e,t,s,r,a)),!0}return!1}function Zj(e){var t=Pi(e.target);if(t!==null){var s=oo(t);if(s!==null){if(t=s.tag,t===13){if(t=Fj(s),t!==null){e.blockedOn=t,Jj(e.priority,function(){Kj(s)});return}}else if(t===3&&s.stateNode.current.memoizedState.isDehydrated){e.blockedOn=s.tag===3?s.stateNode.containerInfo:null;return}}}e.blockedOn=null}function mh(e){if(e.blockedOn!==null)return!1;for(var t=e.targetContainers;0<t.length;){var s=jg(e.domEventName,e.eventSystemFlags,t[0],e.nativeEvent);if(s===null){s=e.nativeEvent;var r=new s.constructor(s.type,s);gg=r,s.target.dispatchEvent(r),gg=null}else return t=Zd(s),t!==null&&gv(t),e.blockedOn=s,!1;t.shift()}return!0}function $b(e,t,s){mh(e)&&s.delete(t)}function WE(){wg=!1,Ua!==null&&mh(Ua)&&(Ua=null),Ba!==null&&mh(Ba)&&(Ba=null),Va!==null&&mh(Va)&&(Va=null),sd.forEach($b),nd.forEach($b)}function pc(e,t){e.blockedOn===t&&(e.blockedOn=null,wg||(wg=!0,vn.unstable_scheduleCallback(vn.unstable_NormalPriority,WE)))}function rd(e){function t(a){return pc(a,e)}if(0<Lu.length){pc(Lu[0],e);for(var s=1;s<Lu.length;s++){var r=Lu[s];r.blockedOn===e&&(r.blockedOn=null)}}for(Ua!==null&&pc(Ua,e),Ba!==null&&pc(Ba,e),Va!==null&&pc(Va,e),sd.forEach(t),nd.forEach(t),s=0;s<_a.length;s++)r=_a[s],r.blockedOn===e&&(r.blockedOn=null);for(;0<_a.length&&(s=_a[0],s.blockedOn===null);)Zj(s),s.blockedOn===null&&_a.shift()}var sl=sa.ReactCurrentBatchConfig,Ih=!0;function GE(e,t,s,r){var a=At,i=sl.transition;sl.transition=null;try{At=1,xv(e,t,s,r)}finally{At=a,sl.transition=i}}function YE(e,t,s,r){var a=At,i=sl.transition;sl.transition=null;try{At=4,xv(e,t,s,r)}finally{At=a,sl.transition=i}}function xv(e,t,s,r){if(Ih){var a=jg(e,t,s,r);if(a===null)nf(e,t,r,Oh,s),Rb(e,r);else if(HE(a,e,t,s,r))r.stopPropagation();else if(Rb(e,r),t&4&&-1<qE.indexOf(e)){for(;a!==null;){var i=Zd(a);if(i!==null&&Yj(i),i=jg(e,t,s,r),i===null&&nf(e,t,r,Oh,s),i===a)break;a=i}a!==null&&r.stopPropagation()}else nf(e,t,r,null,s)}}var Oh=null;function jg(e,t,s,r){if(Oh=null,e=mv(r),e=Pi(e),e!==null)if(t=oo(e),t===null)e=null;else if(s=t.tag,s===13){if(e=Fj(t),e!==null)return e;e=null}else if(s===3){if(t.stateNode.current.memoizedState.isDehydrated)return t.tag===3?t.stateNode.containerInfo:null;e=null}else t!==e&&(e=null);return Oh=e,null}function Xj(e){switch(e){case"cancel":case"click":case"close":case"contextmenu":case"copy":case"cut":case"auxclick":case"dblclick":case"dragend":case"dragstart":case"drop":case"focusin":case"focusout":case"input":case"invalid":case"keydown":case"keypress":case"keyup":case"mousedown":case"mouseup":case"paste":case"pause":case"play":case"pointercancel":case"pointerdown":case"pointerup":case"ratechange":case"reset":case"resize":case"seeked":case"submit":case"touchcancel":case"touchend":case"touchstart":case"volumechange":case"change":case"selectionchange":case"textInput":case"compositionstart":case"compositionend":case"compositionupdate":case"beforeblur":case"afterblur":case"beforeinput":case"blur":case"fullscreenchange":case"focus":case"hashchange":case"popstate":case"select":case"selectstart":return 1;case"drag":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"mousemove":case"mouseout":case"mouseover":case"pointermove":case"pointerout":case"pointerover":case"scroll":case"toggle":case"touchmove":case"wheel":case"mouseenter":case"mouseleave":case"pointerenter":case"pointerleave":return 4;case"message":switch(IE()){case pv:return 1;case qj:return 4;case $h:case OE:return 16;case Hj:return 536870912;default:return 16}default:return 16}}var Ia=null,vv=null,ph=null;function e_(){if(ph)return ph;var e,t=vv,s=t.length,r,a="value"in Ia?Ia.value:Ia.textContent,i=a.length;for(e=0;e<s&&t[e]===a[e];e++);var o=s-e;for(r=1;r<=o&&t[s-r]===a[i-r];r++);return ph=a.slice(e,1<r?1-r:void 0)}function fh(e){var t=e.keyCode;return"charCode"in e?(e=e.charCode,e===0&&t===13&&(e=13)):e=t,e===10&&(e=13),32<=e||e===13?e:0}function Iu(){return!0}
vendor: 6,190 bytes, line 22
22function Lb(){return!1}function _n(e){function t(s,r,a,i,o){this._reactName=s,this._targetInst=a,this.type=r,this.nativeEvent=i,this.target=o,this.currentTarget=null;for(var l in e)e.hasOwnProperty(l)&&(s=e[l],this[l]=s?s(i):i[l]);return this.isDefaultPrevented=(i.defaultPrevented!=null?i.defaultPrevented:i.returnValue===!1)?Iu:Lb,this.isPropagationStopped=Lb,this}return qt(t.prototype,{preventDefault:function(){this.defaultPrevented=!0;var s=this.nativeEvent;s&&(s.preventDefault?s.preventDefault():typeof s.returnValue!="unknown"&&(s.returnValue=!1),this.isDefaultPrevented=Iu)},stopPropagation:function(){var s=this.nativeEvent;s&&(s.stopPropagation?s.stopPropagation():typeof s.cancelBubble!="unknown"&&(s.cancelBubble=!0),this.isPropagationStopped=Iu)},persist:function(){},isPersistent:Iu}),t}var Kl={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},yv=_n(Kl),Jd=qt({},Kl,{view:0,detail:0}),KE=_n(Jd),Yp,Kp,fc,Lm=qt({},Jd,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:bv,button:0,buttons:0,relatedTarget:function(e){return e.relatedTarget===void 0?e.fromElement===e.srcElement?e.toElement:e.fromElement:e.relatedTarget},movementX:function(e){return"movementX"in e?e.movementX:(e!==fc&&(fc&&e.type==="mousemove"?(Yp=e.screenX-fc.screenX,Kp=e.screenY-fc.screenY):Kp=Yp=0,fc=e),Yp)},movementY:function(e){return"movementY"in e?e.movementY:Kp}}),Ib=_n(Lm),QE=qt({},Lm,{dataTransfer:0}),JE=_n(QE),ZE=qt({},Jd,{relatedTarget:0}),Qp=_n(ZE),XE=qt({},Kl,{animationName:0,elapsedTime:0,pseudoElement:0}),eA=_n(XE),tA=qt({},Kl,{clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}}),sA=_n(tA),nA=qt({},Kl,{data:0}),Ob=_n(nA),rA={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},aA={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},iA={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function oA(e){var t=this.nativeEvent;return t.getModifierState?t.getModifierState(e):(e=iA[e])?!!t[e]:!1}function bv(){return oA}var lA=qt({},Jd,{key:function(e){if(e.key){var t=rA[e.key]||e.key;if(t!=="Unidentified")return t}return e.type==="keypress"?(e=fh(e),e===13?"Enter":String.fromCharCode(e)):e.type==="keydown"||e.type==="keyup"?aA[e.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:bv,charCode:function(e){return e.type==="keypress"?fh(e):0},keyCode:function(e){return e.type==="keydown"||e.type==="keyup"?e.keyCode:0},which:function(e){return e.type==="keypress"?fh(e):e.type==="keydown"||e.type==="keyup"?e.keyCode:0}}),cA=_n(lA),dA=qt({},Lm,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),Db=_n(dA),uA=qt({},Jd,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:bv}),hA=_n(uA),mA=qt({},Kl,{propertyName:0,elapsedTime:0,pseudoElement:0}),pA=_n(mA),fA=qt({},Lm,{deltaX:function(e){return"deltaX"in e?e.deltaX:"wheelDeltaX"in e?-e.wheelDeltaX:0},deltaY:function(e){return"deltaY"in e?e.deltaY:"wheelDeltaY"in e?-e.wheelDeltaY:"wheelDelta"in e?-e.wheelDelta:0},deltaZ:0,deltaMode:0}),gA=_n(fA),xA=[9,13,27,32],wv=Yr&&"CompositionEvent"in window,Fc=null;Yr&&"documentMode"in document&&(Fc=document.documentMode);var vA=Yr&&"TextEvent"in window&&!Fc,t_=Yr&&(!wv||Fc&&8<Fc&&11>=Fc),Mb=" ",zb=!1;function s_(e,t){switch(e){case"keyup":return xA.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function n_(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var Fo=!1;function yA(e,t){switch(e){case"compositionend":return n_(t);case"keypress":return t.which!==32?null:(zb=!0,Mb);case"textInput":return e=t.data,e===Mb&&zb?null:e;default:return null}}function bA(e,t){if(Fo)return e==="compositionend"||!wv&&s_(e,t)?(e=e_(),ph=vv=Ia=null,Fo=!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.char.length)return t.char;if(t.which)return String.fromCharCode(t.which)}return null;case"compositionend":return t_&&t.locale!=="ko"?null:t.data;default:return null}}var wA={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function Fb(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t==="input"?!!wA[e.type]:t==="textarea"}function r_(e,t,s,r){Ij(r),t=Dh(t,"onChange"),0<t.length&&(s=new yv("onChange","change",null,s,r),e.push({event:s,listeners:t}))}var Uc=null,ad=null;function jA(e){f_(e,0)}function Im(e){var t=Vo(e);if(Tj(t))return e}function _A(e,t){if(e==="change")return t}var a_=!1;if(Yr){var Jp;if(Yr){var Zp="oninput"in document;if(!Zp){var Ub=document.createElement("div");Ub.setAttribute("oninput","return;"),Zp=typeof Ub.oninput=="function"}Jp=Zp}else Jp=!1;a_=Jp&&(!document.documentMode||9<document.documentMode)}function Bb(){Uc&&(Uc.detachEvent("onpropertychange",i_),ad=Uc=null)}function i_(e){if(e.propertyName==="value"&&Im(ad)){var t=[];r_(t,ad,e,mv(e)),zj(jA,t)}}function kA(e,t,s){e==="focusin"?(Bb(),Uc=t,ad=s,Uc.attachEvent("onpropertychange",i_)):e==="focusout"&&Bb()}function NA(e){if(e==="selectionchange"||e==="keyup"||e==="keydown")return Im(ad)}function SA(e,t){if(e==="click")return Im(t)}function CA(e,t){if(e==="input"||e==="change")return Im(t)}function TA(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var Jn=typeof Object.is=="function"?Object.is:TA;function id(e,t){if(Jn(e,t))return!0;
vendor: 4,808 bytes, line 22
22if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;var s=Object.keys(e),r=Object.keys(t);if(s.length!==r.length)return!1;for(r=0;r<s.length;r++){var a=s[r];if(!rg.call(t,a)||!Jn(e[a],t[a]))return!1}return!0}function Vb(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function qb(e,t){var s=Vb(e);e=0;for(var r;s;){if(s.nodeType===3){if(r=e+s.textContent.length,e<=t&&r>=t)return{node:s,offset:t-e};e=r}e:{for(;s;){if(s.nextSibling){s=s.nextSibling;break e}s=s.parentNode}s=void 0}s=Vb(s)}}function o_(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?o_(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function l_(){for(var e=window,t=Eh();t instanceof e.HTMLIFrameElement;){try{var s=typeof t.contentWindow.location.href=="string"}catch{s=!1}if(s)e=t.contentWindow;else break;t=Eh(e.document)}return t}function jv(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 PA(e){var t=l_(),s=e.focusedElem,r=e.selectionRange;if(t!==s&&s&&s.ownerDocument&&o_(s.ownerDocument.documentElement,s)){if(r!==null&&jv(s)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in s)s.selectionStart=t,s.selectionEnd=Math.min(e,s.value.length);else if(e=(t=s.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var a=s.textContent.length,i=Math.min(r.start,a);r=r.end===void 0?i:Math.min(r.end,a),!e.extend&&i>r&&(a=r,r=i,i=a),a=qb(s,i);var o=qb(s,r);a&&o&&(e.rangeCount!==1||e.anchorNode!==a.node||e.anchorOffset!==a.offset||e.focusNode!==o.node||e.focusOffset!==o.offset)&&(t=t.createRange(),t.setStart(a.node,a.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=s;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof s.focus=="function"&&s.focus(),s=0;s<t.length;s++)e=t[s],e.element.scrollLeft=e.left,e.element.scrollTop=e.top}}var EA=Yr&&"documentMode"in document&&11>=document.documentMode,Uo=null,_g=null,Bc=null,kg=!1;function Hb(e,t,s){var r=s.window===s?s.document:s.nodeType===9?s:s.ownerDocument;kg||Uo==null||Uo!==Eh(r)||(r=Uo,"selectionStart"in r&&jv(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}),Bc&&id(Bc,r)||(Bc=r,r=Dh(_g,"onSelect"),0<r.length&&(t=new yv("onSelect","select",null,t,s),e.push({event:t,listeners:r}),t.target=Uo)))}function Ou(e,t){var s={};return s[e.toLowerCase()]=t.toLowerCase(),s["Webkit"+e]="webkit"+t,s["Moz"+e]="moz"+t,s}var Bo={animationend:Ou("Animation","AnimationEnd"),animationiteration:Ou("Animation","AnimationIteration"),animationstart:Ou("Animation","AnimationStart"),transitionend:Ou("Transition","TransitionEnd")},Xp={},c_={};Yr&&(c_=document.createElement("div").style,"AnimationEvent"in window||(delete Bo.animationend.animation,delete Bo.animationiteration.animation,delete Bo.animationstart.animation),"TransitionEvent"in window||delete Bo.transitionend.transition);function Om(e){if(Xp[e])return Xp[e];if(!Bo[e])return e;var t=Bo[e],s;for(s in t)if(t.hasOwnProperty(s)&&s in c_)return Xp[e]=t[s];return e}var d_=Om("animationend"),u_=Om("animationiteration"),h_=Om("animationstart"),m_=Om("transitionend"),p_=new Map,Wb="abort auxClick cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" ");function hi(e,t){p_.set(e,t),io(t,[e])}for(var ef=0;ef<Wb.length;ef++){var tf=Wb[ef],AA=tf.toLowerCase(),RA=tf[0].toUpperCase()+tf.slice(1);hi(AA,"on"+RA)}hi(d_,"onAnimationEnd");hi(u_,"onAnimationIteration");hi(h_,"onAnimationStart");hi("dblclick","onDoubleClick");hi("focusin","onFocus");hi("focusout","onBlur");hi(m_,"onTransitionEnd");_l("onMouseEnter",["mouseout","mouseover"]);_l("onMouseLeave",["mouseout","mouseover"]);_l("onPointerEnter",["pointerout","pointerover"]);_l("onPointerLeave",["pointerout","pointerover"]);io("onChange","change click focusin focusout input keydown keyup selectionchange".split(" "));
vendor: 4,770 bytes, line 22
22io("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" "));io("onBeforeInput",["compositionend","keypress","textInput","paste"]);io("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" "));io("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" "));io("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var Tc="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),$A=new Set("cancel close invalid load scroll toggle".split(" ").concat(Tc));function Gb(e,t,s){var r=e.type||"unknown-event";e.currentTarget=s,AE(r,t,void 0,e),e.currentTarget=null}function f_(e,t){t=(t&4)!==0;for(var s=0;s<e.length;s++){var r=e[s],a=r.event;r=r.listeners;e:{var i=void 0;if(t)for(var o=r.length-1;0<=o;o--){var l=r[o],c=l.instance,d=l.currentTarget;if(l=l.listener,c!==i&&a.isPropagationStopped())break e;Gb(a,l,d),i=c}else for(o=0;o<r.length;o++){if(l=r[o],c=l.instance,d=l.currentTarget,l=l.listener,c!==i&&a.isPropagationStopped())break e;Gb(a,l,d),i=c}}}if(Rh)throw e=yg,Rh=!1,yg=null,e}function It(e,t){var s=t[Pg];s===void 0&&(s=t[Pg]=new Set);var r=e+"__bubble";s.has(r)||(g_(t,e,2,!1),s.add(r))}function sf(e,t,s){var r=0;t&&(r|=4),g_(s,e,r,t)}var Du="_reactListening"+Math.random().toString(36).slice(2);function od(e){if(!e[Du]){e[Du]=!0,_j.forEach(function(s){s!=="selectionchange"&&($A.has(s)||sf(s,!1,e),sf(s,!0,e))});var t=e.nodeType===9?e:e.ownerDocument;t===null||t[Du]||(t[Du]=!0,sf("selectionchange",!1,t))}}function g_(e,t,s,r){switch(Xj(t)){case 1:var a=GE;break;case 4:a=YE;break;default:a=xv}s=a.bind(null,t,s,e),a=void 0,!vg||t!=="touchstart"&&t!=="touchmove"&&t!=="wheel"||(a=!0),r?a!==void 0?e.addEventListener(t,s,{capture:!0,passive:a}):e.addEventListener(t,s,!0):a!==void 0?e.addEventListener(t,s,{passive:a}):e.addEventListener(t,s,!1)}function nf(e,t,s,r,a){var i=r;if(!(t&1)&&!(t&2)&&r!==null)e:for(;;){if(r===null)return;var o=r.tag;if(o===3||o===4){var l=r.stateNode.containerInfo;if(l===a||l.nodeType===8&&l.parentNode===a)break;if(o===4)for(o=r.return;o!==null;){var c=o.tag;if((c===3||c===4)&&(c=o.stateNode.containerInfo,c===a||c.nodeType===8&&c.parentNode===a))return;o=o.return}for(;l!==null;){if(o=Pi(l),o===null)return;if(c=o.tag,c===5||c===6){r=i=o;continue e}l=l.parentNode}}r=r.return}zj(function(){var d=i,u=mv(s),m=[];e:{var p=p_.get(e);if(p!==void 0){var f=yv,g=e;switch(e){case"keypress":if(fh(s)===0)break e;case"keydown":case"keyup":f=cA;break;case"focusin":g="focus",f=Qp;break;case"focusout":g="blur",f=Qp;break;case"beforeblur":case"afterblur":f=Qp;break;case"click":if(s.button===2)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":f=Ib;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":f=JE;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":f=hA;break;case d_:case u_:case h_:f=eA;break;case m_:f=pA;break;case"scroll":f=KE;break;case"wheel":f=gA;break;case"copy":case"cut":case"paste":f=sA;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":f=Db}var x=(t&4)!==0,b=!x&&e==="scroll",v=x?p!==null?p+"Capture":null:p;x=[];for(var y=d,w;y!==null;){w=y;var j=w.stateNode;if(w.tag===5&&j!==null&&(w=j,v!==null&&(j=td(y,v),j!=null&&x.push(ld(y,j,w)))),b)break;y=y.return}0<x.length&&(p=new f(p,g,null,s,u),m.push({event:p,listeners:x}))}}if(!(t&7)){e:{if(p=e==="mouseover"||e==="pointerover",f=e==="mouseout"||e==="pointerout",p&&s!==gg&&(g=s.relatedTarget||s.fromElement)&&(Pi(g)||g[Kr]))break e;if((f||p)&&(p=u.window===u?u:(p=u.ownerDocument)?p.defaultView||p.parentWindow:window,f?(g=s.relatedTarget||s.toElement,f=d,g=g?Pi(g):null,g!==null&&(b=oo(g),g!==b||g.tag!==5&&g.tag!==6)&&(g=null)):(f=null,g=d),f!==g)){if(x=Ib,j="onMouseLeave",v="onMouseEnter",y="mouse",(e==="pointerout"||e==="pointerover")&&(x=Db,j="onPointerLeave",v="onPointerEnter",y="pointer"),b=f==null?p:Vo(f),w=g==null?p:Vo(g),p=new x(j,y+"leave",f,s,u),p.target=b,p.relatedTarget=w,j=null,Pi(u)===d&&(x=new x(v,y+"enter",g,s,u),x.target=w,x.relatedTarget=b,j=x),b=j,f&&g)t:{for(x=f,v=g,y=0,w=x;w;w=fo(w))y++;for(w=0,j=v;j;j=fo(j))w++;for(;0<y-w;)x=fo(x),y--;for(;0<w-y;)v=fo(v),w--;for(;y--;){if(x===v||v!==null&&x===v.alternate)break t;x=fo(x),v=fo(v)}x=null}else x=null;f!==null&&Yb(m,p,f,x,!1),g!==null&&b!==null&&Yb(m,b,g,x,!0)}}
vendor: 4,576 bytes, lines 22-23
22e:{if(p=d?Vo(d):window,f=p.nodeName&&p.nodeName.toLowerCase(),f==="select"||f==="input"&&p.type==="file")var _=_A;else if(Fb(p))if(a_)_=CA;else{_=NA;var N=kA}else(f=p.nodeName)&&f.toLowerCase()==="input"&&(p.type==="checkbox"||p.type==="radio")&&(_=SA);if(_&&(_=_(e,d))){r_(m,_,s,u);break e}N&&N(e,p,d),e==="focusout"&&(N=p._wrapperState)&&N.controlled&&p.type==="number"&&ug(p,"number",p.value)}switch(N=d?Vo(d):window,e){case"focusin":(Fb(N)||N.contentEditable==="true")&&(Uo=N,_g=d,Bc=null);break;case"focusout":Bc=_g=Uo=null;break;case"mousedown":kg=!0;break;case"contextmenu":case"mouseup":case"dragend":kg=!1,Hb(m,s,u);break;case"selectionchange":if(EA)break;case"keydown":case"keyup":Hb(m,s,u)}var k;if(wv)e:{switch(e){case"compositionstart":var S="onCompositionStart";break e;case"compositionend":S="onCompositionEnd";break e;case"compositionupdate":S="onCompositionUpdate";break e}S=void 0}else Fo?s_(e,s)&&(S="onCompositionEnd"):e==="keydown"&&s.keyCode===229&&(S="onCompositionStart");S&&(t_&&s.locale!=="ko"&&(Fo||S!=="onCompositionStart"?S==="onCompositionEnd"&&Fo&&(k=e_()):(Ia=u,vv="value"in Ia?Ia.value:Ia.textContent,Fo=!0)),N=Dh(d,S),0<N.length&&(S=new Ob(S,e,null,s,u),m.push({event:S,listeners:N}),k?S.data=k:(k=n_(s),k!==null&&(S.data=k)))),(k=vA?yA(e,s):bA(e,s))&&(d=Dh(d,"onBeforeInput"),0<d.length&&(u=new Ob("onBeforeInput","beforeinput",null,s,u),m.push({event:u,listeners:d}),u.data=k))}f_(m,t)})}function ld(e,t,s){return{instance:e,listener:t,currentTarget:s}}function Dh(e,t){for(var s=t+"Capture",r=[];e!==null;){var a=e,i=a.stateNode;a.tag===5&&i!==null&&(a=i,i=td(e,s),i!=null&&r.unshift(ld(e,i,a)),i=td(e,t),i!=null&&r.push(ld(e,i,a))),e=e.return}return r}function fo(e){if(e===null)return null;do e=e.return;while(e&&e.tag!==5);return e||null}function Yb(e,t,s,r,a){for(var i=t._reactName,o=[];s!==null&&s!==r;){var l=s,c=l.alternate,d=l.stateNode;if(c!==null&&c===r)break;l.tag===5&&d!==null&&(l=d,a?(c=td(s,i),c!=null&&o.unshift(ld(s,c,l))):a||(c=td(s,i),c!=null&&o.push(ld(s,c,l)))),s=s.return}o.length!==0&&e.push({event:t,listeners:o})}var LA=/\r\n?/g,IA=/\u0000|\uFFFD/g;function Kb(e){return(typeof e=="string"?e:""+e).replace(LA,`
23`).replace(IA,"")}function Mu(e,t,s){if(t=Kb(t),Kb(e)!==t&&s)throw Error(be(425))}function Mh(){}var Ng=null,Sg=null;function Cg(e,t){return e==="textarea"||e==="noscript"||typeof t.children=="string"||typeof t.children=="number"||typeof t.dangerouslySetInnerHTML=="object"&&t.dangerouslySetInnerHTML!==null&&t.dangerouslySetInnerHTML.__html!=null}var Tg=typeof setTimeout=="function"?setTimeout:void 0,OA=typeof clearTimeout=="function"?clearTimeout:void 0,Qb=typeof Promise=="function"?Promise:void 0,DA=typeof queueMicrotask=="function"?queueMicrotask:typeof Qb<"u"?function(e){return Qb.resolve(null).then(e).catch(MA)}:Tg;function MA(e){setTimeout(function(){throw e})}function rf(e,t){var s=t,r=0;do{var a=s.nextSibling;if(e.removeChild(s),a&&a.nodeType===8)if(s=a.data,s==="/$"){if(r===0){e.removeChild(a),rd(t);return}r--}else s!=="$"&&s!=="$?"&&s!=="$!"||r++;s=a}while(s);rd(t)}function qa(e){for(;e!=null;e=e.nextSibling){var t=e.nodeType;if(t===1||t===3)break;if(t===8){if(t=e.data,t==="$"||t==="$!"||t==="$?")break;if(t==="/$")return null}}return e}function Jb(e){e=e.previousSibling;for(var t=0;e;){if(e.nodeType===8){var s=e.data;if(s==="$"||s==="$!"||s==="$?"){if(t===0)return e;t--}else s==="/$"&&t++}e=e.previousSibling}return null}var Ql=Math.random().toString(36).slice(2),xr="__reactFiber$"+Ql,cd="__reactProps$"+Ql,Kr="__reactContainer$"+Ql,Pg="__reactEvents$"+Ql,zA="__reactListeners$"+Ql,FA="__reactHandles$"+Ql;function Pi(e){var t=e[xr];if(t)return t;for(var s=e.parentNode;s;){if(t=s[Kr]||s[xr]){if(s=t.alternate,t.child!==null||s!==null&&s.child!==null)for(e=Jb(e);e!==null;){if(s=e[xr])return s;e=Jb(e)}return t}e=s,s=e.parentNode}return null}function Zd(e){return e=e[xr]||e[Kr],!e||e.tag!==5&&e.tag!==6&&e.tag!==13&&e.tag!==3?null:e}function Vo(e){if(e.tag===5||e.tag===6)return e.stateNode;throw Error(be(33))}function Dm(e){return e[cd]||null}var Eg=[],qo=-1;function mi(e){return{current:e}}function Dt(e){0>qo||(e.current=Eg[qo],Eg[qo]=null,qo--)}function $t(e,t){qo++,Eg[qo]=e.current,e.current=t}var si={},$s=mi(si),Ks=mi(!1),Wi=si;function kl(e,t){var s=e.type.contextTypes;if(!s)return si;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var a={},i;for(i in s)a[i]=t[i];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=a
vendor: 14,475 bytes, line 23
23),a}function Qs(e){return e=e.childContextTypes,e!=null}function zh(){Dt(Ks),Dt($s)}function Zb(e,t,s){if($s.current!==si)throw Error(be(168));$t($s,t),$t(Ks,s)}function x_(e,t,s){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return s;r=r.getChildContext();for(var a in r)if(!(a in t))throw Error(be(108,kE(e)||"Unknown",a));return qt({},s,r)}function Fh(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||si,Wi=$s.current,$t($s,e),$t(Ks,Ks.current),!0}function Xb(e,t,s){var r=e.stateNode;if(!r)throw Error(be(169));s?(e=x_(e,t,Wi),r.__reactInternalMemoizedMergedChildContext=e,Dt(Ks),Dt($s),$t($s,e)):Dt(Ks),$t(Ks,s)}var Ur=null,Mm=!1,af=!1;function v_(e){Ur===null?Ur=[e]:Ur.push(e)}function UA(e){Mm=!0,v_(e)}function pi(){if(!af&&Ur!==null){af=!0;var e=0,t=At;try{var s=Ur;for(At=1;e<s.length;e++){var r=s[e];do r=r(!0);while(r!==null)}Ur=null,Mm=!1}catch(a){throw Ur!==null&&(Ur=Ur.slice(e+1)),Vj(pv,pi),a}finally{At=t,af=!1}}return null}var Ho=[],Wo=0,Uh=null,Bh=0,Cn=[],Tn=0,Gi=null,qr=1,Hr="";function Ni(e,t){Ho[Wo++]=Bh,Ho[Wo++]=Uh,Uh=e,Bh=t}function y_(e,t,s){Cn[Tn++]=qr,Cn[Tn++]=Hr,Cn[Tn++]=Gi,Gi=e;var r=qr;e=Hr;var a=32-Yn(r)-1;r&=~(1<<a),s+=1;var i=32-Yn(t)+a;if(30<i){var o=a-a%5;i=(r&(1<<o)-1).toString(32),r>>=o,a-=o,qr=1<<32-Yn(t)+a|s<<a|r,Hr=i+e}else qr=1<<i|s<<a|r,Hr=e}function _v(e){e.return!==null&&(Ni(e,1),y_(e,1,0))}function kv(e){for(;e===Uh;)Uh=Ho[--Wo],Ho[Wo]=null,Bh=Ho[--Wo],Ho[Wo]=null;for(;e===Gi;)Gi=Cn[--Tn],Cn[Tn]=null,Hr=Cn[--Tn],Cn[Tn]=null,qr=Cn[--Tn],Cn[Tn]=null}var mn=null,dn=null,Mt=!1,Gn=null;function b_(e,t){var s=Pn(5,null,null,0);s.elementType="DELETED",s.stateNode=t,s.return=e,t=e.deletions,t===null?(e.deletions=[s],e.flags|=16):t.push(s)}function e0(e,t){switch(e.tag){case 5:var s=e.type;return t=t.nodeType!==1||s.toLowerCase()!==t.nodeName.toLowerCase()?null:t,t!==null?(e.stateNode=t,mn=e,dn=qa(t.firstChild),!0):!1;case 6:return t=e.pendingProps===""||t.nodeType!==3?null:t,t!==null?(e.stateNode=t,mn=e,dn=null,!0):!1;case 13:return t=t.nodeType!==8?null:t,t!==null?(s=Gi!==null?{id:qr,overflow:Hr}:null,e.memoizedState={dehydrated:t,treeContext:s,retryLane:1073741824},s=Pn(18,null,null,0),s.stateNode=t,s.return=e,e.child=s,mn=e,dn=null,!0):!1;default:return!1}}function Ag(e){return(e.mode&1)!==0&&(e.flags&128)===0}function Rg(e){if(Mt){var t=dn;if(t){var s=t;if(!e0(e,t)){if(Ag(e))throw Error(be(418));t=qa(s.nextSibling);var r=mn;t&&e0(e,t)?b_(r,s):(e.flags=e.flags&-4097|2,Mt=!1,mn=e)}}else{if(Ag(e))throw Error(be(418));e.flags=e.flags&-4097|2,Mt=!1,mn=e}}}function t0(e){for(e=e.return;e!==null&&e.tag!==5&&e.tag!==3&&e.tag!==13;)e=e.return;mn=e}function zu(e){if(e!==mn)return!1;if(!Mt)return t0(e),Mt=!0,!1;var t;if((t=e.tag!==3)&&!(t=e.tag!==5)&&(t=e.type,t=t!=="head"&&t!=="body"&&!Cg(e.type,e.memoizedProps)),t&&(t=dn)){if(Ag(e))throw w_(),Error(be(418));for(;t;)b_(e,t),t=qa(t.nextSibling)}if(t0(e),e.tag===13){if(e=e.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(be(317));e:{for(e=e.nextSibling,t=0;e;){if(e.nodeType===8){var s=e.data;if(s==="/$"){if(t===0){dn=qa(e.nextSibling);break e}t--}else s!=="$"&&s!=="$!"&&s!=="$?"||t++}e=e.nextSibling}dn=null}}else dn=mn?qa(e.stateNode.nextSibling):null;return!0}function w_(){for(var e=dn;e;)e=qa(e.nextSibling)}function Nl(){dn=mn=null,Mt=!1}function Nv(e){Gn===null?Gn=[e]:Gn.push(e)}var BA=sa.ReactCurrentBatchConfig;function gc(e,t,s){if(e=s.ref,e!==null&&typeof e!="function"&&typeof e!="object"){if(s._owner){if(s=s._owner,s){if(s.tag!==1)throw Error(be(309));var r=s.stateNode}if(!r)throw Error(be(147,e));var a=r,i=""+e;return t!==null&&t.ref!==null&&typeof t.ref=="function"&&t.ref._stringRef===i?t.ref:(t=function(o){var l=a.refs;o===null?delete l[i]:l[i]=o},t._stringRef=i,t)}if(typeof e!="string")throw Error(be(284));if(!s._owner)throw Error(be(290,e))}return e}function Fu(e,t){throw e=Object.prototype.toString.call(t),Error(be(31,e==="[object Object]"?"object with keys {"+Object.keys(t).join(", ")+"}":e))}function s0(e){var t=e._init;return t(e._payload)}function j_(e){function t(v,y){if(e){var w=v.deletions;w===null?(v.deletions=[y],v.flags|=16):w.push(y)}}function s(v,y){if(!e)return null;for(;y!==null;)t(v,y),y=y.sibling;return null}function r(v,y){for(v=new Map;y!==null;)y.key!==null?v.set(y.key,y):v.set(y.index,y),y=y.sibling;return v}function a(v,y){return v=Ya(v,y),v.index=0,v.sibling=null,v}function i(v,y,w){return v.index=w,e?(w=v.alternate,w!==null?(w=w.index,w<y?(v.flags|=2,y):w):(v.flags|=2,y)):(v.flags|=1048576,y)}function o(v){return e&&v.alternate===null&&(v.flags|=2),v}function l(v,y,w,j){return y===null||y.tag!==6?(y=mf(w,v.mode,j),y.return=v,y):(y=a(y,w),y.return=v,y)}function c(v,y,w,j){var _=w.type;return _===zo?u(v,y,w.props.children,j,w.key):y!==null&&(y.elementType===_||typeof _=="object"&&_!==null&&_.$$typeof===ba&&s0(_)===y.type)?(j=a(y,w.props),j.ref=gc(v,y,w),j.return=v,j):(j=jh(w.type,w.key,w.props,null,v.mode,j),j.ref=gc(v,y,w),j.return=v,j)}function d(v,y,w,j){return y===null||y.tag!==4||y.stateNode.containerInfo!==w.containerInfo||y.stateNode.implementation!==w.implementation?(y=pf(w,v.mode,j),y.return=v,y):(y=a(y,w.children||[]),y.return=v,y)}function u(v,y,w,j,_){return y===null||y.tag!==7?(y=qi(w,v.mode,j,_),y.return=v,y):(y=a(y,w),y.return=v,y)}function m(v,y,w){if(typeof y=="string"&&y!==""||typeof y=="number")return y=mf(""+y,v.mode,w),y.return=v,y;if(typeof y=="object"&&y!==null){switch(y.$$typeof){case Pu:return w=jh(y.type,y.key,y.props,null,v.mode,w),w.ref=gc(v,null,y),w.return=v,w;case Mo:return y=pf(y,v.mode,w),y.return=v,y;case ba:var j=y._init;return m(v,j(y._payload),w)}if(Sc(y)||uc(y))return y=qi(y,v.mode,w,null),y.return=v,y;Fu(v,y)}return null}function p(v,y,w,j){var _=y!==null?y.key:null;if(typeof w=="string"&&w!==""||typeof w=="number")return _!==null?null:l(v,y,""+w,j);if(typeof w=="object"&&w!==null){switch(w.$$typeof){case Pu:return w.key===_?c(v,y,w,j):null;case Mo:return w.key===_?d(v,y,w,j):null;case ba:return _=w._init,p(v,y,_(w._payload),j)}if(Sc(w)||uc(w))return _!==null?null:u(v,y,w,j,null);Fu(v,w)}return null}function f(v,y,w,j,_){if(typeof j=="string"&&j!==""||typeof j=="number")return v=v.get(w)||null,l(y,v,""+j,_);if(typeof j=="object"&&j!==null){switch(j.$$typeof){case Pu:return v=v.get(j.key===null?w:j.key)||null,c(y,v,j,_);case Mo:return v=v.get(j.key===null?w:j.key)||null,d(y,v,j,_);case ba:var N=j._init;return f(v,y,w,N(j._payload),_)}if(Sc(j)||uc(j))return v=v.get(w)||null,u(y,v,j,_,null);Fu(y,j)}return null}function g(v,y,w,j){for(var _=null,N=null,k=y,S=y=0,T=null;k!==null&&S<w.length;S++){k.index>S?(T=k,k=null):T=k.sibling;var C=p(v,k,w[S],j);if(C===null){k===null&&(k=T);break}e&&k&&C.alternate===null&&t(v,k),y=i(C,y,S),N===null?_=C:N.sibling=C,N=C,k=T}if(S===w.length)return s(v,k),Mt&&Ni(v,S),_;if(k===null){for(;S<w.length;S++)k=m(v,w[S],j),k!==null&&(y=i(k,y,S),N===null?_=k:N.sibling=k,N=k);return Mt&&Ni(v,S),_}for(k=r(v,k);S<w.length;S++)T=f(k,v,S,w[S],j),T!==null&&(e&&T.alternate!==null&&k.delete(T.key===null?S:T.key),y=i(T,y,S),N===null?_=T:N.sibling=T,N=T);return e&&k.forEach(function(B){return t(v,B)}),Mt&&Ni(v,S),_}function x(v,y,w,j){var _=uc(w);if(typeof _!="function")throw Error(be(150));if(w=_.call(w),w==null)throw Error(be(151));for(var N=_=null,k=y,S=y=0,T=null,C=w.next();k!==null&&!C.done;S++,C=w.next()){k.index>S?(T=k,k=null):T=k.sibling;var B=p(v,k,C.value,j);if(B===null){k===null&&(k=T);break}e&&k&&B.alternate===null&&t(v,k),y=i(B,y,S),N===null?_=B:N.sibling=B,N=B,k=T}if(C.done)return s(v,k),Mt&&Ni(v,S),_;if(k===null){for(;!C.done;S++,C=w.next())C=m(v,C.value,j),C!==null&&(y=i(C,y,S),N===null?_=C:N.sibling=C,N=C);return Mt&&Ni(v,S),_}for(k=r(v,k);!C.done;S++,C=w.next())C=f(k,v,S,C.value,j),C!==null&&(e&&C.alternate!==null&&k.delete(C.key===null?S:C.key),y=i(C,y,S),N===null?_=C:N.sibling=C,N=C);return e&&k.forEach(function(E){return t(v,E)}),Mt&&Ni(v,S),_}function b(v,y,w,j){if(typeof w=="object"&&w!==null&&w.type===zo&&w.key===null&&(w=w.props.children),typeof w=="object"&&w!==null){switch(w.$$typeof){case Pu:e:{for(var _=w.key,N=y;N!==null;){if(N.key===_){if(_=w.type,_===zo){if(N.tag===7){s(v,N.sibling),y=a(N,w.props.children),y.return=v,v=y;break e}}else if(N.elementType===_||typeof _=="object"&&_!==null&&_.$$typeof===ba&&s0(_)===N.type){s(v,N.sibling),y=a(N,w.props),y.ref=gc(v,N,w),y.return=v,v=y;break e}s(v,N);break}else t(v,N);N=N.sibling}w.type===zo?(y=qi(w.props.children,v.mode,j,w.key),y.return=v,v=y):(j=jh(w.type,w.key,w.props,null,v.mode,j),j.ref=gc(v,y,w),j.return=v,v=j)}return o(v);case Mo:e:{for(N=w.key;y!==null;){if(y.key===N)if(y.tag===4&&y.stateNode.containerInfo===w.containerInfo&&y.stateNode.implementation===w.implementation){s(v,y.sibling),y=a(y,w.children||[]),y.return=v,v=y;break e}else{s(v,y);break}else t(v,y);y=y.sibling}y=pf(w,v.mode,j),y.return=v,v=y}return o(v);case ba:return N=w._init,b(v,y,N(w._payload),j)}if(Sc(w))return g(v,y,w,j);if(uc(w))return x(v,y,w,j);Fu(v,w)}return typeof w=="string"&&w!==""||typeof w=="number"?(w=""+w,y!==null&&y.tag===6?(s(v,y.sibling),y=a(y,w),y.return=v,v=y):(s(v,y),y=mf(w,v.mode,j),y.return=v,v=y),o(v)):s(v,y)}return b}var Sl=j_(!0),__=j_(!1),Vh=mi(null),qh=null,Go=null,Sv=null;function Cv(){Sv=Go=qh=null}function Tv(e){var t=Vh.current;Dt(Vh),e._currentValue=t}function $g(e,t,s){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===s)break;e=e.return}}function nl(e,t){qh=e,Sv=Go=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(Ys=!0),e.firstContext=null)}function Rn(e){var t=e._currentValue;if(Sv!==e)if(e={context:e,memoizedValue:t,next:null},Go===null){if(qh===null)throw Error(be(308));Go=e,qh.dependencies={lanes:0,firstContext:e}}else Go=Go.next=e;return t}var Ei=null;function Pv(e){Ei===null?Ei=[e]:Ei.push(e)}function k_(e,t,s,r){var a=t.interleaved;return a===null?(s.next=s,Pv(t)):(s.next=a.next,a.next=s),t.interleaved=s,Qr(e,r)}function Qr(e,t){e.lanes|=t;var s=e.alternate;for(s!==null&&(s.lanes|=t),s=e,e=e.return;e!==null;)e.childLanes|=t,s=e.alternate,s!==null&&(s.childLanes|=t),s=e,e=e.return;return s.tag===3?s.stateNode:null}var wa=!1;function Ev(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function N_(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 Wr(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function Ha(e,t,s){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,Nt&2){var a=r.pending;return a===null?t.next=t:(t.next=a.next,a.next=t),r.pending=t,Qr(e,s)}return a=r.interleaved,a===null?(t.next=t,Pv(r)):(t.next=a.next,a.next=t),r.interleaved=t,Qr(e,s)}function gh(e,t,s){if(t=t.updateQueue,t!==null&&(t=t.shared,(s&4194240)!==0)){var r=t.lanes;r&=e.pendingLanes,s|=r,t.lanes=s,fv(e,s)}}function n0(e,t){var s=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,s===r)){var a=null,i=null;if(s=s.firstBaseUpdate,s!==null){do{var o={eventTime:s.eventTime,lane:s.lane,tag:s.tag,payload:s.payload,callback:s.callback,next:null};i===null?a=i=o:i=i.next=o,s=s.next}while(s!==null);i===null?a=i=t:i=i.next=t}else a=i=t;s={baseState:r.baseState,firstBaseUpdate:a,lastBaseUpdate:i,shared:r.shared,effects:r.effects},e.updateQueue=s;return}e=s.lastBaseUpdate,e===null?s.firstBaseUpdate=t:e.next=t,s.lastBaseUpdate=t}function Hh(e,t,s,r){var a=e.updateQueue;wa=!1;var i=a.firstBaseUpdate,o=a.lastBaseUpdate,l=a.shared.pending;if(l!==null){a.shared.pending=null;var c=l,d=c.next;c.next=null,o===null?i=d:o.next=d,o=c;var u=e.alternate;u!==null&&(u=u.updateQueue,l=u.lastBaseUpdate,l!==o&&(l===null?u.firstBaseUpdate=d:l.next=d,u.lastBaseUpdate=c))}if(i!==null){var m=a.baseState;o=0,u=d=c=null,l=i;do{var p=l.lane,f=l.eventTime;if((r&p)===p){u!==null&&(u=u.next={eventTime:f,lane:0,tag:l.tag,payload:l.payload,callback:l.callback,next:null});e:{var g=e,x=l;switch(p=t,f=s,x.tag){case 1:if(g=x.payload,typeof g=="function"){m=g.call(f,m,p);break e}m=g;break e;case 3:g.flags=g.flags&-65537|128;case 0:if(g=x.payload,p=typeof g=="function"?g.call(f,m,p):g,p==null)break e;m=qt({},m,p);break e;case 2:wa=!0}}l.callback!==null&&l.lane!==0&&(e.flags|=64,p=a.effects,p===null?a.effects=[l]:p.push(l))}else f={eventTime:f,lane:p,tag:l.tag,payload:l.payload,callback:l.callback,next:null},u===null?(d=u=f,c=m):u=u.next=f,o|=p;if(l=l.next,l===null){if(l=a.shared.pending,l===null)break;p=l,l=p.next,p.next=null,a.lastBaseUpdate=p,a.shared.pending=null}}while(!0);if(u===null&&(c=m),a.baseState=c,a.firstBaseUpdate=d,a.lastBaseUpdate=u,t=a.shared.interleaved,t!==null){a=t;do o|=a.lane,a=a.next;while(a!==t)}else i===null&&(a.shared.lanes=0);Ki|=o,e.lanes=o,e.memoizedState=m}}function r0(e,t,s){if(e=t.effects,t.effects=null,e!==null)for(t=0;t<e.length;t++){var r=e[t],a=r.callback;if(a!==null){if(r.callback=null,r=s,typeof a!="function")throw Error(be(191,a));a.call(r)}}}var Xd={},kr=mi(Xd),dd=mi(Xd),ud=mi(Xd);function Ai(e){if(e===Xd)throw Error(be(174));return e}function Av(e,t){switch($t(ud,t),$t(dd,e),$t(kr,Xd),e=t.nodeType,e){case 9:case 11:t=(t=t.documentElement)?t.namespaceURI:mg(null,"");break;default:e=e===8?t.parentNode:t,t=e.namespaceURI||null,e=e.tagName,t=mg(t,e)}Dt(kr),$t(kr,t)}function Cl(){Dt(kr),Dt(dd),Dt(ud)}function S_(e){Ai(ud.current);var t=Ai(kr.current),s=mg(t,e.type);t!==s&&($t(dd,e),$t(kr,s))}function Rv(e){dd.current===e&&(Dt(kr),Dt(dd))}var Ft=mi(0);function Wh(e){for(var t=e;t!==null;){if(t.tag===13){var s=t.memoizedState;if(s!==null&&(s=s.dehydrated,s===null||s.data==="$?"||s.data==="$!"))return t}else if(t.tag===19&&t.memoizedProps.revealOrder!==void 0){if(t.flags&128)return t}else if(t.child!==null){t.child.return=t,t=t.child;continue}if(t===e)break;for(;t.sibling===null;){if(t.return===null||t.return===e)return null;t=t.return}t.sibling.return=t.return,t=t.sibling}return null}var of=[];function $v(){for(var e=0;e<of.length;e++)of[e]._workInProgressVersionPrimary=null;of.length=0}var xh=sa.ReactCurrentDispatcher,lf=sa.ReactCurrentBatchConfig,Yi=0,Bt=null,ds=null,fs=null,Gh=!1,Vc=!1,hd=0,VA=0;function Ts(){throw Error(be(321))}function Lv(e,t){if(t===null)return!1;for(var s=0;s<t.length&&s<e.length;s++)if(!Jn(e[s],t[s]))return!1;return!0}
vendor: 5,612 bytes, line 23
23function Iv(e,t,s,r,a,i){if(Yi=i,Bt=t,t.memoizedState=null,t.updateQueue=null,t.lanes=0,xh.current=e===null||e.memoizedState===null?GA:YA,e=s(r,a),Vc){i=0;do{if(Vc=!1,hd=0,25<=i)throw Error(be(301));i+=1,fs=ds=null,t.updateQueue=null,xh.current=KA,e=s(r,a)}while(Vc)}if(xh.current=Yh,t=ds!==null&&ds.next!==null,Yi=0,fs=ds=Bt=null,Gh=!1,t)throw Error(be(300));return e}function Ov(){var e=hd!==0;return hd=0,e}function ur(){var e={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return fs===null?Bt.memoizedState=fs=e:fs=fs.next=e,fs}function $n(){if(ds===null){var e=Bt.alternate;e=e!==null?e.memoizedState:null}else e=ds.next;var t=fs===null?Bt.memoizedState:fs.next;if(t!==null)fs=t,ds=e;else{if(e===null)throw Error(be(310));ds=e,e={memoizedState:ds.memoizedState,baseState:ds.baseState,baseQueue:ds.baseQueue,queue:ds.queue,next:null},fs===null?Bt.memoizedState=fs=e:fs=fs.next=e}return fs}function md(e,t){return typeof t=="function"?t(e):t}function cf(e){var t=$n(),s=t.queue;if(s===null)throw Error(be(311));s.lastRenderedReducer=e;var r=ds,a=r.baseQueue,i=s.pending;if(i!==null){if(a!==null){var o=a.next;a.next=i.next,i.next=o}r.baseQueue=a=i,s.pending=null}if(a!==null){i=a.next,r=r.baseState;var l=o=null,c=null,d=i;do{var u=d.lane;if((Yi&u)===u)c!==null&&(c=c.next={lane:0,action:d.action,hasEagerState:d.hasEagerState,eagerState:d.eagerState,next:null}),r=d.hasEagerState?d.eagerState:e(r,d.action);else{var m={lane:u,action:d.action,hasEagerState:d.hasEagerState,eagerState:d.eagerState,next:null};c===null?(l=c=m,o=r):c=c.next=m,Bt.lanes|=u,Ki|=u}d=d.next}while(d!==null&&d!==i);c===null?o=r:c.next=l,Jn(r,t.memoizedState)||(Ys=!0),t.memoizedState=r,t.baseState=o,t.baseQueue=c,s.lastRenderedState=r}if(e=s.interleaved,e!==null){a=e;do i=a.lane,Bt.lanes|=i,Ki|=i,a=a.next;while(a!==e)}else a===null&&(s.lanes=0);return[t.memoizedState,s.dispatch]}function df(e){var t=$n(),s=t.queue;if(s===null)throw Error(be(311));s.lastRenderedReducer=e;var r=s.dispatch,a=s.pending,i=t.memoizedState;if(a!==null){s.pending=null;var o=a=a.next;do i=e(i,o.action),o=o.next;while(o!==a);Jn(i,t.memoizedState)||(Ys=!0),t.memoizedState=i,t.baseQueue===null&&(t.baseState=i),s.lastRenderedState=i}return[i,r]}function C_(){}function T_(e,t){var s=Bt,r=$n(),a=t(),i=!Jn(r.memoizedState,a);if(i&&(r.memoizedState=a,Ys=!0),r=r.queue,Dv(A_.bind(null,s,r,e),[e]),r.getSnapshot!==t||i||fs!==null&&fs.memoizedState.tag&1){if(s.flags|=2048,pd(9,E_.bind(null,s,r,a,t),void 0,null),gs===null)throw Error(be(349));Yi&30||P_(s,t,a)}return a}function P_(e,t,s){e.flags|=16384,e={getSnapshot:t,value:s},t=Bt.updateQueue,t===null?(t={lastEffect:null,stores:null},Bt.updateQueue=t,t.stores=[e]):(s=t.stores,s===null?t.stores=[e]:s.push(e))}function E_(e,t,s,r){t.value=s,t.getSnapshot=r,R_(t)&&$_(e)}function A_(e,t,s){return s(function(){R_(t)&&$_(e)})}function R_(e){var t=e.getSnapshot;e=e.value;try{var s=t();return!Jn(e,s)}catch{return!0}}function $_(e){var t=Qr(e,1);t!==null&&Kn(t,e,1,-1)}function a0(e){var t=ur();return typeof e=="function"&&(e=e()),t.memoizedState=t.baseState=e,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:md,lastRenderedState:e},t.queue=e,e=e.dispatch=WA.bind(null,Bt,e),[t.memoizedState,e]}function pd(e,t,s,r){return e={tag:e,create:t,destroy:s,deps:r,next:null},t=Bt.updateQueue,t===null?(t={lastEffect:null,stores:null},Bt.updateQueue=t,t.lastEffect=e.next=e):(s=t.lastEffect,s===null?t.lastEffect=e.next=e:(r=s.next,s.next=e,e.next=r,t.lastEffect=e)),e}function L_(){return $n().memoizedState}function vh(e,t,s,r){var a=ur();Bt.flags|=e,a.memoizedState=pd(1|t,s,void 0,r===void 0?null:r)}function zm(e,t,s,r){var a=$n();r=r===void 0?null:r;var i=void 0;if(ds!==null){var o=ds.memoizedState;if(i=o.destroy,r!==null&&Lv(r,o.deps)){a.memoizedState=pd(t,s,i,r);return}}Bt.flags|=e,a.memoizedState=pd(1|t,s,i,r)}function i0(e,t){return vh(8390656,8,e,t)}function Dv(e,t){return zm(2048,8,e,t)}function I_(e,t){return zm(4,2,e,t)}function O_(e,t){return zm(4,4,e,t)}function D_(e,t){if(typeof t=="function")return e=e(),t(e),function(){t(null)};if(t!=null)return e=e(),t.current=e,function(){t.current=null}}function M_(e,t,s){return s=s!=null?s.concat([e]):null,zm(4,4,D_.bind(null,t,e),s)}function Mv(){}function z_(e,t){var s=$n();t=t===void 0?null:t;var r=s.memoizedState;return r!==null&&t!==null&&Lv(t,r[1])?r[0]:(s.memoizedState=[e,t],e)}function F_(e,t){var s=$n();t=t===void 0?null:t;var r=s.memoizedState;return r!==null&&t!==null&&Lv(t,r[1])?r[0]:(e=e(),s.memoizedState=[e,t],e)}function U_(e,t,s){return Yi&21?(Jn(s,t)||(s=Wj(),Bt.lanes|=s,Ki|=s,e.baseState=!0),t):(e.baseState&&(e.baseState=!1,Ys=!0),e.memoizedState=s)}function qA(e,t){var s=At;At=s!==0&&4>s?s:4,e(!0);var r=lf.transition;lf.transition={};try{e(!1),t()}finally{At=s,lf.transition=r}}function B_(){return $n().memoizedState}function HA(e,t,s){var r=Ga(e);if(s={lane:r,action:s,hasEagerState:!1,eagerState:null,next:null},V_(e))q_(t,s);else if(s=k_(e,t,s,r),s!==null){var a=zs();Kn(s,e,r,a),H_(s,t,r)}}function WA(e,t,s){var r=Ga(e),a={lane:r,action:s,hasEagerState:!1,eagerState:null,next:null};if(V_(e))q_(t,a);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=t.lastRenderedReducer,i!==null))try{var o=t.lastRenderedState,l=i(o,s);if(a.hasEagerState=!0,a.eagerState=l,Jn(l,o)){var c=t.interleaved;c===null?(a.next=a,Pv(t)):(a.next=c.next,c.next=a),t.interleaved=a;return}}catch{}finally{}s=k_(e,t,a,r),s!==null&&(a=zs(),Kn(s,e,r,a),H_(s,t,r))}}function V_(e){var t=e.alternate;return e===Bt||t!==null&&t===Bt}function q_(e,t){Vc=Gh=!0;var s=e.pending;
vendor: 5,852 bytes, lines 23-25
23s===null?t.next=t:(t.next=s.next,s.next=t),e.pending=t}function H_(e,t,s){if(s&4194240){var r=t.lanes;r&=e.pendingLanes,s|=r,t.lanes=s,fv(e,s)}}var Yh={readContext:Rn,useCallback:Ts,useContext:Ts,useEffect:Ts,useImperativeHandle:Ts,useInsertionEffect:Ts,useLayoutEffect:Ts,useMemo:Ts,useReducer:Ts,useRef:Ts,useState:Ts,useDebugValue:Ts,useDeferredValue:Ts,useTransition:Ts,useMutableSource:Ts,useSyncExternalStore:Ts,useId:Ts,unstable_isNewReconciler:!1},GA={readContext:Rn,useCallback:function(e,t){return ur().memoizedState=[e,t===void 0?null:t],e},useContext:Rn,useEffect:i0,useImperativeHandle:function(e,t,s){return s=s!=null?s.concat([e]):null,vh(4194308,4,D_.bind(null,t,e),s)},useLayoutEffect:function(e,t){return vh(4194308,4,e,t)},useInsertionEffect:function(e,t){return vh(4,2,e,t)},useMemo:function(e,t){var s=ur();return t=t===void 0?null:t,e=e(),s.memoizedState=[e,t],e},useReducer:function(e,t,s){var r=ur();return t=s!==void 0?s(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=HA.bind(null,Bt,e),[r.memoizedState,e]},useRef:function(e){var t=ur();return e={current:e},t.memoizedState=e},useState:a0,useDebugValue:Mv,useDeferredValue:function(e){return ur().memoizedState=e},useTransition:function(){var e=a0(!1),t=e[0];return e=qA.bind(null,e[1]),ur().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,s){var r=Bt,a=ur();if(Mt){if(s===void 0)throw Error(be(407));s=s()}else{if(s=t(),gs===null)throw Error(be(349));Yi&30||P_(r,t,s)}a.memoizedState=s;var i={value:s,getSnapshot:t};return a.queue=i,i0(A_.bind(null,r,i,e),[e]),r.flags|=2048,pd(9,E_.bind(null,r,i,s,t),void 0,null),s},useId:function(){var e=ur(),t=gs.identifierPrefix;if(Mt){var s=Hr,r=qr;s=(r&~(1<<32-Yn(r)-1)).toString(32)+s,t=":"+t+"R"+s,s=hd++,0<s&&(t+="H"+s.toString(32)),t+=":"}else s=VA++,t=":"+t+"r"+s.toString(32)+":";return e.memoizedState=t},unstable_isNewReconciler:!1},YA={readContext:Rn,useCallback:z_,useContext:Rn,useEffect:Dv,useImperativeHandle:M_,useInsertionEffect:I_,useLayoutEffect:O_,useMemo:F_,useReducer:cf,useRef:L_,useState:function(){return cf(md)},useDebugValue:Mv,useDeferredValue:function(e){var t=$n();return U_(t,ds.memoizedState,e)},useTransition:function(){var e=cf(md)[0],t=$n().memoizedState;return[e,t]},useMutableSource:C_,useSyncExternalStore:T_,useId:B_,unstable_isNewReconciler:!1},KA={readContext:Rn,useCallback:z_,useContext:Rn,useEffect:Dv,useImperativeHandle:M_,useInsertionEffect:I_,useLayoutEffect:O_,useMemo:F_,useReducer:df,useRef:L_,useState:function(){return df(md)},useDebugValue:Mv,useDeferredValue:function(e){var t=$n();return ds===null?t.memoizedState=e:U_(t,ds.memoizedState,e)},useTransition:function(){var e=df(md)[0],t=$n().memoizedState;return[e,t]},useMutableSource:C_,useSyncExternalStore:T_,useId:B_,unstable_isNewReconciler:!1};function Bn(e,t){if(e&&e.defaultProps){t=qt({},t),e=e.defaultProps;for(var s in e)t[s]===void 0&&(t[s]=e[s]);return t}return t}function Lg(e,t,s,r){t=e.memoizedState,s=s(r,t),s=s==null?t:qt({},t,s),e.memoizedState=s,e.lanes===0&&(e.updateQueue.baseState=s)}var Fm={isMounted:function(e){return(e=e._reactInternals)?oo(e)===e:!1},enqueueSetState:function(e,t,s){e=e._reactInternals;var r=zs(),a=Ga(e),i=Wr(r,a);i.payload=t,s!=null&&(i.callback=s),t=Ha(e,i,a),t!==null&&(Kn(t,e,a,r),gh(t,e,a))},enqueueReplaceState:function(e,t,s){e=e._reactInternals;var r=zs(),a=Ga(e),i=Wr(r,a);i.tag=1,i.payload=t,s!=null&&(i.callback=s),t=Ha(e,i,a),t!==null&&(Kn(t,e,a,r),gh(t,e,a))},enqueueForceUpdate:function(e,t){e=e._reactInternals;var s=zs(),r=Ga(e),a=Wr(s,r);a.tag=2,t!=null&&(a.callback=t),t=Ha(e,a,r),t!==null&&(Kn(t,e,r,s),gh(t,e,r))}};function o0(e,t,s,r,a,i,o){return e=e.stateNode,typeof e.shouldComponentUpdate=="function"?e.shouldComponentUpdate(r,i,o):t.prototype&&t.prototype.isPureReactComponent?!id(s,r)||!id(a,i):!0}function W_(e,t,s){var r=!1,a=si,i=t.contextType;return typeof i=="object"&&i!==null?i=Rn(i):(a=Qs(t)?Wi:$s.current,r=t.contextTypes,i=(r=r!=null)?kl(e,a):si),t=new t(s,i),e.memoizedState=t.state!==null&&t.state!==void 0?t.state:null,t.updater=Fm,e.stateNode=t,t._reactInternals=e,r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=a,e.__reactInternalMemoizedMaskedChildContext=i),t}function l0(e,t,s,r){e=t.state,typeof t.componentWillReceiveProps=="function"&&t.componentWillReceiveProps(s,r),typeof t.UNSAFE_componentWillReceiveProps=="function"&&t.UNSAFE_componentWillReceiveProps(s,r),t.state!==e&&Fm.enqueueReplaceState(t,t.state,null)}function Ig(e,t,s,r){var a=e.stateNode;a.props=s,a.state=e.memoizedState,a.refs={},Ev(e);var i=t.contextType;typeof i=="object"&&i!==null?a.context=Rn(i):(i=Qs(t)?Wi:$s.current,a.context=kl(e,i)),a.state=e.memoizedState,i=t.getDerivedStateFromProps,typeof i=="function"&&(Lg(e,t,i,s),a.state=e.memoizedState),typeof t.getDerivedStateFromProps=="function"||typeof a.getSnapshotBeforeUpdate=="function"||typeof a.UNSAFE_componentWillMount!="function"&&typeof a.componentWillMount!="function"||(t=a.state,typeof a.componentWillMount=="function"&&a.componentWillMount(),typeof a.UNSAFE_componentWillMount=="function"&&a.UNSAFE_componentWillMount(),t!==a.state&&Fm.enqueueReplaceState(a,a.state,null),Hh(e,s,a,r),a.state=e.memoizedState),typeof a.componentDidMount=="function"&&(e.flags|=4194308)}function Tl(e,t){try{var s="",r=t;do s+=_E(r),r=r.return;while(r);var a=s}catch(i){a=`
24Error generating stack: `+i.message+`
25`+i.stack}return{value:e,source:t,stack:a,digest:null}}function uf(e,t,s){return{value:e,source:null,stack:s??null,digest:t??null}}function Og(e,t){try{console.error(t.value)}catch(s){setTimeout(function(){throw s})}}var QA=typeof WeakMap=="function"?WeakMap:Map;function G_(e,t,s){s=Wr(-1,s),s.tag=3,s.payload={element:null};var r=t.value;
vendor: 16,384 bytes, line 25
25return s.callback=function(){Qh||(Qh=!0,Wg=r),Og(e,t)},s}function Y_(e,t,s){s=Wr(-1,s),s.tag=3;var r=e.type.getDerivedStateFromError;if(typeof r=="function"){var a=t.value;s.payload=function(){return r(a)},s.callback=function(){Og(e,t)}}var i=e.stateNode;return i!==null&&typeof i.componentDidCatch=="function"&&(s.callback=function(){Og(e,t),typeof r!="function"&&(Wa===null?Wa=new Set([this]):Wa.add(this));var o=t.stack;this.componentDidCatch(t.value,{componentStack:o!==null?o:""})}),s}function c0(e,t,s){var r=e.pingCache;if(r===null){r=e.pingCache=new QA;var a=new Set;r.set(t,a)}else a=r.get(t),a===void 0&&(a=new Set,r.set(t,a));a.has(s)||(a.add(s),e=dR.bind(null,e,t,s),t.then(e,e))}function d0(e){do{var t;if((t=e.tag===13)&&(t=e.memoizedState,t=t!==null?t.dehydrated!==null:!0),t)return e;e=e.return}while(e!==null);return null}function u0(e,t,s,r,a){return e.mode&1?(e.flags|=65536,e.lanes=a,e):(e===t?e.flags|=65536:(e.flags|=128,s.flags|=131072,s.flags&=-52805,s.tag===1&&(s.alternate===null?s.tag=17:(t=Wr(-1,1),t.tag=2,Ha(s,t,1))),s.lanes|=1),e)}var JA=sa.ReactCurrentOwner,Ys=!1;function Ms(e,t,s,r){t.child=e===null?__(t,null,s,r):Sl(t,e.child,s,r)}function h0(e,t,s,r,a){s=s.render;var i=t.ref;return nl(t,a),r=Iv(e,t,s,r,i,a),s=Ov(),e!==null&&!Ys?(t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~a,Jr(e,t,a)):(Mt&&s&&_v(t),t.flags|=1,Ms(e,t,r,a),t.child)}function m0(e,t,s,r,a){if(e===null){var i=s.type;return typeof i=="function"&&!Wv(i)&&i.defaultProps===void 0&&s.compare===null&&s.defaultProps===void 0?(t.tag=15,t.type=i,K_(e,t,i,r,a)):(e=jh(s.type,null,r,t,t.mode,a),e.ref=t.ref,e.return=t,t.child=e)}if(i=e.child,!(e.lanes&a)){var o=i.memoizedProps;if(s=s.compare,s=s!==null?s:id,s(o,r)&&e.ref===t.ref)return Jr(e,t,a)}return t.flags|=1,e=Ya(i,r),e.ref=t.ref,e.return=t,t.child=e}function K_(e,t,s,r,a){if(e!==null){var i=e.memoizedProps;if(id(i,r)&&e.ref===t.ref)if(Ys=!1,t.pendingProps=r=i,(e.lanes&a)!==0)e.flags&131072&&(Ys=!0);else return t.lanes=e.lanes,Jr(e,t,a)}return Dg(e,t,s,r,a)}function Q_(e,t,s){var r=t.pendingProps,a=r.children,i=e!==null?e.memoizedState:null;if(r.mode==="hidden")if(!(t.mode&1))t.memoizedState={baseLanes:0,cachePool:null,transitions:null},$t(Ko,an),an|=s;else{if(!(s&1073741824))return e=i!==null?i.baseLanes|s:s,t.lanes=t.childLanes=1073741824,t.memoizedState={baseLanes:e,cachePool:null,transitions:null},t.updateQueue=null,$t(Ko,an),an|=e,null;t.memoizedState={baseLanes:0,cachePool:null,transitions:null},r=i!==null?i.baseLanes:s,$t(Ko,an),an|=r}else i!==null?(r=i.baseLanes|s,t.memoizedState=null):r=s,$t(Ko,an),an|=r;return Ms(e,t,a,s),t.child}function J_(e,t){var s=t.ref;(e===null&&s!==null||e!==null&&e.ref!==s)&&(t.flags|=512,t.flags|=2097152)}function Dg(e,t,s,r,a){var i=Qs(s)?Wi:$s.current;return i=kl(t,i),nl(t,a),s=Iv(e,t,s,r,i,a),r=Ov(),e!==null&&!Ys?(t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~a,Jr(e,t,a)):(Mt&&r&&_v(t),t.flags|=1,Ms(e,t,s,a),t.child)}function p0(e,t,s,r,a){if(Qs(s)){var i=!0;Fh(t)}else i=!1;if(nl(t,a),t.stateNode===null)yh(e,t),W_(t,s,r),Ig(t,s,r,a),r=!0;else if(e===null){var o=t.stateNode,l=t.memoizedProps;o.props=l;var c=o.context,d=s.contextType;typeof d=="object"&&d!==null?d=Rn(d):(d=Qs(s)?Wi:$s.current,d=kl(t,d));var u=s.getDerivedStateFromProps,m=typeof u=="function"||typeof o.getSnapshotBeforeUpdate=="function";m||typeof o.UNSAFE_componentWillReceiveProps!="function"&&typeof o.componentWillReceiveProps!="function"||(l!==r||c!==d)&&l0(t,o,r,d),wa=!1;var p=t.memoizedState;o.state=p,Hh(t,r,o,a),c=t.memoizedState,l!==r||p!==c||Ks.current||wa?(typeof u=="function"&&(Lg(t,s,u,r),c=t.memoizedState),(l=wa||o0(t,s,l,r,p,c,d))?(m||typeof o.UNSAFE_componentWillMount!="function"&&typeof o.componentWillMount!="function"||(typeof o.componentWillMount=="function"&&o.componentWillMount(),typeof o.UNSAFE_componentWillMount=="function"&&o.UNSAFE_componentWillMount()),typeof o.componentDidMount=="function"&&(t.flags|=4194308)):(typeof o.componentDidMount=="function"&&(t.flags|=4194308),t.memoizedProps=r,t.memoizedState=c),o.props=r,o.state=c,o.context=d,r=l):(typeof o.componentDidMount=="function"&&(t.flags|=4194308),r=!1)}else{o=t.stateNode,N_(e,t),l=t.memoizedProps,d=t.type===t.elementType?l:Bn(t.type,l),o.props=d,m=t.pendingProps,p=o.context,c=s.contextType,typeof c=="object"&&c!==null?c=Rn(c):(c=Qs(s)?Wi:$s.current,c=kl(t,c));var f=s.getDerivedStateFromProps;(u=typeof f=="function"||typeof o.getSnapshotBeforeUpdate=="function")||typeof o.UNSAFE_componentWillReceiveProps!="function"&&typeof o.componentWillReceiveProps!="function"||(l!==m||p!==c)&&l0(t,o,r,c),wa=!1,p=t.memoizedState,o.state=p,Hh(t,r,o,a);var g=t.memoizedState;l!==m||p!==g||Ks.current||wa?(typeof f=="function"&&(Lg(t,s,f,r),g=t.memoizedState),(d=wa||o0(t,s,d,r,p,g,c)||!1)?(u||typeof o.UNSAFE_componentWillUpdate!="function"&&typeof o.componentWillUpdate!="function"||(typeof o.componentWillUpdate=="function"&&o.componentWillUpdate(r,g,c),typeof o.UNSAFE_componentWillUpdate=="function"&&o.UNSAFE_componentWillUpdate(r,g,c)),typeof o.componentDidUpdate=="function"&&(t.flags|=4),typeof o.getSnapshotBeforeUpdate=="function"&&(t.flags|=1024)):(typeof o.componentDidUpdate!="function"||l===e.memoizedProps&&p===e.memoizedState||(t.flags|=4),typeof o.getSnapshotBeforeUpdate!="function"||l===e.memoizedProps&&p===e.memoizedState||(t.flags|=1024),t.memoizedProps=r,t.memoizedState=g),o.props=r,o.state=g,o.context=c,r=d):(typeof o.componentDidUpdate!="function"||l===e.memoizedProps&&p===e.memoizedState||(t.flags|=4),typeof o.getSnapshotBeforeUpdate!="function"||l===e.memoizedProps&&p===e.memoizedState||(t.flags|=1024),r=!1)}return Mg(e,t,s,r,i,a)}function Mg(e,t,s,r,a,i){J_(e,t);var o=(t.flags&128)!==0;if(!r&&!o)return a&&Xb(t,s,!1),Jr(e,t,i);r=t.stateNode,JA.current=t;var l=o&&typeof s.getDerivedStateFromError!="function"?null:r.render();return t.flags|=1,e!==null&&o?(t.child=Sl(t,e.child,null,i),t.child=Sl(t,null,l,i)):Ms(e,t,l,i),t.memoizedState=r.state,a&&Xb(t,s,!0),t.child}function Z_(e){var t=e.stateNode;t.pendingContext?Zb(e,t.pendingContext,t.pendingContext!==t.context):t.context&&Zb(e,t.context,!1),Av(e,t.containerInfo)}function f0(e,t,s,r,a){return Nl(),Nv(a),t.flags|=256,Ms(e,t,s,r),t.child}var zg={dehydrated:null,treeContext:null,retryLane:0};function Fg(e){return{baseLanes:e,cachePool:null,transitions:null}}function X_(e,t,s){var r=t.pendingProps,a=Ft.current,i=!1,o=(t.flags&128)!==0,l;if((l=o)||(l=e!==null&&e.memoizedState===null?!1:(a&2)!==0),l?(i=!0,t.flags&=-129):(e===null||e.memoizedState!==null)&&(a|=1),$t(Ft,a&1),e===null)return Rg(t),e=t.memoizedState,e!==null&&(e=e.dehydrated,e!==null)?(t.mode&1?e.data==="$!"?t.lanes=8:t.lanes=1073741824:t.lanes=1,null):(o=r.children,e=r.fallback,i?(r=t.mode,i=t.child,o={mode:"hidden",children:o},!(r&1)&&i!==null?(i.childLanes=0,i.pendingProps=o):i=Vm(o,r,0,null),e=qi(e,r,s,null),i.return=t,e.return=t,i.sibling=e,t.child=i,t.child.memoizedState=Fg(s),t.memoizedState=zg,e):zv(t,o));if(a=e.memoizedState,a!==null&&(l=a.dehydrated,l!==null))return ZA(e,t,o,r,l,a,s);if(i){i=r.fallback,o=t.mode,a=e.child,l=a.sibling;var c={mode:"hidden",children:r.children};return!(o&1)&&t.child!==a?(r=t.child,r.childLanes=0,r.pendingProps=c,t.deletions=null):(r=Ya(a,c),r.subtreeFlags=a.subtreeFlags&14680064),l!==null?i=Ya(l,i):(i=qi(i,o,s,null),i.flags|=2),i.return=t,r.return=t,r.sibling=i,t.child=r,r=i,i=t.child,o=e.child.memoizedState,o=o===null?Fg(s):{baseLanes:o.baseLanes|s,cachePool:null,transitions:o.transitions},i.memoizedState=o,i.childLanes=e.childLanes&~s,t.memoizedState=zg,r}return i=e.child,e=i.sibling,r=Ya(i,{mode:"visible",children:r.children}),!(t.mode&1)&&(r.lanes=s),r.return=t,r.sibling=null,e!==null&&(s=t.deletions,s===null?(t.deletions=[e],t.flags|=16):s.push(e)),t.child=r,t.memoizedState=null,r}function zv(e,t){return t=Vm({mode:"visible",children:t},e.mode,0,null),t.return=e,e.child=t}function Uu(e,t,s,r){return r!==null&&Nv(r),Sl(t,e.child,null,s),e=zv(t,t.pendingProps.children),e.flags|=2,t.memoizedState=null,e}function ZA(e,t,s,r,a,i,o){if(s)return t.flags&256?(t.flags&=-257,r=uf(Error(be(422))),Uu(e,t,o,r)):t.memoizedState!==null?(t.child=e.child,t.flags|=128,null):(i=r.fallback,a=t.mode,r=Vm({mode:"visible",children:r.children},a,0,null),i=qi(i,a,o,null),i.flags|=2,r.return=t,i.return=t,r.sibling=i,t.child=r,t.mode&1&&Sl(t,e.child,null,o),t.child.memoizedState=Fg(o),t.memoizedState=zg,i);if(!(t.mode&1))return Uu(e,t,o,null);if(a.data==="$!"){if(r=a.nextSibling&&a.nextSibling.dataset,r)var l=r.dgst;return r=l,i=Error(be(419)),r=uf(i,r,void 0),Uu(e,t,o,r)}if(l=(o&e.childLanes)!==0,Ys||l){if(r=gs,r!==null){switch(o&-o){case 4:a=2;break;case 16:a=8;break;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:a=32;break;case 536870912:a=268435456;break;default:a=0}a=a&(r.suspendedLanes|o)?0:a,a!==0&&a!==i.retryLane&&(i.retryLane=a,Qr(e,a),Kn(r,e,a,-1))}return Hv(),r=uf(Error(be(421))),Uu(e,t,o,r)}return a.data==="$?"?(t.flags|=128,t.child=e.child,t=uR.bind(null,e),a._reactRetry=t,null):(e=i.treeContext,dn=qa(a.nextSibling),mn=t,Mt=!0,Gn=null,e!==null&&(Cn[Tn++]=qr,Cn[Tn++]=Hr,Cn[Tn++]=Gi,qr=e.id,Hr=e.overflow,Gi=t),t=zv(t,r.children),t.flags|=4096,t)}function g0(e,t,s){e.lanes|=t;var r=e.alternate;r!==null&&(r.lanes|=t),$g(e.return,t,s)}function hf(e,t,s,r,a){var i=e.memoizedState;i===null?e.memoizedState={isBackwards:t,rendering:null,renderingStartTime:0,last:r,tail:s,tailMode:a}:(i.isBackwards=t,i.rendering=null,i.renderingStartTime=0,i.last=r,i.tail=s,i.tailMode=a)}function ek(e,t,s){var r=t.pendingProps,a=r.revealOrder,i=r.tail;if(Ms(e,t,r.children,s),r=Ft.current,r&2)r=r&1|2,t.flags|=128;else{if(e!==null&&e.flags&128)e:for(e=t.child;e!==null;){if(e.tag===13)e.memoizedState!==null&&g0(e,s,t);else if(e.tag===19)g0(e,s,t);else if(e.child!==null){e.child.return=e,e=e.child;continue}if(e===t)break e;for(;e.sibling===null;){if(e.return===null||e.return===t)break e;e=e.return}e.sibling.return=e.return,e=e.sibling}r&=1}if($t(Ft,r),!(t.mode&1))t.memoizedState=null;else switch(a){case"forwards":for(s=t.child,a=null;s!==null;)e=s.alternate,e!==null&&Wh(e)===null&&(a=s),s=s.sibling;s=a,s===null?(a=t.child,t.child=null):(a=s.sibling,s.sibling=null),hf(t,!1,a,s,i);break;case"backwards":for(s=null,a=t.child,t.child=null;a!==null;){if(e=a.alternate,e!==null&&Wh(e)===null){t.child=a;break}e=a.sibling,a.sibling=s,s=a,a=e}hf(t,!0,s,null,i);break;case"together":hf(t,!1,null,null,void 0);break;default:t.memoizedState=null}return t.child}function yh(e,t){!(t.mode&1)&&e!==null&&(e.alternate=null,t.alternate=null,t.flags|=2)}function Jr(e,t,s){if(e!==null&&(t.dependencies=e.dependencies),Ki|=t.lanes,!(s&t.childLanes))return null;if(e!==null&&t.child!==e.child)throw Error(be(153));if(t.child!==null){for(e=t.child,s=Ya(e,e.pendingProps),t.child=s,s.return=t;e.sibling!==null;)e=e.sibling,s=s.sibling=Ya(e,e.pendingProps),s.return=t;s.sibling=null}return t.child}function XA(e,t,s){switch(t.tag){case 3:Z_(t),Nl();break;case 5:S_(t);break;case 1:Qs(t.type)&&Fh(t);break;case 4:Av(t,t.stateNode.containerInfo);break;case 10:var r=t.type._context,a=t.memoizedProps.value;$t(Vh,r._currentValue),r._currentValue=a;break;case 13:if(r=t.memoizedState,r!==null)return r.dehydrated!==null?($t(Ft,Ft.current&1),t.flags|=128,null):s&t.child.childLanes?X_(e,t,s):($t(Ft,Ft.current&1),e=Jr(e,t,s),e!==null?e.sibling:null);$t(Ft,Ft.current&1);break;case 19:if(r=(s&t.childLanes)!==0,e.flags&128){if(r)return ek(e,t,s);t.flags|=128}if(a=t.memoizedState,a!==null&&(a.rendering=null,a.tail=null,a.lastEffect=null),$t(Ft,Ft.current),r)break;return null;case 22:case 23:return t.lanes=0,Q_(e,t,s)}return Jr(e,t,s)}var tk,Ug,sk,nk;tk=function(e,t){for(var s=t.child;s!==null;){if(s.tag===5||s.tag===6)e.appendChild(s.stateNode);else if(s.tag!==4&&s.child!==null){s.child.return=s,s=s.child;continue}if(s===t)break;for(;s.sibling===null;){if(s.return===null||s.return===t)return;s=s.return}s.sibling.return=s.return,s=s.sibling}};Ug=function(){};sk=function(e,t,s,r){var a=e.memoizedProps;if(a!==r){e=t.stateNode,Ai(kr.current);var i=null;switch(s){case"input":a=cg(e,a),r=cg(e,r),i=[];break;case"select":a=qt({},a,{value:void 0}),r=qt({},r,{value:void 0}),i=[];break;case"textarea":a=hg(e,a),r=hg(e,r),i=[];break;default:typeof a.onClick!="function"&&typeof r.onClick=="function"&&(e.onclick=Mh)}pg(s,r);var o;s=null;for(d in a)if(!r.hasOwnProperty(d)&&a.hasOwnProperty(d)&&a[d]!=null)if(d==="style"){var l=a[d];for(o in l)l.hasOwnProperty(o)&&(s||(s={}),s[o]="")}else d!=="dangerouslySetInnerHTML"&&d!=="children"&&d!=="suppressContentEditableWarning"&&d!=="suppressHydrationWarning"&&d!=="autoFocus"&&(Xc.hasOwnProperty(d)?i||(i=[]):(i=i||[]).push(d,null));for(d in r){var c=r[d];if(l=a!=null?a[d]:void 0,r.hasOwnProperty(d)&&c!==l&&(c!=null||l!=null))if(d==="style")if(l){for(o in l)!l.hasOwnProperty(o)||c&&c.hasOwnProperty(o)||(s||(s={}),s[o]="");for(o in c)c.hasOwnProperty(o)&&l[o]!==c[o]&&(s||(s={}),s[o]=c[o])}else s||(i||(i=[]),i.push(d,s)),s=c;else d==="dangerouslySetInnerHTML"?(c=c?c.__html:void 0,l=l?l.__html:void 0,c!=null&&l!==c&&(i=i||[]).push(d,c)):d==="children"?typeof c!="string"&&typeof c!="number"||(i=i||[]).push(d,""+c):d!=="suppressContentEditableWarning"&&d!=="suppressHydrationWarning"&&(Xc.hasOwnProperty(d)?(c!=null&&d==="onScroll"&&It("scroll",e),i||l===c||(i=[])):(i=i||[]).push(d,c))}s&&(i=i||[]).push("style",s);var d=i;(t.updateQueue=d)&&(t.flags|=4)}};nk=function(e,t,s,r){s!==r&&(t.flags|=4)};function xc(e,t){if(!Mt)switch(e.tailMode){case"hidden":t=e.tail;for(var s=null;t!==null;)t.alternate!==null&&(s=t),t=t.sibling;s===null?e.tail=null:s.sibling=null;break;case"collapsed":s=e.tail;for(var r=null;s!==null;)s.alternate!==null&&(r=s),s=s.sibling;r===null?t||e.tail===null?e.tail=null:e.tail.sibling=null:r.sibling=null}}function Ps(e){var t=e.alternate!==null&&e.alternate.child===e.child,s=0,r=0;if(t)for(var a=e.child;a!==null;)s|=a.lanes|a.childLanes,r|=a.subtreeFlags&14680064,r|=a.flags&14680064,a.return=e,a=a.sibling;else for(a=e.child;a!==null;)s|=a.lanes|a.childLanes,r|=a.subtreeFlags,r|=a.flags,a.return=e,a=a.sibling;return e.subtreeFlags|=r,e.childLanes=s,t}function eR(e,t,s){var r=t.pendingProps;switch(kv(t),t.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return Ps(t),null;case 1:return Qs(t.type)&&zh(),Ps(t),null;case 3:return r=t.stateNode,Cl(),Dt(Ks),Dt($s),$v(),r.pendingContext&&(r.context=r.pendingContext,r.pendingContext=null),(e===null||e.child===null)&&(zu(t)?t.flags|=4:e===null||e.memoizedState.isDehydrated&&!(t.flags&256)||(t.flags|=1024,Gn!==null&&(Kg(Gn),Gn=null))),Ug(e,t),Ps(t),null;case 5:Rv(t);var a=Ai(ud.current);if(s=t.type,e!==null&&t.stateNode!=null)sk(e,t,s,r,a),e.ref!==t.ref&&(t.flags|=512,t.flags|=2097152);else{if(!r){if(t.stateNode===null)throw Error(be(166));return Ps(t),null}if(e=Ai(kr.current),zu(t)){r=t.stateNode,s=t.type;var i=t.memoizedProps;switch(r[xr]=t,r[cd]=i,e=(t.mode&1)!==0,s){case"dialog":It("cancel",r),It("close",r);break;case"iframe":case"object":case"embed":It("load",r);break;case"video":case"audio":for(a=0;a<Tc.length;a++)It(Tc[a],r);break;case"source":It("error",r);break;case"img":case"image":case"link":It("error",r),It("load",r);break;case"details":It("toggle",r);break;case"input":Nb(r,i),It("invalid",r);break;case"select":r._wrapperState={wasMultiple:!!i.multiple},It("invalid",r);break;case"textarea":Cb(r,i),It("invalid",r)}pg(s,i),a=null;for(var o in i)if(i.hasOwnProperty(o)){var l=i[o];o==="children"?typeof l=="string"?r.textContent!==l&&(i.suppressHydrationWarning!==!0&&Mu(r.textContent,l,e),a=["children",l]):typeof l=="number"&&r.textContent!==""+l&&(i.suppressHydrationWarning!==!0&&Mu(r.textContent,l,e),a=["children",""+l]):Xc.hasOwnProperty(o)&&l!=null&&o==="onScroll"&&It("scroll",r)}switch(s){case"input":Eu(r),Sb(r,i,!0);break;case"textarea":Eu(r),Tb(r);break;case"select":case"option":break;default:typeof i.onClick=="function"&&(r.onclick=Mh)}r=a,t.updateQueue=r,r!==null&&(t.flags|=4)}else{o=a.nodeType===9?a:a.ownerDocument,e==="http://www.w3.org/1999/xhtml"&&(e=Aj(s)),e==="http://www.w3.org/1999/xhtml"?s==="script"?(e=o.createElement("div"),e.innerHTML="<script><\/script>",e=e.removeChild(e.firstChi
vendor: 13,038 bytes, line 25
25ld)):typeof r.is=="string"?e=o.createElement(s,{is:r.is}):(e=o.createElement(s),s==="select"&&(o=e,r.multiple?o.multiple=!0:r.size&&(o.size=r.size))):e=o.createElementNS(e,s),e[xr]=t,e[cd]=r,tk(e,t,!1,!1),t.stateNode=e;e:{switch(o=fg(s,r),s){case"dialog":It("cancel",e),It("close",e),a=r;break;case"iframe":case"object":case"embed":It("load",e),a=r;break;case"video":case"audio":for(a=0;a<Tc.length;a++)It(Tc[a],e);a=r;break;case"source":It("error",e),a=r;break;case"img":case"image":case"link":It("error",e),It("load",e),a=r;break;case"details":It("toggle",e),a=r;break;case"input":Nb(e,r),a=cg(e,r),It("invalid",e);break;case"option":a=r;break;case"select":e._wrapperState={wasMultiple:!!r.multiple},a=qt({},r,{value:void 0}),It("invalid",e);break;case"textarea":Cb(e,r),a=hg(e,r),It("invalid",e);break;default:a=r}pg(s,a),l=a;for(i in l)if(l.hasOwnProperty(i)){var c=l[i];i==="style"?Lj(e,c):i==="dangerouslySetInnerHTML"?(c=c?c.__html:void 0,c!=null&&Rj(e,c)):i==="children"?typeof c=="string"?(s!=="textarea"||c!=="")&&ed(e,c):typeof c=="number"&&ed(e,""+c):i!=="suppressContentEditableWarning"&&i!=="suppressHydrationWarning"&&i!=="autoFocus"&&(Xc.hasOwnProperty(i)?c!=null&&i==="onScroll"&&It("scroll",e):c!=null&&cv(e,i,c,o))}switch(s){case"input":Eu(e),Sb(e,r,!1);break;case"textarea":Eu(e),Tb(e);break;case"option":r.value!=null&&e.setAttribute("value",""+ti(r.value));break;case"select":e.multiple=!!r.multiple,i=r.value,i!=null?Xo(e,!!r.multiple,i,!1):r.defaultValue!=null&&Xo(e,!!r.multiple,r.defaultValue,!0);break;default:typeof a.onClick=="function"&&(e.onclick=Mh)}switch(s){case"button":case"input":case"select":case"textarea":r=!!r.autoFocus;break e;case"img":r=!0;break e;default:r=!1}}r&&(t.flags|=4)}t.ref!==null&&(t.flags|=512,t.flags|=2097152)}return Ps(t),null;case 6:if(e&&t.stateNode!=null)nk(e,t,e.memoizedProps,r);else{if(typeof r!="string"&&t.stateNode===null)throw Error(be(166));if(s=Ai(ud.current),Ai(kr.current),zu(t)){if(r=t.stateNode,s=t.memoizedProps,r[xr]=t,(i=r.nodeValue!==s)&&(e=mn,e!==null))switch(e.tag){case 3:Mu(r.nodeValue,s,(e.mode&1)!==0);break;case 5:e.memoizedProps.suppressHydrationWarning!==!0&&Mu(r.nodeValue,s,(e.mode&1)!==0)}i&&(t.flags|=4)}else r=(s.nodeType===9?s:s.ownerDocument).createTextNode(r),r[xr]=t,t.stateNode=r}return Ps(t),null;case 13:if(Dt(Ft),r=t.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(Mt&&dn!==null&&t.mode&1&&!(t.flags&128))w_(),Nl(),t.flags|=98560,i=!1;else if(i=zu(t),r!==null&&r.dehydrated!==null){if(e===null){if(!i)throw Error(be(318));if(i=t.memoizedState,i=i!==null?i.dehydrated:null,!i)throw Error(be(317));i[xr]=t}else Nl(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;Ps(t),i=!1}else Gn!==null&&(Kg(Gn),Gn=null),i=!0;if(!i)return t.flags&65536?t:null}return t.flags&128?(t.lanes=s,t):(r=r!==null,r!==(e!==null&&e.memoizedState!==null)&&r&&(t.child.flags|=8192,t.mode&1&&(e===null||Ft.current&1?hs===0&&(hs=3):Hv())),t.updateQueue!==null&&(t.flags|=4),Ps(t),null);case 4:return Cl(),Ug(e,t),e===null&&od(t.stateNode.containerInfo),Ps(t),null;case 10:return Tv(t.type._context),Ps(t),null;case 17:return Qs(t.type)&&zh(),Ps(t),null;case 19:if(Dt(Ft),i=t.memoizedState,i===null)return Ps(t),null;if(r=(t.flags&128)!==0,o=i.rendering,o===null)if(r)xc(i,!1);else{if(hs!==0||e!==null&&e.flags&128)for(e=t.child;e!==null;){if(o=Wh(e),o!==null){for(t.flags|=128,xc(i,!1),r=o.updateQueue,r!==null&&(t.updateQueue=r,t.flags|=4),t.subtreeFlags=0,r=s,s=t.child;s!==null;)i=s,e=r,i.flags&=14680066,o=i.alternate,o===null?(i.childLanes=0,i.lanes=e,i.child=null,i.subtreeFlags=0,i.memoizedProps=null,i.memoizedState=null,i.updateQueue=null,i.dependencies=null,i.stateNode=null):(i.childLanes=o.childLanes,i.lanes=o.lanes,i.child=o.child,i.subtreeFlags=0,i.deletions=null,i.memoizedProps=o.memoizedProps,i.memoizedState=o.memoizedState,i.updateQueue=o.updateQueue,i.type=o.type,e=o.dependencies,i.dependencies=e===null?null:{lanes:e.lanes,firstContext:e.firstContext}),s=s.sibling;return $t(Ft,Ft.current&1|2),t.child}e=e.sibling}i.tail!==null&&ts()>Pl&&(t.flags|=128,r=!0,xc(i,!1),t.lanes=4194304)}else{if(!r)if(e=Wh(o),e!==null){if(t.flags|=128,r=!0,s=e.updateQueue,s!==null&&(t.updateQueue=s,t.flags|=4),xc(i,!0),i.tail===null&&i.tailMode==="hidden"&&!o.alternate&&!Mt)return Ps(t),null}else 2*ts()-i.renderingStartTime>Pl&&s!==1073741824&&(t.flags|=128,r=!0,xc(i,!1),t.lanes=4194304);i.isBackwards?(o.sibling=t.child,t.child=o):(s=i.last,s!==null?s.sibling=o:t.child=o,i.last=o)}return i.tail!==null?(t=i.tail,i.rendering=t,i.tail=t.sibling,i.renderingStartTime=ts(),t.sibling=null,s=Ft.current,$t(Ft,r?s&1|2:s&1),t):(Ps(t),null);case 22:case 23:return qv(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?an&1073741824&&(Ps(t),t.subtreeFlags&6&&(t.flags|=8192)):Ps(t),null;case 24:return null;case 25:return null}throw Error(be(156,t.tag))}function tR(e,t){switch(kv(t),t.tag){case 1:return Qs(t.type)&&zh(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Cl(),Dt(Ks),Dt($s),$v(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Rv(t),null;case 13:if(Dt(Ft),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(be(340));Nl()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return Dt(Ft),null;case 4:return Cl(),null;case 10:return Tv(t.type._context),null;case 22:case 23:return qv(),null;case 24:return null;default:return null}}var Bu=!1,As=!1,sR=typeof WeakSet=="function"?WeakSet:Set,Ie=null;function Yo(e,t){var s=e.ref;if(s!==null)if(typeof s=="function")try{s(null)}catch(r){Qt(e,t,r)}else s.current=null}function Bg(e,t,s){try{s()}catch(r){Qt(e,t,r)}}var x0=!1;function nR(e,t){if(Ng=Ih,e=l_(),jv(e)){if("selectionStart"in e)var s={start:e.selectionStart,end:e.selectionEnd};else e:{s=(s=e.ownerDocument)&&s.defaultView||window;var r=s.getSelection&&s.getSelection();if(r&&r.rangeCount!==0){s=r.anchorNode;var a=r.anchorOffset,i=r.focusNode;r=r.focusOffset;try{s.nodeType,i.nodeType}catch{s=null;break e}var o=0,l=-1,c=-1,d=0,u=0,m=e,p=null;t:for(;;){for(var f;m!==s||a!==0&&m.nodeType!==3||(l=o+a),m!==i||r!==0&&m.nodeType!==3||(c=o+r),m.nodeType===3&&(o+=m.nodeValue.length),(f=m.firstChild)!==null;)p=m,m=f;for(;;){if(m===e)break t;if(p===s&&++d===a&&(l=o),p===i&&++u===r&&(c=o),(f=m.nextSibling)!==null)break;m=p,p=m.parentNode}m=f}s=l===-1||c===-1?null:{start:l,end:c}}else s=null}s=s||{start:0,end:0}}else s=null;for(Sg={focusedElem:e,selectionRange:s},Ih=!1,Ie=t;Ie!==null;)if(t=Ie,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,Ie=e;else for(;Ie!==null;){t=Ie;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 x=g.memoizedProps,b=g.memoizedState,v=t.stateNode,y=v.getSnapshotBeforeUpdate(t.elementType===t.type?x:Bn(t.type,x),b);v.__reactInternalSnapshotBeforeUpdate=y}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(be(163))}}catch(j){Qt(t,t.return,j)}if(e=t.sibling,e!==null){e.return=t.return,Ie=e;break}Ie=t.return}return g=x0,x0=!1,g}function qc(e,t,s){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var a=r=r.next;do{if((a.tag&e)===e){var i=a.destroy;a.destroy=void 0,i!==void 0&&Bg(t,s,i)}a=a.next}while(a!==r)}}function Um(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var s=t=t.next;do{if((s.tag&e)===e){var r=s.create;s.destroy=r()}s=s.next}while(s!==t)}}function Vg(e){var t=e.ref;if(t!==null){var s=e.stateNode;switch(e.tag){case 5:e=s;break;default:e=s}typeof t=="function"?t(e):t.current=e}}function rk(e){var t=e.alternate;t!==null&&(e.alternate=null,rk(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[xr],delete t[cd],delete t[Pg],delete t[zA],delete t[FA])),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 ak(e){return e.tag===5||e.tag===3||e.tag===4}function v0(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||ak(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 qg(e,t,s){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?s.nodeType===8?s.parentNode.insertBefore(e,t):s.insertBefore(e,t):(s.nodeType===8?(t=s.parentNode,t.insertBefore(e,s)):(t=s,t.appendChild(e)),s=s._reactRootContainer,s!=null||t.onclick!==null||(t.onclick=Mh));else if(r!==4&&(e=e.child,e!==null))for(qg(e,t,s),e=e.sibling;e!==null;)qg(e,t,s),e=e.sibling}function Hg(e,t,s){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?s.insertBefore(e,t):s.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(Hg(e,t,s),e=e.sibling;e!==null;)Hg(e,t,s),e=e.sibling}var ws=null,Wn=!1;function fa(e,t,s){for(s=s.child;s!==null;)ik(e,t,s),s=s.sibling}function ik(e,t,s){if(_r&&typeof _r.onCommitFiberUnmount=="function")try{_r.onCommitFiberUnmount($m,s)}catch{}switch(s.tag){case 5:As||Yo(s,t);case 6:var r=ws,a=Wn;ws=null,fa(e,t,s),ws=r,Wn=a,ws!==null&&(Wn?(e=ws,s=s.stateNode,e.nodeType===8?e.parentNode.removeChild(s):e.removeChild(s)):ws.removeChild(s.stateNode));break;case 18:ws!==null&&(Wn?(e=ws,s=s.stateNode,e.nodeType===8?rf(e.parentNode,s):e.nodeType===1&&rf(e,s),rd(e)):rf(ws,s.stateNode));break;case 4:r=ws,a=Wn,ws=s.stateNode.containerInfo,Wn=!0,fa(e,t,s),ws=r,Wn=a;break;case 0:case 11:case 14:case 15:if(!As&&(r=s.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){a=r=r.next;do{var i=a,o=i.destroy;i=i.tag,o!==void 0&&(i&2||i&4)&&Bg(s,t,o),a=a.next}while(a!==r)}fa(e,t,s);break;case 1:if(!As&&(Yo(s,t),r=s.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=s.memoizedProps,r.state=s.memoizedState,r.componentWillUnmount()}catch(l){Qt(s,t,l)}fa(e,t,s);break;case 21:fa(e,t,s);break;case 22:s.mode&1?(As=(r=As)||s.memoizedState!==null,fa(e,t,s),As=r):fa(e,t,s);break;default:fa(e,t,s)}}function y0(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var s=e.stateNode;s===null&&(s=e.stateNode=new sR),t.forEach(function(r){var a=hR.bind(null,e,r);s.has(r)||(s.add(r),r.then(a,a))})}}function Mn(e,t){var s=t.deletions;if(s!==null)for(var r=0;r<s.length;r++){var a=s[r];try{var i=e,o=t,l=o;e:for(;l!==null;){switch(l.tag){case 5:ws=l.stateNode,Wn=!1;break e;case 3:ws=l.stateNode.containerInfo,Wn=!0;break e;case 4:ws=l.stateNode.containerInfo,Wn=!0;break e}l=l.return}if(ws===null)throw Error(be(160));ik(i,o,a),ws=null,Wn=!1;var c=a.alternate;c!==null&&(c.return=null),a.return=null}catch(d){Qt(a,t,d)}}if(t.subtreeFlags&12854)for(t=t.child;t!==null;)ok(t,e),t=t.sibling}function ok(e,t){var s=e.alternate,r=e.flags;switch(e.tag){case 0:case 11:case 14:case 15:if(Mn(t,e),cr(e),r&4){try{qc(3,e,e.return),Um(3,e)}catch(x){Qt(e,e.return,x)}try{qc(5,e,e.return)}catch(x){Qt(e,e.return,x)}}break;case 1:Mn(t,e),cr(e),r&512&&s!==null&&Yo(s,s.return);break;case 5:if(Mn(t,e),cr(e),r&512&&s!==null&&Yo(s,s.return),e.flags&32){var a=e.stateNode;try{ed(a,"")}catch(x){Qt(e,e.return,x)}}if(r&4&&(a=e.stateNode,a!=null)){var i=e.memoizedProps,o=s!==null?s.memoizedProps:i,l=e.type,c=e.updateQueue;if(e.updateQueue=null,c!==null)try{l==="input"&&i.type==="radio"&&i.name!=null&&Pj(a,i),fg(l,o);var d=fg(l,i);for(o=0;o<c.length;o+=2){var u=c[o],m=c[o+1];u==="style"?Lj(a,m):u==="dangerouslySetInnerHTML"?Rj(a,m):u==="children"?ed(a,m):cv(a,u,m,d)}switch(l){case"input":dg(a,i);break;case"textarea":Ej(a,i);break;case"select":var p=a._wrapperState.wasMultiple;a._wrapperState.wasMultiple=!!i.multiple;var f=i.value;f!=null?Xo(a,!!i.multiple,f,!1):p!==!!i.multiple&&(i.defaultValue!=null?Xo(a,!!i.multiple,i.defaultValue,!0):Xo(a,!!i.multiple,i.multiple?[]:"",!1))}a[cd]=i}catch(x){Qt(e,e.return,x)}}break;case 6:if(Mn(t,e),cr(e),r&4){if(e.stateNode===null)throw Error(be(162));a=e.stateNode,i=e.memoizedProps;try{a.nodeValue=i}catch(x){Qt(e,e.return,x)}}break;case 3:if(Mn(t,e),cr(e),r&4&&s!==null&&s.memoizedState.isDehydrated)try{rd(t.containerInfo)}catch(x){Qt(e,e.return,x)}break;case 4:Mn(t,e),cr(e);break;case 13:Mn(t,e),cr(e),a=e.child,a.flags&8192&&(i=a.memoizedState!==null,a.stateNode.isHidden=i,!i||a.alternate!==null&&a.alternate.memoizedState!==null||(Bv=ts())),r&4&&y0(e);break;case 22:if(u=s!==null&&s.memoizedState!==null,e.mode&1?(As=(d=As)||u,Mn(t,e),As=d):Mn(t,e),cr(e),r&8192){if(d=e.memoizedState!==null,(e.stateNode.isHidden=d)&&!u&&e.mode&1)for(Ie=e,u=e.child;u!==null;){for(m=Ie=u;Ie!==null;){switch(p=Ie,f=p.child,p.tag){case 0:case 11:case 14:case 15:qc(4,p,p.return);break;case 1:Yo(p,p.return);var g=p.stateNode;if(typeof g.componentWillUnmount=="function"){r=p,s=p.return;try{t=r,g.props=t.memoizedProps,g.state=t.memoizedState,g.componentWillUnmount()}catch(x){Qt(r,s,x)}}break;case 5:Yo(p,p.return);break;case 22:if(p.memoizedState!==null){w0(m);continue}}
vendor: 1,476 bytes, line 25
25f!==null?(f.return=p,Ie=f):w0(m)}u=u.sibling}e:for(u=null,m=e;;){if(m.tag===5){if(u===null){u=m;try{a=m.stateNode,d?(i=a.style,typeof i.setProperty=="function"?i.setProperty("display","none","important"):i.display="none"):(l=m.stateNode,c=m.memoizedProps.style,o=c!=null&&c.hasOwnProperty("display")?c.display:null,l.style.display=$j("display",o))}catch(x){Qt(e,e.return,x)}}}else if(m.tag===6){if(u===null)try{m.stateNode.nodeValue=d?"":m.memoizedProps}catch(x){Qt(e,e.return,x)}}else if((m.tag!==22&&m.tag!==23||m.memoizedState===null||m===e)&&m.child!==null){m.child.return=m,m=m.child;continue}if(m===e)break e;for(;m.sibling===null;){if(m.return===null||m.return===e)break e;u===m&&(u=null),m=m.return}u===m&&(u=null),m.sibling.return=m.return,m=m.sibling}}break;case 19:Mn(t,e),cr(e),r&4&&y0(e);break;case 21:break;default:Mn(t,e),cr(e)}}function cr(e){var t=e.flags;if(t&2){try{e:{for(var s=e.return;s!==null;){if(ak(s)){var r=s;break e}s=s.return}throw Error(be(160))}switch(r.tag){case 5:var a=r.stateNode;r.flags&32&&(ed(a,""),r.flags&=-33);var i=v0(e);Hg(e,i,a);break;case 3:case 4:var o=r.stateNode.containerInfo,l=v0(e);qg(e,l,o);break;default:throw Error(be(161))}}catch(c){Qt(e,e.return,c)}e.flags&=-3}t&4096&&(e.flags&=-4097)}function rR(e,t,s){Ie=e,lk(e)}function lk(e,t,s){for(var r=(e.mode&1)!==0;Ie!==null;){var a=Ie,i=a.child;if(a.tag===22&&r){var o=a.memoizedState!==null||Bu;if(!o){var l=a.alternate,c=l!==null&&l.memoizedState!==null||As;l=Bu;var d=As;
vendor: 13,329 bytes, line 25
25if(Bu=o,(As=c)&&!d)for(Ie=a;Ie!==null;)o=Ie,c=o.child,o.tag===22&&o.memoizedState!==null?j0(a):c!==null?(c.return=o,Ie=c):j0(a);for(;i!==null;)Ie=i,lk(i),i=i.sibling;Ie=a,Bu=l,As=d}b0(e)}else a.subtreeFlags&8772&&i!==null?(i.return=a,Ie=i):b0(e)}}function b0(e){for(;Ie!==null;){var t=Ie;if(t.flags&8772){var s=t.alternate;try{if(t.flags&8772)switch(t.tag){case 0:case 11:case 15:As||Um(5,t);break;case 1:var r=t.stateNode;if(t.flags&4&&!As)if(s===null)r.componentDidMount();else{var a=t.elementType===t.type?s.memoizedProps:Bn(t.type,s.memoizedProps);r.componentDidUpdate(a,s.memoizedState,r.__reactInternalSnapshotBeforeUpdate)}var i=t.updateQueue;i!==null&&r0(t,i,r);break;case 3:var o=t.updateQueue;if(o!==null){if(s=null,t.child!==null)switch(t.child.tag){case 5:s=t.child.stateNode;break;case 1:s=t.child.stateNode}r0(t,o,s)}break;case 5:var l=t.stateNode;if(s===null&&t.flags&4){s=l;var c=t.memoizedProps;switch(t.type){case"button":case"input":case"select":case"textarea":c.autoFocus&&s.focus();break;case"img":c.src&&(s.src=c.src)}}break;case 6:break;case 4:break;case 12:break;case 13:if(t.memoizedState===null){var d=t.alternate;if(d!==null){var u=d.memoizedState;if(u!==null){var m=u.dehydrated;m!==null&&rd(m)}}}break;case 19:case 17:case 21:case 22:case 23:case 25:break;default:throw Error(be(163))}As||t.flags&512&&Vg(t)}catch(p){Qt(t,t.return,p)}}if(t===e){Ie=null;break}if(s=t.sibling,s!==null){s.return=t.return,Ie=s;break}Ie=t.return}}function w0(e){for(;Ie!==null;){var t=Ie;if(t===e){Ie=null;break}var s=t.sibling;if(s!==null){s.return=t.return,Ie=s;break}Ie=t.return}}function j0(e){for(;Ie!==null;){var t=Ie;try{switch(t.tag){case 0:case 11:case 15:var s=t.return;try{Um(4,t)}catch(c){Qt(t,s,c)}break;case 1:var r=t.stateNode;if(typeof r.componentDidMount=="function"){var a=t.return;try{r.componentDidMount()}catch(c){Qt(t,a,c)}}var i=t.return;try{Vg(t)}catch(c){Qt(t,i,c)}break;case 5:var o=t.return;try{Vg(t)}catch(c){Qt(t,o,c)}}}catch(c){Qt(t,t.return,c)}if(t===e){Ie=null;break}var l=t.sibling;if(l!==null){l.return=t.return,Ie=l;break}Ie=t.return}}var aR=Math.ceil,Kh=sa.ReactCurrentDispatcher,Fv=sa.ReactCurrentOwner,En=sa.ReactCurrentBatchConfig,Nt=0,gs=null,is=null,ks=0,an=0,Ko=mi(0),hs=0,fd=null,Ki=0,Bm=0,Uv=0,Hc=null,Gs=null,Bv=0,Pl=1/0,Mr=null,Qh=!1,Wg=null,Wa=null,Vu=!1,Oa=null,Jh=0,Wc=0,Gg=null,bh=-1,wh=0;function zs(){return Nt&6?ts():bh!==-1?bh:bh=ts()}function Ga(e){return e.mode&1?Nt&2&&ks!==0?ks&-ks:BA.transition!==null?(wh===0&&(wh=Wj()),wh):(e=At,e!==0||(e=window.event,e=e===void 0?16:Xj(e.type)),e):1}function Kn(e,t,s,r){if(50<Wc)throw Wc=0,Gg=null,Error(be(185));Qd(e,s,r),(!(Nt&2)||e!==gs)&&(e===gs&&(!(Nt&2)&&(Bm|=s),hs===4&&ka(e,ks)),Js(e,r),s===1&&Nt===0&&!(t.mode&1)&&(Pl=ts()+500,Mm&&pi()))}function Js(e,t){var s=e.callbackNode;BE(e,t);var r=Lh(e,e===gs?ks:0);if(r===0)s!==null&&Ab(s),e.callbackNode=null,e.callbackPriority=0;else if(t=r&-r,e.callbackPriority!==t){if(s!=null&&Ab(s),t===1)e.tag===0?UA(_0.bind(null,e)):v_(_0.bind(null,e)),DA(function(){!(Nt&6)&&pi()}),s=null;else{switch(Gj(r)){case 1:s=pv;break;case 4:s=qj;break;case 16:s=$h;break;case 536870912:s=Hj;break;default:s=$h}s=gk(s,ck.bind(null,e))}e.callbackPriority=t,e.callbackNode=s}}function ck(e,t){if(bh=-1,wh=0,Nt&6)throw Error(be(327));var s=e.callbackNode;if(rl()&&e.callbackNode!==s)return null;var r=Lh(e,e===gs?ks:0);if(r===0)return null;if(r&30||r&e.expiredLanes||t)t=Zh(e,r);else{t=r;var a=Nt;Nt|=2;var i=uk();(gs!==e||ks!==t)&&(Mr=null,Pl=ts()+500,Vi(e,t));do try{lR();break}catch(l){dk(e,l)}while(!0);Cv(),Kh.current=i,Nt=a,is!==null?t=0:(gs=null,ks=0,t=hs)}if(t!==0){if(t===2&&(a=bg(e),a!==0&&(r=a,t=Yg(e,a))),t===1)throw s=fd,Vi(e,0),ka(e,r),Js(e,ts()),s;if(t===6)ka(e,r);else{if(a=e.current.alternate,!(r&30)&&!iR(a)&&(t=Zh(e,r),t===2&&(i=bg(e),i!==0&&(r=i,t=Yg(e,i))),t===1))throw s=fd,Vi(e,0),ka(e,r),Js(e,ts()),s;switch(e.finishedWork=a,e.finishedLanes=r,t){case 0:case 1:throw Error(be(345));case 2:Si(e,Gs,Mr);break;case 3:if(ka(e,r),(r&130023424)===r&&(t=Bv+500-ts(),10<t)){if(Lh(e,0)!==0)break;if(a=e.suspendedLanes,(a&r)!==r){zs(),e.pingedLanes|=e.suspendedLanes&a;break}e.timeoutHandle=Tg(Si.bind(null,e,Gs,Mr),t);break}Si(e,Gs,Mr);break;case 4:if(ka(e,r),(r&4194240)===r)break;for(t=e.eventTimes,a=-1;0<r;){var o=31-Yn(r);i=1<<o,o=t[o],o>a&&(a=o),r&=~i}if(r=a,r=ts()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*aR(r/1960))-r,10<r){e.timeoutHandle=Tg(Si.bind(null,e,Gs,Mr),r);break}Si(e,Gs,Mr);break;case 5:Si(e,Gs,Mr);break;default:throw Error(be(329))}}}return Js(e,ts()),e.callbackNode===s?ck.bind(null,e):null}function Yg(e,t){var s=Hc;return e.current.memoizedState.isDehydrated&&(Vi(e,t).flags|=256),e=Zh(e,t),e!==2&&(t=Gs,Gs=s,t!==null&&Kg(t)),e}function Kg(e){Gs===null?Gs=e:Gs.push.apply(Gs,e)}function iR(e){for(var t=e;;){if(t.flags&16384){var s=t.updateQueue;if(s!==null&&(s=s.stores,s!==null))for(var r=0;r<s.length;r++){var a=s[r],i=a.getSnapshot;a=a.value;try{if(!Jn(i(),a))return!1}catch{return!1}}}if(s=t.child,t.subtreeFlags&16384&&s!==null)s.return=t,t=s;else{if(t===e)break;for(;t.sibling===null;){if(t.return===null||t.return===e)return!0;t=t.return}t.sibling.return=t.return,t=t.sibling}}return!0}function ka(e,t){for(t&=~Uv,t&=~Bm,e.suspendedLanes|=t,e.pingedLanes&=~t,e=e.expirationTimes;0<t;){var s=31-Yn(t),r=1<<s;e[s]=-1,t&=~r}}function _0(e){if(Nt&6)throw Error(be(327));rl();var t=Lh(e,0);if(!(t&1))return Js(e,ts()),null;var s=Zh(e,t);if(e.tag!==0&&s===2){var r=bg(e);r!==0&&(t=r,s=Yg(e,r))}if(s===1)throw s=fd,Vi(e,0),ka(e,t),Js(e,ts()),s;if(s===6)throw Error(be(345));return e.finishedWork=e.current.alternate,e.finishedLanes=t,Si(e,Gs,Mr),Js(e,ts()),null}function Vv(e,t){var s=Nt;Nt|=1;try{return e(t)}finally{Nt=s,Nt===0&&(Pl=ts()+500,Mm&&pi())}}function Qi(e){Oa!==null&&Oa.tag===0&&!(Nt&6)&&rl();var t=Nt;Nt|=1;var s=En.transition,r=At;try{if(En.transition=null,At=1,e)return e()}finally{At=r,En.transition=s,Nt=t,!(Nt&6)&&pi()}}function qv(){an=Ko.current,Dt(Ko)}function Vi(e,t){e.finishedWork=null,e.finishedLanes=0;var s=e.timeoutHandle;if(s!==-1&&(e.timeoutHandle=-1,OA(s)),is!==null)for(s=is.return;s!==null;){var r=s;switch(kv(r),r.tag){case 1:r=r.type.childContextTypes,r!=null&&zh();break;case 3:Cl(),Dt(Ks),Dt($s),$v();break;case 5:Rv(r);break;case 4:Cl();break;case 13:Dt(Ft);break;case 19:Dt(Ft);break;case 10:Tv(r.type._context);break;case 22:case 23:qv()}s=s.return}if(gs=e,is=e=Ya(e.current,null),ks=an=t,hs=0,fd=null,Uv=Bm=Ki=0,Gs=Hc=null,Ei!==null){for(t=0;t<Ei.length;t++)if(s=Ei[t],r=s.interleaved,r!==null){s.interleaved=null;var a=r.next,i=s.pending;if(i!==null){var o=i.next;i.next=a,r.next=o}s.pending=r}Ei=null}return e}function dk(e,t){do{var s=is;try{if(Cv(),xh.current=Yh,Gh){for(var r=Bt.memoizedState;r!==null;){var a=r.queue;a!==null&&(a.pending=null),r=r.next}Gh=!1}if(Yi=0,fs=ds=Bt=null,Vc=!1,hd=0,Fv.current=null,s===null||s.return===null){hs=1,fd=t,is=null;break}e:{var i=e,o=s.return,l=s,c=t;if(t=ks,l.flags|=32768,c!==null&&typeof c=="object"&&typeof c.then=="function"){var d=c,u=l,m=u.tag;if(!(u.mode&1)&&(m===0||m===11||m===15)){var p=u.alternate;p?(u.updateQueue=p.updateQueue,u.memoizedState=p.memoizedState,u.lanes=p.lanes):(u.updateQueue=null,u.memoizedState=null)}var f=d0(o);if(f!==null){f.flags&=-257,u0(f,o,l,i,t),f.mode&1&&c0(i,d,t),t=f,c=d;var g=t.updateQueue;if(g===null){var x=new Set;x.add(c),t.updateQueue=x}else g.add(c);break e}else{if(!(t&1)){c0(i,d,t),Hv();break e}c=Error(be(426))}}else if(Mt&&l.mode&1){var b=d0(o);if(b!==null){!(b.flags&65536)&&(b.flags|=256),u0(b,o,l,i,t),Nv(Tl(c,l));break e}}i=c=Tl(c,l),hs!==4&&(hs=2),Hc===null?Hc=[i]:Hc.push(i),i=o;do{switch(i.tag){case 3:i.flags|=65536,t&=-t,i.lanes|=t;var v=G_(i,c,t);n0(i,v);break e;case 1:l=c;var y=i.type,w=i.stateNode;if(!(i.flags&128)&&(typeof y.getDerivedStateFromError=="function"||w!==null&&typeof w.componentDidCatch=="function"&&(Wa===null||!Wa.has(w)))){i.flags|=65536,t&=-t,i.lanes|=t;var j=Y_(i,l,t);n0(i,j);break e}}i=i.return}while(i!==null)}mk(s)}catch(_){t=_,is===s&&s!==null&&(is=s=s.return);continue}break}while(!0)}function uk(){var e=Kh.current;return Kh.current=Yh,e===null?Yh:e}function Hv(){(hs===0||hs===3||hs===2)&&(hs=4),gs===null||!(Ki&268435455)&&!(Bm&268435455)||ka(gs,ks)}function Zh(e,t){var s=Nt;Nt|=2;var r=uk();(gs!==e||ks!==t)&&(Mr=null,Vi(e,t));do try{oR();break}catch(a){dk(e,a)}while(!0);if(Cv(),Nt=s,Kh.current=r,is!==null)throw Error(be(261));return gs=null,ks=0,hs}function oR(){for(;is!==null;)hk(is)}function lR(){for(;is!==null&&!$E();)hk(is)}function hk(e){var t=fk(e.alternate,e,an);e.memoizedProps=e.pendingProps,t===null?mk(e):is=t,Fv.current=null}function mk(e){var t=e;do{var s=t.alternate;if(e=t.return,t.flags&32768){if(s=tR(s,t),s!==null){s.flags&=32767,is=s;return}if(e!==null)e.flags|=32768,e.subtreeFlags=0,e.deletions=null;else{hs=6,is=null;return}}else if(s=eR(s,t,an),s!==null){is=s;return}if(t=t.sibling,t!==null){is=t;return}is=t=e}while(t!==null);hs===0&&(hs=5)}function Si(e,t,s){var r=At,a=En.transition;try{En.transition=null,At=1,cR(e,t,s,r)}finally{En.transition=a,At=r}return null}function cR(e,t,s,r){do rl();while(Oa!==null);if(Nt&6)throw Error(be(327));s=e.finishedWork;var a=e.finishedLanes;if(s===null)return null;if(e.finishedWork=null,e.finishedLanes=0,s===e.current)throw Error(be(177));e.callbackNode=null,e.callbackPriority=0;var i=s.lanes|s.childLanes;if(VE(e,i),e===gs&&(is=gs=null,ks=0),!(s.subtreeFlags&2064)&&!(s.flags&2064)||Vu||(Vu=!0,gk($h,function(){return rl(),null})),i=(s.flags&15990)!==0,s.subtreeFlags&15990||i){i=En.transition,En.transition=null;var o=At;At=1;var l=Nt;Nt|=4,Fv.current=null,nR(e,s),ok(s,e),PA(Sg),Ih=!!Ng,Sg=Ng=null,e.current=s,rR(s),LE(),Nt=l,At=o,En.transition=i}else e.current=s;if(Vu&&(Vu=!1,Oa=e,Jh=a),i=e.pendingLanes,i===0&&(Wa=null),DE(s.stateNode),Js(e,ts()),t!==null)for(r=e.onRecoverableError,s=0;s<t.length;s++)a=t[s],r(a.value,{componentStack:a.stack,digest:a.digest});if(Qh)throw Qh=!1,e=Wg,Wg=null,e;return Jh&1&&e.tag!==0&&rl(),i=e.pendingLanes,i&1?e===Gg?Wc++:(Wc=0,Gg=e):Wc=0,pi(),null}function rl(){if(Oa!==null){var e=Gj(Jh),t=En.transition,s=At;try{if(En.transition=null,At=16>e?16:e,Oa===null)var r=!1;else{if(e=Oa,Oa=null,Jh=0,Nt&6)throw Error(be(331));var a=Nt;for(Nt|=4,Ie=e.current;Ie!==null;){var i=Ie,o=i.child;if(Ie.flags&16){var l=i.deletions;if(l!==null){for(var c=0;c<l.length;c++){var d=l[c];for(Ie=d;Ie!==null;){var u=Ie;switch(u.tag){case 0:case 11:case 15:qc(8,u,i)}var m=u.child;if(m!==null)m.return=u,Ie=m;else for(;Ie!==null;){u=Ie;var p=u.sibling,f=u.return;if(rk(u),u===d){Ie=null;break}if(p!==null){p.return=f,Ie=p;break}Ie=f}}}var g=i.alternate;if(g!==null){var x=g.child;if(x!==null){g.child=null;do{var b=x.sibling;x.sibling=null,x=b}while(x!==null)}}Ie=i}}if(i.subtreeFlags&2064&&o!==null)o.return=i,Ie=o;else e:for(;Ie!==null;){if(i=Ie,i.flags&2048)switch(i.tag){case 0:case 11:case 15:qc(9,i,i.return)}var v=i.sibling;if(v!==null){v.return=i.return,Ie=v;break e}Ie=i.return}}var y=e.current;for(Ie=y;Ie!==null;){o=Ie;var w=o.child;if(o.subtreeFlags&2064&&w!==null)w.return=o,Ie=w;else e:for(o=y;Ie!==null;){if(l=Ie,l.flags&2048)try{switch(l.tag){case 0:case 11:case 15:Um(9,l)}}catch(_){Qt(l,l.return,_)}if(l===o){Ie=null;break e}var j=l.sibling;if(j!==null){j.return=l.return,Ie=j;break e}Ie=l.return}}if(Nt=a,pi(),_r&&typeof _r.onPostCommitFiberRoot=="function")try{_r.onPostCommitFiberRoot($m,e)}catch{}r=!0}return r}finally{At=s,En.transition=t}}return!1}function k0(e,t,s){t=Tl(s,t),t=G_(e,t,1),e=Ha(e,t,1),t=zs(),e!==null&&(Qd(e,1,t),Js(e,t))}function Qt(e,t,s){if(e.tag===3)k0(e,e,s);else for(;t!==null;){if(t.tag===3){k0(t,e,s);break}else if(t.tag===1){var r=t.stateNode;if(typeof t.type.getDerivedStateFromError=="function"||typeof r.componentDidCatch=="function"&&(Wa===null||!Wa.has(r))){e=Tl(s,e),e=Y_(t,e,1),t=Ha(t,e,1),e=zs(),t!==null&&(Qd(t,1,e),Js(t,e));break}}t=t.return}}function dR(e,t,s){var r=e.pingCache;r!==null&&r.delete(t),t=zs(),e.pingedLanes|=e.suspendedLanes&s,gs===e&&(ks&s)===s&&(hs===4||hs===3&&(ks&130023424)===ks&&500>ts()-Bv?Vi(e,0):Uv|=s),Js(e,t)}function pk(e,t){t===0&&(e.mode&1?(t=$u,$u<<=1,!($u&130023424)&&($u=4194304)):t=1);var s=zs();e=Qr(e,t),e!==null&&(Qd(e,t,s),Js(e,s))}function uR(e){var t=e.memoizedState,s=0;t!==null&&(s=t.retryLane),pk(e,s)}function hR(e,t){var s=0;switch(e.tag){case 13:var r=e.stateNode,a=e.memoizedState;a!==null&&(s=a.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(be(314))}r!==null&&r.delete(t),pk(e,s)}var fk;fk=function(e,t,s){if(e!==null)if(e.memoizedProps!==t.pendingProps||Ks.current)Ys=!0;else{if(!(e.lanes&s)&&!(t.flags&128))return Ys=!1,XA(e,t,s);Ys=!!(e.flags&131072)}else Ys=!1,Mt&&t.flags&1048576&&y_(t,Bh,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;yh(e,t),e=t.pendingProps;var a=kl(t,$s.current);nl(t,s),a=Iv(null,t,r,e,a,s);var i=Ov();return t.flags|=1,typeof a=="object"&&a!==null&&typeof a.render=="function"&&a.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,Qs(r)?(i=!0,Fh(t)):i=!1,t.memoizedState=a.state!==null&&a.state!==void 0?a.state:null,Ev(t),a.updater=Fm,t.stateNode=a,a._reactInternals=t,Ig(t,r,e,s),t=Mg(null,t,r,!0,i,s)):(t.tag=0,Mt&&i&&_v(t),Ms(null,t,a,s),t=t.child),t;case 16:r=t.elementType;e:{switch(yh(e,t),e=t.pendingProps,a=r._init,r=a(r._payload),t.type=r,a=t.tag=pR(r),e=
vendor: 4,150 bytes, line 25
25Bn(r,e),a){case 0:t=Dg(null,t,r,e,s);break e;case 1:t=p0(null,t,r,e,s);break e;case 11:t=h0(null,t,r,e,s);break e;case 14:t=m0(null,t,r,Bn(r.type,e),s);break e}throw Error(be(306,r,""))}return t;case 0:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:Bn(r,a),Dg(e,t,r,a,s);case 1:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:Bn(r,a),p0(e,t,r,a,s);case 3:e:{if(Z_(t),e===null)throw Error(be(387));r=t.pendingProps,i=t.memoizedState,a=i.element,N_(e,t),Hh(t,r,null,s);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){a=Tl(Error(be(423)),t),t=f0(e,t,r,s,a);break e}else if(r!==a){a=Tl(Error(be(424)),t),t=f0(e,t,r,s,a);break e}else for(dn=qa(t.stateNode.containerInfo.firstChild),mn=t,Mt=!0,Gn=null,s=__(t,null,r,s),t.child=s;s;)s.flags=s.flags&-3|4096,s=s.sibling;else{if(Nl(),r===a){t=Jr(e,t,s);break e}Ms(e,t,r,s)}t=t.child}return t;case 5:return S_(t),e===null&&Rg(t),r=t.type,a=t.pendingProps,i=e!==null?e.memoizedProps:null,o=a.children,Cg(r,a)?o=null:i!==null&&Cg(r,i)&&(t.flags|=32),J_(e,t),Ms(e,t,o,s),t.child;case 6:return e===null&&Rg(t),null;case 13:return X_(e,t,s);case 4:return Av(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=Sl(t,null,r,s):Ms(e,t,r,s),t.child;case 11:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:Bn(r,a),h0(e,t,r,a,s);case 7:return Ms(e,t,t.pendingProps,s),t.child;case 8:return Ms(e,t,t.pendingProps.children,s),t.child;case 12:return Ms(e,t,t.pendingProps.children,s),t.child;case 10:e:{if(r=t.type._context,a=t.pendingProps,i=t.memoizedProps,o=a.value,$t(Vh,r._currentValue),r._currentValue=o,i!==null)if(Jn(i.value,o)){if(i.children===a.children&&!Ks.current){t=Jr(e,t,s);break e}}else for(i=t.child,i!==null&&(i.return=t);i!==null;){var l=i.dependencies;if(l!==null){o=i.child;for(var c=l.firstContext;c!==null;){if(c.context===r){if(i.tag===1){c=Wr(-1,s&-s),c.tag=2;var d=i.updateQueue;if(d!==null){d=d.shared;var u=d.pending;u===null?c.next=c:(c.next=u.next,u.next=c),d.pending=c}}i.lanes|=s,c=i.alternate,c!==null&&(c.lanes|=s),$g(i.return,s,t),l.lanes|=s;break}c=c.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(be(341));o.lanes|=s,l=o.alternate,l!==null&&(l.lanes|=s),$g(o,s,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}Ms(e,t,a.children,s),t=t.child}return t;case 9:return a=t.type,r=t.pendingProps.children,nl(t,s),a=Rn(a),r=r(a),t.flags|=1,Ms(e,t,r,s),t.child;case 14:return r=t.type,a=Bn(r,t.pendingProps),a=Bn(r.type,a),m0(e,t,r,a,s);case 15:return K_(e,t,t.type,t.pendingProps,s);case 17:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:Bn(r,a),yh(e,t),t.tag=1,Qs(r)?(e=!0,Fh(t)):e=!1,nl(t,s),W_(t,r,a),Ig(t,r,a,s),Mg(null,t,r,!0,e,s);case 19:return ek(e,t,s);case 22:return Q_(e,t,s)}throw Error(be(156,t.tag))};function gk(e,t){return Vj(e,t)}function mR(e,t,s,r){this.tag=e,this.key=s,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 Pn(e,t,s,r){return new mR(e,t,s,r)}function Wv(e){return e=e.prototype,!(!e||!e.isReactComponent)}function pR(e){if(typeof e=="function")return Wv(e)?1:0;if(e!=null){if(e=e.$$typeof,e===uv)return 11;if(e===hv)return 14}return 2}function Ya(e,t){var s=e.alternate;return s===null?(s=Pn(e.tag,t,e.key,e.mode),s.elementType=e.elementType,s.type=e.type,s.stateNode=e.stateNode,s.alternate=e,e.alternate=s):(s.pendingProps=t,s.type=e.type,s.flags=0,s.subtreeFlags=0,s.deletions=null),s.flags=e.flags&14680064,s.childLanes=e.childLanes,s.lanes=e.lanes,s.child=e.child,s.memoizedProps=e.memoizedProps,s.memoizedState=e.memoizedState,s.updateQueue=e.updateQueue,t=e.depen
vendor: 9,115 bytes, line 25
25dencies,s.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},s.sibling=e.sibling,s.index=e.index,s.ref=e.ref,s}function jh(e,t,s,r,a,i){var o=2;if(r=e,typeof e=="function")Wv(e)&&(o=1);else if(typeof e=="string")o=5;else e:switch(e){case zo:return qi(s.children,a,i,t);case dv:o=8,a|=8;break;case ag:return e=Pn(12,s,t,a|2),e.elementType=ag,e.lanes=i,e;case ig:return e=Pn(13,s,t,a),e.elementType=ig,e.lanes=i,e;case og:return e=Pn(19,s,t,a),e.elementType=og,e.lanes=i,e;case Sj:return Vm(s,a,i,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case kj:o=10;break e;case Nj:o=9;break e;case uv:o=11;break e;case hv:o=14;break e;case ba:o=16,r=null;break e}throw Error(be(130,e==null?e:typeof e,""))}return t=Pn(o,s,t,a),t.elementType=e,t.type=r,t.lanes=i,t}function qi(e,t,s,r){return e=Pn(7,e,r,t),e.lanes=s,e}function Vm(e,t,s,r){return e=Pn(22,e,r,t),e.elementType=Sj,e.lanes=s,e.stateNode={isHidden:!1},e}function mf(e,t,s){return e=Pn(6,e,null,t),e.lanes=s,e}function pf(e,t,s){return t=Pn(4,e.children!==null?e.children:[],e.key,t),t.lanes=s,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function fR(e,t,s,r,a){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Gp(0),this.expirationTimes=Gp(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Gp(0),this.identifierPrefix=r,this.onRecoverableError=a,this.mutableSourceEagerHydrationData=null}function Gv(e,t,s,r,a,i,o,l,c){return e=new fR(e,t,s,l,c),t===1?(t=1,i===!0&&(t|=8)):t=0,i=Pn(3,null,null,t),e.current=i,i.stateNode=e,i.memoizedState={element:r,isDehydrated:s,cache:null,transitions:null,pendingSuspenseBoundaries:null},Ev(i),e}function gR(e,t,s){var r=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:Mo,key:r==null?null:""+r,children:e,containerInfo:t,implementation:s}}function xk(e){if(!e)return si;e=e._reactInternals;e:{if(oo(e)!==e||e.tag!==1)throw Error(be(170));var t=e;do{switch(t.tag){case 3:t=t.stateNode.context;break e;case 1:if(Qs(t.type)){t=t.stateNode.__reactInternalMemoizedMergedChildContext;break e}}t=t.return}while(t!==null);throw Error(be(171))}if(e.tag===1){var s=e.type;if(Qs(s))return x_(e,s,t)}return t}function vk(e,t,s,r,a,i,o,l,c){return e=Gv(s,r,!0,e,a,i,o,l,c),e.context=xk(null),s=e.current,r=zs(),a=Ga(s),i=Wr(r,a),i.callback=t??null,Ha(s,i,a),e.current.lanes=a,Qd(e,a,r),Js(e,r),e}function qm(e,t,s,r){var a=t.current,i=zs(),o=Ga(a);return s=xk(s),t.context===null?t.context=s:t.pendingContext=s,t=Wr(i,o),t.payload={element:e},r=r===void 0?null:r,r!==null&&(t.callback=r),e=Ha(a,t,o),e!==null&&(Kn(e,a,o,i),gh(e,a,o)),o}function Xh(e){if(e=e.current,!e.child)return null;switch(e.child.tag){case 5:return e.child.stateNode;default:return e.child.stateNode}}function N0(e,t){if(e=e.memoizedState,e!==null&&e.dehydrated!==null){var s=e.retryLane;e.retryLane=s!==0&&s<t?s:t}}function Yv(e,t){N0(e,t),(e=e.alternate)&&N0(e,t)}function xR(){return null}var yk=typeof reportError=="function"?reportError:function(e){console.error(e)};function Kv(e){this._internalRoot=e}Hm.prototype.render=Kv.prototype.render=function(e){var t=this._internalRoot;if(t===null)throw Error(be(409));qm(e,t,null,null)};Hm.prototype.unmount=Kv.prototype.unmount=function(){var e=this._internalRoot;if(e!==null){this._internalRoot=null;var t=e.containerInfo;Qi(function(){qm(null,e,null,null)}),t[Kr]=null}};function Hm(e){this._internalRoot=e}Hm.prototype.unstable_scheduleHydration=function(e){if(e){var t=Qj();e={blockedOn:null,target:e,priority:t};for(var s=0;s<_a.length&&t!==0&&t<_a[s].priority;s++);_a.splice(s,0,e),s===0&&Zj(e)}};function Qv(e){return!(!e||e.nodeType!==1&&e.nodeType!==9&&e.nodeType!==11)}function Wm(e){return!(!e||e.nodeType!==1&&e.nodeType!==9&&e.nodeType!==11&&(e.nodeType!==8||e.nodeValue!==" react-mount-point-unstable "))}function S0(){}function vR(e,t,s,r,a){if(a){if(typeof r=="function"){var i=r;r=function(){var d=Xh(o);i.call(d)}}var o=vk(t,r,e,0,null,!1,!1,"",S0);return e._reactRootContainer=o,e[Kr]=o.current,od(e.nodeType===8?e.parentNode:e),Qi(),o}for(;a=e.lastChild;)e.removeChild(a);if(typeof r=="function"){var l=r;r=function(){var d=Xh(c);l.call(d)}}var c=Gv(e,0,!1,null,null,!1,!1,"",S0);return e._reactRootContainer=c,e[Kr]=c.current,od(e.nodeType===8?e.parentNode:e),Qi(function(){qm(t,c,s,r)}),c}function Gm(e,t,s,r,a){var i=s._reactRootContainer;if(i){var o=i;if(typeof a=="function"){var l=a;a=function(){var c=Xh(o);l.call(c)}}qm(t,o,e,a)}else o=vR(s,t,e,a,r);return Xh(o)}Yj=function(e){switch(e.tag){case 3:var t=e.stateNode;if(t.current.memoizedState.isDehydrated){var s=Cc(t.pendingLanes);s!==0&&(fv(t,s|1),Js(t,ts()),!(Nt&6)&&(Pl=ts()+500,pi()))}break;case 13:Qi(function(){var r=Qr(e,1);if(r!==null){var a=zs();Kn(r,e,1,a)}}),Yv(e,1)}};gv=function(e){if(e.tag===13){var t=Qr(e,134217728);if(t!==null){var s=zs();Kn(t,e,134217728,s)}Yv(e,134217728)}};Kj=function(e){if(e.tag===13){var t=Ga(e),s=Qr(e,t);if(s!==null){var r=zs();Kn(s,e,t,r)}Yv(e,t)}};Qj=function(){return At};Jj=function(e,t){var s=At;try{return At=e,t()}finally{At=s}};xg=function(e,t,s){switch(t){case"input":if(dg(e,s),t=s.name,s.type==="radio"&&t!=null){for(s=e;s.parentNode;)s=s.parentNode;for(s=s.querySelectorAll("input[name="+JSON.stringify(""+t)+'][type="radio"]'),t=0;t<s.length;t++){var r=s[t];if(r!==e&&r.form===e.form){var a=Dm(r);if(!a)throw Error(be(90));Tj(r),dg(r,a)}}}break;case"textarea":Ej(e,s);break;case"select":t=s.value,t!=null&&Xo(e,!!s.multiple,t,!1)}};Dj=Vv;Mj=Qi;var yR={usingClientEntryPoint:!1,Events:[Zd,Vo,Dm,Ij,Oj,Vv]},vc={findFiberByHostInstance:Pi,bundleType:0,version:"18.3.1",rendererPackageName:"react-dom"},bR={bundleType:vc.bundleType,version:vc.version,rendererPackageName:vc.rendererPackageName,rendererConfig:vc.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:sa.ReactCurrentDispatcher,findHostInstanceByFiber:function(e){return e=Uj(e),e===null?null:e.stateNode},findFiberByHostInstance:vc.findFiberByHostInstance||xR,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.3.1-next-f1338f8080-20240426"};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"){var qu=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!qu.isDisabled&&qu.supportsFiber)try{$m=qu.inject(bR),_r=qu}catch{}}jn.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=yR;jn.createPortal=function(e,t){var s=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!Qv(t))throw Error(be(200));return gR(e,t,null,s)};jn.createRoot=function(e,t){if(!Qv(e))throw Error(be(299));var s=!1,r="",a=yk;return t!=null&&(t.unstable_strictMode===!0&&(s=!0),t.identifierPrefix!==void 0&&(r=t.identifierPrefix),t.onRecoverableError!==void 0&&(a=t.onRecoverableError)),t=Gv(e,1,!1,null,null,s,!1,r,a),e[Kr]=t.current,od(e.nodeType===8?e.parentNode:e),new Kv(t)};jn.findDOMNode=function(e){if(e==null)return null;if(e.nodeType===1)return e;var t=e._reactInternals;if(t===void 0)throw typeof e.render=="function"?Error(be(188)):(e=Object.keys(e).join(","),Error(be(268,e)));return e=Uj(t),e=e===null?null:e.stateNode,e};jn.flushSync=function(e){return Qi(e)};jn.hydrate=function(e,t,s){if(!Wm(t))throw Error(be(200));return Gm(null,e,t,!0,s)};jn.hydrateRoot=function(e,t,s){if(!Qv(e))throw Error(be(405));var r=s!=null&&s.hydratedSources||null,a=!1,i="",o=yk;if(s!=null&&(s.unstable_strictMode===!0&&(a=!0),s.identifierPrefix!==void 0&&(i=s.identifierPrefix),s.onRecoverableError!==void 0&&(o=s.onRecoverableError)),t=vk(t,null,e,1,s??null,a,!1,i,o),e[Kr]=t.current,od(e),r)for(e=0;e<r.length;e++)s=r[e],a=s._getVersion,a=a(s._source),t.mutableSourceEagerHydrationData==null?t.mutableSourceEagerHydrationData=[s,a]:t.mutableSourceEagerHydrationData.push(s,a);return new Hm(t)};jn.render=function(e,t,s){if(!Wm(t))throw Error(be(200));return Gm(null,e,t,!1,s)};jn.unmountComponentAtNode=function(e){if(!Wm(e))throw Error(be(40));return e._reactRootContainer?(Qi(function(){Gm(null,null,e,!1,function(){e._reactRootContainer=null,e[Kr]=null})}),!0):!1};jn.unstable_batchedUpdates=Vv;jn.unstable_renderSubtreeIntoContainer=function(e,t,s,r){if(!Wm(s))throw Error(be(200));if(e==null||e._reactInternals===void 0)throw Error(be(38));return Gm(e,t,s,!1,r)};jn.version="18.3.1-next-f1338f8080-20240426";function bk(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(bk)}catch(e){console.error(e)}}bk(),bj.exports=jn;var Jl=bj.exports;const wk=gE(Jl);var jk,C0=Jl;jk=C0.createRoot,C0.hydrateRoot;const wR="modulepreload",jR=function(e){return"/"+e},T0={}
25,tn=function(t,s,r){let a=Promise.resolve();if(s&&s.length>0){document.getElementsByTagName("link");const o=document.querySelector("meta[property=csp-nonce]"),l=(o==null?void 0:o.nonce)||(o==null?void 0:o.getAttribute("nonce"));a=Promise.allSettled(s.map(c=>{if(c=jR(c),c in T0)return;T0[c]=!0;const d=c.endsWith(".css"),u=d?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${c}"]${u}`))return;const m=document.createElement("link");if(m.rel=d?"stylesheet":wR,d||(m.as="script"),m.crossOrigin="",m.href=c,l&&m.setAttribute("nonce",l),document.head.appendChild(m),d)return new Promise((p,f)=>{m.addEventListener("load",p),m.addEventListener("error",()=>f(new Error(`Unable to preload CSS for ${c}`)))})}))}function i(o){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=o,window.dispatchEvent(l),!l.defaultPrevented)throw o}return a.then(o=>{for(const l of o||[])l.status==="rejected"&&i(l.reason);return t().catch(i)})};var eu=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},Ji=typeof window>"u"||"Deno"in globalThis;function Ws(){}function _R(e,t){return typeof e=="function"?e(t):e}function Qg(e){return typeof e=="number"&&e>=0&&e!==1/0}function _k(e,t){return Math.max(e+(t||0)-Date.now(),0)}function Ka(e,t){return typeof e=="function"?e(t):e}function Sn(e,t){return typeof e=="function"?e(t):e}function P0(e,t){const{type:s="all",exact:r,fetchStatus:a,predicate:i,queryKey:o,stale:l}=e;if(o){if(r){if(t.queryHash!==Jv(o,t.options))return!1}else if(!xd(t.queryKey,o))return!1}if(s!=="all"){const c=t.isActive();if(s==="active"&&!c||s==="inactive"&&c)return!1}return!(typeof l=="boolean"&&t.isStale()!==l||a&&a!==t.state.fetchStatus||i&&!i(t))}function E0(e,t){const{exact:s,status:r,predicate:a,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(s){if(gd(t.options.mutationKey)!==gd(i))return!1}else if(!xd(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||a&&!a(t))}function Jv(e,t){return((t==null?void 0:t.queryKeyHashFn)||gd)(e)}function gd(e){return JSON.stringify(e,(t,s)=>Zg(s)?Object.keys(s).sort().reduce((r,a)=>(r[a]=s[a],r),{}):s)}function xd(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(s=>xd(e[s],t[s])):!1}function kk(e,t){if(e===t)return e;const s=A0(e)&&A0(t);if(s||Zg(e)&&Zg(t)){const r=s?e:Object.keys(e),a=r.length,i=s?t:Object.keys(t),o=i.length,l=s?[]:{},c=new Set(r);let d=0;for(let u=0;u<o;u++){const m=s?u:i[u];(!s&&c.has(m)||s)&&e[m]===void 0&&t[m]===void 0?(l[m]=void 0,d++):(l[m]=kk(e[m],t[m]),l[m]===e[m]&&e[m]!==void 0&&d++)}return a===o&&d===a?e:l}return t}function Jg(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(const s in e)if(e[s]!==t[s])return!1;return!0}function A0(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Zg(e){if(!R0(e))return!1;const t=e.constructor;if(t===void 0)return!0;const s=t.prototype;return!(!R0(s)||!s.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function R0(e){return Object.prototype.toString.call(e)==="[object Object]"}function kR(e){return new Promise(t=>{setTimeout(t,e)})}function Xg(e,t,s){return typeof s.structuralSharing=="function"?s.structuralSharing(e,t):s.structuralSharing!==!1?kk(e,t):t}function NR(e){return e}function SR(e,t,s=0){const r=[...e,t];return s&&r.length>s?r.slice(1):r}function CR(e,t,s=0){const r=[t,...e];return s&&r.length>s?r.slice(0,-1):r}var Zv=Symbol();function Nk(e,t){return!e.queryFn&&(t!=null&&t.initialPromise)?()=>t.initialPromise:!e.queryFn||e.queryFn===Zv?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function TR(e,t){return typeof e=="function"?e(...t):!!e}var Li,Ca,ul,uj,PR=(uj=class extends eu{constructor(){super();Xe(this,Li);Xe(this,Ca);Xe(this,ul);ze(this,ul,t=>{if(!Ji&&window.addEventListener){const s=()=>t();return window.addEventListener("visibilitychange",s,!1),()=>{window.removeEventListener("visibilitychange",s)}}})}onSubscribe(){q(this,Ca)||this.setEventListener(q(this,ul))}onUnsubscribe(){var t;this.hasListeners()||((t=q(this,Ca))==null||t.call(this),ze(this,Ca,void 0))}setEventListener(t){var s;ze(this,ul,t),(s=q(this,Ca))==null||s.call(this),ze(this,Ca,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){q(this,Li)!==t&&(ze(this,Li,t),this.onFocus())}onFocus(){const t=this.isFocused();
vendor: 4,924 bytes, line 25
25this.listeners.forEach(s=>{s(t)})}isFocused(){var t;return typeof q(this,Li)=="boolean"?q(this,Li):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},Li=new WeakMap,Ca=new WeakMap,ul=new WeakMap,uj),Xv=new PR,hl,Ta,ml,hj,ER=(hj=class extends eu{constructor(){super();Xe(this,hl,!0);Xe(this,Ta);Xe(this,ml);ze(this,ml,t=>{if(!Ji&&window.addEventListener){const s=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",s,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",s),window.removeEventListener("offline",r)}}})}onSubscribe(){q(this,Ta)||this.setEventListener(q(this,ml))}onUnsubscribe(){var t;this.hasListeners()||((t=q(this,Ta))==null||t.call(this),ze(this,Ta,void 0))}setEventListener(t){var s;ze(this,ml,t),(s=q(this,Ta))==null||s.call(this),ze(this,Ta,t(this.setOnline.bind(this)))}setOnline(t){q(this,hl)!==t&&(ze(this,hl,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return q(this,hl)}},hl=new WeakMap,Ta=new WeakMap,ml=new WeakMap,hj),em=new ER;function ex(){let e,t;const s=new Promise((a,i)=>{e=a,t=i});s.status="pending",s.catch(()=>{});function r(a){Object.assign(s,a),delete s.resolve,delete s.reject}return s.resolve=a=>{r({status:"fulfilled",value:a}),e(a)},s.reject=a=>{r({status:"rejected",reason:a}),t(a)},s}function AR(e){return Math.min(1e3*2**e,3e4)}function Sk(e){return(e??"online")==="online"?em.isOnline():!0}var Ck=class extends Error{constructor(e){super("CancelledError"),this.revert=e==null?void 0:e.revert,this.silent=e==null?void 0:e.silent}};function ff(e){return e instanceof Ck}function Tk(e){let t=!1,s=0,r=!1,a;const i=ex(),o=x=>{var b;r||(p(new Ck(x)),(b=e.abort)==null||b.call(e))},l=()=>{t=!0},c=()=>{t=!1},d=()=>Xv.isFocused()&&(e.networkMode==="always"||em.isOnline())&&e.canRun(),u=()=>Sk(e.networkMode)&&e.canRun(),m=x=>{var b;r||(r=!0,(b=e.onSuccess)==null||b.call(e,x),a==null||a(),i.resolve(x))},p=x=>{var b;r||(r=!0,(b=e.onError)==null||b.call(e,x),a==null||a(),i.reject(x))},f=()=>new Promise(x=>{var b;a=v=>{(r||d())&&x(v)},(b=e.onPause)==null||b.call(e)}).then(()=>{var x;a=void 0,r||(x=e.onContinue)==null||x.call(e)}),g=()=>{if(r)return;let x;const b=s===0?e.initialPromise:void 0;try{x=b??e.fn()}catch(v){x=Promise.reject(v)}Promise.resolve(x).then(m).catch(v=>{var N;if(r)return;const y=e.retry??(Ji?0:3),w=e.retryDelay??AR,j=typeof w=="function"?w(s,v):w,_=y===!0||typeof y=="number"&&s<y||typeof y=="function"&&y(s,v);if(t||!_){p(v);return}s++,(N=e.onFail)==null||N.call(e,s,v),kR(j).then(()=>d()?void 0:f()).then(()=>{t?p(v):g()})})};return{promise:i,cancel:o,continue:()=>(a==null||a(),i),cancelRetry:l,continueRetry:c,canStart:u,start:()=>(u()?g():f().then(g),i)}}var RR=e=>setTimeout(e,0);function $R(){let e=[],t=0,s=l=>{l()},r=l=>{l()},a=RR;const i=l=>{t?e.push(l):a(()=>{s(l)})},o=()=>{const l=e;e=[],l.length&&a(()=>{r(()=>{l.forEach(c=>{s(c)})})})};return{batch:l=>{let c;t++;try{c=l()}finally{t--,t||o()}return c},batchCalls:l=>(...c)=>{i(()=>{l(...c)})},schedule:i,setNotifyFunction:l=>{s=l},setBatchNotifyFunction:l=>{r=l},setScheduler:l=>{a=l}}}var _s=$R(),Ii,mj,Pk=(mj=class{constructor(){Xe(this,Ii)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Qg(this.gcTime)&&ze(this,Ii,setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Ji?1/0:5*60*1e3))}clearGcTimeout(){q(this,Ii)&&(clearTimeout(q(this,Ii)),ze(this,Ii,void 0))}},Ii=new WeakMap,mj),pl,Oi,Nn,Di,Es,Wd,Mi,qn,Dr,pj,LR=(pj=class extends Pk{constructor(t){super();Xe(this,qn);Xe(this,pl);Xe(this,Oi);Xe(this,Nn);Xe(this,Di);Xe(this,Es);Xe(this,Wd);Xe(this,Mi);ze(this,Mi,!1),ze(this,Wd,t.defaultOptions),this.setOptions(t.options),this.observers=[],ze(this,Di,t.client),ze(this,Nn,q(this,Di).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,ze(this,pl,IR(this.options)),this.state=t.state??q(this,pl),this.scheduleGc()}get meta(){return this.options.meta}get promise(){var t;return(t=q(this,Es))==null?void 0:t.promise}setOptions(t){this.options={...q(this,Wd),...t},this.updateGcTime(this.options.gcTime)}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&q(this,Nn).remove(this)}setData(t,s){const r=Xg(this.state.data,t,this.options);return jt(this,qn,Dr).call(this,{data:r,type:"success",dataUpdatedAt:s==null?void 0:s.updatedAt,manual:s==null?void 0:s.manual}),r}setState(t,s){jt(this,qn,Dr).call(this,{type:"setState",state:t,setStateOptions:s})}cancel(t){var r,a;const s=(r=q(this,Es))==null?void 0:r.promise;return(a=q(this,Es))==null||a.cancel(t),s?s.then(Ws).catch(Ws):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(q(this,pl))}isActive(){return this.observers.some(t=>Sn(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Zv||this.state.dataUpdateCount+this.state.errorUpdate
25Count===0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>Ka(t.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(t=>t.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(t=0){return this.state.data===void 0?!0:t==="static"?!1:this.state.isInvalidated?!0:!_k(this.state.dataUpdatedAt,t)}onFocus(){var s;const t=this.observers.find(r=>r.shouldFetchOnWindowFocus());t==null||t.refetch({cancelRefetch:!1}),(s=q(this,Es))==null||s.continue()}onOnline(){var s;const t=this.observers.find(r=>r.shouldFetchOnReconnect());t==null||t.refetch({cancelRefetch:!1}),(s=q(this,Es))==null||s.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),q(this,Nn).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(s=>s!==t),this.observers.length||(q(this,Es)&&(q(this,Mi)?q(this,Es).cancel({revert:!0}):q(this,Es).cancelRetry()),this.scheduleGc()),q(this,Nn).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||jt(this,qn,Dr).call(this,{type:"invalidate"})}fetch(t,s){var d,u,m;if(this.state.fetchStatus!=="idle"){if(this.state.data!==void 0&&(s!=null&&s.cancelRefetch))this.cancel({silent:!0});else if(q(this,Es))return q(this,Es).continueRetry(),q(this,Es).promise}if(t&&this.setOptions(t),!this.options.queryFn){const p=this.observers.find(f=>f.options.queryFn);p&&this.setOptions(p.options)}const r=new AbortController,a=p=>{Object.defineProperty(p,"signal",{enumerable:!0,get:()=>(ze(this,Mi,!0),r.signal)})},i=()=>{const p=Nk(this.options,s),g=(()=>{const x={client:q(this,Di),queryKey:this.queryKey,meta:this.meta};return a(x),x})();return ze(this,Mi,!1),this.options.persister?this.options.persister(p,g,this):p(g)},l=(()=>{const p={fetchOptions:s,options:this.options,queryKey:this.queryKey,client:q(this,Di),state:this.state,fetchFn:i};return a(p),p})();(d=this.options.behavior)==null||d.onFetch(l,this),ze(this,Oi,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((u=l.fetchOptions)==null?void 0:u.meta))&&jt(this,qn,Dr).call(this,{type:"fetch",meta:(m=l.fetchOptions)==null?void 0:m.meta});const c=p=>{var f,g,x,b;ff(p)&&p.silent||jt(this,qn,Dr).call(this,{type:"error",error:p}),ff(p)||((g=(f=q(this,Nn).config).onError)==null||g.call(f,p,this),(b=(x=q(this,Nn).config).onSettled)==null||b.call(x,this.state.data,p,this)),this.scheduleGc()};return ze(this,Es,Tk({initialPromise:s==null?void 0:s.initialPromise,fn:l.fetchFn,abort:r.abort.bind(r),onSuccess:p=>{var f,g,x,b;if(p===void 0){c(new Error(`${this.queryHash} data is undefined`));return}try{this.setData(p)}catch(v){c(v);return}(g=(f=q(this,Nn).config).onSuccess)==null||g.call(f,p,this),(b=(x=q(this,Nn).config).onSettled)==null||b.call(x,p,this.state.error,this),this.scheduleGc()},onError:c,onFail:(p,f)=>{jt(this,qn,Dr).call(this,{type:"failed",failureCount:p,error:f})},onPause:()=>{jt(this,qn,Dr).call(this,{type:"pause"})},onContinue:()=>{jt(this,qn,Dr).call(this,{type:"continue"})},retry:l.options.retry,retryDelay:l.options.retryDelay,networkMode:l.options.networkMode,canRun:()=>!0})),q(this,Es).start()}},pl=new WeakMap,Oi=new WeakMap,Nn=new WeakMap,Di=new WeakMap,Es=new WeakMap,Wd=new WeakMap,Mi=new WeakMap,qn=new WeakSet,Dr=function(t){const s=r=>{switch(t.type){case"failed":return{...r,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,...Ek(r.data,this.options),fetchMeta:t.meta??null};case"success":return ze(this,Oi,void 0),{...r,data:t.data,dataUpdateCount:r.dataUpdateCount+1,dataUpdatedAt:t.dataUpdatedAt??Date.now(),error:null,isInvalidated:!1,status:"success",...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};case"error":const a=t.error;return ff(a)&&a.revert&&q(this,Oi)?{...q(this,Oi),fetchStatus:"idle"}
vendor: 22,112 bytes, line 25
25:{...r,error:a,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:a,fetchStatus:"idle",status:"error"};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}};this.state=s(this.state),_s.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),q(this,Nn).notify({query:this,type:"updated",action:t})})},pj);function Ek(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Sk(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function IR(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,s=t!==void 0,r=s?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:s?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:s?"success":"pending",fetchStatus:"idle"}}var mr,fj,OR=(fj=class extends eu{constructor(t={}){super();Xe(this,mr);this.config=t,ze(this,mr,new Map)}build(t,s,r){const a=s.queryKey,i=s.queryHash??Jv(a,s);let o=this.get(i);return o||(o=new LR({client:t,queryKey:a,queryHash:i,options:t.defaultQueryOptions(s),state:r,defaultOptions:t.getQueryDefaults(a)}),this.add(o)),o}add(t){q(this,mr).has(t.queryHash)||(q(this,mr).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const s=q(this,mr).get(t.queryHash);s&&(t.destroy(),s===t&&q(this,mr).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){_s.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return q(this,mr).get(t)}getAll(){return[...q(this,mr).values()]}find(t){const s={exact:!0,...t};return this.getAll().find(r=>P0(s,r))}findAll(t={}){const s=this.getAll();return Object.keys(t).length>0?s.filter(r=>P0(t,r)):s}notify(t){_s.batch(()=>{this.listeners.forEach(s=>{s(t)})})}onFocus(){_s.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){_s.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},mr=new WeakMap,fj),pr,Os,zi,fr,va,gj,DR=(gj=class extends Pk{constructor(t){super();Xe(this,fr);Xe(this,pr);Xe(this,Os);Xe(this,zi);this.mutationId=t.mutationId,ze(this,Os,t.mutationCache),ze(this,pr,[]),this.state=t.state||MR(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){q(this,pr).includes(t)||(q(this,pr).push(t),this.clearGcTimeout(),q(this,Os).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){ze(this,pr,q(this,pr).filter(s=>s!==t)),this.scheduleGc(),q(this,Os).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){q(this,pr).length||(this.state.status==="pending"?this.scheduleGc():q(this,Os).remove(this))}continue(){var t;return((t=q(this,zi))==null?void 0:t.continue())??this.execute(this.state.variables)}async execute(t){var i,o,l,c,d,u,m,p,f,g,x,b,v,y,w,j,_,N,k,S;const s=()=>{jt(this,fr,va).call(this,{type:"continue"})};ze(this,zi,Tk({fn:()=>this.options.mutationFn?this.options.mutationFn(t):Promise.reject(new Error("No mutationFn found")),onFail:(T,C)=>{jt(this,fr,va).call(this,{type:"failed",failureCount:T,error:C})},onPause:()=>{jt(this,fr,va).call(this,{type:"pause"})},onContinue:s,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>q(this,Os).canRun(this)}));const r=this.state.status==="pending",a=!q(this,zi).canStart();try{if(r)s();else{jt(this,fr,va).call(this,{type:"pending",variables:t,isPaused:a}),await((o=(i=q(this,Os).config).onMutate)==null?void 0:o.call(i,t,this));const C=await((c=(l=this.options).onMutate)==null?void 0:c.call(l,t));C!==this.state.context&&jt(this,fr,va).call(this,{type:"pending",context:C,variables:t,isPaused:a})}const T=await q(this,zi).start();return await((u=(d=q(this,Os).config).onSuccess)==null?void 0:u.call(d,T,t,this.state.context,this)),await((p=(m=this.options).onSuccess)==null?void 0:p.call(m,T,t,this.state.context)),await((g=(f=q(this,Os).config).onSettled)==null?void 0:g.call(f,T,null,this.state.variables,this.state.context,this)),await((b=(x=this.options).onSettled)==null?void 0:b.call(x,T,null,t,this.state.context)),jt(this,fr,va).call(this,{type:"success",data:T}),T}catch(T){try{throw await((y=(v=q(this,Os).config).onError)==null?void 0:y.call(v,T,t,this.state.context,this)),await((j=(w=this.options).onError)==null?void 0:j.call(w,T,t,this.state.context)),await((N=(_=q(this,Os).config).onSettled)==null?void 0:N.call(_,void 0,T,this.state.variables,this.state.context,this)),await((S=(k=this.options).onSettled)==null?void 0:S.call(k,void 0,T,t,this.state.context)),T}finally{jt(this,fr,va).call(this,{type:"error",error:T})}}finally{q(this,Os).runNext(this)}}},pr=new WeakMap,Os=new WeakMap,zi=new WeakMap,fr=new WeakSet,va=function(t){const s=r=>{switch(t.type){case"failed":return{...r,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:t.isPaused,status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...r,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:t.error,failureCount:r.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=s(this.state),_s.batch(()=>{q(this,pr).forEach(r=>{r.onMutationUpdate(t)}),q(this,Os).notify({mutation:this,type:"updated",action:t})})},gj);function MR(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Vr,Hn,Gd,xj,zR=(xj=class extends eu{constructor(t={}){super();Xe(this,Vr);Xe(this,Hn);Xe(this,Gd);this.config=t,ze(this,Vr,new Set),ze(this,Hn,new Map),ze(this,Gd,0)}build(t,s,r){const a=new DR({mutationCache:this,mutationId:++Tu(this,Gd)._,options:t.defaultMutationOptions(s),state:r});return this.add(a),a}add(t){q(this,Vr).add(t);const s=Hu(t);if(typeof s=="string"){const r=q(this,Hn).get(s);r?r.push(t):q(this,Hn).set(s,[t])}this.notify({type:"added",mutation:t})}remove(t){if(q(this,Vr).delete(t)){const s=Hu(t);if(typeof s=="string"){const r=q(this,Hn).get(s);if(r)if(r.length>1){const a=r.indexOf(t);a!==-1&&r.splice(a,1)}else r[0]===t&&q(this,Hn).delete(s)}}this.notify({type:"removed",mutation:t})}canRun(t){const s=Hu(t);if(typeof s=="string"){const r=q(this,Hn).get(s),a=r==null?void 0:r.find(i=>i.state.status==="pending");return!a||a===t}else return!0}runNext(t){var r;const s=Hu(t);if(typeof s=="string"){const a=(r=q(this,Hn).get(s))==null?void 0:r.find(i=>i!==t&&i.state.isPaused);return(a==null?void 0:a.continue())??Promise.resolve()}else return Promise.resolve()}clear(){_s.batch(()=>{q(this,Vr).forEach(t=>{this.notify({type:"removed",mutation:t})}),q(this,Vr).clear(),q(this,Hn).clear()})}getAll(){return Array.from(q(this,Vr))}find(t){const s={exact:!0,...t};return this.getAll().find(r=>E0(s,r))}findAll(t={}){return this.getAll().filter(s=>E0(t,s))}notify(t){_s.batch(()=>{this.listeners.forEach(s=>{s(t)})})}resumePausedMutations(){const t=this.getAll().filter(s=>s.state.isPaused);return _s.batch(()=>Promise.all(t.map(s=>s.continue().catch(Ws))))}},Vr=new WeakMap,Hn=new WeakMap,Gd=new WeakMap,xj);function Hu(e){var t;return(t=e.options.scope)==null?void 0:t.id}function $0(e){return{onFetch:(t,s)=>{var u,m,p,f,g;const r=t.options,a=(p=(m=(u=t.fetchOptions)==null?void 0:u.meta)==null?void 0:m.fetchMore)==null?void 0:p.direction,i=((f=t.state.data)==null?void 0:f.pages)||[],o=((g=t.state.data)==null?void 0:g.pageParams)||[];let l={pages:[],pageParams:[]},c=0;const d=async()=>{let x=!1;const b=w=>{Object.defineProperty(w,"signal",{enumerable:!0,get:()=>(t.signal.aborted?x=!0:t.signal.addEventListener("abort",()=>{x=!0}),t.signal)})},v=Nk(t.options,t.fetchOptions),y=async(w,j,_)=>{if(x)return Promise.reject();if(j==null&&w.pages.length)return Promise.resolve(w);const k=(()=>{const B={client:t.client,queryKey:t.queryKey,pageParam:j,direction:_?"backward":"forward",meta:t.options.meta};return b(B),B})(),S=await v(k),{maxPages:T}=t.options,C=_?CR:SR;return{pages:C(w.pages,S,T),pageParams:C(w.pageParams,j,T)}};if(a&&i.length){const w=a==="backward",j=w?FR:L0,_={pages:i,pageParams:o},N=j(r,_);l=await y(_,N,w)}else{const w=e??i.length;do{const j=c===0?o[0]??r.initialPageParam:L0(r,l);if(c>0&&j==null)break;l=await y(l,j),c++}while(c<w)}return l};t.options.persister?t.fetchFn=()=>{var x,b;return(b=(x=t.options).persister)==null?void 0:b.call(x,d,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},s)}:t.fetchFn=d}}}function L0(e,{pages:t,pageParams:s}){const r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,s[r],s):void 0}function FR(e,{pages:t,pageParams:s}){var r;return t.length>0?(r=e.getPreviousPageParam)==null?void 0:r.call(e,t[0],t,s[0],s):void 0}var Gt,Pa,Ea,fl,gl,Aa,xl,vl,vj,UR=(vj=class{constructor(e={}){Xe(this,Gt);Xe(this,Pa);Xe(this,Ea);Xe(this,fl);Xe(this,gl);Xe(this,Aa);Xe(this,xl);Xe(this,vl);ze(this,Gt,e.queryCache||new OR),ze(this,Pa,e.mutationCache||new zR),ze(this,Ea,e.defaultOptions||{}),ze(this,fl,new Map),ze(this,gl,new Map),ze(this,Aa,0)}mount(){Tu(this,Aa)._++,q(this,Aa)===1&&(ze(this,xl,Xv.subscribe(async e=>{e&&(await this.resumePausedMutations(),q(this,Gt).onFocus())})),ze(this,vl,em.subscribe(async e=>{e&&(await this.resumePausedMutations(),q(this,Gt).onOnline())})))}unmount(){var e,t;Tu(this,Aa)._--,q(this,Aa)===0&&((e=q(this,xl))==null||e.call(this),ze(this,xl,void 0),(t=q(this,vl))==null||t.call(this),ze(this,vl,void 0))}isFetching(e){return q(this,Gt).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return q(this,Pa).findAll({...e,status:"pending"}).length}getQueryData(e){var s;const t=this.defaultQueryOptions({queryKey:e});return(s=q(this,Gt).get(t.queryHash))==null?void 0:s.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),s=q(this,Gt).build(this,t),r=s.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&s.isStaleByTime(Ka(t.staleTime,s))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return q(this,Gt).findAll(e).map(({queryKey:t,state:s})=>{const r=s.data;return[t,r]})}setQueryData(e,t,s){const r=this.defaultQueryOptions({queryKey:e}),a=q(this,Gt).get(r.queryHash),i=a==null?void 0:a.state.data,o=_R(t,i);if(o!==void 0)return q(this,Gt).build(this,r).setData(o,{...s,manual:!0})}setQueriesData(e,t,s){return _s.batch(()=>q(this,Gt).findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,s)]))}getQueryState(e){var s;const t=this.defaultQueryOptions({queryKey:e});return(s=q(this,Gt).get(t.queryHash))==null?void 0:s.state}removeQueries(e){const t=q(this,Gt);_s.batch(()=>{t.findAll(e).forEach(s=>{t.remove(s)})})}resetQueries(e,t){const s=q(this,Gt);return _s.batch(()=>(s.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const s={revert:!0,...t},r=_s.batch(()=>q(this,Gt).findAll(e).map(a=>a.cancel(s)));return Promise.all(r).then(Ws).catch(Ws)}invalidateQueries(e,t={}){return _s.batch(()=>(q(this,Gt).findAll(e).forEach(s=>{s.invalidate()}),(e==null?void 0:e.refetchType)==="none"?Promise.resolve():this.refetchQueries({...e,type:(e==null?void 0:e.refetchType)??(e==null?void 0:e.type)??"active"},t)))}refetchQueries(e,t={}){const s={...t,cancelRefetch:t.cancelRefetch??!0},r=_s.batch(()=>q(this,Gt).findAll(e).filter(a=>!a.isDisabled()&&!a.isStatic()).map(a=>{let i=a.fetch(void 0,s);return s.throwOnError||(i=i.catch(Ws)),a.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(Ws)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const s=q(this,Gt).build(this,t);return s.isStaleByTime(Ka(t.staleTime,s))?s.fetch(t):Promise.resolve(s.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Ws).catch(Ws)}fetchInfiniteQuery(e){return e.behavior=$0(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Ws).catch(Ws)}ensureInfiniteQueryData(e){return e.behavior=$0(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return em.isOnline()?q(this,Pa).resumePausedMutations():Promise.resolve()}getQueryCache(){return q(this,Gt)}getMutationCache(){return q(this,Pa)}getDefaultOptions(){return q(this,Ea)}setDefaultOptions(e){ze(this,Ea,e)}setQueryDefaults(e,t){q(this,fl).set(gd(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...q(this,fl).values()],s={};return t.forEach(r=>{xd(e,r.queryKey)&&Object.assign(s,r.defaultOptions)}),s}setMutationDefaults(e,t){q(this,gl).set(gd(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...q(this,gl).values()],s={};return t.forEach(r=>{xd(e,r.mutationKey)&&Object.assign(s,r.defaultOptions)}),s}defaultQueryOptions(e){if(e._defaulted)return e;const t={...q(this,Ea).queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Jv(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===Zv&&(t.enabled=!1),t}defaultMutationOptions(e){return e!=null&&e._defaulted?e:{...q(this,Ea).mutations,...(e==null?void 0:e.mutationKey)&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){q(this,Gt).clear(),q(this,Pa).clear()}},Gt=new WeakMap,Pa=new WeakMap,Ea=new WeakMap,fl=new WeakMap,gl=new WeakMap,Aa=new WeakMap,xl=new WeakMap,vl=new WeakMap,vj),qs,_t,Yd,Ds,Fi,yl,Ra,$a,Kd,bl,wl,Ui,Bi,La,jl,Et,Pc,tx,sx,nx,rx,ax,ix,ox,Ak,yj,BR=(yj=class extends eu{constructor(t,s){super();Xe(this,Et);Xe(this,qs);Xe(this,_t);Xe(this,Yd);Xe(this,Ds);Xe(this,Fi);Xe(this,yl);Xe(this,Ra);Xe(this,$a);Xe(this,Kd);Xe(this,bl);Xe(this,wl);Xe(this,Ui);Xe(this,Bi);Xe(this,La);Xe(this,jl,new Set);this.options=s,ze(this,qs,t),ze(this,$a,null),ze(this,Ra,ex()),this.options.experimental_prefetchInRender||q(this,Ra).reject(new Error("experimental_prefetchInRender feature flag is not enabled")),this.bindMethods(),this.setOptions(s)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(q(this,_t).addObserver(this),I0(q(this,_t),this.options)?jt(this,Et,Pc).call(this):this.updateResult(),jt(this,Et,rx).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return lx(q(this,_t),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return lx(q(this,_t),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,jt(this,Et,ax).call(this),jt(this,Et,ix).call(this),q(this,_t).removeObserver(this)}setOptions(t){const s=this.options,r=q(this,_t);if(this.options=q(this,qs).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof Sn(this.options.enabled,q(this,_t))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");jt(this,Et,ox).call(this),q(this,_t).setOptions(this.options),s._defaulted&&!Jg(this.options,s)&&q(this,qs).getQueryCache().notify({type:"observerOptionsUpdated",query:q(this,_t),observer:this});const a=this.hasListeners();a&&O0(q(this,_t),r,this.options,s)&&jt(this,Et,Pc).call(this),this.updateResult(),a&&(q(this,_t)!==r||Sn(this.options.enabled,q(this,_t))!==Sn(s.enabled,q(this,_t))||Ka(this.options.staleTime,q(this,_t))!==Ka(s.staleTime,q(this,_t)))&&jt(this,Et,tx).call(this);const i=jt(this,Et,sx).call(this);a&&(q(this,_t)!==r||Sn(this.options.enabled,q(this,_t))!==Sn(s.enabled,q(this,_t))||i!==q(this,La))&&jt(this,Et,nx).call(this,i)}getOptimisticResult(t){const s=q(this,qs).getQueryCache().build(q(this,qs),t),r=this.createResult(s,t);return qR(this,r)&&(ze(this,Ds,r),ze(this,yl,this.options),ze(this,Fi,q(this,_t).state)),r}getCurrentResult(){return q(this,Ds)}trackResult(t,s){return new Proxy(t,{get:(r,a)=>(this.trackProp(a),s==null||s(a),Reflect.get(r,a))})}trackProp(t){q(this,jl).add(t)}getCurrentQuery(){return q(this,_t)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const s=q(this,qs).defaultQueryOptions(t),r=q(this,qs).getQueryCache().build(q(this,qs),s);return r.fetch().then(()=>this.createResult(r,s))}fetch(t){return jt(this,Et,Pc).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),q(this,Ds)))}createResult(t,s){var T;const r=q(this,_t),a=this.options,i=q(this,Ds),o=q(this,Fi),l=q(this,yl),d=t!==r?t.state:q(this,Yd),{state:u}=t;let m={...u},p=!1,f;if(s._optimisticResults){const C=this.hasListeners(),B=!C&&I0(t,s),E=C&&O0(t,r,s,a);(B||E)&&(m={...m,...Ek(u.data,t.options)}),s._optimisticResults==="isRestoring"&&(m.fetchStatus="idle")}let{error:g,errorUpdatedAt:x,status:b}=m;f=m.data;let v=!1;if(s.placeholderData!==void 0&&f===void 0&&b==="pending"){let C;i!=null&&i.isPlaceholderData&&s.placeholderData===(l==null?void 0:l.placeholderData)?(C=i.data,v=!0):C=typeof s.placeholderData=="function"?s.placeholderData((T=q(this,wl))==null?void 0:T.state.data,q(this,wl)):s.placeholderData,C!==void 0&&(b="success",f=Xg(i==null?void 0:i.data,C,s),p=!0)}if(s.select&&f!==void 0&&!v)if(i&&f===(o==null?void 0:o.data)&&s.select===q(this,Kd))f=q(this,bl);else try{ze(this,Kd,s.select),f=s.select(f),f=Xg(i==null?void 0:i.data,f,s),ze(this,bl,f),ze(this,$a,null)}catch(C){ze(this,$a,C)}q(this,$a)&&(g=q(this,$a),f=q(this,bl),x=Date.now(),b="error");const y=m.fetchStatus==="fetching",w=b==="pending",j=b==="error",_=w&&y,N=f!==void 0,S={status:b,fetchStatus:m.fetchStatus,isPending:w,isSuccess:b==="success",isError:j,isInitialLoading:_,isLoading:_,data:f,dataUpdatedAt:m.dataUpdatedAt,error:g,errorUpdatedAt:x,failureCount:m.fetchFailureCount,failureReason:m.fetchFailureReason,errorUpdateCount:m.errorUpdateCount,isFetched:m.dataUpdateCount>0||m.errorUpdateCount>0,isFetchedAfterMount:m.dataUpdateCount>d.dataUpdateCount||m.errorUpdateCount>d.errorUpdateCount,isFetching:y,isRefetching:y&&!w,isLoadingError:j&&!N,isPaused:m.fetchStatus==="paused",isPlaceholderData:p,isRefetchError:j&&N,isStale:ey(t,s),refetch:this.refetch,promise:q(this,Ra),isEnabled:Sn(s.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){const C=H=>{S.status==="error"?H.reject(S.error):S.data!==void 0&&H.resolve(S.data)},B=()=>{const H=ze(this,Ra,S.promise=ex());C(H)},E=q(this,Ra);switch(E.status){case"pending":t.queryHash===r.queryHash&&C(E);break;case"fulfilled":(S.status==="error"||S.data!==E.value)&&B();break;case"rejected":(S.status!=="error"||S.error!==E.reason)&&B();break}}return S}updateResult(){const t=q(this,Ds),s=this.createResult(q(this,_t),this.options);if(ze(this,Fi,q(this,_t).state),ze(this,yl,this.options),q(this,Fi).data!==void 0&&ze(this,wl,q(this,_t)),Jg(s,t))return;ze(this,Ds,s);const r=()=>{if(!t)return!0;const{notifyOnChangeProps:a}=this.options,i=typeof a=="function"?a():a;if(i==="all"||!i&&!q(this,jl).size)return!0;const o=new Set(i??q(this,jl));return this.options.throwOnError&&o.add("error"),Object.keys(q(this,Ds)).some(l=>{const c=l;return q(this,Ds)[c]!==t[c]&&o.has(c)})};jt(this,Et,Ak).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&jt(this,Et,rx).call(this)}},qs=new WeakMap,_t=new WeakMap,Yd=new WeakMap,Ds=new WeakMap,Fi=new WeakMap,yl=new WeakMap,Ra=new WeakMap,$a=new WeakMap,Kd=new WeakMap,bl=new WeakMap,wl=new WeakMap,Ui=new WeakMap,Bi=new WeakMap,La=new WeakMap,jl=new WeakMap,Et=new WeakSet,Pc=function(t){jt(this,Et,ox).call(this);let s=q(this,_t).fetch(this.options,t);return t!=null&&t.throwOnError||(s=s.catch(Ws)),s},tx=function(){jt(this,Et,ax).call(this);const t=Ka(this.options.staleTime,q(this,_t));if(Ji||q(this,Ds).isStale||!Qg(t))return;const r=_k(q(this,Ds).dataUpdatedAt,t)+1;ze(this,Ui,setTimeout(()=>{q(this,Ds).isStale||this.updateResult()},r))},sx=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(q(this,_t)):this.options.refetchInterval)??!1},nx=function(t){jt(this,Et,ix).call(this),ze(this,La,t),!(Ji||Sn(this.options.enabled,q(this,_t))===!1||!Qg(q(this,La))||q(this,La)===0)&&ze(this,Bi,setInterval(()=>{(this.options.refetchIntervalInBackground||Xv.isFocused())&&jt(this,Et,Pc).call(this)},q(this,La)))},rx=function(){jt(this,Et,tx).call(this),jt(this,Et,nx).call(this,jt(this,Et,sx).call(this))},ax=function(){q(this,Ui)&&(clearTimeout(q(this,Ui)),ze(this,Ui,void 0))},ix=function(){q(this,Bi)&&(clearInterval(q(this,Bi)),ze(this,Bi,void 0))},ox=function(){const t=q(this,qs).getQueryCache().build(q(this,qs),this.options);if(t===q(this,_t))return;const s=q(this,_t);ze(this,_t,t),ze(this,Yd,t.state),this.hasListeners()&&(s==null||s.removeObserver(this),t.addObserver(this))},Ak=function(t){_s.batch(()=>{t.listeners&&this.listeners.forEach(s=>{s(q(this,Ds))}),q(this,qs).getQueryCache().notify({query:q(this,_t),type:"observerResultsUpdated"})})},yj);function VR(e,t){return Sn(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function I0(e,t){return VR(e,t)||e.state.data!==void 0&&lx(e,t,t.refetchOnMount)}function lx(e,t,s){if(Sn(t.enabled,e)!==!1&&Ka(t.staleTime,e)!=="static"){const r=typeof s=="function"?s(e):s;return r==="always"||r!==!1&&ey(e,t)}return!1}function O0(e,t,s,r){return(e!==t||Sn(r.enabled,e)===!1)&&(!s.suspense||e.state.status!=="error")&&ey(e,s)}function ey(e,t){return Sn(t.enabled,e)!==!1&&e.isStaleByTime(Ka(t.staleTime,e))}function qR(e,t){return!Jg(e.getCurrentResult(),t)}var Rk=h.createContext(void 0),na=e=>{const t=h.useContext(Rk);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},HR=({client:e,children:t})=>(h.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),n.jsx(Rk.Provider,{value:e,children:t})),$k=h.createContext(!1),WR=()=>h.useContext($k);$k.Provider;function GR(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}
25var YR=h.createContext(GR()),KR=()=>h.useContext(YR),QR=(e,t)=>{(e.suspense||e.throwOnError||e.experimental_prefetchInRender)&&(t.isReset()||(e.retryOnMount=!1))},JR=e=>{h.useEffect(()=>{e.clearReset()},[e])},ZR=({result:e,errorResetBoundary:t,throwOnError:s,query:r,suspense:a})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(a&&e.data===void 0||TR(s,[e.error,r])),XR=e=>{if(e.suspense){const t=r=>r==="static"?r:Math.max(r??1e3,1e3),s=e.staleTime;e.staleTime=typeof s=="function"?(...r)=>t(s(...r)):t(s),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},e$=(e,t)=>e.isLoading&&e.isFetching&&!t,t$=(e,t)=>(e==null?void 0:e.suspense)&&t.isPending,D0=(e,t,s)=>t.fetchOptimistic(e).catch(()=>{s.clearReset()});function s$(e,t,s){var m,p,f,g,x;const r=WR(),a=KR(),i=na(),o=i.defaultQueryOptions(e);(p=(m=i.getDefaultOptions().queries)==null?void 0:m._experimental_beforeQuery)==null||p.call(m,o),o._optimisticResults=r?"isRestoring":"optimistic",XR(o),QR(o,a),JR(a);const l=!i.getQueryCache().get(o.queryHash),[c]=h.useState(()=>new t(i,o)),d=c.getOptimisticResult(o),u=!r&&e.subscribed!==!1;if(h.useSyncExternalStore(h.useCallback(b=>{const v=u?c.subscribe(_s.batchCalls(b)):Ws;return c.updateResult(),v},[c,u]),()=>c.getCurrentResult(),()=>c.getCurrentResult()),h.useEffect(()=>{c.setOptions(o)},[o,c]),t$(o,d))throw D0(o,c,a);if(ZR({result:d,errorResetBoundary:a,throwOnError:o.throwOnError,query:i.getQueryCache().get(o.queryHash),suspense:o.suspense}))throw d.error;if((g=(f=i.getDefaultOptions().queries)==null?void 0:f._experimental_afterQuery)==null||g.call(f,o,d),o.experimental_prefetchInRender&&!Ji&&e$(d,r)){const b=l?D0(o,c,a):(x=i.getQueryCache().get(o.queryHash))==null?void 0:x.promise;b==null||b.catch(Ws).finally(()=>{c.updateResult()})}return o.notifyOnChangeProps?d:c.trackResult(d)}function Zr(e,t){return s$(e,BR)}/**
26 * @remix-run/router v1.23.0
27 *
28 * Copyright (c) Remix Software Inc.
29 *
30 * This source code is licensed under the MIT license found in the
31 * LICENSE.md file in the root directory of this source tree.
32 *
33 * @license MIT
34 */function vd(){return vd=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var s=arguments[t];for(var r in s)Object.prototype.hasOwnProperty.call(s,r)&&(e[r]=s[r])}return e},vd.apply(this,arguments)}var Da;(function(e){e.Pop="POP",e.Push="PUSH",e.Replace="REPLACE"})(Da||(Da={}));const M0="popstate";function n$(e){e===void 0&&(e={});function t(r,a){let{pathname:i,search:o,hash:l}=r.location;return cx("",{pathname:i,search:o,hash:l},a.state&&a.state.usr||null,a.state&&a.state.key||"default")}function s(r,a){return typeof a=="string"?a:tm(a)}return a$(t,s,null,e)}function Vt(e,t){if(e===!1||e===null||typeof e>"u")throw new Error(t)}function Lk(e,t){if(!e){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function r$(){return Math.random().toString(36).substr(2,8)}function z0(e,t){return{usr:e.state,key:e.key,idx:t}}function cx(e,t,s,r){return s===void 0&&(s=null),vd({pathname:typeof e=="string"?e:e.pathname,search:"",hash:""},typeof t=="string"?Zl(t):t,{state:s,key:t&&t.key||r||r$()})}function tm(e){let{pathname:t="/",search:s="",hash:r=""}=e;return s&&s!=="?"&&(t+=s.charAt(0)==="?"?s:"?"+s),r&&r!=="#"&&(t+=r.charAt(0)==="#"?r:"#"+r),t}function Zl(e){let t={};if(e){let s=e.indexOf("#");s>=0&&(t.hash=e.substr(s),e=e.substr(0,s));let r=e.indexOf("?");r>=0&&(t.search=e.substr(r),e=e.substr(0,r)),e&&(t.pathname=e)}return t}function a$(e,t,s,r){r===void 0&&(r={});let{window:a=document.defaultView,v5Compat:i=!1}=r,o=a.history,l=Da.Pop,c=null,d=u();d==null&&(d=0,o.replaceState(vd({},o.state,{idx:d}),""));function u(){return(o.state||{idx:null}).idx}function m(){l=Da.Pop;let b=u(),v=b==null?null:b-d;d=b,c&&c({action:l,location:x.location,delta:v})}function p(b,v){l=Da.Push;let y=cx(x.location,b,v);d=u()+1;let w=z0(y,d),j=x.createHref(y);try{o.pushState(w,"",j)}catch(_){if(_ instanceof DOMException&&_.name==="DataCloneError")throw _;a.location.assign(j)}i&&c&&c({action:l,location:x.location,delta:1})}function f(b,v){l=Da.Replace;let y=cx(x.location,b,v);d=u();let w=z0(y,d),j=x.createHref(y);o.replaceState(w,"",j),i&&c&&c({action:l,location:x.location,delta:0})}function g(b){let v=a.location.origin!=="null"?a.location.origin:a.location.href,y=typeof b=="string"?b:tm(b);return y=y.replace(/ $/,"%20"),Vt(v,"No window.location.(origin|href) available to create URL for href: "+y),new URL(y,v)}let x={get action(){return l},get location(){return e(a,o)},listen(b){if(c)throw new Error("A history only accepts one active listener");return a.addEventListener(M0,m),c=b,()=>{a.removeEventListener(M0,m),c=null}},createHref(b){return t(a,b)},createURL:g,encodeLocation(b){let v=g(b);return{pathname:v.pathname,search:v.search,hash:v.hash}},push:p,replace:f,go(b){return o.go(b)}};return x}var F0;(function(e){e.data="data",e.deferred="deferred",e.redirect="redirect",e.error="error"})(F0||(F0={}));function i$(e,t,s){return s===void 0&&(s="/"),o$(e,t,s,!1)}function o$(e,t,s,r){let a=typeof t=="string"?Zl(t):t,i=El(a.pathname||"/",s);if(i==null)return null;let o=Ik(e);l$(o);let l=null;for(let c=0;l==null&&c<o.length;++c){let d=y$(i);l=x$(o[c],d,r)}return l}function Ik(e,t,s,r){t===void 0&&(t=[]),s===void 0&&(s=[]),r===void 0&&(r="");let a=(i,o,l)=>{let c={relativePath:l===void 0?i.path||"":l,caseSensitive:i.caseSensitive===!0,childrenIndex:o,route:i};c.relativePath.startsWith("/")&&(Vt(c.relativePath.startsWith(r),'Absolute route path "'+c.relativePath+'" nested under path '+('"'+r+'" is not val
34id. An absolute child route path ')+"must start with the combined path of all its parent routes."),c.relativePath=c.relativePath.slice(r.length));let d=Qa([r,c.relativePath]),u=s.concat(c);i.children&&i.children.length>0&&(Vt(i.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+d+'".')),Ik(i.children,t,u,d)),!(i.path==null&&!i.index)&&t.push({path:d,score:f$(d,i.index),routesMeta:u})};return e.forEach((i,o)=>{var l;if(i.path===""||!((l=i.path)!=null&&l.includes("?")))a(i,o);else for(let c of Ok(i.path))a(i,o,c)}),t}function Ok(e){let t=e.split("/");if(t.length===0)return[];let[s,...r]=t,a=s.endsWith("?"),i=s.replace(/\?$/,"");if(r.length===0)return a?[i,""]:[i];let o=Ok(r.join("/")),l=[];return l.push(...o.map(c=>c===""?i:[i,c].join("/"))),a&&l.push(...o),l.map(c=>e.startsWith("/")&&c===""?"/":c)}function l$(e){e.sort((t,s)=>t.score!==s.score?s.score-t.score:g$(t.routesMeta.map(r=>r.childrenIndex),s.routesMeta.map(r=>r.childrenIndex)))}const c$=/^:[\w-]+$/,d$=3,u$=2,h$=1,m$=10,p$=-2,U0=e=>e==="*";function f$(e,t){let s=e.split("/"),r=s.length;return s.some(U0)&&(r+=p$),t&&(r+=u$),s.filter(a=>!U0(a)).reduce((a,i)=>a+(c$.test(i)?d$:i===""?h$:m$),r)}function g$(e,t){return e.length===t.length&&e.slice(0,-1).every((r,a)=>r===t[a])?e[e.length-1]-t[t.length-1]:0}function x$(e,t,s){let{routesMeta:r}=e,a={},i="/",o=[];for(let l=0;l<r.length;++l){let c=r[l],d=l===r.length-1,u=i==="/"?t:t.slice(i.length)||"/",m=sm({path:c.relativePath,caseSensitive:c.caseSensitive,end:d},u),p=c.route;if(!m&&d&&s&&!r[r.length-1].route.index&&(m=sm({path:c.relativePath,caseSensitive:c.caseSensitive,end:!1},u)),!m)return null;
vendor: 9,622 bytes, lines 34-43
34Object.assign(a,m.params),o.push({params:a,pathname:Qa([i,m.pathname]),pathnameBase:_$(Qa([i,m.pathnameBase])),route:p}),m.pathnameBase!=="/"&&(i=Qa([i,m.pathnameBase]))}return o}function sm(e,t){typeof e=="string"&&(e={path:e,caseSensitive:!1,end:!0});let[s,r]=v$(e.path,e.caseSensitive,e.end),a=t.match(s);if(!a)return null;let i=a[0],o=i.replace(/(.)\/+$/,"$1"),l=a.slice(1);return{params:r.reduce((d,u,m)=>{let{paramName:p,isOptional:f}=u;if(p==="*"){let x=l[m]||"";o=i.slice(0,i.length-x.length).replace(/(.)\/+$/,"$1")}const g=l[m];return f&&!g?d[p]=void 0:d[p]=(g||"").replace(/%2F/g,"/"),d},{}),pathname:i,pathnameBase:o,pattern:e}}function v$(e,t,s){t===void 0&&(t=!1),s===void 0&&(s=!0),Lk(e==="*"||!e.endsWith("*")||e.endsWith("/*"),'Route path "'+e+'" will be treated as if it were '+('"'+e.replace(/\*$/,"/*")+'" because the `*` character must ')+"always follow a `/` in the pattern. To get rid of this warning, "+('please change the route path to "'+e.replace(/\*$/,"/*")+'".'));let r=[],a="^"+e.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(o,l,c)=>(r.push({paramName:l,isOptional:c!=null}),c?"/?([^\\/]+)?":"/([^\\/]+)"));return e.endsWith("*")?(r.push({paramName:"*"}),a+=e==="*"||e==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):s?a+="\\/*$":e!==""&&e!=="/"&&(a+="(?:(?=\\/|$))"),[new RegExp(a,t?void 0:"i"),r]}function y$(e){try{return e.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return Lk(!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 El(e,t){if(t==="/")return e;if(!e.toLowerCase().startsWith(t.toLowerCase()))return null;let s=t.endsWith("/")?t.length-1:t.length,r=e.charAt(s);return r&&r!=="/"?null:e.slice(s)||"/"}function b$(e,t){t===void 0&&(t="/");let{pathname:s,search:r="",hash:a=""}=typeof e=="string"?Zl(e):e;return{pathname:s?s.startsWith("/")?s:w$(s,t):t,search:k$(r),hash:N$(a)}}function w$(e,t){let s=t.replace(/\/+$/,"").split("/");return e.split("/").forEach(a=>{a===".."?s.length>1&&s.pop():a!=="."&&s.push(a)}),s.length>1?s.join("/"):"/"}function gf(e,t,s,r){return"Cannot include a '"+e+"' character in a manually specified "+("`to."+t+"` field ["+JSON.stringify(r)+"].  Please separate it out to the ")+("`to."+s+"` field. Alternatively you may provide the full path as ")+'a string in <Link to="..."> and the router will parse it for you.'}function j$(e){return e.filter((t,s)=>s===0||t.route.path&&t.route.path.length>0)}function ty(e,t){let s=j$(e);return t?s.map((r,a)=>a===s.length-1?r.pathname:r.pathnameBase):s.map(r=>r.pathnameBase)}function sy(e,t,s,r){r===void 0&&(r=!1);let a;typeof e=="string"?a=Zl(e):(a=vd({},e),Vt(!a.pathname||!a.pathname.includes("?"),gf("?","pathname","search",a)),Vt(!a.pathname||!a.pathname.includes("#"),gf("#","pathname","hash",a)),Vt(!a.search||!a.search.includes("#"),gf("#","search","hash",a)));let i=e===""||a.pathname==="",o=i?"/":a.pathname,l;if(o==null)l=s;else{let m=t.length-1;if(!r&&o.startsWith("..")){let p=o.split("/");for(;p[0]==="..";)p.shift(),m-=1;a.pathname=p.join("/")}l=m>=0?t[m]:"/"}let c=b$(a,l),d=o&&o!=="/"&&o.endsWith("/"),u=(i||o===".")&&s.endsWith("/");return!c.pathname.endsWith("/")&&(d||u)&&(c.pathname+="/"),c}const Qa=e=>e.join("/").replace(/\/\/+/g,"/"),_$=e=>e.replace(/\/+$/,"").replace(/^\/*/,"/"),k$=e=>!e||e==="?"?"":e.startsWith("?")?e:"?"+e,N$=e=>!e||e==="#"?"":e.startsWith("#")?e:"#"+e;function S$(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.internal=="boolean"&&"data"in e}const Dk=["post","put","patch","delete"];new Set(Dk);const C$=["get",...Dk];new Set(C$);/**
35 * React Router v6.30.1
36 *
37 * Copyright (c) Remix Software Inc.
38 *
39 * This source code is licensed under the MIT license found in the
40 * LICENSE.md file in the root directory of this source tree.
41 *
42 * @license MIT
43 */function yd(){return yd=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var s=arguments[t];for(var r in s)Object.prototype.hasOwnProperty.call(s,r)&&(e[r]=s[r])}return e},yd.apply(this,arguments)}const Ym=h.createContext(null),Mk=h.createContext(null),ra=h.createContext(null),Km=h.createContext(null),Ar=h.createContext({outlet:null,matches:[],isDataRoute:!1}),zk=h.createContext(null);function T$(e,t){let{relative:s}=t===void 0?{}:t;Xl()||Vt(!1);let{basename:r,navigator:a}=h.useContext(ra),{hash:i,pathname:o,search:l}=Qm(e,{relative:s}),c=o;return r!=="/"&&(c=o==="/"?r:Qa([r,o])),a.createHref({pathname:c,search:l,hash:i})}function Xl(){return h.useContext(Km)!=null}function rr(){return Xl()||Vt(!1),h.useContext(Km).location}function Fk(e){h.useContext(ra).static||h.useLayoutEffect(e)}function fi(){let{isDataRoute:e}=h.useContext(Ar);return e?q$():P$()}function P$(){Xl()||Vt(!1);let e=h.useContext(Ym),{basename:t,future:s,navigator:r}=h.useContext(ra),{matches:a}=h.useContext(Ar),{pathname:i}=rr(),o=JSON.stringify(ty(a,s.v7_relativeSplatPath)),l=h.useRef(!1);return Fk(()=>{l.current=!0}),h.useCallback(function(d,u){if(u===void 0&&(u={}),!l.current)return;if(typeof d=="number"){r.go(d);return}let m=sy(d,JSON.parse(o),i,u.relative==="path");e==null&&t!=="/"&&(m.pathname=m.pathname==="/"?t:Qa([t,m.pathname])),(u.replace?r.replace:r.push)(m,u.state,u)},[t,r,o,i,e])}const E$=h.createContext(null);function A$(e){let t=h.useContext(Ar).outlet;return t&&h.createElement(E$.Provider,{value:e},t)}function R$(){let{matches:e}=h.useContext(Ar),t=e[e.length-1];return t?t.params:{}}function Qm(e,t){let{relative:s}=t===void 0?{}:t,{future:r}=h.useContext(ra),{matches:a}=h.useContext(Ar),{pathname:i}=rr(),o=JSON.stringify(ty(a,r.v7_relativeSplatPath));return h.useMemo(()=>sy(e,JSON.parse(o),i,s==="path"),[e,o,i,s])}function $$(e,t){return L$(e,t)}function L$(e,t,s,r){Xl()||Vt(!1);let{navigator:a}=h.useContext(ra),{matches:i}=h.useContext(Ar),o=i[i.length-1],l=o?o.params:{};o&&o.pathname;let c=o?o.pathnameBase:"/";o&&o.route;let d=rr(),u;if(t){var m;let b=typeof t=="string"?Zl(t):t;c==="/"||(m=b.pathname)!=null&&m.startsWith(c)||Vt(!1),u=b}else u=d;let p=u.pathname||"/",f=p;if(c!=="/"){let b=c.replace(/^\//,"").split("/");f="/"+p.replace(/^\//,"").split("/").slice(b.length).join("/")}let g=i$(e,{pathname:f}),x=z$(g&&g.map(b=>Object.assign({},b,{params:Object.assign({},l,b.params),pathname:Qa([c,a.encodeLocation?a.encodeLocation(b.pathname).pathname:b.pathname]),pathnameBase:b.pathnameBase==="/"?c:Qa([c,a.encodeLocation?a.encodeLocation(b.pathnameBase).pathname:b.pathnameBase])})),i,s,r);return t&&x?h.createElement(Km.Provider,{value:{location:yd({pathname:"/",search:"",hash:"",state:null,key:"default"},u),navigationType:Da.Pop}},x):x}function I$(){let e=V$(),t=S$(e)?e.status+" "+e.statusText:e instanceof Error?e.message:JSON.stringify(e),s=e instanceof Error?e.stack:null,a={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return h.createElement(h.Fragment,null,h.createElement("h2",null,"Unexpected Application Error!"),h.createElement("h3",{style:{fontStyle:"italic"}},t),s?h.createElement("pre",{style:a},s):null,null)}const O$=h.createElement(I$,null);class D$ extends h.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,s){return s.location!==t.location||s.revalidation!=="idle"&&t.revalidation==="idle"?{error:t.error,location:t.location,revalidation:t.revalidation}:{error:t.error!==void 0?t.error:s.error,location:s.location,revalidation:t.revalidation||s.revalidation}}componentDidCatch(t,s){console.error("React Router caught the following error during render",t,s)}render(){return this.state.error!==void 0?h.createElement(Ar.Provider,{value:this.props.routeContext},h.createElement(zk.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function M$(e){let{routeContext:t,match:s,children:r}=e,a=h.useContext(Ym);return a&&a.static&&a.staticContext&&(s.route.errorElement||s.route.ErrorBoundary)&&(a.staticContext._deepestRenderedBoundaryId=s.route.id),h.createElement(Ar.Provider,{value:t},r)}function z$(e,t,s,r){var a;if(t===void 0&&(t=[]),s===void 0&&(s=null),r===void 0&&(r=null),e==null){var i;if(!s)return null;if(s.errors)e=s.matches;else if((i=r)!=null&&i.v7_partialHydration&&t.length===0&&!s.initialized&&s.matches.length>0)e=s.matches;else return null}let o=e,l=(a=s)==null?void 0:a.errors;if(l!=null){let u=o.findIndex(m=>m.route.id&&(l==null?void 0:l[m.route.id])!==void 0);u>=0||Vt(!1),o=o.slice(0,Math.min(o.length,u+1))}let c=!1,d=-1;if(s&&r&&r.v7_partialHydration)for(let u=0;u<o.length;u++){let m=o[u];if((m.route.HydrateFallback||m.route.hydrateFallbackElement)&&(d=u),m.route.id){let{loaderData:p,errors:f}=s,g=m.route.loader&&p[m.route.id]===void 0&&(!f||f[m.route.id]===void 0);if(m.route.lazy||g){c=!0,d>=0?o=o.slice(0,d+1):o=[o[0]];break}}}return o.reduceRight((u,m,p)=>{let f,g=!1,x=null,b=null;s&&(f=l&&m.route.id?l[m.route.id]:void 0,x=m.route.errorElement||O$,c&&(d<0&&p===0?(g=!0,b=null):d===p&&(g=!0,b=m.route.hydrateFallbackElement||null)));let v=t.concat(o.slice(0,p+1)),y=()=>{let w;return f?w=x:g?w=b:m.route.Component?w=h.createElement(m.route.Component,null):m.route.element?w=m.route.element:w=u,h.createElement(M$,{match:m,routeContext:{outlet:u,matches:v,isDataRoute:s!=null},children:w})};return s&&(m.route.ErrorBoundary||m.route.errorElement||p===0)?h.createElement(D$,{location:s.location,revalidation:s.revalidation,component:x,error:f,children:y(),routeC
43ontext:{outlet:null,matches:v,isDataRoute:!0}}):y()},null)}var Uk=function(e){return e.UseBlocker="useBlocker",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e}(Uk||{}),nm=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}(nm||{});function F$(e){let t=h.useContext(Ym);return t||Vt(!1),t}function U$(e){let t=h.useContext(Mk);return t||Vt(!1),t}function B$(e){let t=h.useContext(Ar);return t||Vt(!1),t}function Bk(e){let t=B$(),s=t.matches[t.matches.length-1];return s.route.id||Vt(!1),s.route.id}function V$(){var e;let t=h.useContext(zk),s=U$(nm.UseRouteError),r=Bk(nm.UseRouteError);return t!==void 0?t:(e=s.errors)==null?void 0:e[r]}function q$(){let{router:e}=F$(Uk.UseNavigateStable),t=Bk(nm.UseNavigateStable),s=h.useRef(!1);return Fk(()=>{s.current=!0}),h.useCallback(function(a,i){i===void 0&&(i={}),s.current&&(typeof a=="number"?e.navigate(a):e.navigate(a,yd({fromRouteId:t},i)))},[e,t])}function H$(e,t){e==null||e.v7_startTransition,e==null||e.v7_relativeSplatPath}function Al(e){let{to:t,replace:s,state:r,relative:a}=e;Xl()||Vt(!1);let{future:i,static:o}=h.useContext(ra),{matches:l}=h.useContext(Ar),{pathname:c}=rr(),d=fi(),u=sy(t,ty(l,i.v7_relativeSplatPath),c,a==="path"),m=JSON.stringify(u);return h.useEffect(()=>d(JSON.parse(m),{replace:s,state:r,relative:a}),[d,m,a,s,r]),null}function W$(e){return A$(e.context)}function vt(e){Vt(!1)}function G$(e){let{basename:t="/",children:s=null,location:r,navigationType:a=Da.Pop,navigator:i,static:o=!1,future:l}=e;Xl()&&Vt(!1);let c=t.replace(/^\/*/,"/"),d=h.useMemo(()=>({basename:c,navigator:i,static:o,future:yd({v7_relativeSplatPath:!1},l)}),[c,l,i,o]);typeof r=="string"&&(r=Zl(r));let{pathname:u="/",search:m="",hash:p="",state:f=null,key:g="default"}=r,x=h.useMemo(()=>{let b=El(u,c);return b==null?null:{location:{pathname:b,search:m,hash:p,state:f,key:g},navigationType:a}},[c,u,m,p,f,g,a]);return x==null?null:h.createElement(ra.Provider,{value:d},h.createElement(Km.Provider,{children:s,value:x}))}function Y$(e){let{children:t,location:s}=e;return $$(dx(t),s)}new Promise(()=>{});function dx(e,t){t===void 0&&(t=[]);let s=[];return h.Children.forEach(e,(r,a)=>{if(!h.isValidElement(r))return;let i=[...t,a];if(r.type===h.Fragment){s.push.apply(s,dx(r.props.children,i));return}r.type!==vt&&Vt(!1),!r.props.index||!r.props.children||Vt(!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=dx(r.props.children,i)),s.push(o)}),s}/**
44 * React Router DOM v6.30.1
45 *
46 * Copyright (c) Remix Software Inc.
47 *
48 * This source code is licensed under the MIT license found in the
49 * LICENSE.md file in the root directory of this source tree.
50 *
51 * @license MIT
52 */function rm(){return rm=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var s=arguments[t];for(var r in s)Object.prototype.hasOwnProperty.call(s,r)&&(e[r]=s[r])}return e},rm.apply(this,arguments)}function Vk(e,t){if(e==null)return{};var s={},r=Object.keys(e),a,i;for(i=0;i<r.length;i++)a=r[i],!(t.indexOf(a)>=0)&&(s[a]=e[a]);return s}function K$(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function Q$(e,t){return e.button===0&&(!t||t==="_self")&&!K$(e)}function ux(e){return e===void 0&&(e=""),new URLSearchParams(typeof e=="string"||Array.isArray(e)||e instanceof URLSearchParams?e:Object.keys(e).reduce((t,s)=>{let r=e[s];return t.concat(Array.isArray(r)?r.map(a=>[s,a]):[[s,r]])},[]))}function J$(e,t){let s=ux(e);return t&&t.forEach((r,a)=>
52{s.has(a)||t.getAll(a).forEach(i=>{s.append(a,i)})}),s}const Z$=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","viewTransition"],X$=["aria-current","caseSensitive","className","end","style","to","viewTransition","children"],eL="6";try{window.__reactRouterVersion=eL}catch{}const tL=h.createContext({isTransitioning:!1}),sL="startTransition",B0=iv[sL];function nL(e){let{basename:t,children:s,future:r,window:a}=e,i=h.useRef();i.current==null&&(i.current=n$({window:a,v5Compat:!0}));let o=i.current,[l,c]=h.useState({action:o.action,location:o.location}),{v7_startTransition:d}=r||{},u=h.useCallback(m=>{d&&B0?B0(()=>c(m)):c(m)},[c,d]);return h.useLayoutEffect(()=>o.listen(u),[o,u]),h.useEffect(()=>H$(r),[r]),h.createElement(G$,{basename:t,children:s,location:l.location,navigationType:l.action,navigator:o,future:r})}const rL=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",aL=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,zt=h.forwardRef(function(t,s){let{onClick:r,relative:a,reloadDocument:i,replace:o,state:l,target:c,to:d,preventScrollReset:u,viewTransition:m}=t,p=Vk(t,Z$),{basename:f}=h.useContext(ra),g,x=!1;if(typeof d=="string"&&aL.test(d)&&(g=d,rL))try{let w=new URL(window.location.href),j=d.startsWith("//")?new URL(w.protocol+d):new URL(d),_=El(j.pathname,f);j.origin===w.origin&&_!=null?d=_+j.search+j.hash:x=!0}catch{}let b=T$(d,{relative:a}),v=lL(d,{replace:o,state:l,target:c,preventScrollReset:u,relative:a,viewTransition:m});function y(w){r&&r(w),w.defaultPrevented||v(w)}return h.createElement("a",rm({},p,{href:g||b,onClick:x||i?r:y,ref:s,target:c}))}),iL=h.forwardRef(function(t,s){let{"aria-current":r="page",caseSensitive:a=!1,className:i="",end:o=!1,style:l,to:c,viewTransition:d,children:u}=t,m=Vk(t,X$),p=Qm(c,{relative:m.relative}),f=rr(),g=h.useContext(Mk),{navigator:x,basename:b}=h.useContext(ra),v=g!=null&&cL(p)&&d===!0,y=x.encodeLocation?x.encodeLocation(p).pathname:p.pathname,w=f.pathname,j=g&&g.navigation&&g.navigation.location?g.navigation.location.pathname:null;a||(w=w.toLowerCase(),j=j?j.toLowerCase():null,y=y.toLowerCase()),j&&b&&(j=El(j,b)||j);const _=y!=="/"&&y.endsWith("/")?y.length-1:y.length;let N=w===y||!o&&w.startsWith(y)&&w.charAt(_)==="/",k=j!=null&&(j===y||!o&&j.startsWith(y)&&j.charAt(y.length)==="/"),S={isActive:N,isPending:k,isTransitioning:v},T=N?r:void 0,C;typeof i=="function"?C=i(S):C=[i,N?"active":null,k?"pending":null,v?"transitioning":null].filter(Boolean).join(" ");let B=typeof l=="function"?l(S):l;return h.createElement(zt,rm({},m,{"aria-current":T,className:C,ref:s,style:B,to:c,viewTransition:d}),typeof u=="function"?u(S):u)});var hx;(function(e){e.UseScrollRestoration="useScrollRestoration",e.UseSubmit="useSubmit",e.UseSubmitFetcher="useSubmitFetcher",e.UseFetcher="useFetcher",e.useViewTransitionState="useViewTransitionState"})(hx||(hx={}));var V0;(function(e){e.UseFetcher="useFetcher",e.UseFetchers="useFetchers",e.UseScrollRestoration="useScrollRestoration"})(V0||(V0={}));function oL(e){let t=h.useContext(Ym);return t||Vt(!1),t}function lL(e,t){let{target:s,replace:r,state:a,preventScrollReset:i,relative:o,viewTransition:l}=t===void 0?{}:t,c=fi(),d=rr(),u=Qm(e,{relative:o});return h.useCallback(m=>{if(Q$(m,s)){m.preventDefault();let p=r!==void 0?r:tm(d)===tm(u);c(e,{replace:p,state:a,preventScrollReset:i,relative:o,viewTransition:l})}},[d,c,u,r,a,s,e,i,o,l])}function tu(e){let t=h.useRef(ux(e)),s=h.useRef(!1),r=rr(),a=h.useMemo(()=>J$(r.search,s.current?null:t.current),[r.search]),i=fi(),o=h.useCallback((l,c)=>{const d=ux(typeof l=="function"?l(a):l);s.current=!0,i("?"+d,c)},[i,a]);return[a,o]}function cL(e,t){t===void 0&&(t={});let s=h.useContext(tL);s==null&&Vt(!1);let{basename:r}=oL(hx.useViewTransitionState),a=Qm(e,{relative:t.relative});if(!s.isTransitioning)return!1;let i=El(s.currentLocation.pathname,r)||s.currentLocation.pathname,o=El(s.nextLocation.pathname,r)||s.nextLocation.pathname;return sm(a.pathname,o)!=null||sm(a.pathname,i)!=null}const dL=e=>{if(!e.startsWith("#"))return null;const t=decodeURIComponent(e.slice(1));return!t||t.includes("=")||t.includes("&")?null:document.getElementById(t)},uL=()=>{const{pathname:e,hash:t}=rr();return h.useEffect(()=>{if(t){const s=dL(t);if(s){s.scrollIntoView({behavior:"smooth"});return}}window.scrollTo(0,0)},[e,t]),null};function Ee(e,t,{checkForDefaultPrevented:s=!0}={}
vendor: 19,907 bytes, line 52
52){return function(a){if(e==null||e(a),s===!1||!a.defaultPrevented)return t==null?void 0:t(a)}}function q0(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Jm(...e){return t=>{let s=!1;const r=e.map(a=>{const i=q0(a,t);return!s&&typeof i=="function"&&(s=!0),i});if(s)return()=>{for(let a=0;a<r.length;a++){const i=r[a];typeof i=="function"?i():q0(e[a],null)}}}}function bt(...e){return h.useCallback(Jm(...e),e)}function hL(e,t){const s=h.createContext(t),r=i=>{const{children:o,...l}=i,c=h.useMemo(()=>l,Object.values(l));return n.jsx(s.Provider,{value:c,children:o})};r.displayName=e+"Provider";function a(i){const o=h.useContext(s);if(o)return o;if(t!==void 0)return t;throw new Error(`\`${i}\` must be used within \`${e}\``)}return[r,a]}function Is(e,t=[]){let s=[];function r(i,o){const l=h.createContext(o),c=s.length;s=[...s,o];const d=m=>{var v;const{scope:p,children:f,...g}=m,x=((v=p==null?void 0:p[e])==null?void 0:v[c])||l,b=h.useMemo(()=>g,Object.values(g));return n.jsx(x.Provider,{value:b,children:f})};d.displayName=i+"Provider";function u(m,p){var x;const f=((x=p==null?void 0:p[e])==null?void 0:x[c])||l,g=h.useContext(f);if(g)return g;if(o!==void 0)return o;throw new Error(`\`${m}\` must be used within \`${i}\``)}return[d,u]}const a=()=>{const i=s.map(o=>h.createContext(o));return function(l){const c=(l==null?void 0:l[e])||i;return h.useMemo(()=>({[`__scope${e}`]:{...l,[e]:c}}),[l,c])}};return a.scopeName=e,[r,mL(a,...t)]}function mL(...e){const t=e[0];if(e.length===1)return t;const s=()=>{const r=e.map(a=>({useScope:a(),scopeName:a.scopeName}));return function(i){const o=r.reduce((l,{useScope:c,scopeName:d})=>{const m=c(i)[`__scope${d}`];return{...l,...m}},{});return h.useMemo(()=>({[`__scope${t.scopeName}`]:o}),[o])}};return s.scopeName=t.scopeName,s}function ni(e){const t=pL(e),s=h.forwardRef((r,a)=>{const{children:i,...o}=r,l=h.Children.toArray(i),c=l.find(fL);if(c){const d=c.props.children,u=l.map(m=>m===c?h.Children.count(d)>1?h.Children.only(null):h.isValidElement(d)?d.props.children:null:m);return n.jsx(t,{...o,ref:a,children:h.isValidElement(d)?h.cloneElement(d,void 0,u):null})}return n.jsx(t,{...o,ref:a,children:i})});return s.displayName=`${e}.Slot`,s}var ec=ni("Slot");function pL(e){const t=h.forwardRef((s,r)=>{const{children:a,...i}=s;if(h.isValidElement(a)){const o=xL(a),l=gL(i,a.props);return a.type!==h.Fragment&&(l.ref=r?Jm(r,o):o),h.cloneElement(a,l)}return h.Children.count(a)>1?h.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var qk=Symbol("radix.slottable");function Hk(e){const t=({children:s})=>n.jsx(n.Fragment,{children:s});return t.displayName=`${e}.Slottable`,t.__radixId=qk,t}function fL(e){return h.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===qk}function gL(e,t){const s={...t};for(const r in t){const a=e[r],i=t[r];/^on[A-Z]/.test(r)?a&&i?s[r]=(...l)=>{const c=i(...l);return a(...l),c}:a&&(s[r]=a):r==="style"?s[r]={...a,...i}:r==="className"&&(s[r]=[a,i].filter(Boolean).join(" "))}return{...e,...s}}function xL(e){var r,a;let t=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,s=t&&"isReactWarning"in t&&t.isReactWarning;return s?e.ref:(t=(a=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:a.get,s=t&&"isReactWarning"in t&&t.isReactWarning,s?e.props.ref:e.props.ref||e.ref)}var vL=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],qe=vL.reduce((e,t)=>{const s=ni(`Primitive.${t}`),r=h.forwardRef((a,i)=>{const{asChild:o,...l}=a,c=o?s:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),n.jsx(c,{...l,ref:i})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function Wk(e,t){e&&Jl.flushSync(()=>e.dispatchEvent(t))}function Zn(e){const t=h.useRef(e);return h.useEffect(()=>{t.current=e}),h.useMemo(()=>(...s)=>{var r;return(r=t.current)==null?void 0:r.call(t,...s)},[])}function yL(e,t=globalThis==null?void 0:globalThis.document){const s=Zn(e);h.useEffect(()=>{const r=a=>{a.key==="Escape"&&s(a)};return t.addEventListener("keydown",r,{capture:!0}),()=>t.removeEventListener("keydown",r,{capture:!0})},[s,t])}var bL="DismissableLayer",mx="dismissableLayer.update",wL="dismissableLayer.pointerDownOutside",jL="dismissableLayer.focusOutside",H0,Gk=h.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),tc=h.forwardRef((e,t)=>{const{disableOutsidePointerEvents:s=!1,onEscapeKeyDown:r,onPointerDownOutside:a,onFocusOutside:i,onInteractOutside:o,onDismiss:l,...c}=e,d=h.useContext(Gk),[u,m]=h.useState(null),p=(u==null?void 0:u.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,f]=h.useState({}),g=bt(t,k=>m(k)),x=Array.from(d.layers),[b]=[...d.layersWithOutsidePointerEventsDisabled].slice(-1),v=x.indexOf(b),y=u?x.indexOf(u):-1,w=d.layersWithOutsidePointerEventsDisabled.size>0,j=y>=v,_=NL(k=>{const S=k.target,T=[...d.branches].some(C=>C.contains(S));!j||T||(a==null||a(k),o==null||o(k),k.defaultPrevented||l==null||l())},p),N=SL(k=>{const S=k.target;[...d.branches].some(C=>C.contains(S))||(i==null||i(k),o==null||o(k),k.defaultPrevented||l==null||l())},p);return yL(k=>{y===d.layers.size-1&&(r==null||r(k),!k.defaultPrevented&&l&&(k.preventDefault(),l()))},p),h.useEffect(()=>{if(u)return s&&(d.layersWithOutsidePointerEventsDisabled.size===0&&(H0=p.body.style.pointerEvents,p.body.style.pointerEvents="none"),d.layersWithOutsidePointerEventsDisabled.add(u)),d.layers.add(u),W0(),()=>{s&&d.layersWithOutsidePointerEventsDisabled.size===1&&(p.body.style.pointerEvents=H0)}},[u,p,s,d]),h.useEffect(()=>()=>{u&&(d.layers.delete(u),d.layersWithOutsidePointerEventsDisabled.delete(u),W0())},[u,d]),h.useEffect(()=>{const k=()=>f({});return document.addEventListener(mx,k),()=>document.removeEventListener(mx,k)},[]),n.jsx(qe.div,{...c,ref:g,style:{pointerEvents:w?j?"auto":"none":void 0,...e.style},onFocusCapture:Ee(e.onFocusCapture,N.onFocusCapture),onBlurCapture:Ee(e.onBlurCapture,N.onBlurCapture),onPointerDownCapture:Ee(e.onPointerDownCapture,_.onPointerDownCapture)})});tc.displayName=bL;var _L="DismissableLayerBranch",kL=h.forwardRef((e,t)=>{const s=h.useContext(Gk),r=h.useRef(null),a=bt(t,r);return h.useEffect(()=>{const i=r.current;if(i)return s.branches.add(i),()=>{s.branches.delete(i)}},[s.branches]),n.jsx(qe.div,{...e,ref:a})});kL.displayName=_L;function NL(e,t=globalThis==null?void 0:globalThis.document){const s=Zn(e),r=h.useRef(!1),a=h.useRef(()=>{});return h.useEffect(()=>{const i=l=>{if(l.target&&!r.current){let c=function(){Yk(wL,s,d,{discrete:!0})};const d={originalEvent:l};l.pointerType==="touch"?(t.removeEventListener("click",a.current),a.current=c,t.addEventListener("click",a.current,{once:!0})):c()}else t.removeEventListener("click",a.current);r.current=!1},o=window.setTimeout(()=>{t.addEventListener("pointerdown",i)},0);return()=>{window.clearTimeout(o),t.removeEventListener("pointerdown",i),t.removeEventListener("click",a.current)}},[t,s]),{onPointerDownCapture:()=>r.current=!0}}function SL(e,t=globalThis==null?void 0:globalThis.document){const s=Zn(e),r=h.useRef(!1);return h.useEffect(()=>{const a=i=>{i.target&&!r.current&&Yk(jL,s,{originalEvent:i},{discrete:!1})};return t.addEventListener("focusin",a),()=>t.removeEventListener("focusin",a)},[t,s]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function W0(){const e=new CustomEvent(mx);document.dispatchEvent(e)}function Yk(e,t,s,{discrete:r}){const a=s.originalEvent.target,i=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:s});t&&a.addEventListener(e,t,{once:!0}),r?Wk(a,i):a.dispatchEvent(i)}var cs=globalThis!=null&&globalThis.document?h.useLayoutEffect:()=>{},CL=iv[" useId ".trim().toString()]||(()=>{}),TL=0;function pn(e){const[t,s]=h.useState(CL());return cs(()=>{s(r=>r??String(TL++))},[e]),t?`radix-${t}`:""}const PL=["top","right","bottom","left"],ri=Math.min,ln=Math.max,am=Math.round,Wu=Math.floor,Nr=e=>({x:e,y:e}),EL={left:"right",right:"left",bottom:"top",top:"bottom"},AL={start:"end",end:"start"};function px(e,t,s){return ln(e,ri(t,s))}function Xr(e,t){return typeof e=="function"?e(t):e}function ea(e){return e.split("-")[0]}function sc(e){return e.split("-")[1]}function ny(e){return e==="x"?"y":"x"}function ry(e){return e==="y"?"height":"width"}const RL=new Set(["top","bottom"]);function wr(e){return RL.has(ea(e))?"y":"x"}function ay(e){return ny(wr(e))}function $L(e,t,s){s===void 0&&(s=!1);const r=sc(e),a=ay(e),i=ry(a);let o=a==="x"?r===(s?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[i]>t.floating[i]&&(o=im(o)),[o,im(o)]}function LL(e){const t=im(e);return[fx(e),t,fx(t)]}function fx(e){return e.replace(/start|end/g,t=>AL[t])}const G0=["left","right"],Y0=["right","left"],IL=["top","bottom"],OL=["bottom","top"];function DL(e,t,s){switch(e){case"top":case"bottom":return s?t?Y0:G0:t?G0:Y0;case"left":case"right":return t?IL:OL;default:return[]}}function ML(e,t,s,r){const a=sc(e);let i=DL(ea(e),s==="start",r);return a&&(i=i.map(o=>o+"-"+a),t&&(i=i.concat(i.map(fx)))),i}function im(e){return e.replace(/left|right|bottom|top/g,t=>EL[t])}function zL(e){return{top:0,right:0,bottom:0,left:0,...e}}function Kk(e){return typeof e!="number"?zL(e):{top:e,right:e,bottom:e,left:e}}function om(e){const{x:t,y:s,width:r,height:a}=e;return{width:r,height:a,top:s,left:t,right:t+r,bottom:s+a,x:t,y:s}}function K0(e,t,s){let{reference:r,floating:a}=e;const i=wr(t),o=ay(t),l=ry(o),c=ea(t),d=i==="y",u=r.x+r.width/2-a.width/2,m=r.y+r.height/2-a.height/2,p=r[l]/2-a[l]/2;let f;switch(c){case"top":f={x:u,y:r.y-a.height};break;case"bottom":f={x:u,y:r.y+r.height};break;case"right":f={x:r.x+r.width,y:m};break;case"left":f={x:r.x-a.width,y:m};break;default:f={x:r.x,y:r.y}}switch(sc(t)){case"start":f[o]-=p*(s&&d?-1:1);break;case"end":f[o]+=p*(s&&d?-1:1);break}return f}const FL=async(e,t,s)=>{const{placement:r="bottom",strategy:a="absolute",middleware:i=[],platform:o}=s,l=i.filter(Boolean),c=await(o.isRTL==null?void 0:o.isRTL(t));let d=await o.getElementRects({reference:e,floating:t,strategy:a}),{x:u,y:m}=K0(d,r,c),p=r,f={},g=0;for(let x=0;x<l.length;x++){const{name:b,fn:v}=l[x],{x:y,y:w,data:j,reset:_}=await v({x:u,y:m,initialPlacement:r,placement:p,strategy:a,middlewareData:f,rects:d,platform:o,elements:{reference:e,floating:t}});u=y??u,m=w??m,f={...f,[b]:{...f[b],...j}},_&&g<=50&&(g++,typeof _=="object"&&(_.placement&&(p=_.placement),_.rects&&(d=_.rects===!0?await o.getElementRects({reference:e,floating:t,strategy:a}):_.rects),{x:u,y:m}=K0(d,p,c)),x=-1)}return{x:u,y:m,placement:p,strategy:a,middlewareData:f}};async function bd(e,t){var s;t===void 0&&(t={});const{x:r,y:a,platform:i,rects:o,elements:l,strategy:c}=e,{boundary:d="clippingAncestors",rootBoundary:u="viewport",elementContext:m="floating",altBoundary:p=!1,padding:f=0}=Xr(t,e),g=Kk(f),b=l[p?m==="floating"?"reference":"floating":m],v=om(await i.getClippingRect({element:(s=await(i.isElement==null?void 0:i.isElement(b)))==null||s?b:b.contextElement||await(i.getDocumentElement==null?void 0:i.getDocumentElement(l.floating)),boundary:d,rootBoundary:u,strategy:c})),y=m==="floating"?{x:r,y:a,width:o.floating.width,height:o.floating.height}:o.reference,w=await(i.getOffsetParent==null?void 0:i.getOffsetParent(l.floating)),j=await(i.isElement==null?void 0:i.isElement(w))?await(i.getScale==null?void 0:i.getScale(w))||{x:1,y:1}:{x:1,y:1},_=om(i.convertOffsetParentRelativeRectToViewportRelativeRect?await i.convertOffsetParentRelativeRectToViewportRelativeRect({elements:l,rect:y,offsetParent:w,strategy:c}):y);return{top:(v.top-_.top+g.top)/j.y,bottom:(_.bottom-v.bottom+g.bottom)/j.y,left:(v.left-_.left+g.left)/j.x,right:(_.right-v.right+g.right)/j.x}}const UL=e=>({name:"arrow",options:e,async fn(t){const{x:s,y:r,placement:a,rects:i,platform:o,elements:l,middlewareData:c}=t,{element:d,padding:u=0}=Xr(e,t)||{};if(d==null)return{};const m=Kk(u),p={x:s,y:r},f=ay(a),g=ry(f),x=await o.getDimensions(d),b=f==="y",v=b?"top":"left",y=b?"bottom":"right",w=b?"clientHeight":"clientWidth",j=i.reference[g]+i.reference[f]-p[f]-i.floating[g],_=p[f]-i.reference[f],N=await(o.getOffsetParent==null?void 0:o.getOffsetParent(d));let k=N?N[w]:0;(!k||!await(o.isElement==null?void 0:o.isElement(N)))&&(k=l.floating[w]||i.floating[g]);const S=j/2-_/2,T=k/2-x[g]/2-1,C=ri(m[v],T),B=ri(m[y],T),E=C,H=k-x[g]-B,z=k/2-x[g]/2+S,ne=px(E,z,H),V=!c.arrow&&sc(a)!=null&&z!==ne&&i.reference[g]/2-(z<E?C:B)-x[g]/2<0,te=V?z<E?z-E:z-H:0;return{[f]:p[f]+te,data:{[f]:ne,centerOffset:z-ne-te,...V&&{alignmentOffset:te}},reset:V}}}),BL=function(e){return e===void 0&&(e={}),{name:"flip",options:e,async fn(t){var s,r;const{placement:a,middlewareData:i,rects:o,initialPlacement:l,platform:c,elements:d}=t,{mainAxis:u=!0,crossAxis:m=!0,fallbackPlacements:p,fallbackStrategy:f="bestFit",fallbackAxisSideDirection:g="none",flipAlignment:x=!0,...b}=Xr(e,t);if((s=i.arrow)!=null&&s.alignmentOffset)return{};const v=ea(a),y=wr(l),w=ea(l)===l,j=await(c.isRTL==null?void 0:c.isRTL(d.floating)),_=p||(w||!x?[im(l)]:LL(l)),N=g!=="none";!p&&N&&_.push(...ML(l,x,g,j));const k=[l,..._],S=await bd(t,b),T=[];let C=((r=i.flip)==null?void 0:r.overflows)||[];if(u&&T.push(S[v]),m){const z=$L(a,o,j);T.push(S[z[0]],S[z[1]])}if(C=[...C,{placement:a,overflows:T}],!T.every(z=>z<=0)){var B,E;const z=(((B=i.flip)==null?void 0:B.index)||0)+1,ne=k[z];if(ne&&(!(m==="alignment"?y!==wr(ne):!1)||C.every(R=>R.overflows[0]>0&&wr(R.placement)===y)))return{data:{index:z,overflows:C},reset:{placement:ne}};let V=(E=C.filter(te=>te.overflows[0]<=0).sort((te,R)=>te.overflows[1]-R.overflows[1])[0])==null?void 0:E.placement;if(!V)switch(f){case"bestFit":{var H;const te=(H=C.filter(R=>{if(N){const F=wr(R.placement);return F===y||F==="y"}return!0}).map(R=>[R.placement,R.overflows.filter(F=>F>0).reduce((F,$)=>F+$,0)]).sort((R,F)=>R[1]-F[1])[0])==null?void 0:H[0];te&&(V=te);break}case"initialPlacement":V=l;break}if(a!==V)return{reset:{placement:V}}}return{}}}};function Q0(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function J0(e){return PL.some(t=>e[t]>=0)}const VL=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:s}=t,{strategy:r="referenceHidden",...a}=Xr(e,t);switch(r){case"referenceHidden":{const i=await bd(t,{...a,elementContext:"reference"}),o=Q0(i,s.reference);return{data:{referenceHiddenOffsets:o,referenceHidden:J0(o)}}}case"escaped":{const i=await bd(t,{...a,altBoundary:!0}),o=Q0(i,s.floating);return{data:{escapedOffsets:o,escaped:J0(o)}}}default:return{}}}}},Qk=new Set(["left","top"]);async function qL(e,t){const{placement:s,platform:r,elements:a}=e,i=await(r.isRTL==null?void 0:r.isRTL(a.floating)),o=ea(s),l=sc(s),c=wr(s)==="y",d=Qk.has(o)?-1:1,u=i&&c?-1:1,m=Xr(t,e);let{mainAxis:p,crossAxis:f,alignmentAxis:g}=typeof m=="number"?{mainAxis:m,crossAxis:0,alignmentAxis:null}:{mainAxis:m.mainAxis||0,crossAxis:m.crossAxis||0,alignmentAxis:m.alignmentAxis};return l&&typeof g=="number"&&(f=l==="end"?g*-1:g),c?{x:f*u,y:p*d}:{x:p*d,y:f*u}}const HL=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var s,r;const{x:a,y:i,placement:o,middlewareData:l}=t,c=await qL(t,e);return o===((s=l.offset)==null?void 0:s.placement)&&(r=l.arrow)!=null&&r.alignmentOffset?{}:{x:a+c.x,y:i+c.y,data:{...c,placement:o}}}}},WL=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:s,y:r,placement:a}=t,{mainAxis:i=!0,crossAxis:o=!1,limiter:l={fn:b=>{let{x:v,y}=b;return{x:v,y}}},...c}=Xr(e,t),d={x:s,y:r},u=await bd(t,c),m=wr(ea(a)),p=ny(m);let f=d[p],g=d[m];if(i){const b=p==="y"?"top":"left",v=p==="y"?"bottom":"right",y=f+u[b],w=f-u[v];f=px(y,f,w)}if(o){const b=m==="y"?"top":"left",v=m==="y"?"bottom":"right",y=g+u[b],w=g-u[v];g=px(y,g,w)}const x=l.fn({...t,[p]:f,[m]:g});return{...x,data:{x:x.x-s,y:x.y-r,enabled:{[p]:i,[m]:o}}}}}},GL=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:s,y:r,placement:a,rects:i,middlewareData:o}=t,{offset:l=0,mainAxis:c=!0,crossAxis:d=!0}=Xr(e,t),u={x:s,y:r},m=wr(a),p=ny(m);let f=u[p],g=u[m];const x=Xr(l,t),b=typeof x=="number"?{mainAxis:x,crossAxis:0}:{mainAxis:0,crossAxis:0,...x};if(c){const w=p==="y"?"height":"width",j=i.reference[p]-i.floating[w]+b.mainAxis,_=i.reference[p]+i.reference[w]-b.mainAxis;f<j?f=j:f>_&&(f=_)}if(d){var v,y;const w=p==="y"?"width":"height",j=Qk.has(ea(a)),_=i.reference[m]-i.floating[w]+(j&&((v=o.offset)==null?void 0:v[m])||0)+(j?0:b.crossAxis),N=i.reference[m]+i.reference[w]+(j?0:((y=o.offset)==null?void 0:y[m])||0)-(j?b.crossAxis:0);g<_?g=_:g>N&&(g=N)}return{[p]:f,[m]:g}}}},YL=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){var s,r;const{placement:a,rects:i,platform:o,elements:l}=t,{apply:c=()=>{},...d}=Xr(e,t),u=await bd(t,d),m=ea(a),p=sc(a),f=wr(a)==="y",{width:g,height:x}=i.floating;let b,v;m==="top"||m==="bottom"?(b=m,v=p===(await(o.isRTL==null?void 0:o.isRTL(l.floating))?"start":"end")?"left":"right"):(v=m,b=p==="end"?"top":"bottom");const y=x-u.top-u.bottom,w=g-u.left-u.right,j=ri(x-u[b],y),_=ri(g-u[v],w),N=!t.middlewareData.shift;let k=j,S=_;if((s=t.middlewareData.shift)!=null&&s.enabled.x&&(S=w),(r=t.middlewareData.shift)!=null&&r.enabled.y&&(k=y),N&&!p){const C=ln(u.left,0),B=ln(u.right,0),E=ln(u.top,0),H=ln(u.bottom,0);f?S=g-2*(C!==0||B!==0?C+B:ln(u.left,u.right)):k=x-2*(E!==0||H!==0?E+H:ln(u.top,u.bottom))}await c({...t,availableWidth:S,availableHeight:k});const T=await o.getDimensions(l.floating);return g!==T.width||x!==T.height?{reset:{rects:!0}}:{}}}};function Zm(){return typeof window<"u"}function nc(e){return Jk(e)?(e.nodeName||"").toLowerCase():"#document"}function fn(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Rr(e){var t;return(t=(Jk(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function Jk(e){return Zm()?e instanceof Node||e instanceof fn(e).Node:!1}function Xn(e){return Zm()?e instanceof Element||e instanceof fn(e).Element:!1}function Cr(e){return Zm()?e instanceof HTMLElement||e instanceof fn(e).HTMLElement:!1}function Z0(e){return!Zm()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof fn(e).ShadowRoot}const KL=new Set(["inline","contents"]);function su(e){const{overflow:t,overflowX:s,overflowY:r,display:a}=er(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+s)&&!KL.has(a)}const QL=new Set(["table","td","th"]);function JL(e){return QL.has(nc(e))}const ZL=[":popover-open",":modal"];function Xm(e){return ZL.some(t=>{try{return e.matches(t)}catch{return!1}})}const XL=["transform","translate","scale","rotate","perspective"],eI=["transform","translate","scale","rotate","perspective","filter"],tI=["paint","layout","strict","content"];function iy(e){const t=oy(),s=Xn(e)?er(e):e;return XL.some(r=>s[r]?s[r]!=="none":!1)||(s.containerType?s.containerType!=="normal":!1)||!t&&(s.backdropFilter?s.backdropFilter!=="none":!1)||!t&&(s.filter?s.filter!=="none":!1)||eI.some(r=>(s.willChange||"").includes(r))||tI.some(r=>(s.contain||"").includes(r))}function sI(e){let t=ai(e);for(;Cr(t)&&!Rl(t);){if(iy(t))return t;if(Xm(t))return null;t=ai(t)}return null}function oy(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}const nI=new Set(["html","body","#document"]);function Rl(e){return nI.has(nc(e))}function er(e){return fn(e).getComputedStyle(e)}function ep(e){return Xn(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function ai(e){if(nc(e)==="html")return e;const t=e.assignedSlot||e.parentNode||Z0(e)&&e.host||Rr(e);return Z0(t)?t.host:t}function Zk(e){const t=ai(e);return Rl(t)?e.ownerDocument?e.ownerDocument.body:e.body:Cr(t)&&su(t)?t:Zk(t)}function wd(e,t,s){var r;t===void 0&&(t=[]),s===void 0&&(s=!0);const a=Zk(e),i=a===((r=e.ownerDocument)==null?void 0:r.body),o=fn(a);if(i){const l=gx(o);
vendor: 7,136 bytes, line 52
52return t.concat(o,o.visualViewport||[],su(a)?a:[],l&&s?wd(l):[])}return t.concat(a,wd(a,[],s))}function gx(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function Xk(e){const t=er(e);let s=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const a=Cr(e),i=a?e.offsetWidth:s,o=a?e.offsetHeight:r,l=am(s)!==i||am(r)!==o;return l&&(s=i,r=o),{width:s,height:r,$:l}}function ly(e){return Xn(e)?e:e.contextElement}function al(e){const t=ly(e);if(!Cr(t))return Nr(1);const s=t.getBoundingClientRect(),{width:r,height:a,$:i}=Xk(t);let o=(i?am(s.width):s.width)/r,l=(i?am(s.height):s.height)/a;return(!o||!Number.isFinite(o))&&(o=1),(!l||!Number.isFinite(l))&&(l=1),{x:o,y:l}}const rI=Nr(0);function eN(e){const t=fn(e);return!oy()||!t.visualViewport?rI:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function aI(e,t,s){return t===void 0&&(t=!1),!s||t&&s!==fn(e)?!1:t}function Zi(e,t,s,r){t===void 0&&(t=!1),s===void 0&&(s=!1);const a=e.getBoundingClientRect(),i=ly(e);let o=Nr(1);t&&(r?Xn(r)&&(o=al(r)):o=al(e));const l=aI(i,s,r)?eN(i):Nr(0);let c=(a.left+l.x)/o.x,d=(a.top+l.y)/o.y,u=a.width/o.x,m=a.height/o.y;if(i){const p=fn(i),f=r&&Xn(r)?fn(r):r;let g=p,x=gx(g);for(;x&&r&&f!==g;){const b=al(x),v=x.getBoundingClientRect(),y=er(x),w=v.left+(x.clientLeft+parseFloat(y.paddingLeft))*b.x,j=v.top+(x.clientTop+parseFloat(y.paddingTop))*b.y;c*=b.x,d*=b.y,u*=b.x,m*=b.y,c+=w,d+=j,g=fn(x),x=gx(g)}}return om({width:u,height:m,x:c,y:d})}function cy(e,t){const s=ep(e).scrollLeft;return t?t.left+s:Zi(Rr(e)).left+s}function tN(e,t,s){s===void 0&&(s=!1);const r=e.getBoundingClientRect(),a=r.left+t.scrollLeft-(s?0:cy(e,r)),i=r.top+t.scrollTop;return{x:a,y:i}}function iI(e){let{elements:t,rect:s,offsetParent:r,strategy:a}=e;const i=a==="fixed",o=Rr(r),l=t?Xm(t.floating):!1;if(r===o||l&&i)return s;let c={scrollLeft:0,scrollTop:0},d=Nr(1);const u=Nr(0),m=Cr(r);if((m||!m&&!i)&&((nc(r)!=="body"||su(o))&&(c=ep(r)),Cr(r))){const f=Zi(r);d=al(r),u.x=f.x+r.clientLeft,u.y=f.y+r.clientTop}const p=o&&!m&&!i?tN(o,c,!0):Nr(0);return{width:s.width*d.x,height:s.height*d.y,x:s.x*d.x-c.scrollLeft*d.x+u.x+p.x,y:s.y*d.y-c.scrollTop*d.y+u.y+p.y}}function oI(e){return Array.from(e.getClientRects())}function lI(e){const t=Rr(e),s=ep(e),r=e.ownerDocument.body,a=ln(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),i=ln(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let o=-s.scrollLeft+cy(e);const l=-s.scrollTop;return er(r).direction==="rtl"&&(o+=ln(t.clientWidth,r.clientWidth)-a),{width:a,height:i,x:o,y:l}}function cI(e,t){const s=fn(e),r=Rr(e),a=s.visualViewport;let i=r.clientWidth,o=r.clientHeight,l=0,c=0;if(a){i=a.width,o=a.height;const d=oy();(!d||d&&t==="fixed")&&(l=a.offsetLeft,c=a.offsetTop)}return{width:i,height:o,x:l,y:c}}const dI=new Set(["absolute","fixed"]);function uI(e,t){const s=Zi(e,!0,t==="fixed"),r=s.top+e.clientTop,a=s.left+e.clientLeft,i=Cr(e)?al(e):Nr(1),o=e.clientWidth*i.x,l=e.clientHeight*i.y,c=a*i.x,d=r*i.y;return{width:o,height:l,x:c,y:d}}function X0(e,t,s){let r;if(t==="viewport")r=cI(e,s);else if(t==="document")r=lI(Rr(e));else if(Xn(t))r=uI(t,s);else{const a=eN(e);r={x:t.x-a.x,y:t.y-a.y,width:t.width,height:t.height}}return om(r)}function sN(e,t){const s=ai(e);return s===t||!Xn(s)||Rl(s)?!1:er(s).position==="fixed"||sN(s,t)}function hI(e,t){const s=t.get(e);if(s)return s;let r=wd(e,[],!1).filter(l=>Xn(l)&&nc(l)!=="body"),a=null;const i=er(e).position==="fixed";let o=i?ai(e):e;for(;Xn(o)&&!Rl(o);){const l=er(o),c=iy(o);!c&&l.position==="fixed"&&(a=null),(i?!c&&!a:!c&&l.position==="static"&&!!a&&dI.has(a.position)||su(o)&&!c&&sN(e,o))?r=r.filter(u=>u!==o):a=l,o=ai(o)}return t.set(e,r),r}function mI(e){let{element:t,boundary:s,rootBoundary:r,strategy:a}=e;const o=[...s==="clippingAncestors"?Xm(t)?[]:hI(t,this._c):[].concat(s),r],l=o[0],c=o.reduce((d,u)=>{const m=X0(t,u,a);return d.top=ln(m.top,d.top),d.right=ri(m.right,d.right),d.bottom=ri(m.bottom,d.bottom),d.left=ln(m.left,d.left),d},X0(t,l,a));return{width:c.right-c.left,height:c.bottom-c.top,x:c.left,y:c.top}}function pI(e){const{width:t,height:s}=Xk(e);return{width:t,height:s}}function fI(e,t,s){const r=Cr(t),a=Rr(t),i=s==="fixed",o=Zi(e,!0,i,t);let l={scrollLeft:0,scrollTop:0};const c=Nr(0);function d(){c.x=cy(a)}if(r||!r&&!i)if((nc(t)!=="body"||su(a))&&(l=ep(t)),r){const f=Zi(t,!0,i,t);c.x=f.x+t.clientLeft,c.y=f.y+t.clientTop}else a&&d();i&&!r&&a&&d();const u=a&&!r&&!i?tN(a,l):Nr(0),m=o.left+l.scrollLeft-c.x-u.x,p=o.top+l.scrollTop-c.y-u.y;return{x:m,y:p,width:o.width,height:o.height}}function xf(e){return er(e).position==="static"}function ew(e,t){if(!Cr(e)||er(e).position==="fixed")return null;if(t)return t(e);let s=e.offsetParent;return Rr(e)===s&&(s=s.ownerDocument.body),s}function nN(e,t){const s=fn(e);if(Xm(e))return s;if(!Cr(e)){let a=ai(e);for(;a&&!Rl(a);){if(Xn(a)&&!xf(a))return a;a=ai(a)}return s}let r=ew(e,t);for(;r&&JL(r)&&xf(r);)r=ew(r,t);return r&&Rl(r)&&xf(r)&&!iy(r)?s:r||sI(e)||s}const gI=async function(e){const t=this.getOffsetParent||nN,s=this.getDimensions,r=await s(e.floating);return{reference:fI(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function xI(e){return er(e).direction==="rtl"}const vI={convertOffsetParentRelativeRectToViewportRelativeRect:iI,getDocumentElement:Rr,getClippingRect:mI,getOffsetParent:nN,getElementRects:gI,getClientRects:oI,getDimensions:pI,getScale:al,isElement:Xn,isRTL:xI};function rN(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function yI(e,t){let s=null,r;const a=Rr(e);function i(){var l;clearTimeout(r),(l=s)==null||l.disconnect(),s=null}function o(l,c){l===void 0&&(l=!1),c===void 0&&(c=1),i();const d=e.getBoundingClientRect(),{left:u,top:m,width:p,height:f}=d;if(l||t(),!p||!f)return;const g=Wu(m),x=Wu(a.clientWidth-(u+p)),b=Wu(a.clientHeight-(m+f)),v=Wu(u),w={rootMargin:-g+"px "+-x+"px "+-b+"px "+-v+"px",threshold:ln(0,ri(1,c))||1};let j=!0;function _(N){const k=N[0].intersectionRatio;if(k!==c){if(!j)return o();k?o(!1,k):r=setTimeout(()=>{o(!1,1e-7)},1e3)}k===1&&!rN(d,e.getBoundingClientRect())&&o(),j=!1}try{s=new IntersectionObserver(_,{...w,root:a.ownerDocument})}catch{s=new IntersectionObserver(_,w)}s.observe(e)}return o(!0),i}function bI(e,t,s,r){r===void 0&&(r={});const{ancestorScroll:a=!0,ancestorResize:i=!0,elementResize:o=typeof ResizeObserver=="function",layoutShift:l=typeof IntersectionObserver=="function",animationFrame:c=!1}=r,d=ly(e),u=a||i?[...d?wd(d):[],...wd(t)]:[];u.forEach(v=>{a&&v.addEventListener("scroll",s,{passive:!0}),i&&v.addEventListener("resize",s)});const m=d&&l?yI(d,s):null;let p=-1,f=null;o&&(f=new ResizeObserver(v=>{let[y]=v;y&&y.target===d&&f&&(f.unobserve(t),cancelAnimationFrame(p),p=requestAnimationFrame(()=>{var w;(w=f)==null||w.observe(t)})),s()}),d&&!c&&f.observe(d),f.observe(t));let g,x=c?Zi(e):null;c&&b();function b(){const v=Zi(e);x&&!rN(x,v)&&s(),x=v,g=requestAnimationFrame(b)}return s(),()=>{var v;u.forEach(y=>{a&&y.removeEventListener("scroll",s),i&&y.removeEventListener("resize",s)}),m==null||m(),(v=f)==null||v.disconnect(),f=null,c&&cancelAnimationFrame(g)}}
vendor: 6,777 bytes, line 52
52const wI=HL,jI=WL,_I=BL,kI=YL,NI=VL,tw=UL,SI=GL,CI=(e,t,s)=>{const r=new Map,a={platform:vI,...s},i={...a.platform,_c:r};return FL(e,t,{...a,platform:i})};var TI=typeof document<"u",PI=function(){},_h=TI?h.useLayoutEffect:PI;function lm(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let s,r,a;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(s=e.length,s!==t.length)return!1;for(r=s;r--!==0;)if(!lm(e[r],t[r]))return!1;return!0}if(a=Object.keys(e),s=a.length,s!==Object.keys(t).length)return!1;for(r=s;r--!==0;)if(!{}.hasOwnProperty.call(t,a[r]))return!1;for(r=s;r--!==0;){const i=a[r];if(!(i==="_owner"&&e.$$typeof)&&!lm(e[i],t[i]))return!1}return!0}return e!==e&&t!==t}function aN(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function sw(e,t){const s=aN(e);return Math.round(t*s)/s}function vf(e){const t=h.useRef(e);return _h(()=>{t.current=e}),t}function EI(e){e===void 0&&(e={});const{placement:t="bottom",strategy:s="absolute",middleware:r=[],platform:a,elements:{reference:i,floating:o}={},transform:l=!0,whileElementsMounted:c,open:d}=e,[u,m]=h.useState({x:0,y:0,strategy:s,placement:t,middlewareData:{},isPositioned:!1}),[p,f]=h.useState(r);lm(p,r)||f(r);const[g,x]=h.useState(null),[b,v]=h.useState(null),y=h.useCallback(R=>{R!==N.current&&(N.current=R,x(R))},[]),w=h.useCallback(R=>{R!==k.current&&(k.current=R,v(R))},[]),j=i||g,_=o||b,N=h.useRef(null),k=h.useRef(null),S=h.useRef(u),T=c!=null,C=vf(c),B=vf(a),E=vf(d),H=h.useCallback(()=>{if(!N.current||!k.current)return;const R={placement:t,strategy:s,middleware:p};B.current&&(R.platform=B.current),CI(N.current,k.current,R).then(F=>{const $={...F,isPositioned:E.current!==!1};z.current&&!lm(S.current,$)&&(S.current=$,Jl.flushSync(()=>{m($)}))})},[p,t,s,B,E]);_h(()=>{d===!1&&S.current.isPositioned&&(S.current.isPositioned=!1,m(R=>({...R,isPositioned:!1})))},[d]);const z=h.useRef(!1);_h(()=>(z.current=!0,()=>{z.current=!1}),[]),_h(()=>{if(j&&(N.current=j),_&&(k.current=_),j&&_){if(C.current)return C.current(j,_,H);H()}},[j,_,H,C,T]);const ne=h.useMemo(()=>({reference:N,floating:k,setReference:y,setFloating:w}),[y,w]),V=h.useMemo(()=>({reference:j,floating:_}),[j,_]),te=h.useMemo(()=>{const R={position:s,left:0,top:0};if(!V.floating)return R;const F=sw(V.floating,u.x),$=sw(V.floating,u.y);return l?{...R,transform:"translate("+F+"px, "+$+"px)",...aN(V.floating)>=1.5&&{willChange:"transform"}}:{position:s,left:F,top:$}},[s,l,V.floating,u.x,u.y]);return h.useMemo(()=>({...u,update:H,refs:ne,elements:V,floatingStyles:te}),[u,H,ne,V,te])}const AI=e=>{function t(s){return{}.hasOwnProperty.call(s,"current")}return{name:"arrow",options:e,fn(s){const{element:r,padding:a}=typeof e=="function"?e(s):e;return r&&t(r)?r.current!=null?tw({element:r.current,padding:a}).fn(s):{}:r?tw({element:r,padding:a}).fn(s):{}}}},RI=(e,t)=>({...wI(e),options:[e,t]}),$I=(e,t)=>({...jI(e),options:[e,t]}),LI=(e,t)=>({...SI(e),options:[e,t]}),II=(e,t)=>({..._I(e),options:[e,t]}),OI=(e,t)=>({...kI(e),options:[e,t]}),DI=(e,t)=>({...NI(e),options:[e,t]}),MI=(e,t)=>({...AI(e),options:[e,t]});var zI="Arrow",iN=h.forwardRef((e,t)=>{const{children:s,width:r=10,height:a=5,...i}=e;return n.jsx(qe.svg,{...i,ref:t,width:r,height:a,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?s:n.jsx("polygon",{points:"0,0 30,0 15,10"})})});iN.displayName=zI;var FI=iN;function dy(e){const[t,s]=h.useState(void 0);return cs(()=>{if(e){s({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(a=>{if(!Array.isArray(a)||!a.length)return;const i=a[0];let o,l;if("borderBoxSize"in i){const c=i.borderBoxSize,d=Array.isArray(c)?c[0]:c;o=d.inlineSize,l=d.blockSize}else o=e.offsetWidth,l=e.offsetHeight;s({width:o,height:l})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else s(void 0)},[e]),t}var uy="Popper",[oN,gi]=Is(uy),[UI,lN]=oN(uy),cN=e=>{const{__scopePopper:t,children:s}=e,[r,a]=h.useState(null);return n.jsx(UI,{scope:t,anchor:r,onAnchorChange:a,children:s})};cN.displayName=uy;var dN="PopperAnchor",uN=h.forwardRef((e,t)=>{const{__scopePopper:s,virtualRef:r,...a}=e,i=lN(dN,s),o=h.useRef(null),l=bt(t,o);return h.useEffect(()=>{i.onAnchorChange((r==null?void 0:r.current)||o.current)}),r?null:n.jsx(qe.div,{...a,ref:l})});uN.displayName=dN;var hy="PopperContent",[BI,VI]=oN(hy),hN=h.forwardRef((e,t)=>{var A,oe,ue,je,ae,ie;const{__scopePopper:s,side:r="bottom",sideOffset:a=0,align:i="center",alignOffset:o=0,arrowPadding:l=0,avoidCollisions:c=!0,collisionBoundary:d=[],collisionPadding:u=0,sticky:m="partial",hideWhenDetached:p=!1,updatePositionStrategy:f="optimized",onPlaced:g,...x}=e,b=lN(hy,s),[v,y]=h.useState(null),w=bt(t,we=>y(we)),[j,_]=h.useState(null),N=dy(j),k=(N==null?void 0:N.width)??0,S=(N==null?void 0:N.height)??0,T=r+(i!=="center"?"-"+i:""),C=typeof u=="number"?u:{top:0,right:0,bottom:0,left:0,...u},B=Array.isArray(d)?d:[d],E=B.length>0,H={padding:C,boundary:B.filter(HI),altBoundary:E},{refs:z,floatingStyles:ne,placement:V,isPositioned:te,middlewareData:R}=EI({strategy:"fixed",placement:T,whileElementsMounted:(...we)=>bI(...we,{animationFrame:f==="always"}),elements:{reference:b.anchor},middleware:[RI({mainAxis:a+S,alignmentAxis:o}),c&&$I({mainAxis:!0,crossAxis:!1,limiter:m==="partial"?LI():void 0,...H}),c&&II({...H}),OI({...H,apply:({elements:we,rects:Ae,availableWidth:nt,availableHeight:Qe})=>{const{width:P,height:U}=Ae.reference,Q=we.floating.style;Q.setProperty("--radix-popper-available-width",`${nt}px`),Q.setProperty("--radix-popper-available-height",`${Qe}px`),Q.setProperty("--radix-popper-anchor-width",`${P}px`),Q.setProperty("--radix-popper-anchor-height",`${U}px`)}}),j&&MI({element:j,padding:l}),WI({arrowWidth:k,arrowHeight:S}),p&&DI({strategy:"referenceHidden",...H})]}),[F,$]=fN(V),J=Zn(g);cs(()=>{te&&(J==null||J())},[te,J]);const Y=(A=R.arrow)==null?void 0:A.x,re=(oe=R.arrow)==null?void 0:oe.y,G=((ue=R.arrow)==null?void 0:ue.centerOffset)!==0,[O,Z]=h.useState();return cs(()=>{v&&Z(window.getComputedStyle(v).zIndex)},[v]),n.jsx("div",{ref:z.setFloating,"data-radix-popper-content-wrapper":"",style:{...ne,transform:te?ne.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:O,"--radix-popper-transform-origin":[(je=R.transformOrigin)==null?void 0:je.x,(ae=R.transformOrigin)==null?void 0:ae.y].join(" "),...((ie=R.hide)==null?void 0:ie.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:n.jsx(BI,{scope:s,placedSide:F,onArrowChange:_,arrowX:Y,arrowY:re,shouldHideArrow:G,children:n.jsx(qe.div,{"data-side":F,"data-align":$,...x,ref:w,style:{...x.style,animation:te?void 0:"none"}})})})});hN.displayName=hy;var mN="PopperArrow",qI={top:"bottom",right:"left",bottom:"top",left:"r
52ight"},pN=h.forwardRef(function(t,s){const{__scopePopper:r,...a}=t,i=VI(mN,r),o=qI[i.placedSide];return n.jsx("span",{ref:i.onArrowChange,style:{position:"absolute",left:i.arrowX,top:i.arrowY,[o]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[i.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[i.placedSide],visibility:i.shouldHideArrow?"hidden":void 0},children:n.jsx(FI,{...a,ref:s,style:{...a.style,display:"block"}})})});pN.displayName=mN;function HI(e){return e!==null}var WI=e=>({name:"transformOrigin",options:e,fn(t){var b,v,y;const{placement:s,rects:r,middlewareData:a}=t,o=((b=a.arrow)==null?void 0:b.centerOffset)!==0,l=o?0:e.arrowWidth,c=o?0:e.arrowHeight,[d,u]=fN(s),m={start:"0%",center:"50%",end:"100%"}[u],p=(((v=a.arrow)==null?void 0:v.x)??0)+l/2,f=(((y=a.arrow)==null?void 0:y.y)??0)+c/2;let g="",x="";return d==="bottom"?(g=o?m:`${p}px`,x=`${-c}px`):d==="top"?(g=o?m:`${p}px`,x=`${r.floating.height+c}px`):d==="right"?(g=`${-c}px`,x=o?m:`${f}px`):d==="left"&&(g=`${r.floating.width+c}px`,x=o?m:`${f}px`),{data:{x:g,y:x}}}});function fN(e){const[t,s="center"]=e.split("-");return[t,s]}var tp=cN,nu=uN,sp=hN,np=pN,GI="Portal",ru=h.forwardRef((e,t)=>{var l;const{container:s,...r}=e,[a,i]=h.useState(!1);cs(()=>i(!0),[]);const o=s||a&&((l=globalThis==null?void 0:globalThis.document)==null?void 0:l.body);return o?wk.createPortal(n.jsx(qe.div,{...r,ref:t}),o):null});ru.displayName=GI;function YI(e,t){return h.useReducer((s,r)=>t[s][r]??s,e)}var sn=e=>{const{present:t,children:s}=e,r=KI(t),a=typeof s=="function"?s({present:r.isPresent}):h.Children.only(s),i=bt(r.ref,QI(a));return typeof s=="function"||r.isPresent?h.cloneElement(a,{ref:i}):null};sn.displayName="Presence";function KI(e){const[t,s]=h.useState(),r=h.useRef(null),a=h.useRef(e),i=h.useRef("none"),o=e?"mounted":"unmounted",[l,c]=YI(o,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return h.useEffect(()=>{const d=Gu(r.current);i.current=l==="mounted"?d:"none"},[l]),cs(()=>{const d=r.current,u=a.current;if(u!==e){const p=i.current,f=Gu(d);e?c("MOUNT"):f==="none"||(d==null?void 0:d.display)==="none"?c("UNMOUNT"):c(u&&p!==f?"ANIMATION_OUT":"UNMOUNT"),a.current=e}},[e,c]),cs(()=>{if(t){let d;const u=t.ownerDocument.defaultView??window,m=f=>{const x=Gu(r.current).includes(f.animationName);if(f.target===t&&x&&(c("ANIMATION_END"),!a.current)){const b=t.style.animationFillMode;t.style.animationFillMode="forwards",d=u.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=b)})}},p=f=>{f.target===t&&(i.current=Gu(r.current))};return t.addEventListener("animationstart",p),t.addEventListener("animationcancel",m),t.addEventListener("animationend",m),()=>{u.clearTimeout(d),t.removeEventListener("animationstart",p),t.removeEventListener("animationcancel",m),t.removeEventListener("animationend",m)}}else c("ANIMATION_END")},[t,c]),{isPresent:["mounted","unmountSuspended"].includes(l),ref:h.useCallback(d=>{r.current=d?getComputedStyle(d):null,s(d)},[])}}function Gu(e){return(e==null?void 0:e.animationName)||"none"}function QI(e){var r,a;let t=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,s=t&&"isReactWarning"in t&&t.isReactWarning;return s?e.ref:(t=(a=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:a.get,s=t&&"isReactWarning"in t&&t.isReactWarning,s?e.props.ref:e.props.ref||e.ref)}var JI=iv[" useInsertionEffect ".trim().toString()]||cs;function tr({prop:e,defaultProp:t,onChange:s=()=>{},caller:r}){const[a,i,o]=ZI({defaultProp:t,onChange:s}),l=e!==void 0,c=l?e:a;{const u=h.useRef(e!==void 0);h.useEffect(()=>{const m=u.current;m!==l&&console.warn(`${r} is changing from ${m?"controlled":"uncontrolled"} to ${l?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),u.current=l},[l,r])}const d=h.useCallback(u=>{var m;if(l){const p=XI(u)?u(e):u;p!==e&&((m=o.current)==null||m.call(o,p))}else i(u)},[l,e,i,o]);return[c,d]}function ZI({defaultProp:e,onChange:t}){const[s,r]=h.useState(e),a=h.useRef(s),i=h.useRef(t);return JI(()=>{i.current=t},[t]),h.useEffect(()=>{var o;a.current!==s&&((o=i.current)==null||o.call(i,s),a.current=s)},[s,a]),[s,r,i]}function XI(e){return typeof e=="function"}var gN=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),e5="VisuallyHidden",xN=h.forwardRef((e,t)=>
vendor: 8,517 bytes, line 52
52n.jsx(qe.span,{...e,ref:t,style:{...gN,...e.style}}));xN.displayName=e5;var t5=xN,[rp,W1e]=Is("Tooltip",[gi]),ap=gi(),vN="TooltipProvider",s5=700,xx="tooltip.open",[n5,my]=rp(vN),yN=e=>{const{__scopeTooltip:t,delayDuration:s=s5,skipDelayDuration:r=300,disableHoverableContent:a=!1,children:i}=e,o=h.useRef(!0),l=h.useRef(!1),c=h.useRef(0);return h.useEffect(()=>{const d=c.current;return()=>window.clearTimeout(d)},[]),n.jsx(n5,{scope:t,isOpenDelayedRef:o,delayDuration:s,onOpen:h.useCallback(()=>{window.clearTimeout(c.current),o.current=!1},[]),onClose:h.useCallback(()=>{window.clearTimeout(c.current),c.current=window.setTimeout(()=>o.current=!0,r)},[r]),isPointerInTransitRef:l,onPointerInTransitChange:h.useCallback(d=>{l.current=d},[]),disableHoverableContent:a,children:i})};yN.displayName=vN;var jd="Tooltip",[r5,ip]=rp(jd),bN=e=>{const{__scopeTooltip:t,children:s,open:r,defaultOpen:a,onOpenChange:i,disableHoverableContent:o,delayDuration:l}=e,c=my(jd,e.__scopeTooltip),d=ap(t),[u,m]=h.useState(null),p=pn(),f=h.useRef(0),g=o??c.disableHoverableContent,x=l??c.delayDuration,b=h.useRef(!1),[v,y]=tr({prop:r,defaultProp:a??!1,onChange:k=>{k?(c.onOpen(),document.dispatchEvent(new CustomEvent(xx))):c.onClose(),i==null||i(k)},caller:jd}),w=h.useMemo(()=>v?b.current?"delayed-open":"instant-open":"closed",[v]),j=h.useCallback(()=>{window.clearTimeout(f.current),f.current=0,b.current=!1,y(!0)},[y]),_=h.useCallback(()=>{window.clearTimeout(f.current),f.current=0,y(!1)},[y]),N=h.useCallback(()=>{window.clearTimeout(f.current),f.current=window.setTimeout(()=>{b.current=!0,y(!0),f.current=0},x)},[x,y]);return h.useEffect(()=>()=>{f.current&&(window.clearTimeout(f.current),f.current=0)},[]),n.jsx(tp,{...d,children:n.jsx(r5,{scope:t,contentId:p,open:v,stateAttribute:w,trigger:u,onTriggerChange:m,onTriggerEnter:h.useCallback(()=>{c.isOpenDelayedRef.current?N():j()},[c.isOpenDelayedRef,N,j]),onTriggerLeave:h.useCallback(()=>{g?_():(window.clearTimeout(f.current),f.current=0)},[_,g]),onOpen:j,onClose:_,disableHoverableContent:g,children:s})})};bN.displayName=jd;var vx="TooltipTrigger",wN=h.forwardRef((e,t)=>{const{__scopeTooltip:s,...r}=e,a=ip(vx,s),i=my(vx,s),o=ap(s),l=h.useRef(null),c=bt(t,l,a.onTriggerChange),d=h.useRef(!1),u=h.useRef(!1),m=h.useCallback(()=>d.current=!1,[]);return h.useEffect(()=>()=>document.removeEventListener("pointerup",m),[m]),n.jsx(nu,{asChild:!0,...o,children:n.jsx(qe.button,{"aria-describedby":a.open?a.contentId:void 0,"data-state":a.stateAttribute,...r,ref:c,onPointerMove:Ee(e.onPointerMove,p=>{p.pointerType!=="touch"&&!u.current&&!i.isPointerInTransitRef.current&&(a.onTriggerEnter(),u.current=!0)}),onPointerLeave:Ee(e.onPointerLeave,()=>{a.onTriggerLeave(),u.current=!1}),onPointerDown:Ee(e.onPointerDown,()=>{a.open&&a.onClose(),d.current=!0,document.addEventListener("pointerup",m,{once:!0})}),onFocus:Ee(e.onFocus,()=>{d.current||a.onOpen()}),onBlur:Ee(e.onBlur,a.onClose),onClick:Ee(e.onClick,a.onClose)})})});wN.displayName=vx;var a5="TooltipPortal",[G1e,i5]=rp(a5,{forceMount:void 0}),$l="TooltipContent",jN=h.forwardRef((e,t)=>{const s=i5($l,e.__scopeTooltip),{forceMount:r=s.forceMount,side:a="top",...i}=e,o=ip($l,e.__scopeTooltip);return n.jsx(sn,{present:r||o.open,children:o.disableHoverableContent?n.jsx(_N,{side:a,...i,ref:t}):n.jsx(o5,{side:a,...i,ref:t})})}),o5=h.forwardRef((e,t)=>{const s=ip($l,e.__scopeTooltip),r=my($l,e.__scopeTooltip),a=h.useRef(null),i=bt(t,a),[o,l]=h.useState(null),{trigger:c,onClose:d}=s,u=a.current,{onPointerInTransitChange:m}=r,p=h.useCallback(()=>{l(null),m(!1)},[m]),f=h.useCallback((g,x)=>{const b=g.currentTarget,v={x:g.clientX,y:g.clientY},y=h5(v,b.getBoundingClientRect()),w=m5(v,y),j=p5(x.getBoundingClientRect()),_=g5([...w,...j]);l(_),m(!0)},[m]);return h.useEffect(()=>()=>p(),[p]),h.useEffect(()=>{if(c&&u){const g=b=>f(b,u),x=b=>f(b,c);return c.addEventListener("pointerleave",g),u.addEventListener("pointerleave",x),()=>{c.removeEventListener("pointerleave",g),u.removeEventListener("pointerleave",x)}}},[c,u,f,p]),h.useEffect(()=>{if(o){const g=x=>{const b=x.target,v={x:x.clientX,y:x.clientY},y=(c==null?void 0:c.contains(b))||(u==null?void 0:u.contains(b)),w=!f5(v,o);y?p():w&&(p(),d())};return document.addEventListener("pointermove",g),()=>document.removeEventListener("pointermove",g)}},[c,u,o,d,p]),n.jsx(_N,{...e,ref:i})}),[l5,c5]=rp(jd,{isInside:!1}),d5=Hk("TooltipContent"),_N=h.forwardRef((e,t)=>{const{__scopeTooltip:s,children:r,"aria-label":a,onEscapeKeyDown:i,onPointerDownOutside:o,...l}=e,c=ip($l,s),d=ap(s),{onClose:u}=c;return h.useEffect(()=>(document.addEventListener(xx,u),()=>document.removeEventListener(xx,u)),[u]),h.useEffect(()=>{if(c.trigger){const m=p=>{const f=p.target;f!=null&&f.contains(c.trigger)&&u()};return window.addEventListener("scroll",m,{capture:!0}),()=>window.removeEventListener("scroll",m,{capture:!0})}},[c.trigger,u]),n.jsx(tc,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:i,onPointerDownOutside:o,onFocusOutside:m=>m.preventDefault(),onDismiss:u,children:n.jsxs(sp,{"data-state":c.stateAttribute,...d,...l,ref:t,style:{...l.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[n.jsx(d5,{children:r}),n.jsx(l5,{scope:s,isInside:!0,children:n.jsx(t5,{id:c.contentId,role:"tooltip",children:a||r})})]})})});jN.displayName=$l;var kN="TooltipArrow",u5=h.forwardRef((e,t)=>{const{__scopeTooltip:s,...r}=e,a=ap(s);return c5(kN,s).isInside?null:n.jsx(np,{...a,...r,ref:t})});u5.displayName=kN;function h5(e,t){const s=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),a=Math.abs(t.right-e.x),i=Math.abs(t.left-e.x);switch(Math.min(s,r,a,i)){case i:return"left";case a:return"right";case s:return"top";case r:return"bottom";default:throw new Error("unreachable")}}function m5(e,t,s=5){const r=[];switch(t){case"top":r.push({x:e.x-s,y:e.y+s},{x:e.x+s,y:e.y+s});break;case"bottom":r.push({x:e.x-s,y:e.y-s},{x:e.x+s,y:e.y-s});break;case"left":r.push({x:e.x+s,y:e.y-s},{x:e.x+s,y:e.y+s});break;case"right":r.push({x:e.x-s,y:e.y-s},{x:e.x-s,y:e.y+s});break}return r}function p5(e){const{top:t,right:s,bottom:r,left:a}=e;return[{x:a,y:t},{x:s,y:t},{x:s,y:r},{x:a,y:r}]}function f5(e,t){const{x:s,y:r}=e;let a=!1;for(let i=0,o=t.length-1;i<t.length;o=i++){const l=t[i],c=t[o],d=l.x,u=l.y,m=c.x,p=c.y;u>r!=p>r&&s<(m-d)*(r-u)/(p-u)+d&&(a=!a)}return a}function g5(e){const t=e.slice();return t.sort((s,r)=>s.x<r.x?-1:s.x>r.x?1:s.y<r.y?-1:s.y>r.y?1:0),x5(t)}function x5(e){if(e.length<=1)return e.slice();const t=[];for(let r=0;r<e.length;r++){const a=e[r];for(;t.length>=2;){const i=t[t.length-1],o=t[t.length-2];if((i.x-o.x)*(a.y-o.y)>=(i.y-o.y)*(a.x-o.x))t.pop();else break}t.push(a)}t.pop();const s=[];for(let r=e.length-1;r>=0;r--){const a=e[r];for(;s.length>=2;){const i=s[s.length-1],o=s[s.length-2];if((i.x-o.x)*(a.y-o.y)>=(i.y-o.y)*(a.x-o.x))s.pop();else break}s.push(a)}return s.pop(),t.length===1&&s.length===1&&t[0].x===s[0].x&&t[0].y===s[0].y?t:t.concat(s)}var v5=yN,y5=bN,b5=wN,NN=jN;function SN(e){var t,s,r="";if(typeof e=="string"||typeof e=="number")r+=e;else if(typeof e=="object")if(Array.isArray(e)){var a=e.length;for(t=0;t<a;t++)e[t]&&(s=SN(e[t]))&&(r&&(r+=" "),r+=s)}else for(s in e)e[s]&&(r&&(r+=" "),r+=s);return r}function CN(){for(var e,t,s=0,r="",a=arguments.length;s<a;s++)(e=arguments[s])&&(t=SN(e))&&(r&&(r+=" "),r+=t);return r}const py="-",w5=e=>{const t=_5(e),{conflictingClassGroups:s,conflictingClassGroupModifiers:r}=e;return{getClassGroupId:o=>{const l=o.split(py);return l[0]===""&&l.length!==1&&l.shift(),TN(l,t)||j5(o)},getConflictingClassGroupIds:(o,l)=>{const c=s[o]||[];return l&&r[o]?[...c,...r[o]]:c}}},TN=(e,t)=>{var o;if(e.length===0)return t.classGroupId;const s=e[0],r=t.nextPart.get(s),a=r?TN(e.slice(1),r):void 0;if(a)return a;if(t.validators.length===0)return;const i=e.join(py);return(o=t.validators.find(({validator:l})=>l(i)))==null?void 0:o.classGroupId},nw=/^\[(.+)\]$/,j5=e=>{if(nw.test(e)){const t=nw.exec(e)[1],s=t==null?void 0:t.substring(0,t.indexOf(":"));if(s)return"arbitrary.."+s}},_5=e=>{const{theme:t,prefix:s}=e,r={nextPart:new Map,validators:[]};return N5(Object.entries(e.classGroups),s).forEach(([i,o])=>{yx(o,r,i,t)}),r},yx=(e,t,s,r)=>{e.forEach(a=>
vendor: 4,467 bytes, line 52
52{if(typeof a=="string"){const i=a===""?t:rw(t,a);i.classGroupId=s;return}if(typeof a=="function"){if(k5(a)){yx(a(r),t,s,r);return}t.validators.push({validator:a,classGroupId:s});return}Object.entries(a).forEach(([i,o])=>{yx(o,rw(t,i),s,r)})})},rw=(e,t)=>{let s=e;return t.split(py).forEach(r=>{s.nextPart.has(r)||s.nextPart.set(r,{nextPart:new Map,validators:[]}),s=s.nextPart.get(r)}),s},k5=e=>e.isThemeGetter,N5=(e,t)=>t?e.map(([s,r])=>{const a=r.map(i=>typeof i=="string"?t+i:typeof i=="object"?Object.fromEntries(Object.entries(i).map(([o,l])=>[t+o,l])):i);return[s,a]}):e,S5=e=>{if(e<1)return{get:()=>{},set:()=>{}};let t=0,s=new Map,r=new Map;const a=(i,o)=>{s.set(i,o),t++,t>e&&(t=0,r=s,s=new Map)};return{get(i){let o=s.get(i);if(o!==void 0)return o;if((o=r.get(i))!==void 0)return a(i,o),o},set(i,o){s.has(i)?s.set(i,o):a(i,o)}}},PN="!",C5=e=>{const{separator:t,experimentalParseClassName:s}=e,r=t.length===1,a=t[0],i=t.length,o=l=>{const c=[];let d=0,u=0,m;for(let b=0;b<l.length;b++){let v=l[b];if(d===0){if(v===a&&(r||l.slice(b,b+i)===t)){c.push(l.slice(u,b)),u=b+i;continue}if(v==="/"){m=b;continue}}v==="["?d++:v==="]"&&d--}const p=c.length===0?l:l.substring(u),f=p.startsWith(PN),g=f?p.substring(1):p,x=m&&m>u?m-u:void 0;return{modifiers:c,hasImportantModifier:f,baseClassName:g,maybePostfixModifierPosition:x}};return s?l=>s({className:l,parseClassName:o}):o},T5=e=>{if(e.length<=1)return e;const t=[];let s=[];return e.forEach(r=>{r[0]==="["?(t.push(...s.sort(),r),s=[]):s.push(r)}),t.push(...s.sort()),t},P5=e=>({cache:S5(e.cacheSize),parseClassName:C5(e),...w5(e)}),E5=/\s+/,A5=(e,t)=>{const{parseClassName:s,getClassGroupId:r,getConflictingClassGroupIds:a}=t,i=[],o=e.trim().split(E5);let l="";for(let c=o.length-1;c>=0;c-=1){const d=o[c],{modifiers:u,hasImportantModifier:m,baseClassName:p,maybePostfixModifierPosition:f}=s(d);let g=!!f,x=r(g?p.substring(0,f):p);if(!x){if(!g){l=d+(l.length>0?" "+l:l);continue}if(x=r(p),!x){l=d+(l.length>0?" "+l:l);continue}g=!1}const b=T5(u).join(":"),v=m?b+PN:b,y=v+x;if(i.includes(y))continue;i.push(y);const w=a(x,g);for(let j=0;j<w.length;++j){const _=w[j];i.push(v+_)}l=d+(l.length>0?" "+l:l)}return l};function R5(){let e=0,t,s,r="";for(;e<arguments.length;)(t=arguments[e++])&&(s=EN(t))&&(r&&(r+=" "),r+=s);return r}const EN=e=>{if(typeof e=="string")return e;let t,s="";for(let r=0;r<e.length;r++)e[r]&&(t=EN(e[r]))&&(s&&(s+=" "),s+=t);return s};function $5(e,...t){let s,r,a,i=o;function o(c){const d=t.reduce((u,m)=>m(u),e());return s=P5(d),r=s.cache.get,a=s.cache.set,i=l,l(c)}function l(c){const d=r(c);if(d)return d;const u=A5(c,s);return a(c,u),u}return function(){return i(R5.apply(null,arguments))}}const Lt=e=>{const t=s=>s[e]||[];return t.isThemeGetter=!0,t},AN=/^\[(?:([a-z-]+):)?(.+)\]$/i,L5=/^\d+\/\d+$/,I5=new Set(["px","full","screen"]),O5=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,D5=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,M5=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,z5=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,F5=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Lr=e=>il(e)||I5.has(e)||L5.test(e),ga=e=>rc(e,"length",Y5),il=e=>!!e&&!Number.isNaN(Number(e)),yf=e=>rc(e,"number",il),yc=e=>!!e&&Number.isInteger(Number(e)),U5=e=>e.endsWith("%")&&il(e.slice(0,-1)),mt=e=>AN.test(e),xa=e=>O5.test(e),B5=new Set(["length","size","percentage"]),V5=e=>rc(e,B5,RN),q5=e=>rc(e,"position",RN),H5=new Set(["image","url"]),W5=e=>rc(e,H5,Q5),G5=e=>rc(e,"",K5),bc=()=>!0,rc=(e,t,s)=>{const r=AN.exec(e);return r?r[1]?typeof t=="string"?r[1]===t:t.has(r[1]):s(r[2]):!1},Y5=e=>D5.test(e)&&!M5.test(e),RN=()=>!1,K5=e=>z5.test(e),Q5=e=>F5.test(e),J5=()=>{const e=Lt("colors"),t=Lt("spacing"),s=Lt("blur"),r=Lt("brightness"),a=Lt("borderColor"),i=Lt("borderRadius"),o=Lt("borderSpacing"),l=Lt("borderWidth"),c=Lt("contrast"),d=Lt("grayscale"),u=Lt("hueRotate"),m=Lt("invert"),p=Lt("gap"),f=Lt("gradientColorStops"),g=Lt("gradientColorStopPositions"),x=Lt("inset"),b=Lt("margin"),v=Lt("opacity"),y=Lt("padding"),w=Lt("saturate"),j=Lt("scale"),_=Lt("sepia"),N=Lt("skew"),k=Lt("space"),S=Lt("translate"),T=()=>["auto","contain","none"],C=()=>["auto","hidden","clip","visible","scroll"],B=()=>["auto",mt,t],E=()=>[mt,t],H=()=>["",Lr,ga],z=()=>["auto",il,mt],ne=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],
vendor: 12,076 bytes, line 52
52V=()=>["solid","dashed","dotted","double","none"],te=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],R=()=>["start","end","center","between","around","evenly","stretch"],F=()=>["","0",mt],$=()=>["auto","avoid","all","avoid-page","page","left","right","column"],J=()=>[il,mt];return{cacheSize:500,separator:":",theme:{colors:[bc],spacing:[Lr,ga],blur:["none","",xa,mt],brightness:J(),borderColor:[e],borderRadius:["none","","full",xa,mt],borderSpacing:E(),borderWidth:H(),contrast:J(),grayscale:F(),hueRotate:J(),invert:F(),gap:E(),gradientColorStops:[e],gradientColorStopPositions:[U5,ga],inset:B(),margin:B(),opacity:J(),padding:E(),saturate:J(),scale:J(),sepia:F(),skew:J(),space:E(),translate:E()},classGroups:{aspect:[{aspect:["auto","square","video",mt]}],container:["container"],columns:[{columns:[xa]}],"break-after":[{"break-after":$()}],"break-before":[{"break-before":$()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...ne(),mt]}],overflow:[{overflow:C()}],"overflow-x":[{"overflow-x":C()}],"overflow-y":[{"overflow-y":C()}],overscroll:[{overscroll:T()}],"overscroll-x":[{"overscroll-x":T()}],"overscroll-y":[{"overscroll-y":T()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[x]}],"inset-x":[{"inset-x":[x]}],"inset-y":[{"inset-y":[x]}],start:[{start:[x]}],end:[{end:[x]}],top:[{top:[x]}],right:[{right:[x]}],bottom:[{bottom:[x]}],left:[{left:[x]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",yc,mt]}],basis:[{basis:B()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",mt]}],grow:[{grow:F()}],shrink:[{shrink:F()}],order:[{order:["first","last","none",yc,mt]}],"grid-cols":[{"grid-cols":[bc]}],"col-start-end":[{col:["auto",{span:["full",yc,mt]},mt]}],"col-start":[{"col-start":z()}],"col-end":[{"col-end":z()}],"grid-rows":[{"grid-rows":[bc]}],"row-start-end":[{row:["auto",{span:[yc,mt]},mt]}],"row-start":[{"row-start":z()}],"row-end":[{"row-end":z()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",mt]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",mt]}],gap:[{gap:[p]}],"gap-x":[{"gap-x":[p]}],"gap-y":[{"gap-y":[p]}],"justify-content":[{justify:["normal",...R()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...R(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...R(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[y]}],px:[{px:[y]}],py:[{py:[y]}],ps:[{ps:[y]}],pe:[{pe:[y]}],pt:[{pt:[y]}],pr:[{pr:[y]}],pb:[{pb:[y]}],pl:[{pl:[y]}],m:[{m:[b]}],mx:[{mx:[b]}],my:[{my:[b]}],ms:[{ms:[b]}],me:[{me:[b]}],mt:[{mt:[b]}],mr:[{mr:[b]}],mb:[{mb:[b]}],ml:[{ml:[b]}],"space-x":[{"space-x":[k]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[k]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",mt,t]}],"min-w":[{"min-w":[mt,t,"min","max","fit"]}],"max-w":[{"max-w":[mt,t,"none","full","min","max","fit","prose",{screen:[xa]},xa]}],h:[{h:[mt,t,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[mt,t,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[mt,t,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[mt,t,"auto","min","max","fit"]}],"font-size":[{text:["base",xa,ga]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",yf]}],"font-family":[{font:[bc]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:["tighter","tight","normal","wide","wider","widest",mt]}],"line-clamp":[{"line-clamp":["none",il,yf]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",Lr,mt]}],"list-image":[{"list-image":["none",mt]}],"list-style-type":[{list:["none","disc","decimal",mt]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[e]}],"placeholder-opacity":[{"placeholder-opacity":[v]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[e]}],"text-opacity":[{"text-opacity":[v]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...V(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",Lr,ga]}],"underline-offset":[{"underline-offset":["auto",Lr,mt]}],"text-decoration-color":[{decoration:[e]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:E()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",mt]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",mt]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[v]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...ne(),q5]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",V5]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},W5]}],"bg-color":[{bg:[e]}],"gradient-from-pos":[{from:[g]}],"gradient-via-pos":[{via:[g]}],"gradient-to-pos":[{to:[g]}],"gradient-from":[{from:[f]}],"gradient-via":[{via:[f]}],"gradient-to":[{to:[f]}],rounded:[{rounded:[i]}],"rounded-s":[{"rounded-s":[i]}],"rounded-e":[{"rounded-e":[i]}],"rounded-t":[{"rounded-t":[i]}],"rounded-r":[{"rounded-r":[i]}],"rounded-b":[{"rounded-b":[i]}],"rounded-l":[{"rounded-l":[i]}],"rounded-ss":[{"rounded-ss":[i]}],"rounded-se":[{"rounded-se":[i]}],"rounded-ee":[{"rounded-ee":[i]}],"rounded-es":[{"rounded-es":[i]}],"rounded-tl":[{"rounded-tl":[i]}],"rounded-tr":[{"rounded-tr":[i]}],"rounded-br":[{"rounded-br":[i]}],"rounded-bl":[{"rounded-bl":[i]}],"border-w":[{border:[l]}],"border-w-x":[{"border-x":[l]}],"border-w-y":[{"border-y":[l]}],"border-w-s":[{"border-s":[l]}],"border-w-e":[{"border-e":[l]}],"border-w-t":[{"border-t":[l]}],"border-w-r":[{"border-r":[l]}],"border-w-b":[{"border-b":[l]}],"border-w-l":[{"border-l":[l]}],"border-opacity":[{"border-opacity":[v]}],"border-style":[{border:[...V(),"hidden"]}],"divide-x":[{"divide-x":[l]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[l]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[v]}],"divide-style":[{divide:V()}],"border-color":[{border:[a]}],"border-color-x":[{"border-x":[a]}],"border-color-y":[{"border-y":[a]}],"border-color-s":[{"border-s":[a]}],"border-color-e":[{"border-e":[a]}],"border-color-t":[{"border-t":[a]}],"border-color-r":[{"border-r":[a]}],"border-color-b":[{"border-b":[a]}],"border-color-l":[{"border-l":[a]}],"divide-color":[{divide:[a]}],"outline-style":[{outline:["",...V()]}],"outline-offset":[{"outline-offset":[Lr,mt]}],"outline-w":[{outline:[Lr,ga]}],"outline-color":[{outline:[e]}],"ring-w":[{ring:H()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[e]}],"ring-opacity":[{"ring-opacity":[v]}],"ring-offset-w":[{"ring-offset":[Lr,ga]}],"ring-offset-color":[{"ring-offset":[e]}],shadow:[{shadow:["","inner","none",xa,G5]}],"shadow-color":[{shadow:[bc]}],opacity:[{opacity:[v]}],"mix-blend":[{"mix-blend":[...te(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":te()}],filter:[{filter:["","none"]}],blur:[{blur:[s]}],brightness:[{brightness:[r]}],contrast:[{contrast:[c]}],"drop-shadow":[{"drop-shadow":["","none",xa,mt]}],grayscale:[{grayscale:[d]}],"hue-rotate":[{"hue-rotate":[u]}],invert:[{invert:[m]}],saturate:[{saturate:[w]}],sepia:[{sepia:[_]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[s]}],"backdrop-brightness":[{"backdrop-brightness":[r]}],"backdrop-contrast":[{"backdrop-contrast":[c]}],"backdrop-grayscale":[{"backdrop-grayscale":[d]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[u]}],"backdrop-invert":[{"backdrop-invert":[m]}],"backdrop-opacity":[{"backdrop-opacity":[v]}],"backdrop-saturate":[{"backdrop-saturate":[w]}],"backdrop-sepia":[{"backdrop-sepia":[_]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[o]}],"border-spacing-x":[{"border-spacing-x":[o]}],"border-spacing-y":[{"border-spacing-y":[o]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",mt]}],duration:[{duration:J()}],ease:[{ease:["linear","in","out","in-out",mt]}],delay:[{delay:J()}],animate:[{animate:["none","spin","ping","pulse","bounce",mt]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[j]}],"scale-x":[{"scale-x":[j]}],"scale-y":[{"scale-y":[j]}],rotate:[{rotate:[yc,mt]}],"translate-x":[{"translate-x":[S]}],"translate-y":[{"translate-y":[S]}],"skew-x":[{"skew-x":[N]}],"skew-y":[{"skew-y":[N]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",mt]}],accent:[{accent:["auto",e]}],appearance:[{appearance:["none","auto"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",mt]}],"caret-color":[{caret:[e]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":E()}],"scroll-mx":[{"scroll-mx":E()}],"scroll-my":[{"scroll-my":E()}],"scroll-ms":[{"scroll-ms":E()}],"scroll-me":[{"scroll-me":E()}],"scroll-mt":[{"scroll-mt":E()}],"scroll-mr":[{"scroll-mr":E()}],"scroll-mb":[{"scroll-mb":E()}],"scroll-ml":[{"scroll-ml":E()}],"scroll-p":[{"scroll-p":E()}],"scroll-px":[{"scroll-px":E()}],"scroll-py":[{"scroll-py":E()}],"scroll-ps":[{"scroll-ps":E()}],"scroll-pe":[{"scroll-pe":E()}],"scroll-pt":[{"scroll-pt":E()}],"scroll-pr":[{"scroll-pr":E()}],"scroll-pb":[{"scroll-pb":E()}],"scroll-pl":[{"scroll-pl":E()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}
52],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",mt]}],fill:[{fill:[e,"none"]}],"stroke-w":[{stroke:[Lr,ga,yf]}],stroke:[{stroke:[e,"none"]}],sr:["sr-only","not-sr-only"],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]}}},Z5=$5(J5);function _e(...e){return Z5(CN(e))}const $N=v5,LN=y5,IN=b5,fy=h.forwardRef(({className:e,sideOffset:t=4,...s},r)=>n.jsx(NN,{ref:r,sideOffset:t,className:_e("z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...s}));fy.displayName=NN.displayName;var vr=function(){return vr=Object.assign||function(t){for(var s,r=1,a=arguments.length;r<a;r++){s=arguments[r];for(var i in s)Object.prototype.hasOwnProperty.call(s,i)&&(t[i]=s[i])}return t},vr.apply(this,arguments)};function ac(e,t){var s={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(s[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var a=0,r=Object.getOwnPropertySymbols(e);a<r.length;a++)t.indexOf(r[a])<0&&Object.prototype.propertyIsEnumerable.call(e,r[a])&&(s[r[a]]=e[r[a]]);return s}function X5(e,t,s,r){function a(i){return i instanceof s?i:new s(function(o){o(i)})}return new(s||(s=Promise))(function(i,o){function l(u){try{d(r.next(u))}catch(m){o(m)}}function c(u){try{d(r.throw(u))}catch(m){o(m)}}function d(u){u.done?i(u.value):a(u.value).then(l,c)}d((r=r.apply(e,t||[])).next())})}
52function e3(e,t,s){if(s||arguments.length===2)for(var r=0,a=t.length,i;r<a;r++)(i||!(r in t))&&(i||(i=Array.prototype.slice.call(t,0,r)),i[r]=t[r]);return e.concat(i||Array.prototype.slice.call(t))}const t3=e=>e?(...t)=>e(...t):(...t)=>fetch(...t);class gy extends Error{constructor(t,s="FunctionsError",r){super(t),this.name=s,this.context=r}}class s3 extends gy{constructor(t){super("Failed to send a request to the Edge Function","FunctionsFetchError",t)}}class aw extends gy{constructor(t){super("Relay Error invoking the Edge Function","FunctionsRelayError",t)}}class iw extends gy{constructor(t){super("Edge Function returned a non-2xx status code","FunctionsHttpError",t)}}var bx;(function(e){e.Any="any",e.ApNortheast1="ap-northeast-1",e.ApNortheast2="ap-northeast-2",e.ApSouth1="ap-south-1",e.ApSoutheast1="ap-southeast-1",e.ApSoutheast2="ap-southeast-2",e.CaCentral1="ca-central-1",e.EuCentral1="eu-central-1",e.EuWest1="eu-west-1",e.EuWest2="eu-west-2",e.EuWest3="eu-west-3",e.SaEast1="sa-east-1",e.UsEast1="us-east-1",e.UsWest1="us-west-1",e.UsWest2="us-west-2"})(bx||(bx={}));class n3{constructor(t,{headers:s={},customFetch:r,region:a=bx.Any}={}){this.url=t,this.headers=s,this.region=a,this.fetch=t3(r)}setAuth(t){this.headers.Authorization=`Bearer ${t}`}invoke(t){return X5(this,arguments,void 0,function*(s,r={}){var a;let i,o;try{const{headers:l,method:c,body:d,signal:u,timeout:m}=r;let p={},{region:f}=r;f||(f=this.region);const g=new URL(`${this.url}/${s}`);f&&f!=="any"&&(p["x-region"]=f,g.searchParams.set("forceFunctionRegion",f));let x;d&&(l&&!Object.prototype.hasOwnProperty.call(l,"Content-Type")||!l)?typeof Blob<"u"&&d instanceof Blob||d instanceof ArrayBuffer?(p["Content-Type"]="application/octet-stream",x=d):typeof d=="string"?(p["Content-Type"]="text/plain",x=d):typeof FormData<"u"&&d instanceof FormData?x=d:(p["Content-Type"]="application/json",x=JSON.stringify(d)):d&&typeof d!="string"&&!(typeof Blob<"u"&&d instanceof Blob)&&!(d instanceof ArrayBuffer)&&!(typeof FormData<"u"&&d instanceof FormData)?x=JSON.stringify(d):x=d;let b=u;m&&(o=new AbortController,i=setTimeout(()=>o.abort(),m),u?(b=o.signal,u.addEventListener("abort",()=>o.abort())):b=o.signal);const v=yield this.fetch(g.toString(),{method:c||"POST",headers:Object.assign(Object.assign(Object.assign({},p),this.headers),l),body:x,signal:b}).catch(_=>{throw new s3(_)}),y=v.headers.get("x-relay-error");if(y&&y==="true")throw new aw(v);if(!v.ok)throw new iw(v);let w=((a=v.headers.get("Content-Type"))!==null&&a!==void 0?a:"text/plain").split(";")[0].trim(),j;return w==="application/json"?j=yield v.json():w==="application/octet-stream"||w==="application/pdf"?j=yield v.blob():w==="text/event-stream"?j=v:w==="multipart/form-data"?j=yield v.formData():j=yield v.text(),{data:j,error:null,response:v}}catch(l){return{data:null,error:l,response:l instanceof iw||l instanceof aw?l.context:void 0}}finally{i&&clearTimeout(i)}})}}var r3=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.co
52de=e.code}},a3=class{constructor(e){var t,s,r;this.shouldThrowOnError=!1,this.method=e.method,this.url=e.url,this.headers=new Headers(e.headers),this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=(t=e.shouldThrowOnError)!==null&&t!==void 0?t:!1,this.signal=e.signal,this.isMaybeSingle=(s=e.isMaybeSingle)!==null&&s!==void 0?s:!1,this.urlLengthLimit=(r=e.urlLengthLimit)!==null&&r!==void 0?r:8e3,e.fetch?this.fetch=e.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(e,t){return this.headers=new Headers(this.headers),this.headers.set(e,t),this}then(e,t){var s=this;this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),this.method!=="GET"&&this.method!=="HEAD"&&this.headers.set("Content-Type","application/json");const r=this.fetch;let a=r(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async i=>{let o=null,l=null,c=null,d=i.status,u=i.statusText;if(i.ok){var m,p;if(s.method!=="HEAD"){var f;const b=await i.text();b===""||(s.headers.get("Accept")==="text/csv"||s.headers.get("Accept")&&(!((f=s.headers.get("Accept"))===null||f===void 0)&&f.includes("application/vnd.pgrst.plan+text"))?l=b:l=JSON.parse(b))}const g=(m=s.headers.get("Prefer"))===null||m===void 0?void 0:m.match(/count=(exact|planned|estimated)/),x=(p=i.headers.get("content-range"))===null||p===void 0?void 0:p.split("/");g&&x&&x.length>1&&(c=parseInt(x[1])),s.isMaybeSingle&&Array.isArray(l)&&(l.length>1?(o={code:"PGRST116",details:`Results contain ${l.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},l=null,c=null,d=406,u="Not Acceptable"):l.length===1?l=l[0]:l=null)}else{const g=await i.text();try{o=JSON.parse(g),Array.isArray(o)&&i.status===404&&(l=[],o=null,d=200,u="OK")}catch{i.status===404&&g===""?(d=204,u="No Content"):o={message:g}}if(o&&s.shouldThrowOnError)throw new r3(o)}return{error:o,data:l,count:c,status:d,statusText:u}});return this.shouldThrowOnError||(a=a.catch(i=>{var o;let l="",c="",d="";const u=i==null?void 0:i.cause;if(u){var m,p,f,g;const v=(m=u==null?void 0:u.message)!==null&&m!==void 0?m:"",y=(p=u==null?void 0:u.code)!==null&&p!==void 0?p:"";l=`${(f=i==null?void 0:i.name)!==null&&f!==void 0?f:"FetchError"}: ${i==null?void 0:i.message}`,l+=`
53
54Caused by: ${(g=u==null?void 0:u.name)!==null&&g!==void 0?g:"Error"}: ${v}`,y&&(l+=` (${y})`),u!=null&&u.stack&&(l+=`
55${u.stack}`)}else{var x;l=(x=i==null?void 0:i.stack)!==null&&x!==void 0?x:""}const b=this.url.toString().length;return(i==null?void 0:i.name)==="AbortError"||(i==null?void 0:i.code)==="ABORT_ERR"?(d="",c="Request was aborted (timeout or manual cancellation)",b>this.urlLengthLimit&&(c+=`. Note: Your request URL is ${b} characters, which may exceed server limits. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [many IDs])), consider using an RPC function to pass values server-side.`)):((u==null?void 0:u.name)==="HeadersOverflowError"||(u==null?void 0:u.code)==="UND_ERR_HEADERS_OVERFLOW")&&(d="",c="HTTP headers exceeded server limits (typically 16KB)",b>this.urlLengthLimit&&(c+=`. Your request URL is ${b} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`)),{error:{message:`${(o=i==null?void 0:i.name)!==null&&o!==void 0?o:"FetchError"}: ${i==null?void 0:i.message}`,details:l,hint:c,code:d},data:null,count:null,status:0,statusText:""}})),a.then(e,t)}returns(){return this}overrideTypes(){return this}},i3=class extends a3{select(e){let t=!1;const s=(e??"*").split("").map(r=>/\s/.test(r)&&!t?"":(r==='"'&&(t=!t),r)).join("");return this.url.searchParams.set("select",s),this.headers.append("Prefer","return=representation"),this}order(e,{ascending:t=!0,nullsFirst:s,foreignTable:r,referencedTable:a=r}={}){const i=a?`${a}.order`:"order",o=this.url.searchParams.get(i);return this.url.searchParams.set(i,`${o?`${o},`:""}${e}.${t?"asc":"desc"}${s===void 0?"":s?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:s=t}={}){const r=typeof s>"u"?"limit":`${s}.limit`;return this.url.searchParams.set(r,`${e}`),this}range(e,t,{foreignTable:s,referencedTable:r=s}={}){const a=typeof r>"u"?"offset":`${r}.offset`,i=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(a,`${e}`),this.url.searchParams.set(i,`${t-e+1}`),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}
55explain({analyze:e=!1,verbose:t=!1,settings:s=!1,buffers:r=!1,wal:a=!1,format:i="text"}={}){var o;const l=[e?"analyze":null,t?"verbose":null,s?"settings":null,r?"buffers":null,a?"wal":null].filter(Boolean).join("|"),c=(o=this.headers.get("Accept"))!==null&&o!==void 0?o:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${i}; for="${c}"; options=${l};`),i==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(e){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${e}`),this}};const ow=new RegExp("[,()]");var Ro=class extends i3{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}regexMatch(e,t){return this.url.searchParams.append(e,`match.${t}`),this}regexIMatch(e,t){return this.url.searchParams.append(e,`imatch.${t}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}isDistinct(e,t){return this.url.searchParams.append(e,`isdistinct.${t}`),this}in(e,t){const s=Array.from(new Set(t)).map(r=>typeof r=="string"&&ow.test(r)?`"${r}"`:`${r}`).join(",");return this.url.searchParams.append(e,`in.(${s})`),this}notIn(e,t){const s=Array.from(new Set(t)).map(r=>typeof r=="string"&&ow.test(r)?`"${r}"`:`${r}`).join(",");return this.url.searchParams.append(e,`not.in.(${s})`),this}contains(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return typeof t=="string"?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:s,type:r}={}){let a="";r==="plain"?a="pl":r==="phrase"?a="ph":r==="websearch"&&(a="w");const i=s===void 0?"":`(${s})`;return this.url.searchParams.append(e,`${a}fts${i}.${t}`),this}match(e){return Object.entries(e).filter(([t,s])=>s!==void 0).forEach(([t,s])=>{this.url.searchParams.append(t,`eq.${s}`)}),this}not(e,t,s){return this.url.searchParams.append(e,`not.${t}.${s}`),this}or(e,{foreignTable:t,referencedTable:s=t}={}){const r=s?`${s}.or`:"or";return this.url.searchParams.append(r,`(${e})`),this}filter(e,t,s){return this.url.searchParams.append(e,`${t}.${s}`),this}},o3=class{constructor(e,{headers:t={},schema:s,fetch:r,urlLengthLimit:a=8e3}){this.url=e,this.headers=new Headers(t),this.schema=s,this.fetch=r,this.urlLengthLimit=a}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(e,t){const{head:s=!1,count:r}=t??{},a=s?"HEAD":"GET";let i=!1;const o=(e??"*").split("").map(d=>/\s/.test(d)&&!i?"":(d==='"'&&(i=!i),d)).join(""),{url:l,headers:c}=this.cloneRequestState();return l.searchParams.set("select",o),r&&c.append("Prefer",`count=${r}`),new Ro({method:a,url:l,headers:c,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}insert(e,{count:t,defaultToNull:s=!0}={}){var r;const a="POST",{url:i,headers:o}=this.cloneRequestState();if(t&&o.append("Prefer",`count=${t}`),s||o.append("Prefer","missing=default"),Array.isArray(e)){const l=e.reduce((c,d)=>c.concat(Object.keys(d)),[]);if(l.length>0){const c=[...new Set(l)].map(d=>`"${d}"`);i.searchParams.set("columns",c.join(","))}}return new Ro({method:a,url:i,headers:o,schema:this.schema,body:e,fetch:(r=this.fetch)!==null&&r!==void 0?r:fetch,urlLengthLimit:this.urlLengthLimit})}upsert(e,{onConflict:t,ignoreDuplicates:s=!1,count:r,defaultToNull:a=!0}={}){var i;const o="POST",{url:l,headers:c}=this.cloneRequestState();if(c.append("Prefer",`resolution=${s?"ignore":"merge"}-duplicates`),t!==void 0&&l.searchParams.set("on_conflict",t),r&&c.append("Prefer",`count=${r}`),a||c.append("Prefer","missing=default"),Array.isArray(e)){const d=e.reduce((u,m)=>u.concat(Object.keys(m)),[]);if(d.length>0){const u=[...new Set(d)].map(m=>`"${m}"`);l.searchParams.set("columns",u.join(","))}}return new Ro({method:o,url:l,headers:c,schema:this.schema,body:e,fetch:(i=this.fetch)!==null&&i!==void 0?i:fetch,urlLengthLimit:this.urlLengthLimit})}update(e,{count:t}={}){var s;const r="PATCH",{url:a,headers:i}=this.cloneRequestState();return t&&i.append("Prefer",`count=${t}`),new Ro({method:r,url:a,headers:i,schema:this.schema,body:e,fetch:(s=this.fetch)!==null&&s!==void 0?s:fetch,urlLengthLimit:this.urlLengthLimit})}delete({count:e}={}){var t;const s="DELETE",{url:r,headers:a}=this.cloneRequestState();return e&&a.append("Prefer",`count=${e}`),new Ro({method:s,url:r,headers:a,schema:this.schema,fetch:(t=this.fetch)!==null&&t!==void 0?t:fetch,urlLengthLimit:this.urlLengthLimit})}};function _d(e){"@babel/helpers - typeof";return _d=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},_d(e)}function l3(e,t){if(_d(e)!="object"||!e)return e;var s=e[Symbol.toPrimitive];if(s!==void 0){var r=s.call(e,t||"default");if(_d(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function c3(e){var t=l3(e,"string");return _d(t)=="symbol"?t:t+""}function d3(e,t,s){return(t=c3(t))in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s,e}function lw(e,t){var s=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),s.push.apply(s,r)}return s}function Yu(e){for(var t=1;t<arguments.length;t++){var s=arguments[t]!=null?arguments[t]:{};
55t%2?lw(Object(s),!0).forEach(function(r){d3(e,r,s[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(s)):lw(Object(s)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(s,r))})}return e}var u3=class ON{constructor(t,{headers:s={},schema:r,fetch:a,timeout:i,urlLengthLimit:o=8e3}={}){this.url=t,this.headers=new Headers(s),this.schemaName=r,this.urlLengthLimit=o;const l=a??globalThis.fetch;i!==void 0&&i>0?this.fetch=(c,d)=>{const u=new AbortController,m=setTimeout(()=>u.abort(),i),p=d==null?void 0:d.signal;if(p){if(p.aborted)return clearTimeout(m),l(c,d);const f=()=>{clearTimeout(m),u.abort()};return p.addEventListener("abort",f,{once:!0}),l(c,Yu(Yu({},d),{},{signal:u.signal})).finally(()=>{clearTimeout(m),p.removeEventListener("abort",f)})}return l(c,Yu(Yu({},d),{},{signal:u.signal})).finally(()=>clearTimeout(m))}:this.fetch=l}from(t){if(!t||typeof t!="string"||t.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new o3(new URL(`${this.url}/${t}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(t){return new ON(this.url,{headers:this.headers,schema:t,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}rpc(t,s={},{head:r=!1,get:a=!1,count:i}={}){var o;let l;const c=new URL(`${this.url}/rpc/${t}`);let d;const u=f=>f!==null&&typeof f=="object"&&(!Array.isArray(f)||f.some(u)),m=r&&Object.values(s).some(u);m?(l="POST",d=s):r||a?(l=r?"HEAD":"GET",Object.entries(s).filter(([f,g])=>g!==void 0).map(([f,g])=>[f,Array.isArray(g)?`{${g.join(",")}}`:`${g}`]).forEach(([f,g])=>{c.searchParams.append(f,g)})):(l="POST",d=s);const p=new Headers(this.headers);return m?p.set("Prefer",i?`count=${i},return=minimal`:"return=minimal"):i&&p.set("Prefer",`count=${i}`),new Ro({method:l,url:c,headers:p,schema:this.schemaName,body:d,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch,urlLengthLimit:this.urlLengthLimit})}};class h3{constructor(){}static detectEnvironment(){var t;if(typeof WebSocket<"u")return{type:"native",constructor:WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocket<"u")return{type:"native",constructor:globalThis.WebSocket};if(typeof global<"u"&&typeof global.WebSocket<"u")return{type:"native",constructor:global.WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocketPair<"u"&&typeof globalThis.WebSocket>"u")return{type:"cloudflare",error:"Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.",workaround:"Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime."};if(typeof globalThis<"u"&&globalThis.EdgeRuntime||typeof navigator<"u"&&(!((t=navigator.userAgent)===null||t===void 0)&&t.includes("Vercel-Edge")))return{type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};const s=globalThis.process;if(s){const r=s.versions;if(r&&r.node){const a=r.node,i=parseInt(a.replace(/^v/,"").split(".")[0]);return i>=22?typeof globalThis.WebSocket<"u"?{type:"native",constructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${i} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${i} detected without native WebSocket support.`,workaround:`For Node.js < 22, install "ws" package and provide it via the transport option:
56import ws from "ws"
57new RealtimeClient(url, { transport: ws })`}}}return{type:"unsupported",error:"Unknown JavaScript runtime without WebSocket support.",workaround:"Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation."}}static getWebSocketConstructor(){const t=this.detectEnvironment();if(t.constructor)return t.constructor;let s=t.error||"WebSocket not supported in this environment.";throw t.workaround&&(s+=`
58
59Suggested solution: ${t.workaround}`),new Error(s)}static isWebSocketSupported(){try{const t=this.detectEnvironment();return t.type==="native"||t.type==="ws"}catch{return!1}}}const m3="2.101.0",p3=`realtime-js/${m3}`,f3="1.0.0",DN="2.0.0",g3=DN,x3=1e4,v3=100,Na={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},MN={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave",access_token:"access_token"},wx={connecting:"connecting",open:"open",closing:"closing",closed:"closed"};class y3{constructor(t){this.HEADER_LENGTH=1,this.USER_BROADCAST_PUSH_META_LENGTH=6,this.KINDS={userBroadcastPush:3,userBroadcast:4},this.BINARY_ENCODING=0,this.JSON_ENCODING=1,this.BROADCAST_EVENT="broadcast",this.allowedMetadataKeys=[],this.allowedMetadataKeys=t??[]}encode(t,s){if(t.event===this.BROADCAST_EVENT&&!(t.payload instanceof ArrayBuffer)&&typeof t.payload.event=="string")return s(this._binaryEncodeUserBroadcastPush(t));let r=[t.join_ref,t.ref,t.topic,t.event,t.payload];return s(JSON.stringify(r))}_binaryEncodeUserBroadcastPush(t){var s;return this._isArrayBuffer((s=t.payload)===null||s===void 0?void 0:s.payload)?this._encodeBinaryUserBroadcastPush(t):this._encodeJsonUserBroadcastPush(t)}_encodeBinaryUserBroadcastPush(t){var s,r;const a=(r=(s=t.payload)===null||s===void 0?void 0:s.payload)!==null&&r!==void 0?r:new ArrayBuffer(0);return this._encodeUserBroadcastPush(t,this.BINARY_ENCODING,a)}_encodeJsonUserBroadcastPush(t){var s,r;const a=(r=(s=t.payload)===null||s===void 0?void 0:s.payload)!==null&&r!==void 0?r:{},o=new TextEncoder().encode(JSON.stringify(a)).buffer;return this._encodeUserBroadcastPush(t,this.JSON_ENCODING,o)}_encodeUserBroadcastPush(t,s,r){var a,i;const o=t.topic,l=(a=t.ref)!==null&&a!==void 0?a:"",c=(i=t.join_ref)!==null&&i!==void 0?i:"",d=t.payload.event,u=this.allowedMetadataKeys?this._pick(t.payload,this.allowedMetadataKeys):{},m=Object.keys(u).length===0?"":JSON.stringify(u);if(c.length>255)throw new Error(`joinRef length ${c.length} exceeds maximum of 255`);if(l.length>255)throw new Error(`ref length ${l.length} exceeds maximum of 255`);if(o.length>255)throw new Error(`topic length ${o.length} exceeds maximum of 255`);if(d.length>255)throw new Error(`userEvent length ${d.length} exceeds maximum of 255`);if(m.length>255)throw new Error(`metadata length ${m.length} exceeds maximum of 255`);const p=this.USER_BROADCAST_PUSH_META_LENGTH+c.length+l.length+o.length+d.length+m.length,f=new ArrayBuffer(this.HEADER_LENGTH+p);let g=new DataView(f),x=0;g.setUint8(x++,this.KINDS.userBroadcastPush),g.setUint8(x++,c.length),g.setUint8(x++,l.length),g.setUint8(x++,o.length),g.setUint8(x++,d.length),g.setUint8(x++,m.length),g.setUint8(x++,s),Array.from(c,v=>g.setUint8(x++,v.charCodeAt(0))),Array.from(l,v=>g.setUint8(x++,v.charCodeAt(0))),Array.from(o,v=>g.setUint8(x++,v.charCodeAt(0))),Array.from(d,v=>g.setUint8(x++,v.charCodeAt(0))),Array.from(m,v=>g.setUint8(x++,v.charCodeAt(0)));var b=new Uint8Array(f.byteLength+r.byteLength);return b.set(new Uint8Array(f),0),b.set(new Uint8Array(r),f.byteLength),b.buffer}decode(t,s){if(this._isArrayBuffer(t)){let r=this._binaryDecode(t);return s(r)}if(typeof t=="string"){const r=JSON.parse(t),[a,i,o,l,c]=r;
59return s({join_ref:a,ref:i,topic:o,event:l,payload:c})}return s({})}_binaryDecode(t){const s=new DataView(t),r=s.getUint8(0),a=new TextDecoder;switch(r){case this.KINDS.userBroadcast:return this._decodeUserBroadcast(t,s,a)}}_decodeUserBroadcast(t,s,r){const a=s.getUint8(1),i=s.getUint8(2),o=s.getUint8(3),l=s.getUint8(4);let c=this.HEADER_LENGTH+4;const d=r.decode(t.slice(c,c+a));c=c+a;const u=r.decode(t.slice(c,c+i));c=c+i;const m=r.decode(t.slice(c,c+o));c=c+o;const p=t.slice(c,t.byteLength),f=l===this.JSON_ENCODING?JSON.parse(r.decode(p)):p,g={type:this.BROADCAST_EVENT,event:u,payload:f};return o>0&&(g.meta=JSON.parse(m)),{join_ref:null,ref:null,topic:d,event:this.BROADCAST_EVENT,payload:g}}_isArrayBuffer(t){var s;return t instanceof ArrayBuffer||((s=t==null?void 0:t.constructor)===null||s===void 0?void 0:s.name)==="ArrayBuffer"}_pick(t,s){return!t||typeof t!="object"?{}:Object.fromEntries(Object.entries(t).filter(([r])=>s.includes(r)))}}var Rt;(function(e){e.abstime="abstime",e.bool="bool",e.date="date",e.daterange="daterange",e.float4="float4",e.float8="float8",e.int2="int2",e.int4="int4",e.int4range="int4range",e.int8="int8",e.int8range="int8range",e.json="json",e.jsonb="jsonb",e.money="money",e.numeric="numeric",e.oid="oid",e.reltime="reltime",e.text="text",e.time="time",e.timestamp="timestamp",e.timestamptz="timestamptz",e.timetz="timetz",e.tsrange="tsrange",e.tstzrange="tstzrange"})(Rt||(Rt={}));const cw=(e,t,s={})=>{var r;const a=(r=s.skipTypes)!==null&&r!==void 0?r:[];return t?Object.keys(t).reduce((i,o)=>(i[o]=b3(o,e,t,a),i),{}):{}},b3=(e,t,s,r)=>{const a=t.find(l=>
vendor: 5,523 bytes, line 59
59l.name===e),i=a==null?void 0:a.type,o=s[e];return i&&!r.includes(i)?zN(i,o):jx(o)},zN=(e,t)=>{if(e.charAt(0)==="_"){const s=e.slice(1,e.length);return k3(t,s)}switch(e){case Rt.bool:return w3(t);case Rt.float4:case Rt.float8:case Rt.int2:case Rt.int4:case Rt.int8:case Rt.numeric:case Rt.oid:return j3(t);case Rt.json:case Rt.jsonb:return _3(t);case Rt.timestamp:return N3(t);case Rt.abstime:case Rt.date:case Rt.daterange:case Rt.int4range:case Rt.int8range:case Rt.money:case Rt.reltime:case Rt.text:case Rt.time:case Rt.timestamptz:case Rt.timetz:case Rt.tsrange:case Rt.tstzrange:return jx(t);default:return jx(t)}},jx=e=>e,w3=e=>{switch(e){case"t":return!0;case"f":return!1;default:return e}},j3=e=>{if(typeof e=="string"){const t=parseFloat(e);if(!Number.isNaN(t))return t}return e},_3=e=>{if(typeof e=="string")try{return JSON.parse(e)}catch{return e}return e},k3=(e,t)=>{if(typeof e!="string")return e;const s=e.length-1,r=e[s];if(e[0]==="{"&&r==="}"){let i;const o=e.slice(1,s);try{i=JSON.parse("["+o+"]")}catch{i=o?o.split(","):[]}return i.map(l=>zN(t,l))}return e},N3=e=>typeof e=="string"?e.replace(" ","T"):e,FN=e=>{const t=new URL(e);return t.protocol=t.protocol.replace(/^ws/i,"http"),t.pathname=t.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),t.pathname===""||t.pathname==="/"?t.pathname="/api/broadcast":t.pathname=t.pathname+"/api/broadcast",t.href};var Gc=e=>typeof e=="function"?e:function(){return e},S3=typeof self<"u"?self:null,$o=typeof window<"u"?window:null,hr=S3||$o||globalThis,C3="2.0.0",T3=1e4,P3=1e3,gr={connecting:0,open:1,closing:2,closed:3},Vs={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},zr={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave"},_x={longpoll:"longpoll",websocket:"websocket"},E3={complete:4},kx="base64url.bearer.phx.",Ku=class{constructor(e,t,s,r){this.channel=e,this.event=t,this.payload=s||function(){return{}},this.receivedResp=null,this.timeout=r,this.timeoutTimer=null,this.recHooks=[],this.sent=!1,this.ref=void 0}resend(e){this.timeout=e,this.reset(),this.send()}send(){this.hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload(),ref:this.ref,join_ref:this.channel.joinRef()}))}receive(e,t){return this.hasReceived(e)&&t(this.receivedResp.response),this.recHooks.push({status:e,callback:t}),this}reset(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=!1}destroy(){this.cancelRefEvent(),this.cancelTimeout()}matchReceive({status:e,response:t,_ref:s}){this.recHooks.filter(r=>r.status===e).forEach(r=>r.callback(t))}cancelRefEvent(){this.refEvent&&this.channel.off(this.refEvent)}cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=null}startTimeout(){this.timeoutTimer&&this.cancelTimeout(),this.ref=this.channel.socket.makeRef(),this.refEvent=this.channel.replyEventName(this.ref),this.channel.on(this.refEvent,e=>{this.cancelRefEvent(),this.cancelTimeout(),this.receivedResp=e,this.matchReceive(e)}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}trigger(e,t){this.channel.trigger(this.refEvent,{status:e,response:t})}},UN=class{constructor(t,s){this.callback=t,this.timerCalc=s,this.timer=void 0,this.tries=0}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}},A3=class{constructor(e,t,s){this.state=Vs.closed,this.topic=e,this.params=Gc(t||{}),this.socket=s,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new Ku(this,zr.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new UN(()=>{this.socket.isConnected()&&this.rejoin()},this.socket.rejoinAfterMs),this.stateChangeRefs.push(this.socket.onError(()=>this.rejoinTimer.reset())),this.stateChangeRefs.push(this.socket.onOpen(()=>{this.rejoinTimer.reset(),this.isErrored()&&this.rejoin()})),this.joinPush.receive("ok",()=>{this.state=Vs.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(r=>r.send()),this.pushBuffer=[]}),this.joinPush.receive("error",r=>{this.state=Vs.errored,this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,r),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.onClose(()=>{this.rejoinTimer.reset(),this.socket.hasLogger()&&this.socket.log("channel",`close ${this.topic}`),this.state=Vs.closed,this.socket.remove(this)}),this.onError(r=>{this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,r),this.isJoining()&&this.joinPush.reset(),this.state=Vs.errored,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.joinPush.receive("timeout",()=>{this.socket.hasLogger()&&this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),new Ku(this,zr.leave,Gc({}),this.timeout).send(),this.state=Vs.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.on(zr.reply,(r,a)=>{this.trigger(this.replyEventName(a),r)})}join(e=this.timeout){if(this.joinedOnce)throw new Error("tried to join multiple times. 'join' can only be called a single time per channel instance");return this.timeout=e,this.joinedOnce=!0,this.rejoin(),this.joinPush}
vendor: 2,019 bytes, line 59
59teardown(){this.pushBuffer.forEach(e=>e.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=Vs.closed,this.bindings=[]}onClose(e){this.on(zr.close,e)}onError(e){return this.on(zr.error,t=>e(t))}on(e,t){let s=this.bindingRef++;return this.bindings.push({event:e,ref:s,callback:t}),s}off(e,t){this.bindings=this.bindings.filter(s=>!(s.event===e&&(typeof t>"u"||t===s.ref)))}canPush(){return this.socket.isConnected()&&this.isJoined()}push(e,t,s=this.timeout){if(t=t||{},!this.joinedOnce)throw new Error(`tried to push '${e}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let r=new Ku(this,e,function(){return t},s);return this.canPush()?r.send():(r.startTimeout(),this.pushBuffer.push(r)),r}leave(e=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=Vs.leaving;let t=()=>{this.socket.hasLogger()&&this.socket.log("channel",`leave ${this.topic}`),this.trigger(zr.close,"leave")},s=new Ku(this,zr.leave,Gc({}),e);return s.receive("ok",()=>t()).receive("timeout",()=>t()),s.send(),this.canPush()||s.trigger("ok",{}),s}onMessage(e,t,s){return t}filterBindings(e,t,s){return!0}isMember(e,t,s,r){return this.topic!==e?!1:r&&r!==this.joinRef()?(this.socket.hasLogger()&&this.socket.log("channel","dropping outdated message",{topic:e,event:t,payload:s,joinRef:r}),!1):!0}joinRef(){return this.joinPush.ref}rejoin(e=this.timeout){this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=Vs.joining,this.joinPush.resend(e))}trigger(e,t,s,r){let a=this.onMessage(e,t,s,r);if(t&&!a)throw new Error("channel onMessage callbacks must return the payload, modified or unmodified");let i=this.bindings.filter(o=>o.event===e&&this.filterBindings(o,t,s));for(let o=0;o<i.length;o++)i[o].callback(a,s,r||this.joinRef())}replyEventName(e){return`chan_reply_${e}`}isClosed(){return this.state===Vs.closed}isErrored(){return this.state===Vs.errored}isJoined(){return this.state===Vs.joined}isJoining(){return this.state===Vs.joining}
vendor: 3,244 bytes, line 59
59isLeaving(){return this.state===Vs.leaving}},cm=class{static request(e,t,s,r,a,i,o){if(hr.XDomainRequest){let l=new hr.XDomainRequest;return this.xdomainRequest(l,e,t,r,a,i,o)}else if(hr.XMLHttpRequest){let l=new hr.XMLHttpRequest;return this.xhrRequest(l,e,t,s,r,a,i,o)}else{if(hr.fetch&&hr.AbortController)return this.fetchRequest(e,t,s,r,a,i,o);throw new Error("No suitable XMLHttpRequest implementation found")}}static fetchRequest(e,t,s,r,a,i,o){let l={method:e,headers:s,body:r},c=null;return a&&(c=new AbortController,setTimeout(()=>c.abort(),a),l.signal=c.signal),hr.fetch(t,l).then(d=>d.text()).then(d=>this.parseJSON(d)).then(d=>o&&o(d)).catch(d=>{d.name==="AbortError"&&i?i():o&&o(null)}),c}static xdomainRequest(e,t,s,r,a,i,o){return e.timeout=a,e.open(t,s),e.onload=()=>{let l=this.parseJSON(e.responseText);o&&o(l)},i&&(e.ontimeout=i),e.onprogress=()=>{},e.send(r),e}static xhrRequest(e,t,s,r,a,i,o,l){e.open(t,s,!0),e.timeout=i;for(let[c,d]of Object.entries(r))e.setRequestHeader(c,d);return e.onerror=()=>l&&l(null),e.onreadystatechange=()=>{if(e.readyState===E3.complete&&l){let c=this.parseJSON(e.responseText);l(c)}},o&&(e.ontimeout=o),e.send(a),e}static parseJSON(e){if(!e||e==="")return null;try{return JSON.parse(e)}catch{return console&&console.log("failed to parse JSON response",e),null}}static serialize(e,t){let s=[];for(var r in e){if(!Object.prototype.hasOwnProperty.call(e,r))continue;let a=t?`${t}[${r}]`:r,i=e[r];typeof i=="object"?s.push(this.serialize(i,a)):s.push(encodeURIComponent(a)+"="+encodeURIComponent(i))}return s.join("&")}static appendParams(e,t){if(Object.keys(t).length===0)return e;let s=e.match(/\?/)?"&":"?";return`${e}${s}${this.serialize(t)}`}},R3=e=>{let t="",s=new Uint8Array(e),r=s.byteLength;for(let a=0;a<r;a++)t+=String.fromCharCode(s[a]);return btoa(t)},go=class{constructor(e,t){t&&t.length===2&&t[1].startsWith(kx)&&(this.authToken=atob(t[1].slice(kx.length))),this.endPoint=null,this.token=null,this.skipHeartbeat=!0,this.reqs=new Set,this.awaitingBatchAck=!1,this.currentBatch=null,this.currentBatchTimer=null,this.batchBuffer=[],this.onopen=function(){},this.onerror=function(){},this.onmessage=function(){},this.onclose=function(){},this.pollEndpoint=this.normalizeEndpoint(e),this.readyState=gr.connecting,setTimeout(()=>this.poll(),0)}normalizeEndpoint(e){return e.replace("ws://","http://").replace("wss://","https://").replace(new RegExp("(.*)/"+_x.websocket),"$1/"+_x.longpoll)}endpointURL(){return cm.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(e,t,s){this.close(e,t,s),this.readyState=gr.connecting}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return this.readyState===gr.open||this.readyState===gr.connecting}poll(){const e={Accept:"application/json"};this.authToken&&(e["X-Phoenix-AuthToken"]=this.authToken),this.ajax("GET",e,null,()=>this.ontimeout(),t=>{if(t){var{status:s,token:r,messages:a}=t;if(s===410&&this.token!==null){this.onerror(410),this.closeAndRetry(3410,"session_gone",!1);return}this.token=r}else s=0;switch(s){case 200:a.forEach(i=>{setTimeout(()=>this.onmessage({data:i}),0)}),this.poll();break;case 204:this.poll();break;case 410:this.readyState=gr.open,this.onopen({}),this.poll();break;
vendor: 12,958 bytes, lines 59-60
59case 403:this.onerror(403),this.close(1008,"forbidden",!1);break;case 0:case 500:this.onerror(500),this.closeAndRetry(1011,"internal server error",500);break;default:throw new Error(`unhandled poll status ${s}`)}})}send(e){typeof e!="string"&&(e=R3(e)),this.currentBatch?this.currentBatch.push(e):this.awaitingBatchAck?this.batchBuffer.push(e):(this.currentBatch=[e],this.currentBatchTimer=setTimeout(()=>{this.batchSend(this.currentBatch),this.currentBatch=null},0))}batchSend(e){this.awaitingBatchAck=!0,this.ajax("POST",{"Content-Type":"application/x-ndjson"},e.join(`
60`),()=>this.onerror("timeout"),t=>{this.awaitingBatchAck=!1,!t||t.status!==200?(this.onerror(t&&t.status),this.closeAndRetry(1011,"internal server error",!1)):this.batchBuffer.length>0&&(this.batchSend(this.batchBuffer),this.batchBuffer=[])})}close(e,t,s){for(let a of this.reqs)a.abort();this.readyState=gr.closed;let r=Object.assign({code:1e3,reason:void 0,wasClean:!0},{code:e,reason:t,wasClean:s});this.batchBuffer=[],clearTimeout(this.currentBatchTimer),this.currentBatchTimer=null,typeof CloseEvent<"u"?this.onclose(new CloseEvent("close",r)):this.onclose(r)}ajax(e,t,s,r,a){let i,o=()=>{this.reqs.delete(i),r()};i=cm.request(e,this.endpointURL(),t,s,this.timeout,o,l=>{this.reqs.delete(i),this.isActive()&&a(l)}),this.reqs.add(i)}},$3=class Ec{constructor(t,s={}){let r=s.events||{state:"presence_state",diff:"presence_diff"};this.state={},this.pendingDiffs=[],this.channel=t,this.joinRef=null,this.caller={onJoin:function(){},onLeave:function(){},onSync:function(){}},this.channel.on(r.state,a=>{let{onJoin:i,onLeave:o,onSync:l}=this.caller;this.joinRef=this.channel.joinRef(),this.state=Ec.syncState(this.state,a,i,o),this.pendingDiffs.forEach(c=>{this.state=Ec.syncDiff(this.state,c,i,o)}),this.pendingDiffs=[],l()}),this.channel.on(r.diff,a=>{let{onJoin:i,onLeave:o,onSync:l}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(a):(this.state=Ec.syncDiff(this.state,a,i,o),l())})}onJoin(t){this.caller.onJoin=t}onLeave(t){this.caller.onLeave=t}onSync(t){this.caller.onSync=t}list(t){return Ec.list(this.state,t)}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel.joinRef()}static syncState(t,s,r,a){let i=this.clone(t),o={},l={};return this.map(i,(c,d)=>{s[c]||(l[c]=d)}),this.map(s,(c,d)=>{let u=i[c];if(u){let m=d.metas.map(x=>x.phx_ref),p=u.metas.map(x=>x.phx_ref),f=d.metas.filter(x=>p.indexOf(x.phx_ref)<0),g=u.metas.filter(x=>m.indexOf(x.phx_ref)<0);f.length>0&&(o[c]=d,o[c].metas=f),g.length>0&&(l[c]=this.clone(u),l[c].metas=g)}else o[c]=d}),this.syncDiff(i,{joins:o,leaves:l},r,a)}static syncDiff(t,s,r,a){let{joins:i,leaves:o}=this.clone(s);return r||(r=function(){}),a||(a=function(){}),this.map(i,(l,c)=>{let d=t[l];if(t[l]=this.clone(c),d){let u=t[l].metas.map(p=>p.phx_ref),m=d.metas.filter(p=>u.indexOf(p.phx_ref)<0);t[l].metas.unshift(...m)}r(l,d,c)}),this.map(o,(l,c)=>{let d=t[l];if(!d)return;let u=c.metas.map(m=>m.phx_ref);d.metas=d.metas.filter(m=>u.indexOf(m.phx_ref)<0),a(l,d,c),d.metas.length===0&&delete t[l]}),t}static list(t,s){return s||(s=function(r,a){return a}),this.map(t,(r,a)=>s(r,a))}static map(t,s){return Object.getOwnPropertyNames(t).map(r=>s(r,t[r]))}static clone(t){return JSON.parse(JSON.stringify(t))}},Qu={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(e,t){if(e.payload.constructor===ArrayBuffer)return t(this.binaryEncode(e));{let s=[e.join_ref,e.ref,e.topic,e.event,e.payload];return t(JSON.stringify(s))}},decode(e,t){if(e.constructor===ArrayBuffer)return t(this.binaryDecode(e));{let[s,r,a,i,o]=JSON.parse(e);return t({join_ref:s,ref:r,topic:a,event:i,payload:o})}},binaryEncode(e){let{join_ref:t,ref:s,event:r,topic:a,payload:i}=e,o=this.META_LENGTH+t.length+s.length+a.length+r.length,l=new ArrayBuffer(this.HEADER_LENGTH+o),c=new DataView(l),d=0;c.setUint8(d++,this.KINDS.push),c.setUint8(d++,t.length),c.setUint8(d++,s.length),c.setUint8(d++,a.length),c.setUint8(d++,r.length),Array.from(t,m=>c.setUint8(d++,m.charCodeAt(0))),Array.from(s,m=>c.setUint8(d++,m.charCodeAt(0))),Array.from(a,m=>c.setUint8(d++,m.charCodeAt(0))),Array.from(r,m=>c.setUint8(d++,m.charCodeAt(0)));var u=new Uint8Array(l.byteLength+i.byteLength);return u.set(new Uint8Array(l),0),u.set(new Uint8Array(i),l.byteLength),u.buffer},binaryDecode(e){let t=new DataView(e),s=t.getUint8(0),r=new TextDecoder;switch(s){case this.KINDS.push:return this.decodePush(e,t,r);case this.KINDS.reply:return this.decodeReply(e,t,r);case this.KINDS.broadcast:return this.decodeBroadcast(e,t,r)}},decodePush(e,t,s){let r=t.getUint8(1),a=t.getUint8(2),i=t.getUint8(3),o=this.HEADER_LENGTH+this.META_LENGTH-1,l=s.decode(e.slice(o,o+r));o=o+r;let c=s.decode(e.slice(o,o+a));o=o+a;let d=s.decode(e.slice(o,o+i));o=o+i;let u=e.slice(o,e.byteLength);return{join_ref:l,ref:null,topic:c,event:d,payload:u}},decodeReply(e,t,s){let r=t.getUint8(1),a=t.getUint8(2),i=t.getUint8(3),o=t.getUint8(4),l=this.HEADER_LENGTH+this.META_LENGTH,c=s.decode(e.slice(l,l+r));l=l+r;let d=s.decode(e.slice(l,l+a));l=l+a;let u=s.decode(e.slice(l,l+i));l=l+i;let m=s.decode(e.slice(l,l+o));l=l+o;let p=e.slice(l,e.byteLength),f={status:m,response:p};return{join_ref:c,ref:d,topic:u,event:zr.reply,payload:f}},decodeBroadcast(e,t,s){let r=t.getUint8(1),a=t.getUint8(2),i=this.HEADER_LENGTH+2,o=s.decode(e.slice(i,i+r));i=i+r;let l=s.decode(e.slice(i,i+a));i=i+a;let c=e.slice(i,e.byteLength);return{join_ref:null,ref:null,topic:o,event:l,payload:c}}},L3=class{constructor(e,t={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.fallbackRef=null,this.timeout=t.timeout||T3,this.transport=t.transport||hr.WebSocket||go,this.conn=void 0,this.primaryPassedHealthCheck=!1,this.longPollFallbackMs=t.longPollFallbackMs,this.fallbackTimer=null,this.sessionStore=t.sessionStorage||hr&&hr.sessionStorage,this.establishedConnections=0,this.defaultEncoder=Qu.encode.bind(Qu),this.defaultDecoder=Qu.decode.bind(Qu),this.closeWasClean=!0,this.disconnecting=!1,this.binaryType=t.binaryType||"arraybuffer",this.connectClock=1,this.pageHidden=!1,this.encode=void 0,this.decode=void 0,this.transport!==go?(this.encode=t.encode||this.defaultEncoder,this.decode=t.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let s=null;$o&&$o.addEventListener&&($o.addEventListener("pagehide",r=>{this.conn&&(this.disconnect(),s=this.connectClock)}),$o.addEventListener("pageshow",r=>{s===this.connectClock&&(s=null,this.connect())}),$o.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?this.pageHidden=!0:(this.pageHidden=!1,!this.isConnected()&&!this.closeWasClean&&this.teardown(()=>this.connect()))})),this.heartbeatIntervalMs=t.heartbeatIntervalMs||3e4,this.autoSendHeartbeat=t.autoSendHeartbeat??!0,this.heartbeatCallback=t.heartbeatCallback??(()=>{}),this.rejoinAfterMs=r=>t.rejoinAfterMs?t.rejoinAfterMs(r):[1e3,2e3,5e3][r-1]||1e4,this.reconnectAfterMs=r=>t.reconnectAfterMs?t.reconnectAfterMs(r):[10,50,100,150,200,250,500,1e3,2e3][r-1]||5e3,this.logger=t.logger||null,!this.logger&&t.debug&&(this.logger=(r,a,i)=>{console.log(`${r}: ${a}`,i)}),this.longpollerTimeout=t.longpollerTimeout||2e4,this.params=Gc(t.params||{}),this.endPoint=`${e}/${_x.websocket}`,this.vsn=t.vsn||C3,this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.heartbeatSentAt=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new UN(()=>{if(this.pageHidden){this.log("Not reconnecting as page is hidden!"),this.teardown();return}this.teardown(async()=>{t.beforeReconnect&&await t.beforeReconnect(),this.connect()})},this.reconnectAfterMs),this.authToken=t.authToken}getLongPollTransport(){return go}replaceTransport(e){this.connectClock++,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.conn&&(this.conn.close(),this.conn=null),this.transport=e}protocol(){return location.protocol.match(/^https/)?"wss":"ws"}endPointURL(){let e=cm.appendParams(cm.appendParams(this.endPoint,this.params()),{vsn:this.vsn});return e.charAt(0)!=="/"?e:e.charAt(1)==="/"?`${this.protocol()}:${e}`:`${this.protocol()}://${location.host}${e}`}disconnect(e,t,s){this.connectClock++,this.disconnecting=!0,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.teardown(()=>{this.disconnecting=!1,e&&e()},t,s)}connect(e){e&&(console&&console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor"),this.params=Gc(e)),!(this.conn&&!this.disconnecting)&&(this.longPollFallbackMs&&this.transport!==go?this.connectWithFallback(go,this.longPollFallbackMs):this.transportConnect())}log(e,t,s){this.logger&&this.logger(e,t,s)}hasLogger(){return this.logger!==null}onOpen(e){let t=this.makeRef();return this.stateChangeCallbacks.open.push([t,e]),t}onClose(e){let t=this.makeRef();return this.stateChangeCallbacks.close.push([t,e]),t}onError(e){let t=this.makeRef();return this.stateChangeCallbacks.error.push([t,e]),t}onMessage(e){let t=this.makeRef();return this.stateChangeCallbacks.message.push([t,e]),t}onHeartbeat(e){this.heartbeatCallback=e}ping(e){if(!this.isConnected())return!1;let t=this.makeRef(),s=Date.now();this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:t});let r=this.onMessage(a=>{a.ref===t&&(this.off([r]),e(Date.now()-s))});return!0}transportName(e){switch(e){case go:return"LongPoll";default:return e.name}}transportConnect(){this.connectClock++,this.closeWasClean=!1;let e;this.authToken&&(e=["phoenix",`${kx}${btoa(this.authToken).replace(/=/g,"")}`]),this.conn=new this.transport(this.endPointURL(),e),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,this.conn.onopen=()=>this.onConnOpen(),this.conn.onerror=t=>this.onConnError(t),this.conn.onmessage=t=>this.onConnMessage(t),this.conn.onclose=t=>this.onConnClose(t)}getSession(e){return this.sessionStore&&this.sessionStore.getItem(e)}storeSession(e,t){this.sessionStore&&this.sessionStore.setItem(e,t)}connectWithFallback(e,t=2500){clearTimeout(this.fallbackTimer);let s=!1,r=!0,a,i,o=this.transportName(e),l=c=>{this.log("transport",`falling back to ${o}...`,c),this.off([a,i]),r=!1,this.replaceTransport(e),this.transportConnect()};if(this.getSession(`phx:fallback:${o}`))return l("memorized");this.fallbackTimer=setTimeout(l,t),i=this.onError(c=>{this.log("transport","error",c),r&&!s&&(clearTimeout(this.fallbackTimer),l(c))}),this.fallbackRef&&this.off([this.fallbackRef]),this.fallbackRef=this.onOpen(()=>{if(s=!0,!r){let c=this.transportName(e);return this.primaryPassedHealthCheck||this.storeSession(`phx:fallback:${c}`,"true"),this.log("transport",`established ${c} fallback`)}clearTimeout(this.fallbackTimer),this.fallbackTimer=setTimeout(l,t),this.ping(c=>{this.log("transport","connected to primary after",c),this.primaryPassedHealthCheck=!0,clearTimeout(this.fallbackTimer)})}),this.transportConnect()}clearHeartbeats(){clearTimeout(this.heartbeatTimer),clearTimeout(this.heartbeatTimeoutTimer)}onConnOpen(){this.hasLogger()&&this.log("transport",`connected to ${this.endPointURL()}`),this.closeWasClean=!1,this.disconnecting=!1,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.autoSendHeartbeat&&this.resetHeartbeat(),this.triggerStateCallbacks("open")}heartbeatTimeout(){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.hasLogger()&&this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(e){this.log("error","error in heartbeat callback",e)}this.triggerChanError(),this.closeWasClean=!1,this.teardown(()=>this.reconnectTimer.scheduleTimeout(),P3,"heartbeat timeout")}}resetHeartbeat(){this.conn&&this.conn.skipHeartbeat||(this.pendingHeartbeatRef=null,this.clearHeartbeats(),this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}teardown(e,t,s){if(!this.conn)return e&&e();const r=this.conn;this.waitForBufferDone(r,()=>{t?r.close(t,s||""):r.close(),this.waitForSocketClosed(r,()=>{this.conn===r&&(this.conn.onopen=function(){},this.conn.onerror=function(){},this.conn.onmessage=function(){},this.conn.onclose=function(){},this.conn=null),e&&e()})})}waitForBufferDone(e,t,s=1){if(s===5||!e.bufferedAmount){t();return}setTimeout(()=>{this.waitForBufferDone(e,t,s+1)},150*s)}waitForSocketClosed(e,t,s=1){if(s===5||e.readyState===gr.closed){t();return}setTimeout(()=>{this.waitForSocketClosed(e,t,s+1)},150*s)}onConnClose(e){this.conn&&(this.conn.onclose=()=>{}),this.hasLogger()&&this.log("transport","close",e),this.triggerChanError(),this.clearHeartbeats(),this.closeWasClean||this.reconnectTimer.scheduleTimeout(),this.triggerStateCallbacks("close",e)}onConnError(e){this.hasLogger()&&this.log("transport",e);let t=this.transport,s=this.establishedConnections;this.triggerStateCallbacks("error",e,t,s),(t===this.transport||s>0)&&this.triggerChanError()}
60triggerChanError(){this.channels.forEach(e=>{e.isErrored()||e.isLeaving()||e.isClosed()||e.trigger(zr.error)})}connectionState(){switch(this.conn&&this.conn.readyState){case gr.connecting:return"connecting";case gr.open:return"open";case gr.closing:return"closing";default:return"closed"}}isConnected(){return this.connectionState()==="open"}remove(e){this.off(e.stateChangeRefs),this.channels=this.channels.filter(t=>t!==e)}off(e){for(let t in this.stateChangeCallbacks)this.stateChangeCallbacks[t]=this.stateChangeCallbacks[t].filter(([s])=>e.indexOf(s)===-1)}channel(e,t={}){let s=new A3(e,t,this);return this.channels.push(s),s}push(e){if(this.hasLogger()){let{topic:t,event:s,payload:r,ref:a,join_ref:i}=e;this.log("push",`${t} ${s} (${i}, ${a})`,r)}this.isConnected()?this.encode(e,t=>this.conn.send(t)):this.sendBuffer.push(()=>this.encode(e,t=>this.conn.send(t)))}makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}sendHeartbeat(){if(!this.isConnected()){try{this.heartbeatCallback("disconnected")}catch(e){this.log("error","error in heartbeat callback",e)}return}if(this.pendingHeartbeatRef){this.heartbeatTimeout();return}this.pendingHeartbeatRef=this.makeRef(),this.heartbeatSentAt=Date.now(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(e){this.log("error","error in heartbeat callback",e)}this.heartbeatTimeoutTimer=setTimeout(()=>this.heartbeatTimeout(),this.heartbeatIntervalMs)}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}onConnMessage(e){this.decode(e.data,t=>{let{topic:s,event:r,payload:a,ref:i,join_ref:o}=t;if(i&&i===this.pendingHeartbeatRef){const l=this.heartbeatSentAt?Date.now()-this.heartbeatSentAt:void 0;this.clearHeartbeats();try{this.heartbeatCallback(a.status==="ok"?"ok":"error",l)}catch(c){this.log("error","error in heartbeat callback",c)}this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.autoSendHeartbeat&&(this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}this.hasLogger()&&this.log("receive",`${a.status||""} ${s} ${r} ${i&&"("+i+")"||""}`.trim(),a);for(let l=0;l<this.channels.length;l++){const c=this.channels[l];c.isMember(s,r,a,o)&&c.trigger(r,a,i,o)}this.triggerStateCallbacks("message",t)})}triggerStateCallbacks(e,...t){try{this.stateChangeCallbacks[e].forEach(([s,r])=>{try{r(...t)}catch(a){this.log("error",`error in ${e} callback`,a)}})}catch(s){this.log("error",`error triggering ${e} callbacks`,s)}}leaveOpenTopic(e){let t=this.channels.find(s=>s.topic===e&&(s.isJoined()||s.isJoining()));t&&(this.hasLogger()&&this.log("transport",`leaving duplicate topic "${e}"`),t.leave())}};class Yc{constructor(t,s){const r=O3(s);this.presence=new $3(t.getChannel(),r),this.presence.onJoin((a,i,o)=>{const l=Yc.onJoinPayload(a,i,o);t.getChannel().trigger("presence",l)}),this.presence.onLeave((a,i,o)=>{const l=Yc.onLeavePayload(a,i,o);t.getChannel().trigger("presence",l)}),this.presence.onSync(()=>{t.getChannel().trigger("presence",{event:"sync"})})}get state(){return Yc.transformState(this.presence.state)}static transformState(t){return t=I3(t),Object.getOwnPropertyNames(t).reduce((s,r)=>{const a=t[r];return s[r]=kh(a),s},{})}static onJoinPayload(t,s,r){const a=dw(s),i=kh(r);return{event:"join",key:t,currentPresences:a,newPresences:i}}static onLeavePayload(t,s,r){const a=dw(s),i=kh(r);return{event:"leave",key:t,currentPresences:a,leftPresences:i}}}function kh(e){return e.metas.map(t=>(t.presence_ref=t.phx_ref,delete t.phx_ref,delete t.phx_ref_prev,t))}function I3(e){return JSON.parse(JSON.stringify(e))}function O3(e){return(e==null?void 0:e.events)&&{events:e.events}}function dw(e){return e!=null&&e.metas?kh(e):[]}var uw;(function(e){e.SYNC="sync",e.JOIN="join",e.LEAVE="leave"})(uw||(uw={}));class D3{get state(){return this.presenceAdapter.state}constructor(t,s){this.channel=t,this.presenceAdapter=new Yc(this.channel.channelAdapter,s)}}class M3{constructor(t,s,r){const a=z3(r);this.channel=t.getSocket().channel(s,a),this.socket=t}get state(){return this.channel.state}set state(t){this.channel.state=t}get joinedOnce(){return this.channel.joinedOnce}get joinPush(){return this.channel.joinPush}get rejoinTimer(){return this.channel.rejoinTimer}on(t,s){return this.channel.on(t,s)}off(t,s){this.channel.off(t,s)}subscribe(t){return this.channel.join(t)}unsubscribe(t){return this.channel.leave(t)}teardown(){this.channel.teardown()}onClose(t){this.channel.onClose(t)}onError(t){return this.channel.onError(t)}push(t,s,r){let a;try{a=this.channel.push(t,s,r)}catch{throw`tried to push '${t}' to '${this.channel.topic}' before joining. Use channel.subscribe() before pushing events`}if(this.channel.pushBuffer.length>v3){const i=this.channel.pushBuffer.shift();i.cancelTimeout(),this.socket.log("channel",`discarded push due to buffer overflow: ${i.event}`,i.payload())}return a}updateJoinPayload(t){const s=this.channel.joinPush.payload();this.channel.joinPush.payload=()=>Object.assign(Object.assign({},s),t)}canPush(){return this.socket.isConnected()&&this.state===Na.joined}isJoined(){return this.state===Na.joined}isJoining(){return this.state===Na.joining}isClosed(){return this.state===Na.closed}isLeaving(){return this.state===Na.leaving}updateFilterBindings(t){this.channel.filterBindings=t}updatePayloadTransform(t){this.channel.onMessage=t}getChannel(){return this.channel}}function z3(e){return{config:Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},e.config)}}var hw;(function(e){e.ALL="*",e.INSERT="INSERT",e.UPDATE="UPDATE",e.DELETE="DELETE"})(hw||(hw={}));var Qo;(function(e){e.BROADCAST="broadcast",e.PRESENCE="presence",e.POSTGRES_CHANGES="postgres_changes",e.SYSTEM="system"})(Qo||(Qo={}));var Fr;(function(e){e.SUBSCRIBED="SUBSCRIBED",e.TIMED_OUT="TIMED_OUT",e.CLOSED="CLOSED",e.CHANNEL_ERROR="CHANNEL_ERROR"})(Fr||(Fr={}));class Kc{get state(){return this.channelAdapter.state}set state(t){this.channelAdapter.state=t}get joinedOnce(){return this.channelAdapter.joinedOnce}get timeout(){return this.socket.timeout}get joinPush(){return this.channelAdapter.joinPush}get rejoinTimer(){return this.channelAdapter.rejoinTimer}constructor(t,s={config:{}},r){var a,i;if(this.topic=t,this.params=s,this.socket=r,this.bindings={},this.subTopic=t.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},s.config),this.channelAdapter=new M3(this.socket.socketAdapter,t,this.params),this.presence=new D3(this),this._onClose(()=>{this.socket._remove(this)}),this._updateFilterTransform(),this.broadcastEndpointURL=FN(this.socket.socketAdapter.endPointURL()),this.private=this.params.config.private||!1,!this.private&&(!((i=(a=this.params.config)===null||a===void 0?void 0:a.broadcast)===null||i===void 0)&&i.replay))throw`tried to use replay on public channel '${this.topic}'. It must be a private channel.`}subscribe(t,s=this.timeout){var r,a,i;if(this.socket.isConnected()||this.socket.connect(),this.channelAdapter.isClosed()){const{config:{broadcast:o,presence:l,private:c}}=this.params,d=(a=(r=this.bindings.postgres_changes)===null||r===void 0?void 0:r.map(f=>f.filter))!==null&&a!==void 0?a:[],u=!!this.bindings[Qo.PRESENCE]&&this.bindings[Qo.PRESENCE].length>0||((i=this.params.config.presence)===null||i===void 0?void 0:i.enabled)===!0,m={},p={broadcast:o,presence:Object.assign(Object.assign({},l),{enabled:u}),postgres_changes:d,private:c};this.socket.accessTokenValue&&(m.access_token=this.socket.accessTokenValue),this._onError(f=>{t==null||t(Fr.CHANNEL_ERROR,f)}),this._onClose(()=>t==null?void 0:t(Fr.CLOSED)),this.updateJoinPayload(Object.assign({config:p},m)),this._updateFilterMessage(),this.channelAdapter.subscribe(s).receive("ok",async({postgres_changes:f})=>{if(this.socket._isManualToken()||this.socket.setAuth(),f===void 0){t==null||t(Fr.SUBSCRIBED);return}this._updatePostgresBindings(f,t)}).receive("error",f=>{this.state=Na.errored,t==null||t(Fr.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(f).join(", ")||"error")))}).receive("timeout",()=>{t==null||t(Fr.TIMED_OUT)})}return this}_updatePostgresBindings(t,s){var r;const a=this.bindings.postgres_changes,i=(r=a==null?void 0:a.length)!==null&&r!==void 0?r:0,o=[];for(let l=0;l<i;l++){const c=a[l],{filter:{event:d,schema:u,table:m,filter:p}}=c,f=t&&t[l];if(f&&f.event===d&&Kc.isFilterValueEqual(f.schema,u)&&Kc.isFilterValueEqual(f.table,m)&&Kc.isFilterValueEqual(f.filter,p))o.push(Object.assign(Object.assign({},c),{id:f.id}));else{this.unsubscribe(),this.state=Na.errored,s==null||s(Fr.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=o,this.state!=Na.errored&&s&&s(Fr.SUBSCRIBED)}presenceState(){return this.presence.state}async track(t,s={}){return await this.send({type:"presence",event:"track",payload:t},s.timeout||this.timeout)}async untrack(t={}){return await this.send({type:"presence",event:"untrack"},t)}on(t,s,r){const a=this.channelAdapter.isJoined()||this.channelAdapter.isJoining(),i=t===Qo.PRESENCE||t===Qo.POSTGRES_CHANGES;if(a&&i)throw this.socket.log("channel",`cannot add \`${t}\` callbacks for ${this.topic} after \`subscribe()\`.`),new Error(`cannot add \`${t}\` callbacks for ${this.topic} after \`subscribe()\`.`);return this._on(t,s,r)}async httpSend(t,s,r={}){var a;if(s==null)return Promise.reject("Payload is required for httpSend()");const i={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(i.Authorization=`Bearer ${this.socket.accessTokenValue}`);const o={method:"POST",headers:i,body:JSON.stringify({messages:[{topic:this.subTopic,event:t,payload:s,private:this.private}]})},l=await this._fetchWithTimeout(this.broadcastEndpointURL,o,(a=r.timeout)!==null&&a!==void 0?a:this.timeout);if(l.status===202)return{success:!0};let c=l.statusText;
60try{const d=await l.json();c=d.error||d.message||c}catch{}return Promise.reject(new Error(c))}async send(t,s={}){var r,a;if(!this.channelAdapter.canPush()&&t.type==="broadcast"){console.warn("Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery.");const{event:i,payload:o}=t,l={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(l.Authorization=`Bearer ${this.socket.accessTokenValue}`);const c={method:"POST",headers:l,body:JSON.stringify({messages:[{topic:this.subTopic,event:i,payload:o,private:this.private}]})};try{const d=await this._fetchWithTimeout(this.broadcastEndpointURL,c,(r=s.timeout)!==null&&r!==void 0?r:this.timeout);return await((a=d.body)===null||a===void 0?void 0:a.cancel()),d.ok?"ok":"error"}catch(d){return d.name==="AbortError"?"timed out":"error"}}else return new Promise(i=>{var o,l,c;const d=this.channelAdapter.push(t.type,t,s.timeout||this.timeout);t.type==="broadcast"&&!(!((c=(l=(o=this.params)===null||o===void 0?void 0:o.config)===null||l===void 0?void 0:l.broadcast)===null||c===void 0)&&c.ack)&&i("ok"),d.receive("ok",()=>i("ok")),d.receive("error",()=>i("error")),d.receive("timeout",()=>i("timed out"))})}updateJoinPayload(t){this.channelAdapter.updateJoinPayload(t)}async unsubscribe(t=this.timeout){return new Promise(s=>{this.channelAdapter.unsubscribe(t).receive("ok",()=>s("ok")).receive("timeout",()=>s("timed out")).receive("error",()=>s("error"))})}teardown(){this.channelAdapter.teardown()}async _fetchWithTimeout(t,s,r){const a=new AbortController,i=setTimeout(()=>a.abort(),r),o=await this.socket.fetch(t,Object.assign(Object.assign({},s),{signal:a.signal}));return clearTimeout(i),o}_on(t,s,r){const a=t.toLocaleLowerCase(),i=this.channelAdapter.on(t,r),o={type:a,filter:s,callback:r,ref:i};return this.bindings[a]?this.bindings[a].push(o):this.bindings[a]=[o],this._updateFilterMessage(),this}_onClose(t){this.channelAdapter.onClose(t)}_onError(t){this.channelAdapter.onError(t)}_updateFilterMessage(){this.channelAdapter.updateFilterBindings((t,s,r)=>{var a,i,o,l,c,d,u;const m=t.event.toLocaleLowerCase();if(this._notThisChannelEvent(m,r))return!1;const p=(a=this.bindings[m])===null||a===void 0?void 0:a.find(f=>f.ref===t.ref);if(!p)return!0;if(["broadcast","presence","postgres_changes"].includes(m))if("id"in p){const f=p.id,g=(i=p.filter)===null||i===void 0?void 0:i.event;return f&&((o=s.ids)===null||o===void 0?void 0:o.includes(f))&&(g==="*"||(g==null?void 0:g.toLocaleLowerCase())===((l=s.data)===null||l===void 0?void 0:l.type.toLocaleLowerCase()))}else{const f=(d=(c=p==null?void 0:p.filter)===null||c===void 0?void 0:c.event)===null||d===void 0?void 0:d.toLocaleLowerCase();return f==="*"||f===((u=s==null?void 0:s.event)===null||u===void 0?void 0:u.toLocaleLowerCase())}else return p.type.toLocaleLowerCase()===m})}_notThisChannelEvent(t,s){const{close:r,error:a,leave:i,join:o}=MN;return s&&[r,a,i,o].includes(t)&&s!==this.joinPush.ref}_updateFilterTransform(){this.channelAdapter.updatePayloadTransform((t,s,r)=>{if(typeof s=="object"&&"ids"in s){const a=s.data,{schema:i,table:o,commit_timestamp:l,type:c,errors:d}=a;return Object.assign(Object.assign({},{schema:i,table:o,commit_timestamp:l,eventType:c,new:{},old:{},errors:d}),this._getPayloadRecords(a))}return s})}copyBindings(t){if(this.joinedOnce)throw new Error("cannot copy bindings into joined channel");for(const s in t.bindings)for(const r of t.bindings[s])this._on(r.type,r.filter,r.callback)}static isFilterValueEqual(t,s){return(t??void 0)===(s??void 0)}_getPayloadRecords(t){const s={new:{},old:{}};return(t.type==="INSERT"||t.type==="UPDATE")&&(s.new=cw(t.columns,t.record)),(t.type==="UPDATE"||t.type==="DELETE")&&(s.old=cw(t.columns,t.old_record)),s}}class F3{constructor(t,s){this.socket=new L3(t,s)}get timeout(){return this.socket.timeout}get endPoint(){return this.socket.endPoint}get transport(){return this.socket.transport}get heartbeatIntervalMs(){return this.socket.heartbeatIntervalMs}get heartbeatCallback(){return this.socket.heartbeatCallback}set heartbeatCallback(t){this.socket.heartbeatCallback=t}get heartbeatTimer(){return this.socket.heartbeatTimer}get pendingHeartbeatRef(){return this.socket.pendingHeartbeatRef}get reconnectTimer(){return this.socket.reconnectTimer}get vsn(){return this.socket.vsn}get encode(){return this.socket.encode}get decode(){return this.socket.decode}get reconnectAfterMs(){return this.socket.reconnectAfterMs}get sendBuffer(){return this.socket.sendBuffer}get stateChangeCallbacks(){return this.socket.stateChangeCallbacks}connect(){this.socket.connect()}disconnect(t,s,r,a=1e4){return new Promise(i=>{setTimeout(()=>i("timeout"),a),this.socket.disconnect(()=>{t(),i("ok")},s,r)})}push(t){this.socket.push(t)}log(t,s,r){this.socket.log(t,s,r)}makeRef(){return this.socket.makeRef()}onOpen(t){this.socket.onOpen(t)}onClose(t){this.socket.onClose(t)}onError(t){this.socket.onError(t)}onMessage(t){this.socket.onMessage(t)}isConnected(){return this.socket.isConnected()}isConnecting(){return this.socket.connectionState()==wx.connecting}isDisconnecting(){return this.socket.connectionState()==wx.closing}connectionState(){return this.socket.connectionState()}endPointURL(){return this.socket.endPointURL()}sendHeartbeat(){this.socket.sendHeartbeat()}getSocket(){return this.socket}}const U3={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},B3=[1e3,2e3,5e3,1e4],V3=1e4,q3=`
61  addEventListener("message", (e) => {
62    if (e.data.event === "start") {
63      setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);
64    }
65  });`;class H3{get endPoint(){return this.socketAdapter.endPoint}get timeout(){return this.socketAdapter.timeout}get transport(){return this.socketAdapter.transport}get heartbeatCallback(){return this.socketAdapter.heartbeatCallback}get heartbeatIntervalMs(){return this.socketAdapter.heartbeatIntervalMs}get heartbeatTimer(){return this.worker?this._workerHeartbeatTimer:this.socketAdapter.heartbeatTimer}get pendingHeartbeatRef(){return this.worker?this._pendingWorkerHeartbeatRef:this.socketAdapter.pendingHeartbeatRef}get reconnectTimer(){return this.socketAdapter.reconnectTimer}get vsn(){return this.socketAdapter.vsn}get encode(){return this.socketAdapter.encode}get decode(){return this.socketAdapter.decode}get reconnectAfterMs(){return this.socketAdapter.reconnectAfterMs}get sendBuffer(){return this.socketAdapter.sendBuffer}get stateChangeCallbacks(){return this.socketAdapter.stateChangeCallbacks}constructor(t,s){var r;if(this.channels=new Array,this.accessTokenValue=null,this.accessToken=null,this.apiKey=null,this.httpEndpoint="",this.headers={},this.params={}
65,this.ref=0,this.serializer=new y3,this._manuallySetToken=!1,this._authPromise=null,this._workerHeartbeatTimer=void 0,this._pendingWorkerHeartbeatRef=null,this._resolveFetch=i=>i?(...o)=>i(...o):(...o)=>fetch(...o),!(!((r=s==null?void 0:s.params)===null||r===void 0)&&r.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=s.params.apikey;const a=this._initializeOptions(s);this.socketAdapter=new F3(t,a),this.httpEndpoint=FN(t),this.fetch=this._resolveFetch(s==null?void 0:s.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.isConnected())){this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this._setupConnectionHandlers();try{this.socketAdapter.connect()}catch(t){const s=t.message;throw s.includes("Node.js")?new Error(`${s}
66
67To use Realtime in Node.js, you need to provide a WebSocket implementation:
68
69Option 1: Use Node.js 22+ which has native WebSocket support
70Option 2: Install and provide the "ws" package:
71
72  npm install ws
73
74  import ws from "ws"
75  const client = new RealtimeClient(url, {
76    ...options,
77    transport: ws
78  })`):new Error(`WebSocket not available: ${s}`)}this._handleNodeJsRaceCondition()}}endpointURL(){return this.socketAdapter.endPointURL()}async disconnect(t,s){return this.isDisconnecting()?"ok":await this.socketAdapter.disconnect(()=>{clearInterval(this._workerHeartbeatTimer),this._terminateWorker()},t,s)}getChannels(){return this.channels}async removeChannel(t){const s=await t.unsubscribe();return s==="ok"&&t.teardown(),this.channels.length===0&&this.disconnect(),s}async removeAllChannels(){const t=this.channels.map(async r=>{const a=await r.unsubscribe();return r.teardown(),a}),s=await Promise.all(t);return this.disconnect(),s}log(t,s,r){this.socketAdapter.log(t,s,r)}connectionState(){return this.socketAdapter.connectionState()||wx.closed}isConnected(){return this.socketAdapter.isConnected()}isConnecting(){return this.socketAdapter.isConnecting()}isDisconnecting(){return this.socketAdapter.isDisconnecting()}channel(t,s={config:{}}){const r=`realtime:${t}`,a=this.getChannels().find(i=>i.topic===r);if(a)return a;{const i=new Kc(`realtime:${t}`,s,this);return this.channels.push(i),i}}push(t){this.socketAdapter.push(t)}async setAuth(t=null){this._authPromise=this._performAuth(t);try{await this._authPromise}finally{this._authPromise=null}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){this.socketAdapter.sendHeartbeat()}onHeartbeat(t){this.socketAdapter.heartbeatCallback=this._wrapHeartbeatCallback(t)}_makeRef(){return this.socketAdapter.makeRef()}_remove(t){this.channels=this.channels.filter(s=>s.topic!==t.topic)}async _performAuth(t=null){let s,r=!1;if(t)s=t,r=!0;else if(this.accessToken)try{s=await this.accessToken()}catch(a){this.log("error","Error fetching access token from callback",a),s=this.accessTokenValue}else s=this.accessTokenValue;r?this._manuallySetToken=!0:this.accessToken&&(this._manuallySetToken=!1),this.accessTokenValue!=s&&(this.accessTokenValue=s,this.channels.forEach(a=>{const i={access_token:s,version:p3};s&&a.updateJoinPayload(i),a.joinedOnce&&a.channelAdapter.isJoined()&&a.channelAdapter.push(MN.access_token,{access_token:s})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(t="general"){this._isManualToken()||this.setAuth().catch(s=>{this.log("error",`Error setting auth in ${t}`,s)})}_setupConnectionHandlers(){this.socketAdapter.onOpen(()=>{(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).catch(s=>{this.log("error","error waiting for auth on connect",s)}),this.worker&&!this.workerRef&&this._startWorkerHeartbeat()}),this.socketAdapter.onClose(()=>{this.worker&&this.workerRef&&this._terminateWorker()}),this.socketAdapter.onMessage(t=>{t.ref&&t.ref===this._pendingWorkerHeartbeatRef&&(this._pendingWorkerHeartbeatRef=null)})}_handleNodeJsRaceCondition(){this.socketAdapter.isConnected()&&this.socketAdapter.getSocket().onConnOpen()}_wrapHeartbeatCallback(t){return(s,r)=>{s=="sent"&&this._setAuthSafely(),t&&t(s,r)}}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");const t=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(t),this.workerRef.onerror=s=>{this.log("worker","worker error",s.message),this._terminateWorker(),this.disconnect()},this.workerRef.onmessage=s=>{s.data.event==="keepAlive"&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_terminateWorker(){this.workerRef&&(this.log("worker","terminating worker"),this.workerRef.terminate(),this.workerRef=void 0)}_workerObjectUrl(t){let s;if(t)s=t;else{const r=new Blob([q3],{type:"application/javascript"});s=URL.createObjectURL(r)}return s}_initializeOptions(t){var s,r,a,i,o,l,c,d,u;this.worker=(s=t==null?void 0:t.worker)!==null&&s!==void 0?s:!1,this.accessToken=(r=t==null?void 0:t.accessToken)!==null&&r!==void 0?r:null;const m={};
78m.timeout=(a=t==null?void 0:t.timeout)!==null&&a!==void 0?a:x3,m.heartbeatIntervalMs=(i=t==null?void 0:t.heartbeatIntervalMs)!==null&&i!==void 0?i:U3.HEARTBEAT_INTERVAL,m.transport=(o=t==null?void 0:t.transport)!==null&&o!==void 0?o:h3.getWebSocketConstructor(),m.params=t==null?void 0:t.params,m.logger=t==null?void 0:t.logger,m.heartbeatCallback=this._wrapHeartbeatCallback(t==null?void 0:t.heartbeatCallback),m.reconnectAfterMs=(l=t==null?void 0:t.reconnectAfterMs)!==null&&l!==void 0?l:x=>B3[x-1]||V3;let p,f;const g=(c=t==null?void 0:t.vsn)!==null&&c!==void 0?c:g3;switch(g){case f3:p=(x,b)=>b(JSON.stringify(x)),f=(x,b)=>b(JSON.parse(x));break;case DN:p=this.serializer.encode.bind(this.serializer),f=this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${m.vsn}`)}if(m.vsn=g,m.encode=(d=t==null?void 0:t.encode)!==null&&d!==void 0?d:p,m.decode=(u=t==null?void 0:t.decode)!==null&&u!==void 0?u:f,m.beforeReconnect=this._reconnectAuth.bind(this),(t!=null&&t.logLevel||t!=null&&t.log_level)&&(this.logLevel=t.logLevel||t.log_level,m.params=Object.assign(Object.assign({},m.params),{log_level:this.logLevel})),this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=t==null?void 0:t.workerUrl,m.autoSendHeartbeat=!this.worker}return m}async _reconnectAuth(){await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()}}var kd=class extends Error{constructor(e,t){var s;super(e),this.name="IcebergError",this.status=t.status,this.icebergType=t.icebergType,this.icebergCode=t.icebergCode,this.details=t.details,this.isCommitStateUnknown=t.icebergType==="CommitStateUnknownException"||[500,502,504].includes(t.status)&&((s=t.icebergType)==null?void 0:s.includes("CommitState"))===!0}isNotFound(){return this.status===404}isConflict(){return this.status===409}isAuthenticationTimeout(){return this.status===419}};function W3(e,t,s){const r=new URL(t,e);if(s)for(const[a,i]of Object.entries(s))i!==void 0&&r.searchParams.set(a,i);return r.toString()}async function G3(e){return!e||e.type==="none"?{}:e.type==="bearer"?{Authorization:`Bearer ${e.token}`}:e.type==="header"?{[e.name]:e.value}:e.type==="custom"?await e.getHeaders():{}}function Y3(e){const t=e.fetchImpl??globalThis.fetch;return{async request({method:s,path:r,query:a,body:i,headers:o}){const l=W3(e.baseUrl,r,a),c=await G3(e.auth),d=await t(l,{method:s,headers:{...i?{"Content-Type":"application/json"}:{},...c,...o},body:i?JSON.stringify(i):void 0}),u=await d.text(),m=(d.headers.get("content-type")||"").includes("application/json"),p=m&&u?JSON.parse(u):u;if(!d.ok){const f=m?p:void 0,g=f==null?void 0:f.error;throw new kd((g==null?void 0:g.message)??`Request failed with status ${d.status}`,{status:d.status,icebergType:g==null?void 0:g.type,icebergCode:g==null?void 0:g.code,details:f})}return{status:d.status,headers:d.headers,data:p}}}}function Ju(e){return e.join("�")}var K3=class{constructor(e,t=""){this.client=e,this.prefix=t}async listNamespaces(e){const t=e?{parent:Ju(e.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:t})).data.namespaces.map(r=>({namespace:r}))}async createNamespace(e,t){const s={namespace:e.namespace,properties:t==null?void 0:t.properties};return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:s})).data}async dropNamespace(e){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${Ju(e.namespace)}`})}async loadNamespaceMetadata(e){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Ju(e.namespace)}`})).data.properties}}async namespaceExists(e){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${Ju(e.namespace)}`}),!0}catch(t){if(t instanceof kd&&t.status===404)return!1;throw t}}async createNamespaceIfNotExists(e,t){try{return await this.createNamespace(e,t)}catch(s){if(s instanceof kd&&s.status===409)return;throw s}}};function xo(e){return e.join("�")}var Q3=class{constructor(e,t="",s){this.client=e,this.prefix=t,this.accessDelegation=s}async listTables(e){return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${xo(e.namespace)}/tables`})).data.identifiers}async createTable(e,t){const s={};return this.accessDelegation&&(s["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${xo(e.namespace)}/tables`,body:t,headers:s})).data.metadata}async updateTable(e,t){const s=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${xo(e.namespace)}/tables/${e.name}`,body:t});return{"metadata-location":s.data["metadata-location"],metadata:s.data.metadata}}async dropTable(e,t){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${xo(e.namespace)}/tables/${e.name}`,query:{purgeRequested:String((t==null?void 0:t.purge)??!1)}})}async loadTable(e){const t={};return this.accessDelegation&&(t["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${xo(e.namespace)}/tables/${e.name}`,headers:t})).data.metadata}async tableExists(e){const t={};this.accessDelegation&&(t["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${xo(e.namespace)}/tables/${e.name}`,headers:t}),!0}catch(s){if(s instanceof kd&&s.status===404)return!1;throw s}}async createTableIfNotExists(e,t){try{return await this.createTable(e,t)}catch(s){if(s instanceof kd&&s.status===409)return await this.loadTable({namespace:e.namespace,name:t.name});throw s}}},J3=class{constructor(e){var r;let t="v1";e.catalogName&&(t+=`/${e.catalogName}`);const s=e.baseUrl.endsWith("/")?e.baseUrl:`${e.baseUrl}/`;this.client=Y3({baseUrl:s,auth:e.auth,fetchImpl:e.fetch}),this.accessDelegation=(r=e.accessDelegation)==null?void 0:r.join(","),this.namespaceOps=new K3(this.client,t),this.tableOps=new Q3(this.client,t,this.accessDelegation)}async listNamespaces(e){return this.namespaceOps.listNamespaces(e)}async createNamespace(e,t){return this.namespaceOps.createNamespace(e,t)}async dropNamespace(e){await this.namespaceOps.dropNamespace(e)}async loadNamespaceMetadata(e){return this.namespaceOps.loadNamespaceMetadata(e)}async listTables(e){return this.tableOps.listTables(e)}
78async createTable(e,t){return this.tableOps.createTable(e,t)}async updateTable(e,t){return this.tableOps.updateTable(e,t)}async dropTable(e,t){await this.tableOps.dropTable(e,t)}async loadTable(e){return this.tableOps.loadTable(e)}async namespaceExists(e){return this.namespaceOps.namespaceExists(e)}async tableExists(e){return this.tableOps.tableExists(e)}async createNamespaceIfNotExists(e,t){return this.namespaceOps.createNamespaceIfNotExists(e,t)}async createTableIfNotExists(e,t){return this.tableOps.createTableIfNotExists(e,t)}},op=class extends Error{constructor(e,t="storage",s,r){super(e),this.__isStorageError=!0,this.namespace=t,this.name=t==="vectors"?"StorageVectorsError":"StorageError",this.status=s,this.statusCode=r}};function lp(e){return typeof e=="object"&&e!==null&&"__isStorageError"in e}var Nx=class extends op{constructor(e,t,s,r="storage"){super(e,r,t,s),this.name=r==="vectors"?"StorageVectorsApiError":"StorageApiError",this.status=t,this.statusCode=s}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}},BN=class extends op{constructor(e,t,s="storage"){super(e,s),this.name=s==="vectors"?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=t}};const Z3=e=>e?(...t)=>e(...t):(...t)=>fetch(...t),X3=e=>{if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},Sx=e=>{if(Array.isArray(e))return e.map(s=>Sx(s));if(typeof e=="function"||e!==Object(e))return e;const t={};return Object.entries(e).forEach(([s,r])=>{const a=s.replace(/([-_][a-z])/gi,i=>i.toUpperCase().replace(/[-_]/g,""));t[a]=Sx(r)}),t},eO=e=>!e||typeof e!="string"||e.length===0||e.length>100||e.trim()!==e||e.includes("/")||e.includes("\\")?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(e);function Nd(e){"@babel/helpers - typeof";return Nd=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},Nd(e)}function tO(e,t){if(Nd(e)!="object"||!e)return e;var s=e[Symbol.toPrimitive];if(s!==void 0){var r=s.call(e,t||"default");if(Nd(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function sO(e){var t=tO(e,"string");return Nd(t)=="symbol"?t:t+""}function nO(e,t,s){return(t=sO(t))in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s,e}function mw(e,t){var s=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),s.push.apply(s,r)}return s}function Ke(e){for(var t=1;t<arguments.length;t++){var s=arguments[t]!=null?arguments[t]:{};t%2?mw(Object(s),!0).forEach(function(r){nO(e,r,s[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(s)):mw(Object(s)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(s,r))})}return e}const pw=e=>{var t;return e.msg||e.message||e.error_description||(typeof e.error=="string"?e.error:(t=e.error)===null||t===void 0?void 0:t.message)||JSON.stringify(e)},rO=async(e,t,s,r)=>{if(e!==null&&typeof e=="object"&&typeof e.json=="function"){const a=e;let i=parseInt(a.status,10);Number.isFinite(i)||(i=500),a.json().then(o=>{const l=(o==null?void 0:o.statusCode)||(o==null?void 0:o.code)||i+"";t(new Nx(pw(o),i,l,r))}).catch(()=>{const o=i+"";t(new Nx(a.statusText||`HTTP ${i} error`,i,o,r))})}else t(new BN(pw(e),e,r))},aO=(e,t,s,r)=>{const a={method:e,headers:(t==null?void 0:t.headers)||{}};return e==="GET"||e==="HEAD"||!r?Ke(Ke({},a),s):(X3(r)?(a.headers=Ke({"Content-Type":"application/json"},t==null?void 0:t.headers),a.body=JSON.stringify(r)):a.body=r,t!=null&&t.duplex&&(a.duplex=t.duplex),Ke(Ke({},a),s))};async function wc(e,t,s,r,a,i,o){return new Promise((l,c)=>{e(s,aO(t,r,a,i)).then(d=>{if(!d.ok)throw d;if(r!=null&&r.noResolveJson)return d;if(o==="vectors"){const u=d.headers.get("content-type");if(d.headers.get("content-length")==="0"||d.status===204)return{};if(!u||!u.includes("application/json"))return{}}return d.json()}).then(d=>l(d)).catch(d=>rO(d,c,r,o))})}function VN(e="storage"){return{get:async(t,s,r,a)=>wc(t,"GET",s,r,a,void 0,e),post:async(t,s,r,a,i)=>wc(t,"POST",s,a,i,r,e),put:async(t,s,r,a,i)=>wc(t,"PUT",s,a,i,r,e),head:async(t,s,r,a)=>wc(t,"HEAD",s,Ke(Ke({},r),{},{noResolveJson:!0}),a,void 0,e),remove:async(t,s,r,a,i)=>wc(t,"DELETE",s,a,i,r,e)}}const iO=VN("storage"),{get:Sd,post:Vn,put:Cx,head:oO,remove:xy}=iO,cn=VN("vectors");var ic=class{constructor(e,t={},s,r="storage"){this.shouldThrowOnError=!1,this.url=e,this.headers=t,this.fetch=Z3(s),this.namespace=r}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(e,t){return this.headers=Ke(Ke({},this.headers),{},{[e]:t}),this}async handleOperation(e){var t=this;try{return{data:await e(),error:null}}catch(s){if(t.shouldThrowOnError)throw s;if(lp(s))return{data:null,error:s};throw s}}}
78,lO=class{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t}then(e,t){return this.execute().then(e,t)}async execute(){var e=this;try{return{data:(await e.downloadFn()).body,error:null}}catch(t){if(e.shouldThrowOnError)throw t;if(lp(t))return{data:null,error:t};throw t}}};let qN;qN=Symbol.toStringTag;var cO=class{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t,this[qN]="BlobDownloadBuilder",this.promise=null}asStream(){return new lO(this.downloadFn,this.shouldThrowOnError)}then(e,t){return this.getPromise().then(e,t)}catch(e){return this.getPromise().catch(e)}finally(e){return this.getPromise().finally(e)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){var e=this;try{return{data:await(await e.downloadFn()).blob(),error:null}}catch(t){if(e.shouldThrowOnError)throw t;if(lp(t))return{data:null,error:t};throw t}}};const dO={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},fw={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};var uO=class extends ic{constructor(e,t={},s,r){super(e,t,r,"storage"),this.bucketId=s}async uploadOrUpdate(e,t,s,r){var a=this;return a.handleOperation(async()=>{let i;const o=Ke(Ke({},fw),r);let l=Ke(Ke({},a.headers),e==="POST"&&{"x-upsert":String(o.upsert)});const c=o.metadata;typeof Blob<"u"&&s instanceof Blob?(i=new FormData,i.append("cacheControl",o.cacheControl),c&&i.append("metadata",a.encodeMetadata(c)),i.append("",s)):typeof FormData<"u"&&s instanceof FormData?(i=s,i.has("cacheControl")||i.append("cacheControl",o.cacheControl),c&&!i.has("metadata")&&i.append("metadata",a.encodeMetadata(c))):(i=s,l["cache-control"]=`max-age=${o.cacheControl}`,l["content-type"]=o.contentType,c&&(l["x-metadata"]=a.toBase64(a.encodeMetadata(c))),(typeof ReadableStream<"u"&&i instanceof ReadableStream||i&&typeof i=="object"&&"pipe"in i&&typeof i.pipe=="function")&&!o.duplex&&(o.duplex="half")),r!=null&&r.headers&&(l=Ke(Ke({},l),r.headers));const d=a._removeEmptyFolders(t),u=a._getFinalPath(d),m=await(e=="PUT"?Cx:Vn)(a.fetch,`${a.url}/object/${u}`,i,Ke({headers:l},o!=null&&o.duplex?{duplex:o.duplex}:{}));return{path:d,id:m.Id,fullPath:m.Key}})}async upload(e,t,s){return this.uploadOrUpdate("POST",e,t,s)}async uploadToSignedUrl(e,t,s,r){var a=this;const i=a._removeEmptyFolders(e),o=a._getFinalPath(i),l=new URL(a.url+`/object/upload/sign/${o}`);return l.searchParams.set("token",t),a.handleOperation(async()=>{let c;const d=Ke(Ke({},fw),r),u=Ke(Ke({},a.headers),{"x-upsert":String(d.upsert)});return typeof Blob<"u"&&s instanceof Blob?(c=new FormData,c.append("cacheControl",d.cacheControl),c.append("",s)):typeof FormData<"u"&&s instanceof FormData?(c=s,c.append("cacheControl",d.cacheControl)):(c=s,u["cache-control"]=`max-age=${d.cacheControl}`,u["content-type"]=d.contentType),{path:i,fullPath:(await Cx(a.fetch,l.toString(),c,{headers:u})).Key}})}async createSignedUploadUrl(e,t){var s=this;return s.handleOperation(async()=>{let r=s._getFinalPath(e);const a=Ke({},s.headers);t!=null&&t.upsert&&(a["x-upsert"]="true");const i=await Vn(s.fetch,`${s.url}/object/upload/sign/${r}`,{},{headers:a}),o=new URL(s.url+i.url),l=o.searchParams.get("token");if(!l)throw new op("No token returned by API");return{signedUrl:o.toString(),path:e,token:l}})}async update(e,t,s){return this.uploadOrUpdate("PUT",e,t,s)}async move(e,t,s){var r=this;return r.handleOperation(async()=>await Vn(r.fetch,`${r.url}/object/move`,{bucketId:r.bucketId,sourceKey:e,destinationKey:t,de
78stinationBucket:s==null?void 0:s.destinationBucket},{headers:r.headers}))}async copy(e,t,s){var r=this;return r.handleOperation(async()=>({path:(await Vn(r.fetch,`${r.url}/object/copy`,{bucketId:r.bucketId,sourceKey:e,destinationKey:t,destinationBucket:s==null?void 0:s.destinationBucket},{headers:r.headers})).Key}))}async createSignedUrl(e,t,s){var r=this;return r.handleOperation(async()=>{let a=r._getFinalPath(e);const i=typeof(s==null?void 0:s.transform)=="object"&&s.transform!==null&&Object.keys(s.transform).length>0;let o=await Vn(r.fetch,`${r.url}/object/sign/${a}`,Ke({expiresIn:t},i?{transform:s.transform}:{}),{headers:r.headers});const l=s!=null&&s.download?`&download=${s.download===!0?"":s.download}`:"",c=i&&o.signedURL.includes("/object/sign/")?o.signedURL.replace("/object/sign/","/render/image/sign/"):o.signedURL;return{signedUrl:encodeURI(`${r.url}${c}${l}`)}})}async createSignedUrls(e,t,s){var r=this;return r.handleOperation(async()=>{const a=await Vn(r.fetch,`${r.url}/object/sign/${r.bucketId}`,{expiresIn:t,paths:e},{headers:r.headers}),i=s!=null&&s.download?`&download=${s.download===!0?"":s.download}`:"";return a.map(o=>Ke(Ke({},o),{},{signedUrl:o.signedURL?encodeURI(`${r.url}${o.signedURL}${i}`):null}))})}download(e,t,s){const r=typeof(t==null?void 0:t.transform)<"u"?"render/image/authenticated":"object",a=this.transformOptsToQueryString((t==null?void 0:t.transform)||{}),i=a?`?${a}`:"",o=this._getFinalPath(e),l=()=>Sd(this.fetch,`${this.url}/${r}/${o}${i}`,{headers:this.headers,noResolveJson:!0},s);return new cO(l,this.shouldThrowOnError)}async info(e){var t=this;const s=t._getFinalPath(e);return t.handleOperation(async()=>Sx(await Sd(t.fetch,`${t.url}/object/info/${s}`,{headers:t.headers})))}async exists(e){var t=this;const s=t._getFinalPath(e);try{return await oO(t.fetch,`${t.url}/object/${s}`,{headers:t.headers}),{data:!0,error:null}}catch(a){if(t.shouldThrowOnError)throw a;if(lp(a)){var r;const i=a instanceof Nx?a.status:a instanceof BN?(r=a.originalError)===null||r===void 0?void 0:r.status:void 0;if(i!==void 0&&[400,404].includes(i))return{data:!1,error:a}}throw a}}getPublicUrl(e,t){const s=this._getFinalPath(e),r=[],a=t!=null&&t.download?`download=${t.download===!0?"":t.download}`:"";a!==""&&r.push(a);const i=typeof(t==null?void 0:t.transform)<"u"?"render/image":"object",o=this.transformOptsToQueryString((t==null?void 0:t.transform)||{});o!==""&&r.push(o);let l=r.join("&");return l!==""&&(l=`?${l}`),{data:{publicUrl:encodeURI(`${this.url}/${i}/public/${s}${l}`)}}}async remove(e){var t=this;return t.handleOperation(async()=>await xy(t.fetch,`${t.url}/object/${t.bucketId}`,{prefixes:e},{headers:t.headers}))}async list(e,t,s){var r=this;return r.handleOperation(async()=>{const a=Ke(Ke(Ke({},dO),t),{},{prefix:e||""});return await Vn(r.fetch,`${r.url}/object/list/${r.bucketId}`,a,{headers:r.headers},s)})}async listV2(e,t){var s=this;return s.handleOperation(async()=>{const r=Ke({},e);return await Vn(s.fetch,`${s.url}/object/list-v2/${s.bucketId}`,r,{headers:s.headers},t)})}encodeMetadata(e){return JSON.stringify(e)}toBase64(e){return typeof Buffer<"u"?Buffer.from(e).toString("base64"):btoa(e)}_getFinalPath(e){return`${this.bucketId}/${e.replace(/^\/+/,"")}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){const t=[];return e.width&&t.push(`width=${e.width}`),e.height&&t.push(`height=${e.height}`),e.resize&&t.push(`resize=${e.resize}`),e.format&&t.push(`format=${e.format}`),e.quality&&t.push(`quality=${e.quality}`),t.join("&")}};const hO="2.101.0",au={"X-Client-Info":`storage-js/${hO}`};var mO=class extends ic{constructor(e,t={},s,r){const a=new URL(e);r!=null&&r.useNewHostname&&/supabase\.(co|in|red)$/.test(a.hostname)&&!a.hostname.includes("storage.supabase.")&&(a.hostname=a.hostname.replace("supabase.","storage.supabase."));const i=a.href.replace(/\/$/,""),o=Ke(Ke({},au),t);super(i,o,s,"storage")}async listBuckets(e){var t=this;return t.handleOperation(async()=>{const s=t.listBucketOptionsToQueryString(e);return await Sd(t.fetch,`${t.url}/bucket${s}`,{headers:t.headers})})}async getBucket(e){var t=this;return t.handleOperation(async()=>await Sd(t.fetch,`${t.url}/bucket/${e}`,{headers:t.headers}))}async createBucket(e,t={public:!1}){var s=this;return s.handleOperation(async()=>await Vn(s.fetch,`${s.url}/bucket`,{id:e,name:e,type:t.type,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:s.headers}))}async updateBucket(e,t){var s=this;return s.handleOperation(async()=>await Cx(s.fetch,`${s.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:s.headers}))}async emptyBucket(e){var t=this;return t.handleOperation(async()=>await Vn(t.fetch,`${t.url}/bucket/${e}/empty`,{},{headers:t.headers}))}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await xy(t.fetch,`${t.url}/bucket/${e}`,{},{headers:t.headers}))}listBucketOptionsToQueryString(e){const t={};return e&&("limit"in e&&(t.limit=String(e.limit)),"offset"in e&&(t.offset=String(e.offset)),e.search&&(t.search=e.search),e.sortColumn&&(t.sortColumn=e.sortColumn),e.sortOrder&&(t.sortOrder=e.sortOrder)),Object.keys(t).length>0?"?"+new URLSearchParams(t).toString():""}},pO=class extends ic{constructor(e,t={},s){const r=e.replace(/\/$/,""),a=Ke(Ke({},au),t);super(r,a,s,"storage")}async createBucket(e){var t=this;return t.handleOperation(async()=>await Vn(t.fetch,`${t.url}/bucket`,{name:e},{headers:t.headers}))}async listBuckets(e){var t=this;return t.handleOperation(async()=>{const s=new URLSearchParams;(e==null?void 0:e.limit)!==void 0&&s.set("limit",e.limit.toString()),(e==null?void 0:e.offset)!==void 0&&s.set("offset",e.offset.toString()),e!=null&&e.sortColumn&&s.set("sortColumn",e.sortColumn),e!=null&&e.sortOrder&&s.set("sortOrder",e.sortOrder),e!=null&&e.search&&s.set("search",e.search);const r=s.toString(),a=r?`${t.url}/bucket?${r}`:`${t.url}/bucket`;return await Sd(t.fetch,a,{headers:t.headers})})}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await xy(t.fetch,`${t.url}/bucket/${e}`,{},{headers:t.headers}))}from(e){var t=this;if(!eO(e))throw new op("Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines and should avoid the use of any other characters.");const s=new J3({baseUrl:this.url,catalogName:e,auth:{type:"custom",getHeaders:async()=>t.headers},fetch:this.fetch}
78),r=this.shouldThrowOnError;return new Proxy(s,{get(a,i){const o=a[i];return typeof o!="function"?o:async(...l)=>{try{return{data:await o.apply(a,l),error:null}}catch(c){if(r)throw c;return{data:null,error:c}}}}})}},fO=class extends ic{constructor(e,t={},s){const r=e.replace(/\/$/,""),a=Ke(Ke({},au),{},{"Content-Type":"application/json"},t);super(r,a,s,"vectors")}async createIndex(e){var t=this;return t.handleOperation(async()=>await cn.post(t.fetch,`${t.url}/CreateIndex`,e,{headers:t.headers})||{})}async getIndex(e,t){var s=this;return s.handleOperation(async()=>await cn.post(s.fetch,`${s.url}/GetIndex`,{vectorBucketName:e,indexName:t},{headers:s.headers}))}async listIndexes(e){var t=this;return t.handleOperation(async()=>await cn.post(t.fetch,`${t.url}/ListIndexes`,e,{headers:t.headers}))}async deleteIndex(e,t){var s=this;return s.handleOperation(async()=>await cn.post(s.fetch,`${s.url}/DeleteIndex`,{vectorBucketName:e,indexName:t},{headers:s.headers})||{})}},gO=class extends ic{constructor(e,t={},s){const r=e.replace(/\/$/,""),a=Ke(Ke({},au),{},{"Content-Type":"application/json"},t);super(r,a,s,"vectors")}async putVectors(e){var t=this;if(e.vectors.length<1||e.vectors.length>500)throw new Error("Vector batch size must be between 1 and 500 items");return t.handleOperation(async()=>await cn.post(t.fetch,`${t.url}/PutVectors`,e,{headers:t.headers})||{})}async getVectors(e){var t=this;return t.handleOperation(async()=>await cn.post(t.fetch,`${t.url}/GetVectors`,e,{headers:t.headers}))}async listVectors(e){var t=this;if(e.segmentCount!==void 0){if(e.segmentCount<1||e.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");if(e.segmentIndex!==void 0&&(e.segmentIndex<0||e.segmentIndex>=e.segmentCount))throw new Error(`segmentIndex must be between 0 and ${e.segmentCount-1}`)}return t.handleOperation(async()=>await cn.post(t.fetch,`${t.url}/ListVectors`,e,{headers:t.headers}))}async queryVectors(e){var t=this;return t.handleOperation(async()=>await cn.post(t.fetch,`${t.url}/QueryVectors`,e,{headers:t.headers}))}async deleteVectors(e){var t=this;if(e.keys.length<1||e.keys.length>500)throw new Error("Keys batch size must be between 1 and 500 items");return t.handleOperation(async()=>await cn.post(t.fetch,`${t.url}/DeleteVectors`,e,{headers:t.headers})||{})}},xO=class extends ic{constructor(e,t={},s){const r=e.replace(/\/$/,""),a=Ke(Ke({},au),{},{"Content-Type":"application/json"},t);super(r,a,s,"vectors")}async createBucket(e){var t=this;return t.handleOperation(async()=>await cn.post(t.fetch,`${t.url}/CreateVectorBucket`,{vectorBucketName:e},{headers:t.headers})||{})}async getBucket(e){var t=this;return t.handleOperation(async()=>await cn.post(t.fetch,`${t.url}/GetVectorBucket`,{vectorBucketName:e},{headers:t.headers}))}async listBuckets(e={}){var t=this;return t.handleOperation(async()=>await cn.post(t.fetch,`${t.url}/ListVectorBuckets`,e,{headers:t.headers}))}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await cn.post(t.fetch,`${t.url}/DeleteVectorBucket`,{vectorBucketName:e},{headers:t.headers})||{})}},vO=class extends xO{constructor(e,t={}){super(e,t.headers||{},t.fetch)}from(e){return new yO(this.url,this.headers,e,this.fetch)}async createBucket(e){var t=()=>super.createBucket,s=this;return t().call(s,e)}async getBucket(e){var t=()=>super.getBucket,s=this;return t().call(s,e)}async listBuckets(e={}){var t=()=>super.listBuckets,s=this;return t().call(s,e)}async deleteBucket(e){var t=()=>super.deleteBucket,s=this;return t().call(s,e)}},yO=class extends fO{constructor(e,t,s,r){super(e,t,r),this.vectorBucketName=s}async createIndex(e){var t=()=>super.createIndex,s=this;return t().call(s,Ke(Ke({},e),{},{vectorBucketName:s.vectorBucketName}))}async listIndexes(e={}){var t=()=>super.listIndexes,s=this;return t().call(s,Ke(Ke({},e),{},{vectorBucketName:s.vectorBucketName}))}async getIndex(e){var t=()=>super.getIndex,s=this;return t().call(s,s.vectorBucketName,e)}async deleteIndex(e){var t=()=>super.deleteIndex,s=this;return t().call(s,s.vectorBucketName,e)}index(e){return new bO(this.url,this.headers,this.vectorBucketName,e,this.fetch)}},bO=class extends gO{constructor(e,t,s,r,a){super(e,t,a),this.vectorBucketName=s,this.indexName=r}async putVectors(e){var t=()=>super.putVectors,s=this;return t().call(s,Ke(Ke({},e),{},{vectorBucketName:s.vectorBucketName,indexName:s.indexName}))}async getVectors(e){var t=()=>super.getVectors,s=this;return t().call(s,Ke(Ke({},e),{},{vectorBucketName:s.vectorBucketName,indexName:s.indexName}))}async listVectors(e={}){var t=()=>super.listVectors,s=this;return t().call(s,Ke(Ke({},e),{},{vectorBucketName:s.vectorBucketName,indexName:s.indexName}))}async queryVectors(e){var t=()=>super.queryVectors,s=this;return t().call(s,Ke(Ke({},e),{},{vectorBucketName:s.vectorBucketName,indexName:s.indexName}))}async deleteVectors(e){var t=()=>super.deleteVectors,s=this;return t().call(s,Ke(Ke({},e),{},{vectorBucketName:s.vectorBucketName,indexName:s.indexName}))}},wO=class extends mO{constructor(e,t={},s,r){super(e,t,s,r)}from(e){return new uO(this.url,this.headers,e,this.fetch)}get vectors(){return new vO(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new pO(this.url+"/iceberg",this.headers,this.fetch)}};const HN="2.101.0",Lo=30*1e3,Tx=3,bf=Tx*Lo,jO="http://localhost:9999",_O="supabase.auth.token",kO={"X-Client-Info":`gotrue-js/${HN}`},Px="X-Supabase-Api-Version",WN={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},NO=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,SO=10*60*1e3;
78class Cd extends Error{constructor(t,s,r){super(t),this.__isAuthError=!0,this.name="AuthError",this.status=s,this.code=r}}function Fe(e){return typeof e=="object"&&e!==null&&"__isAuthError"in e}class CO extends Cd{constructor(t,s,r){super(t,s,r),this.name="AuthApiError",this.status=s,this.code=r}}function TO(e){return Fe(e)&&e.name==="AuthApiError"}class Ti extends Cd{constructor(t,s){super(t),this.name="AuthUnknownError",this.originalError=s}}class aa extends Cd{constructor(t,s,r,a){super(t,r,a),this.name=s,this.status=r}}class rn extends aa{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function wf(e){return Fe(e)&&e.name==="AuthSessionMissingError"}class vo extends aa{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class Zu extends aa{constructor(t){super(t,"AuthInvalidCredentialsError",400,void 0)}}class Xu extends aa{constructor(t,s=null){super(t,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=s}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}function PO(e){return Fe(e)&&e.name==="AuthImplicitGrantRedirectError"}class gw extends aa{constructor(t,s=null){super(t,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=s}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class EO extends aa{constructor(){super("PKCE code verifier not found in storage. This can happen if the auth flow was initiated in a different browser or device, or if the storage was cleared. For SSR frameworks (Next.js, SvelteKit, etc.), use @supabase/ssr on both the server and client to store the code verifier in cookies.","AuthPKCECodeVerifierMissingError",400,"pkce_code_verifier_not_found")}}class Ex extends aa{constructor(t,s){super(t,"AuthRetryableFetchError",s,void 0)}}function jf(e){return Fe(e)&&e.name==="AuthRetryableFetchError"}class xw extends aa{constructor(t,s,r){super(t,"AuthWeakPasswordError",s,"weak_password"),this.reasons=r}}class Ax extends aa{constructor(t){super(t,"AuthInvalidJwtError",400,"invalid_jwt")}}const dm="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),vw=` 	
79\r=`.split(""),AO=(()=>{const e=new Array(128);for(let t=0;t<e.length;t+=1)e[t]=-1;for(let t=0;t<vw.length;t+=1)e[vw[t].charCodeAt(0)]=-2;for(let t=0;t<dm.length;t+=1)e[dm[t].charCodeAt(0)]=t;return e})();function yw(e,t,s){if(e!==null)for(t.queue=t.queue<<8|e,t.queuedBits+=8;t.queuedBits>=6;){const r=t.queue>>t.queuedBits-6&63;s(dm[r]),t.queuedBits-=6}else if(t.queuedBits>0)for(t.queue=t.queue<<6-t.queuedBits,t.queuedBits=6;t.queuedBits>=6;){const r=t.queue>>t.queuedBits-6&63;s(dm[r]),t.queuedBits-=6}}function GN(e,t,s){const r=AO[e];if(r>-1)for(t.queue=t.queue<<6|r,t.queuedBits+=6;t.queuedBits>=8;)s(t.queue>>t.queuedBits-8&255),t.queuedBits-=8;else{if(r===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(e)}"`)}}function bw(e){const t=[],s=o=>{t.push(String.fromCodePoint(o))},r={utf8seq:0,codepoint:0},a={queue:0,queuedBits:0},i=o=>{LO(o,r,s)};for(let o=0;o<e.length;o+=1)GN(e.charCodeAt(o),a,i);return t.join("")}function RO(e,t){if(e<=127){t(e);return}else if(e<=2047){t(192|e>>6),t(128|e&63);return}else if(e<=65535){t(224|e>>12),t(128|e>>6&63),t(128|e&63);return}else if(e<=1114111){t(240|e>>18),t(128|e>>12&63),t(128|e>>6&63),t(128|e&63);return}throw new Error(`Unrecognized Unicode codepoint: ${e.toString(16)}`)}function $O(e,t){for(let s=0;s<e.length;s+=1){let r=e.charCodeAt(s);if(r>55295&&r<=56319){const a=(r-55296)*1024&65535;r=(e.charCodeAt(s+1)-56320&65535|a)+65536,s+=1}RO(r,t)}}function LO(e,t,s){if(t.utf8seq===0){if(e<=127){s(e);return}for(let r=1;r<6;r+=1)if(!(e>>7-r&1)){t.utf8seq=r;break}if(t.utf8seq===2)t.codepoint=e&31;else if(t.utf8seq===3)t.codepoint=e&15;else if(t.utf8seq===4)t.codepoint=e&7;else throw new Error("Invalid UTF-8 sequence");t.utf8seq-=1}else if(t.utf8seq>0){if(e<=127)throw new Error("Invalid UTF-8 sequence");t.codepoint=t.codepoint<<6|e&63,t.utf8seq-=1,t.utf8seq===0&&s(t.codepoint)}}function ol(e){const t=[],s={queue:0,queuedBits:0},r=a=>{t.push(a)};for(let a=0;a<e.length;a+=1)GN(e.charCodeAt(a),s,r);return new Uint8Array(t)}function IO(e){const t=[];return $O(e,s=>t.push(s)),new Uint8Array(t)}function Ri(e){const t=[],s={queue:0,queuedBits:0},r=a=>{t.push(a)};return e.forEach(a=>
79yw(a,s,r)),yw(null,s,r),t.join("")}function OO(e){return Math.round(Date.now()/1e3)+e}function DO(){return Symbol("auth-callback")}const bs=()=>typeof window<"u"&&typeof document<"u",_i={tested:!1,writable:!1},YN=()=>{if(!bs())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(_i.tested)return _i.writable;const e=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(e,e),globalThis.localStorage.removeItem(e),_i.tested=!0,_i.writable=!0}catch{_i.tested=!0,_i.writable=!1}return _i.writable};function MO(e){const t={},s=new URL(e);if(s.hash&&s.hash[0]==="#")try{new URLSearchParams(s.hash.substring(1)).forEach((a,i)=>{t[i]=a})}catch{}return s.searchParams.forEach((r,a)=>{t[a]=r}),t}const KN=e=>e?(...t)=>e(...t):(...t)=>fetch(...t),zO=e=>typeof e=="object"&&e!==null&&"status"in e&&"ok"in e&&"json"in e&&typeof e.json=="function",Io=async(e,t,s)=>{await e.setItem(t,JSON.stringify(s))},ki=async(e,t)=>{const s=await e.getItem(t);if(!s)return null;try{return JSON.parse(s)}catch{return s}},ys=async(e,t)=>{await e.removeItem(t)};class cp{constructor(){this.promise=new cp.promiseConstructor((t,s)=>{this.resolve=t,this.reject=s})}}cp.promiseConstructor=Promise;function eh(e){const t=e.split(".");if(t.length!==3)throw new Ax("Invalid JWT structure");for(let r=0;r<t.length;r++)if(!NO.test(t[r]))throw new Ax("JWT not in base64url format");return{header:JSON.parse(bw(t[0])),payload:JSON.parse(bw(t[1])),signature:ol(t[2]),raw:{header:t[0],payload:t[1]}}}async function FO(e){return await new Promise(t=>{setTimeout(()=>t(null),e)})}function UO(e,t){return new Promise((r,a)=>{(async()=>{for(let i=0;i<1/0;i++)try{const o=await e(i);if(!t(i,null,o)){r(o);return}}catch(o){if(!t(i,o)){a(o);return}}})()})}function BO(e){return("0"+e.toString(16)).substr(-2)}function VO(){const t=new Uint32Array(56);if(typeof crypto>"u"){const s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",r=s.length;let a="";for(let i=0;i<56;i++)a+=s.charAt(Math.floor(Math.random()*r));return a}return crypto.getRandomValues(t),Array.from(t,BO).join("")}async function qO(e){const s=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",s),a=new Uint8Array(r);return Array.from(a).map(i=>String.fromCharCode(i)).join("")}async function HO(e){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),e;const s=await qO(e);return btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function yo(e,t,s=!1){const r=VO();let a=r;s&&(a+="/PASSWORD_RECOVERY"),await Io(e,`${t}-code-verifier`,a);const i=await HO(r);return[i,r===i?"plain":"s256"]}const WO=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function GO(e){const t=e.headers.get(Px);if(!t||!t.match(WO))return null;try{return new Date(`${t}T00:00:00.0Z`)}catch{return null}}function YO(e){if(!e)throw new Error("Missing exp claim");const t=Math.floor(Date.now()/1e3);if(e<=t)throw new Error("JWT has expired")}function KO(e){switch(e){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}const QO=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function bo(e){if(!QO.test(e))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function _f(){const e={};return new Proxy(e,{get:(t,s)=>{if(s==="__isUserNotAvailableProxy")return!0;if(typeof s=="symbol"){const r=s.toString();if(r==="Symbol(Symbol.toPrimitive)"||r==="Symbol(Symbol.toStringTag)"||r==="Symbol(util.inspect.custom)")return}throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${s}" property of the session object is not supported. Please use getUser() instead.`)},set:(t,s)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${s}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(t,s)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${s}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function JO(e,t){return new Proxy(e,{get:(s,r,a)=>{if(r==="__isInsecureUserWarningProxy")return!0;
79if(typeof r=="symbol"){const i=r.toString();if(i==="Symbol(Symbol.toPrimitive)"||i==="Symbol(Symbol.toStringTag)"||i==="Symbol(util.inspect.custom)"||i==="Symbol(nodejs.util.inspect.custom)")return Reflect.get(s,r,a)}return!t.value&&typeof r=="string"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),t.value=!0),Reflect.get(s,r,a)}})}function ww(e){return JSON.parse(JSON.stringify(e))}const Ci=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),ZO=[502,503,504];async function jw(e){var t;if(!zO(e))throw new Ex(Ci(e),0);if(ZO.includes(e.status))throw new Ex(Ci(e),e.status);let s;try{s=await e.json()}catch(i){throw new Ti(Ci(i),i)}let r;const a=GO(e);if(a&&a.getTime()>=WN["2024-01-01"].timestamp&&typeof s=="object"&&s&&typeof s.code=="string"?r=s.code:typeof s=="object"&&s&&typeof s.error_code=="string"&&(r=s.error_code),r){if(r==="weak_password")throw new xw(Ci(s),e.status,((t=s.weak_password)===null||t===void 0?void 0:t.reasons)||[]);if(r==="session_not_found")throw new rn}else if(typeof s=="object"&&s&&typeof s.weak_password=="object"&&s.weak_password&&Array.isArray(s.weak_password.reasons)&&s.weak_password.reasons.length&&s.weak_password.reasons.reduce((i,o)=>i&&typeof o=="string",!0))throw new xw(Ci(s),e.status,s.weak_password.reasons);throw new CO(Ci(s),e.status||500,r)}const XO=(e,t,s,r)=>{const a={method:e,headers:(t==null?void 0:t.headers)||{}};return e==="GET"?a:(a.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},t==null?void 0:t.headers),a.body=JSON.stringify(r),Object.assign(Object.assign({},a),s))};async function He(e,t,s,r){var a;const i=Object.assign({},r==null?void 0:r.headers);i[Px]||(i[Px]=WN["2024-01-01"].name),r!=null&&r.jwt&&(i.Authorization=`Bearer ${r.jwt}`);const o=(a=r==null?void 0:r.query)!==null&&a!==void 0?a:{};r!=null&&r.redirectTo&&(o.redirect_to=r.redirectTo);const l=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",c=await eD(e,t,s+l,{headers:i,noResolveJson:r==null?void 0:r.noResolveJson},{},r==null?void 0:r.body);return r!=null&&r.xform?r==null?void 0:r.xform(c):{data:Object.assign({},c),error:null}}async function eD(e,t,s,r,a,i){const o=XO(t,r,a,i);let l;try{l=await e(s,Object.assign({},o))}catch(c){throw console.error(c),new Ex(Ci(c),0)}if(l.ok||await jw(l),r!=null&&r.noResolveJson)return l;try{return await l.json()}catch(c){await jw(c)}}function Fn(e){var t;let s=null;nD(e)&&(s=Object.assign({},e),e.expires_at||(s.expires_at=OO(e.expires_in)));const r=(t=e.user)!==null&&t!==void 0?t:e;return{data:{session:s,user:r},error:null}}function _w(e){const t=Fn(e);return!t.error&&e.weak_password&&typeof e.weak_password=="object"&&Array.isArray(e.weak_password.reasons)&&e.weak_password.reasons.length&&e.weak_password.message&&typeof e.weak_password.message=="string"&&e.weak_password.reasons.reduce((s,r)=>s&&typeof r=="string",!0)&&(t.data.weak_password=e.weak_password),t}function Sa(e){var t;return{data:{user:(t=e.user)!==null&&t!==void 0?t:e},error:null}}function tD(e){return{data:e,error:null}}function sD(e){const{action_link:t,email_otp:s,hashed_token:r,redirect_to:a,verification_type:i}=e,o=ac(e,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),l={action_link:t,email_otp:s,hashed_token:r,redirect_to:a,verification_type:i},c=Object.assign({},o);return{data:{properties:l,user:c},error:null}}function kw(e){return e}function nD(e){return e.access_token&&e.refresh_token&&e.expires_in}const kf=["global","local","others"];class rD{constructor({url:t="",headers:s={},fetch:r}){this.url=t,this.headers=s,this.fetch=KN(r),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)},this.customProviders={listProviders:this._listCustomProviders.bind(this),createProvider:this._createCustomProvider.bind(this),getProvider:this._getCustomProvider.bind(this),updateProvider:this._updateCustomProvider.bind(this),deleteProvider:this._deleteCustomProvider.bind(this)}}async signOut(t,s=kf[0]){if(kf.indexOf(s)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${kf.join(", ")}`);try{return await He(this.fetch,"POST",`${this.url}/logout?scope=${s}`,{headers:this.headers,jwt:t,noResolveJson:!0}),{data:null,error:null}}catch(r){if(Fe(r))return{data:null,error:r};throw r}}async inviteUserByEmail(t,s={}){try{return await He(this.fetch,"POST",`${this.url}/invite`,{body:{email:t,data:s.data},headers:this.headers,redirectTo:s.redirectTo,xform:Sa})}catch(r){if(Fe(r))return{data:{user:null},error:r};throw r}}async generateLink(t){try{const{options:s}=t,r=ac(t,["options"]),a=Object.assign(Object.assign({},r),s);return"newEmail"in r&&(a.new_email=r==null?void 0:r.newEmail,delete a.newEmail),await He(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:a,headers:this.headers,xform:sD,redirectTo:s==null?void 0:s.redirectTo})}catch(s){if(Fe(s))return{data:{properties:null,user:null},error:s};throw s}}async createUser(t){try{return await He(this.fetch,"POST",`${this.url}/admin/users`,{body:t,headers:this.headers,xform:Sa})}catch(s){if(Fe(s))return{data:{user:null},error:s};throw s}}async listUsers(t){var s,r,a,i,o,l,c;try{const d={nextPage:null,lastPage:0,total:0},u=await He(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(s=t==null?void 0:t.page)===null||s===void 0?void 0:s.toString())!==null&&r!==void 0?r:"",per_page:(i=(a=t==null?void 0:t.perPage)===null||a===void 0?void 0:a.toString())!==null&&i!==void 0?i:""},xform:kw});if(u.error)throw u.error;const m=await u.json(),p=(o=u.headers.get("x-total-count"))!==null&&o!==void 0?o:0,f=(c=(l=u.headers.get("link"))===null||l===void 0?void 0:l.split(","))!==null&&c!==void 0?c:[];return f.length>0&&(f.forEach(g=>{const x=parseInt(g.split(";")[0].split("=")[1].substring(0,1)),b=JSON.parse(g.split(";")[1].split("=")[1]);d[`${b}Page`]=x}),d.total=parseInt(p)),{data:Object.assign(Object.assign({},m),d),error:null}}catch(d){if(Fe(d))return{data:{users:[]},error:d};throw d}}async getUserById(t){bo(t);try{return await He(this.fetch,"GET",`${this.url}/admin/users/${t}`,{headers:this.headers,xform:Sa})}catch(s){if(Fe(s))return{data:{user:null},error:s};throw s}}async updateUserById(t,s){bo(t);try{return await He(this.fetch,"PUT",`${this.url}/admin/users/${t}`,{body:s,headers:this.headers,xform:Sa})}catch(r){if(Fe(r))return{data:{user:null},error:r};throw r}}async deleteUser(t,s=!1){bo(t);
79try{return await He(this.fetch,"DELETE",`${this.url}/admin/users/${t}`,{headers:this.headers,body:{should_soft_delete:s},xform:Sa})}catch(r){if(Fe(r))return{data:{user:null},error:r};throw r}}async _listFactors(t){bo(t.userId);try{const{data:s,error:r}=await He(this.fetch,"GET",`${this.url}/admin/users/${t.userId}/factors`,{headers:this.headers,xform:a=>({data:{factors:a},error:null})});return{data:s,error:r}}catch(s){if(Fe(s))return{data:null,error:s};throw s}}async _deleteFactor(t){bo(t.userId),bo(t.id);try{return{data:await He(this.fetch,"DELETE",`${this.url}/admin/users/${t.userId}/factors/${t.id}`,{headers:this.headers}),error:null}}catch(s){if(Fe(s))return{data:null,error:s};throw s}}async _listOAuthClients(t){var s,r,a,i,o,l,c;try{const d={nextPage:null,lastPage:0,total:0},u=await He(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(s=t==null?void 0:t.page)===null||s===void 0?void 0:s.toString())!==null&&r!==void 0?r:"",per_page:(i=(a=t==null?void 0:t.perPage)===null||a===void 0?void 0:a.toString())!==null&&i!==void 0?i:""},xform:kw});if(u.error)throw u.error;const m=await u.json(),p=(o=u.headers.get("x-total-count"))!==null&&o!==void 0?o:0,f=(c=(l=u.headers.get("link"))===null||l===void 0?void 0:l.split(","))!==null&&c!==void 0?c:[];return f.length>0&&(f.forEach(g=>{const x=parseInt(g.split(";")[0].split("=")[1].substring(0,1)),b=JSON.parse(g.split(";")[1].split("=")[1]);d[`${b}Page`]=x}),d.total=parseInt(p)),{data:Object.assign(Object.assign({},m),d),error:null}}catch(d){if(Fe(d))return{data:{clients:[]},error:d};throw d}}async _createOAuthClient(t){try{return await He(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:t,headers:this.headers,xform:s=>({data:s,error:null})})}catch(s){if(Fe(s))return{data:null,error:s};throw s}}async _getOAuthClient(t){try{return await He(this.fetch,"GET",`${this.url}/admin/oauth/clients/${t}`,{headers:this.headers,xform:s=>({data:s,error:null})})}catch(s){if(Fe(s))return{data:null,error:s};throw s}}async _updateOAuthClient(t,s){try{return await He(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${t}`,{body:s,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(Fe(r))return{data:null,error:r};throw r}}async _deleteOAuthClient(t){try{return await He(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${t}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(s){if(Fe(s))return{data:null,error:s};throw s}}async _regenerateOAuthClientSecret(t){try{return await He(this.fetch,"POST",`${this.url}/admin/oauth/clients/${t}/regenerate_secret`,{headers:this.headers,xform:s=>({data:s,error:null})})}catch(s){if(Fe(s))return{data:null,error:s};throw s}}async _listCustomProviders(t){try{const s={};return t!=null&&t.type&&(s.type=t.type),await He(this.fetch,"GET",`${this.url}/admin/custom-providers`,{headers:this.headers,query:s,xform:r=>{var a;return{data:{providers:(a=r==null?void 0:r.providers)!==null&&a!==void 0?a:[]},error:null}}})}catch(s){if(Fe(s))return{data:{providers:[]},error:s};throw s}}async _createCustomProvider(t){try{return await He(this.fetch,"POST",`${this.url}/admin/custom-providers`,{body:t,headers:this.headers,xform:s=>({data:s,error:null})})}catch(s){if(Fe(s))return{data:null,error:s};throw s}}async _getCustomProvider(t){try{return await He(this.fetch,"GET",`${this.url}/admin/custom-providers/${t}`,{headers:this.headers,xform:s=>({data:s,error:null})})}catch(s){if(Fe(s))return{data:null,error:s};throw s}}async _updateCustomProvider(t,s){try{return await He(this.fetch,"PUT",`${this.url}/admin/custom-providers/${t}`,{body:s,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(Fe(r))return{data:null,error:r};throw r}}async _deleteCustomProvider(t){try{return await He(this.fetch,"DELETE",`${this.url}/admin/custom-providers/${t}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(s){if(Fe(s))return{data:null,error:s};throw s}}}function Nw(e={}){return{getItem:t=>e[t]||null,setItem:(t,s)=>{e[t]=s},removeItem:t=>{delete e[t]}}}const dr={debug:!!(globalThis&&YN()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};
79class QN extends Error{constructor(t){super(t),this.isAcquireTimeout=!0}}class Sw extends QN{}async function aD(e,t,s){dr.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",e,t);const r=new globalThis.AbortController;let a;t>0&&(a=setTimeout(()=>{r.abort(),dr.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",e)},t)),await Promise.resolve();try{return await globalThis.navigator.locks.request(e,t===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:r.signal},async i=>{if(i){clearTimeout(a),dr.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",e,i.name);try{return await s()}finally{dr.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",e,i.name)}}else{if(t===0)throw dr.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",e),new Sw(`Acquiring an exclusive Navigator LockManager lock "${e}" immediately failed`);if(dr.debug)try{const o=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(o,null,"  "))}catch(o){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",o)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),clearTimeout(a),await s()}})}catch(i){if(t>0&&clearTimeout(a),(i==null?void 0:i.name)==="AbortError"&&t>0){if(r.signal.aborted)return dr.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire timeout, recovering by stealing lock",e),console.warn(`@supabase/gotrue-js: Lock "${e}" was not released within ${t}ms. This may indicate an orphaned lock from a component unmount (e.g., React Strict Mode). Forcefully acquiring the lock to recover.`),await Promise.resolve().then(()=>globalThis.navigator.locks.request(e,{mode:"exclusive",steal:!0},async o=>{if(o){dr.debug&&console.log("@supabase/gotrue-js: navigatorLock: recovered (stolen)",e,o.name);try{return await s()}finally{dr.debug&&console.log("@supabase/gotrue-js: navigatorLock: released (stolen)",e,o.name)}}else return console.warn("@supabase/gotrue-js: Navigator LockManager returned null lock even with steal: true"),await s()}));throw dr.debug&&console.log("@supabase/gotrue-js: navigatorLock: lock was stolen by another request",e),new Sw(`Lock "${e}" was released because another request stole it`)}throw i}}function iD(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<"u"&&(self.globalThis=self)}}function JN(e){if(!/^0x[a-fA-F0-9]{40}$/.test(e))throw new Error(`@supabase/auth-js: Address "${e}" is invalid.`);return e.toLowerCase()}function oD(e){return parseInt(e,16)}function lD(e){const t=new TextEncoder().encode(e);return"0x"+Array.from(t,r=>r.toString(16).padStart(2,"0")).join("")}function cD(e){var t;const{chainId:s,domain:r,expirationTime:a,issuedAt:i=new Date,nonce:o,notBefore:l,requestId:c,resources:d,scheme:u,uri:m,version:p}=e;{if(!Number.isInteger(s))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${s}`);if(!r)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(o&&o.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${o}`);if(!m)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(p!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${p}`);if(!((t=e.statement)===null||t===void 0)&&t.includes(`
80`))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${e.statement}`)}const f=JN(e.address),g=u?`${u}://${r}`:r,x=e.statement?`${e.statement}
81`:"",b=`${g} wants you to sign in with your Ethereum account:
82${f}
83
84${x}`;let v=`URI: ${m}
85Version: ${p}
86Chain ID: ${s}${o?`
87Nonce: ${o}`:""}
88Issued At: ${i.toISOString()}`;if(a&&(v+=`
89Expiration Time: ${a.toISOString()}`),l&&(v+=`
90Not Before: ${l.toISOString()}
90`),c&&(v+=`
91Request ID: ${c}`),d){let y=`
92Resources:`;for(const w of d){if(!w||typeof w!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${w}`);y+=`
93- ${w}`}v+=y}return`${b}
94${v}`}class as extends Error{constructor({message:t,code:s,cause:r,name:a}){var i;super(t,{cause:r}),this.__isWebAuthnError=!0,this.name=(i=a??(r instanceof Error?r.name:void 0))!==null&&i!==void 0?i:"Unknown Error",this.code=s}}class um extends as{constructor(t,s){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:s,message:t}),this.name="WebAuthnUnknownError",this.originalError=s}}function dD({error:e,options:t}){var s,r,a;const{publicKey:i}=t;if(!i)throw Error("options was missing required publicKey property");if(e.name==="AbortError"){if(t.signal instanceof AbortSignal)return new as({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else if(e.name==="ConstraintError"){if(((s=i.authenticatorSelection)===null||s===void 0?void 0:s.requireResidentKey)===!0)return new as({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:e});if(t.mediation==="conditional"&&((r=i.authenticatorSelection)===null||r===void 0?void 0:r.userVerification)==="required")return new as({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:e});if(((a=i.authenticatorSelection)===null||a===void 0?void 0:a.userVerification)==="required")return new as({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:e})}else{if(e.name==="InvalidStateError")return new as({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:e});if(e.name==="NotAllowedError")return new as({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if(e.name==="NotSupportedError")return i.pubKeyCredParams.filter(l=>l.type==="public-key").length===0?new as({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:e}):new as({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:e});if(e.name==="SecurityError"){const o=window.location.hostname;if(ZN(o)){if(i.rp.id!==o)return new as({message:`The RP ID "${i.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else return new as({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e})}else if(e.name==="TypeError"){if(i.user.id.byteLength<1||i.user.id.byteLength>64)return new as({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:e})}else if(e.name==="UnknownError")return new as({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return new as({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}function uD({error:e,options:t}){const{publicKey:s}=t;if(!s)throw Error("options was missing required publicKey property");if(e.name==="AbortError"){if(t.signal instanceof AbortSignal)return new as({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else{if(e.name==="NotAllowedError")return new as({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if(e.name==="SecurityError"){const r=window.location.hostname;if(ZN(r)){if(s.rpId!==r)return new as({message:`The RP ID "${s.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else return new as({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e})}else if(e.name==="UnknownError")return new as({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ER
94ROR",cause:e})}return new as({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}class hD{createNewAbortSignal(){if(this.controller){const s=new Error("Cancelling existing WebAuthn API call for new one");s.name="AbortError",this.controller.abort(s)}const t=new AbortController;return this.controller=t,t.signal}cancelCeremony(){if(this.controller){const t=new Error("Manually cancelling existing WebAuthn API call");t.name="AbortError",this.controller.abort(t),this.controller=void 0}}}const mD=new hD;function pD(e){if(!e)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(e);const{challenge:t,user:s,excludeCredentials:r}=e,a=ac(e,["challenge","user","excludeCredentials"]),i=ol(t).buffer,o=Object.assign(Object.assign({},s),{id:ol(s.id).buffer}),l=Object.assign(Object.assign({},a),{challenge:i,user:o});if(r&&r.length>0){l.excludeCredentials=new Array(r.length);for(let c=0;c<r.length;c++){const d=r[c];l.excludeCredentials[c]=Object.assign(Object.assign({},d),{id:ol(d.id).buffer,type:d.type||"public-key",transports:d.transports})}}return l}function fD(e){if(!e)throw new Error("Credential request options are required");if(typeof PublicKeyCredential<"u"&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseRequestOptionsFromJSON=="function")return PublicKeyCredential.parseRequestOptionsFromJSON(e);const{challenge:t,allowCredentials:s}=e,r=ac(e,["challenge","allowCredentials"]),a=ol(t).buffer,i=Object.assign(Object.assign({},r),{challenge:a});if(s&&s.length>0){i.allowCredentials=new Array(s.length);for(let o=0;o<s.length;o++){const l=s[o];i.allowCredentials[o]=Object.assign(Object.assign({},l),{id:ol(l.id).buffer,type:l.type||"public-key",transports:l.transports})}}return i}function gD(e){var t;if("toJSON"in e&&typeof e.toJSON=="function")return e.toJSON();const s=e;return{id:e.id,rawId:e.id,response:{attestationObject:Ri(new Uint8Array(e.response.attestationObject)),clientDataJSON:Ri(new Uint8Array(e.response.clientDataJSON))},type:"public-key",clientExtensionResults:e.getClientExtensionResults(),authenticatorAttachment:(t=s.authenticatorAttachment)!==null&&t!==void 0?t:void 0}}function xD(e){var t;if("toJSON"in e&&typeof e.toJSON=="function")return e.toJSON();const s=e,r=e.getClientExtensionResults(),a=e.response;return{id:e.id,rawId:e.id,response:{authenticatorData:Ri(new Uint8Array(a.authenticatorData)),clientDataJSON:Ri(new Uint8Array(a.clientDataJSON)),signature:Ri(new Uint8Array(a.signature)),userHandle:a.userHandle?Ri(new Uint8Array(a.userHandle)):void 0},type:"public-key",clientExtensionResults:r,authenticatorAttachment:(t=s.authenticatorAttachment)!==null&&t!==void 0?t:void 0}}function ZN(e){return e==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(e)}function Cw(){var e,t;return!!(bs()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&typeof((e=navigator==null?void 0:navigator.credentials)===null||e===void 0?void 0:e.create)=="function"&&typeof((t=navigator==null?void 0:navigator.credentials)===null||t===void 0?void 0:t.get)=="function")}async function vD(e){try{const t=await navigator.credentials.create(e);return t?t instanceof PublicKeyCredential?{data:t,error:null}:{data:null,error:new um("Browser returned unexpected credential type",t)}:{data:null,error:new um("Empty credential response",t)}}catch(t){return{data:null,error:dD({error:t,options:e})}}}async function yD(e){try{const t=await navigator.credentials.get(e);return t?t instanceof PublicKeyCredential?{data:t,error:null}:{data:null,error:new um("Browser returned unexpected credential type",t)}:{data:null,error:new um("Empty credential response",t)}}catch(t){return{data:null,error:uD({error:t,options:e})}}}const bD={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},wD={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function hm(...e){const t=a=>a!==null&&typeof a=="object"&&!Array.isArray(a),s=a=>a instanceof ArrayBuffer||ArrayBuffer.isView(a),r={};for(const a of e)if(a)for(const i in a){const o=a[i];if(o!==void 0)if(Array.isArray(o))r[i]=o;else if(s(o))r[i]=o;else if(t(o)){const l=r[i];t(l)?r[i]=hm(l,o):r[i]=hm(o)}else r[i]=o}return r}function jD(e,t){return hm(bD,e,t||{})}function _D(e,t){return hm(wD,e,t||{})}class kD{constructor(t){this.client=t,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}async _enroll(t){return this.client.mfa.enroll(Object.assign(Object.assign({},t),{factorType:"webauthn"}))}async _challenge({factorId:t,webauthn:s,friendlyName:r,signal:a},i){var o;try{const{data:l,error:c}=await this.client.mfa.challenge({factorId:t,webauthn:s});if(!l)return{data:null,error:c};const d=a??mD.createNewAbortSignal();if(l.webauthn.type==="create"){const{user:u}=l.webauthn.credential_options.publicKey;if(!u.name){const m=r;if(m)u.name=`${u.id}:${m}`;else{const f=(await this.client.getUser()).data.user,g=((o=f==null?void 0:f.user_metadata)===null||o===void 0?void 0:o.name)||(f==null?void 0:f.email)||(f==null?void 0:f.id)||"User";u.name=`${u.id}:${g}`}}u.displayName||(u.displayName=u.name)}
94switch(l.webauthn.type){case"create":{const u=jD(l.webauthn.credential_options.publicKey,i==null?void 0:i.create),{data:m,error:p}=await vD({publicKey:u,signal:d});return m?{data:{factorId:t,challengeId:l.id,webauthn:{type:l.webauthn.type,credential_response:m}},error:null}:{data:null,error:p}}case"request":{const u=_D(l.webauthn.credential_options.publicKey,i==null?void 0:i.request),{data:m,error:p}=await yD(Object.assign(Object.assign({},l.webauthn.credential_options),{publicKey:u,signal:d}));return m?{data:{factorId:t,challengeId:l.id,webauthn:{type:l.webauthn.type,credential_response:m}},error:null}:{data:null,error:p}}}}catch(l){return Fe(l)?{data:null,error:l}:{data:null,error:new Ti("Unexpected error in challenge",l)}}}async _verify({challengeId:t,factorId:s,webauthn:r}){return this.client.mfa.verify({factorId:s,challengeId:t,webauthn:r})}async _authenticate({factorId:t,webauthn:{rpId:s=typeof window<"u"?window.location.hostname:void 0,rpOrigins:r=typeof window<"u"?[window.location.origin]:void 0,signal:a}={}},i){if(!s)return{data:null,error:new Cd("rpId is required for WebAuthn authentication")};try{if(!Cw())return{data:null,error:new Ti("Browser does not support WebAuthn",null)};const{data:o,error:l}=await this.challenge({factorId:t,webauthn:{rpId:s,rpOrigins:r},signal:a},{request:i});if(!o)return{data:null,error:l};const{webauthn:c}=o;return this._verify({factorId:t,challengeId:o.challengeId,webauthn:{type:c.type,rpId:s,rpOrigins:r,credential_response:c.credential_response}})}catch(o){return Fe(o)?{data:null,error:o}:{data:null,error:new Ti("Unexpected error in authenticate",o)}}}async _register({friendlyName:t,webauthn:{rpId:s=typeof window<"u"?window.location.hostname:void 0,rpOrigins:r=typeof window<"u"?[window.location.origin]:void 0,signal:a}={}},i){if(!s)return{data:null,error:new Cd("rpId is required for WebAuthn registration")};try{if(!Cw())return{data:null,error:new Ti("Browser does not support WebAuthn",null)};const{data:o,error:l}=await this._enroll({friendlyName:t});if(!o)return await this.client.mfa.listFactors().then(u=>{var m;return(m=u.data)===null||m===void 0?void 0:m.all.find(p=>p.factor_type==="webauthn"&&p.friendly_name===t&&p.status!=="unverified")}).then(u=>u?this.client.mfa.unenroll({factorId:u==null?void 0:u.id}):void 0),{data:null,error:l};const{data:c,error:d}=await this._challenge({factorId:o.id,friendlyName:o.friendly_name,webauthn:{rpId:s,rpOrigins:r},signal:a},{create:i});return c?this._verify({factorId:o.id,challengeId:c.challengeId,webauthn:{rpId:s,rpOrigins:r,type:c.webauthn.type,credential_response:c.webauthn.credential_response}}):{data:null,error:d}}catch(o){return Fe(o)?{data:null,error:o}:{data:null,error:new Ti("Unexpected error in register",o)}}}}iD();const ND={url:jO,storageKey:_O,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:kO,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1};async function Tw(e,t,s){return await s()}const wo={};class Td{get jwks(){var t,s;return(s=(t=wo[this.storageKey])===null||t===void 0?void 0:t.jwks)!==null&&s!==void 0?s:{keys:[]}}set jwks(t){wo[this.storageKey]=Object.assign(Object.assign({},wo[this.storageKey]),{jwks:t})}get jwks_cached_at(){var t,s;return(s=(t=wo[this.storageKey])===null||t===void 0?void 0:t.cachedAt)!==null&&s!==void 0?s:Number.MIN_SAFE_INTEGER}set jwks_cached_at(t){wo[this.storageKey]=Object.assign(Object.assign({},wo[this.storageKey]),{cachedAt:t})}constructor(t){var s,r,a;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;const i=Object.assign(Object.assign({},ND),t);if(this.storageKey=i.storageKey,this.instanceID=(s=Td.nextInstanceID[this.storageKey])!==null&&s!==void 0?s:0,Td.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.instanceID>0&&bs()){const o=`${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`;console.warn(o),this.logDebugMessages&&console.trace(o)}if(this.persistSession=i.persistSession,this.autoRefreshToken=i.autoRefreshToken,this.admin=new rD({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=KN(i.fetch),this.lock=i.lock||Tw,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,this.throwOnError=i.throwOnError,this.lockAcquireTimeout=i.lockAcquireTimeout,i.lock?this.lock=i.lock:this.persistSession&&bs()&&(!((r=globalThis==null?void 0:globalThis.navigator)===null||r===void 0)&&r.locks)?this.lock=aD:this.lock=Tw,this.jwks||(this.jwks={keys:[]},this.jwks_cached_at=Number.MIN_SAFE_INTEGER),this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this),webauthn:new kD(this)}
94,this.oauth={getAuthorizationDetails:this._getAuthorizationDetails.bind(this),approveAuthorization:this._approveAuthorization.bind(this),denyAuthorization:this._denyAuthorization.bind(this),listGrants:this._listOAuthGrants.bind(this),revokeGrant:this._revokeOAuthGrant.bind(this)},this.persistSession?(i.storage?this.storage=i.storage:YN()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=Nw(this.memoryStorage)),i.userStorage&&(this.userStorage=i.userStorage)):(this.memoryStorage={},this.storage=Nw(this.memoryStorage)),bs()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(o){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",o)}(a=this.broadcastChannel)===null||a===void 0||a.addEventListener("message",async o=>{this._debug("received broadcast notification from other tab or client",o);try{await this._notifyAllSubscribers(o.data.event,o.data.session,!1)}catch(l){this._debug("#broadcastChannel","error",l)}})}i.skipAutoInitialize||this.initialize().catch(o=>{this._debug("#initialize()","error",o)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(t){if(this.throwOnError&&t&&t.error)throw t.error;return t}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${HN}) ${new Date().toISOString()}`}_debug(...t){return this.logDebugMessages&&this.logger(this._logPrefix(),...t),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){var t;try{let s={},r="none";if(bs()&&(s=MO(window.location.href),this._isImplicitGrantCallback(s)?r="implicit":await this._isPKCECallback(s)&&(r="pkce")),bs()&&this.detectSessionInUrl&&r!=="none"){const{data:a,error:i}=await this._getSessionFromURL(s,r);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),PO(i)){const c=(t=i.details)===null||t===void 0?void 0:t.code;if(c==="identity_already_exists"||c==="identity_not_found"||c==="single_identity_not_deletable")return{error:i}}return{error:i}}const{session:o,redirectType:l}=a;return this._debug("#_initialize()","detected session in URL",o,"redirect type",l),await this._saveSession(o),setTimeout(async()=>{l==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",o):await this._notifyAllSubscribers("SIGNED_IN",o)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(s){return Fe(s)?this._returnResult({error:s}):this._returnResult({error:new Ti("Unexpected error during initialization",s)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(t){var s,r,a;try{const i=await He(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(r=(s=t==null?void 0:t.options)===null||s===void 0?void 0:s.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:(a=t==null?void 0:t.options)===null||a===void 0?void 0:a.captchaToken}},xform:Fn}),{data:o,error:l}=i;if(l||!o)return this._returnResult({data:{user:null,session:null},error:l});const c=o.session,d=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),this._returnResult({data:{user:d,session:c},error:null})}catch(i){if(Fe(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signUp(t){var s,r,a;try{let i;if("email"in t){const{email:u,password:m,options:p}=t;let f=null,g=null;this.flowType==="pkce"&&([f,g]=await yo(this.storage,this.storageKey)),i=await He(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:p==null?void 0:p.emailRedirectTo,body:{email:u,password:m,data:(s=p==null?void 0:p.data)!==null&&s!==void 0?s:{},gotrue_meta_security:{captcha_token:p==null?void 0:p.captchaToken},code_challenge:f,code_challenge_method:g},xform:Fn})}else if("phone"in t){const{phone:u,password:m,options:p}=t;i=await He(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:u,password:m,data:(r=p==null?void 0:p.data)!==null&&r!==void 0?r:{},channel:(a=p==null?void 0:p.channel)!==null&&a!==void 0?a:"sms",gotrue_meta_security:{captcha_token:p==null?void 0:p.captchaToken}},xform:Fn})}else throw new Zu("You must provide either an email or phone number and a password");const{data:o,error:l}=i;if(l||!o)return await ys(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:l});const c=o.session,d=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),this._returnResult({data:{user:d,session:c},error:null})}catch(i){if(await ys(this.storage,`${this.storageKey}-code-verifier`),Fe(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signInWithPassword(t){try{let s;if("email"in t){const{email:i,password:o,options:l}=t;s=await He(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:i,password:o,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken}},xform:_w})}else if("phone"in t){const{phone:i,password:o,options:l}=t;s=await He(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:i,password:o,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken}},xform:_w})}else throw new Zu("You must provide either an email or phone number and a password");const{data:r,error:a}=s;
94if(a)return this._returnResult({data:{user:null,session:null},error:a});if(!r||!r.session||!r.user){const i=new vo;return this._returnResult({data:{user:null,session:null},error:i})}return r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),this._returnResult({data:Object.assign({user:r.user,session:r.session},r.weak_password?{weakPassword:r.weak_password}:null),error:a})}catch(s){if(Fe(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signInWithOAuth(t){var s,r,a,i;return await this._handleProviderSignIn(t.provider,{redirectTo:(s=t.options)===null||s===void 0?void 0:s.redirectTo,scopes:(r=t.options)===null||r===void 0?void 0:r.scopes,queryParams:(a=t.options)===null||a===void 0?void 0:a.queryParams,skipBrowserRedirect:(i=t.options)===null||i===void 0?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(t){return await this.initializePromise,this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(t))}async signInWithWeb3(t){const{chain:s}=t;switch(s){case"ethereum":return await this.signInWithEthereum(t);case"solana":return await this.signInWithSolana(t);default:throw new Error(`@supabase/auth-js: Unsupported chain "${s}"`)}}async signInWithEthereum(t){var s,r,a,i,o,l,c,d,u,m,p;let f,g;if("message"in t)f=t.message,g=t.signature;else{const{chain:x,wallet:b,statement:v,options:y}=t;let w;if(bs())if(typeof b=="object")w=b;else{const T=window;if("ethereum"in T&&typeof T.ethereum=="object"&&"request"in T.ethereum&&typeof T.ethereum.request=="function")w=T.ethereum;else throw new Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.")}else{if(typeof b!="object"||!(y!=null&&y.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");w=b}const j=new URL((s=y==null?void 0:y.url)!==null&&s!==void 0?s:window.location.href),_=await w.request({method:"eth_requestAccounts"}).then(T=>T).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!_||_.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");const N=JN(_[0]);let k=(r=y==null?void 0:y.signInWithEthereum)===null||r===void 0?void 0:r.chainId;if(!k){const T=await w.request({method:"eth_chainId"});k=oD(T)}const S={domain:j.host,address:N,statement:v,uri:j.href,version:"1",chainId:k,nonce:(a=y==null?void 0:y.signInWithEthereum)===null||a===void 0?void 0:a.nonce,issuedAt:(o=(i=y==null?void 0:y.signInWithEthereum)===null||i===void 0?void 0:i.issuedAt)!==null&&o!==void 0?o:new Date,expirationTime:(l=y==null?void 0:y.signInWithEthereum)===null||l===void 0?void 0:l.expirationTime,notBefore:(c=y==null?void 0:y.signInWithEthereum)===null||c===void 0?void 0:c.notBefore,requestId:(d=y==null?void 0:y.signInWithEthereum)===null||d===void 0?void 0:d.requestId,resources:(u=y==null?void 0:y.signInWithEthereum)===null||u===void 0?void 0:u.resources};f=cD(S),g=await w.request({method:"personal_sign",params:[lD(f),N]})}try{const{data:x,error:b}=await He(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:f,signature:g},!((m=t.options)===null||m===void 0)&&m.captchaToken?{gotrue_meta_security:{captcha_token:(p=t.options)===null||p===void 0?void 0:p.captchaToken}}:null),xform:Fn});if(b)throw b;if(!x||!x.session||!x.user){const v=new vo;return this._returnResult({data:{user:null,session:null},error:v})}return x.session&&(await this._saveSession(x.session),await this._notifyAllSubscribers("SIGNED_IN",x.session)),this._returnResult({data:Object.assign({},x),error:b})}catch(x){if(Fe(x))return this._returnResult({data:{user:null,session:null},error:x});throw x}}async signInWithSolana(t){var s,r,a,i,o,l,c,d,u,m,p,f;let g,x;if("message"in t)g=t.message,x=t.signature;else{const{chain:b,wallet:v,statement:y,options:w}=t;let j;if(bs())if(typeof v=="object")j=v;else{const N=window;if("solana"in N&&typeof N.solana=="object"&&("signIn"in N.solana&&typeof N.solana.signIn=="function"||"signMessage"in N.solana&&typeof N.solana.signMessage=="function"))j=N.solana;else throw new Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.")}else{if(typeof v!="object"||!(w!=null&&w.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");j=v}const _=new URL((s=w==null?void 0:w.url)!==null&&s!==void 0?s:window.location.href);if("signIn"in j&&j.signIn){const N=await j.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},w==null?void 0:w.signInWithSolana),{version:"1",domain:_.host,uri:_.href}),y?{statement:y}:null));let k;if(Array.isArray(N)&&N[0]&&typeof N[0]=="object")k=N[0];else if(N&&typeof N=="object"&&"signedMessage"in N&&"signature"in N)k=N;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in k&&"signature"in k&&(typeof k.signedMessage=="string"||k.signedMessage instanceof Uint8Array)&&k.signature instanceof Uint8Array)g=typeof k.signedMessage=="string"?k.signedMessage:new TextDecoder().decode(k.signedMessage),x=k.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in j)||typeof j.signMessage!="function"||!("publicKey"in j)||typeof j!="object"||!j.publicKey||!("toBase58"in j.publicKey)||typeof j.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");g=[`${_.host} wants you to sign in with your Solana account:`,j.publicKey.toBase58(),...y?["",y,""]:[""],"Version: 1",`URI: ${_.href}`,`Issued At: ${(a=(r=w==null?void 0:w.signInWithSolana)===null||r===void 0?void 0:r.issuedAt)!==null&&a!==void 0?a:new Date().toISOString()}`,...!((i=w==null?void 0:w.signInWithSolana)===null||i===void 0)&&i.notBefore?[`Not Before: ${w.signInWithSolana.notBefore}`]:[],...!((o=w==null?void 0:w.signInWithSolana)===null||o===void 0)&&o.expirationTime?[`Expiration Time: ${w.signInWithSolana.expirationTime}`]:[],...!((l=w==null?void 0:w.signInWithSolana)===null||l===void 0)&&l.chainId?[`Chain ID: ${w.signInWithSolana.chainId}`]:[],...!((c=w==null?void 0:w.signInWithSolana)===null||c===void 0)&&c.nonce?[`Nonce: ${w.signInWithSolana.nonce}`]:[],...!((d=w==null?void 0:w.signInWithSolana)===null||d===void 0)&&d.requestId?[`Request ID: ${w.signInWithSolana.requestId}`]:[],...!((m=(u=w==null?void 0:w.signInWithSolana)===null||u===void 0?void 0:u.resources)===null||m===void 0)&&m.length?["Resources",...w.sign
94InWithSolana.resources.map(k=>`- ${k}`)]:[]].join(`
95`);const N=await j.signMessage(new TextEncoder().encode(g),"utf8");if(!N||!(N instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");x=N}}try{const{data:b,error:v}=await He(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:g,signature:Ri(x)},!((p=t.options)===null||p===void 0)&&p.captchaToken?{gotrue_meta_security:{captcha_token:(f=t.options)===null||f===void 0?void 0:f.captchaToken}}:null),xform:Fn});if(v)throw v;if(!b||!b.session||!b.user){const y=new vo;return this._returnResult({data:{user:null,session:null},error:y})}return b.session&&(await this._saveSession(b.session),await this._notifyAllSubscribers("SIGNED_IN",b.session)),this._returnResult({data:Object.assign({},b),error:v})}catch(b){if(Fe(b))return this._returnResult({data:{user:null,session:null},error:b});throw b}}async _exchangeCodeForSession(t){const s=await ki(this.storage,`${this.storageKey}-code-verifier`),[r,a]=(s??"").split("/");try{if(!r&&this.flowType==="pkce")throw new EO;const{data:i,error:o}=await He(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:t,code_verifier:r},xform:Fn});if(await ys(this.storage,`${this.storageKey}-code-verifier`),o)throw o;if(!i||!i.session||!i.user){const l=new vo;return this._returnResult({data:{user:null,session:null,redirectType:null},error:l})}return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",i.session)),this._returnResult({data:Object.assign(Object.assign({},i),{redirectType:a??null}),error:o})}catch(i){if(await ys(this.storage,`${this.storageKey}-code-verifier`),Fe(i))return this._returnResult({data:{user:null,session:null,redirectType:null},error:i});throw i}}async signInWithIdToken(t){try{const{options:s,provider:r,token:a,access_token:i,nonce:o}=t,l=await He(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:a,access_token:i,nonce:o,gotrue_meta_security:{captcha_token:s==null?void 0:s.captchaToken}},xform:Fn}),{data:c,error:d}=l;if(d)return this._returnResult({data:{user:null,session:null},error:d});if(!c||!c.session||!c.user){const u=new vo;return this._returnResult({data:{user:null,session:null},error:u})}return c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),this._returnResult({data:c,error:d})}catch(s){if(Fe(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signInWithOtp(t){var s,r,a,i,o;try{if("email"in t){const{email:l,options:c}=t;let d=null,u=null;this.flowType==="pkce"&&([d,u]=await yo(this.storage,this.storageKey));const{error:m}=await He(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:l,data:(s=c==null?void 0:c.data)!==null&&s!==void 0?s:{},create_user:(r=c==null?void 0:c.shouldCreateUser)!==null&&r!==void 0?r:!0,gotrue_meta_security:{captcha_token:c==null?void 0:c.captchaToken},code_challenge:d,code_challenge_method:u},redirectTo:c==null?void 0:c.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:m})}if("phone"in t){const{phone:l,options:c}=t,{data:d,error:u}=await He(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:l,data:(a=c==null?void 0:c.data)!==null&&a!==void 0?a:{},create_user:(i=c==null?void 0:c.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:c==null?void 0:c.captchaToken},channel:(o=c==null?void 0:c.channel)!==null&&o!==void 0?o:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:d==null?void 0:d.message_id},error:u})}throw new Zu("You must provide either an email or phone number.")}catch(l){if(await ys(this.storage,`${this.storageKey}-code-verifier`),Fe(l))return this._returnResult({data:{user:null,session:null},error:l});throw l}}async verifyOtp(t){var s,r;try{let a,i;"options"in t&&(a=(s=t.options)===null||s===void 0?void 0:s.redirectTo,i=(r=t.options)===null||r===void 0?void 0:r.captchaToken);const{data:o,error:l}=await He(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},t),{gotrue_meta_security:{captcha_token:i}}),redirectTo:a,xform:Fn});if(l)throw l;if(!o)throw new Error("An error occurred on token verification.");const c=o.session,d=o.user;return c!=null&&c.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(t.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),this._returnResult({data:{user:d,session:c},error:null})}catch(a){if(Fe(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async signInWithSSO(t){var s,r,a,i,o;try{let l=null,c=null;this.flowType==="pkce"&&([l,c]=await yo(this.storage,this.storageKey));const d=await He(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in t?{provider_id:t.providerId}:null),"domain"in t?{domain:t.domain}:null),{redirect_to:(r=(s=t.options)===null||s===void 0?void 0:s.redirectTo)!==null&&r!==void 0?r:void 0}),!((a=t==null?void 0:t.options)===null||a===void 0)&&a.captchaToken?{gotrue_meta_security:{captcha_token:t.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:l,code_challenge_method:c}),headers:this.headers,xform:tD});return!((i=d.data)===null||i===void 0)&&i.url&&bs()&&!(!((o=t.options)===null||o===void 0)&&o.skipBrowserRedirect)&&window.location.assign(d.data.url),this._returnResult(d)}catch(l){if(await ys(this.storage,`${this.storageKey}-code-verifier`),Fe(l))return this._returnResult({data:null,error:l});throw l}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async t=>{const{data:{session:s},error:r}=t;if(r)throw r;if(!s)throw new rn;const{error:a}=await He(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:s.access_token});return this._returnResult({data:{user:null,session:null},error:a})})}catch(t){if(Fe(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async resend(t){try{const s=`${this.url}/resend`;if("email"in t){const{email:r,type:a,options:i}=t,{error:o}=await He(this.fetch,"POST",s,{headers:this.headers,body:{email:r,type:a,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}},redirectTo:i==null?void 0:i.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:o})}else if("phone"in t){const{phone:r,type:a,options:i}=t,{data:o,error:l}=await He(this.fetch,"POST",s,{headers:this.headers,body:{phone:r,type:a,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:o==null?void 0:o.message_id},error:l})}throw new Zu("You must provide either an email or phone number and a type")}catch(s){if(Fe(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async getSession(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async s=>s))}async _acquireLock(t,s){this._debug("#_acquireLock","begin",t);try{if(this.lockAcquired){const r=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),a=(async()=>(await r,await s()))();return this.pendingInLock.push((async()=>{try{await a}catch{}})()),a}return await this.lock(`lock:${this.storageKey}`,t,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const r=s();for(this.pendingInLock.push((async()=>{try{await r}catch{}})()),await r;this.pendingInLock.length;){const a=[...this.pendingInLock];await Promise.all(a),this.pendingInLock.splice(0,a.length)}return await r}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(t){this._debug("#_useSession","begin");try{const s=await this.__loadSession();return await t(s)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let t=null;const s=await ki(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",s),s!==null&&(this._isValidSession(s)?t=s:(this._debug("#getSession()","session from storage is not val
95id"),await this._removeSession())),!t)return{data:{session:null},error:null};const r=t.expires_at?t.expires_at*1e3-Date.now()<bf:!1;if(this._debug("#__loadSession()",`session has${r?"":" not"} expired`,"expires_at",t.expires_at),!r){if(this.userStorage){const o=await ki(this.userStorage,this.storageKey+"-user");o!=null&&o.user?t.user=o.user:t.user=_f()}if(this.storage.isServer&&t.user&&!t.user.__isUserNotAvailableProxy){const o={value:this.suppressGetSessionWarning};t.user=JO(t.user,o),o.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:t},error:null}}const{data:a,error:i}=await this._callRefreshToken(t.refresh_token);return i?this._returnResult({data:{session:null},error:i}):this._returnResult({data:{session:a},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(t){if(t)return await this._getUser(t);await this.initializePromise;const s=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser());return s.data.user&&(this.suppressGetSessionWarning=!0),s}async _getUser(t){try{return t?await He(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:t,xform:Sa}):await this._useSession(async s=>{var r,a,i;const{data:o,error:l}=s;if(l)throw l;return!(!((r=o.session)===null||r===void 0)&&r.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new rn}:await He(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(a=o.session)===null||a===void 0?void 0:a.access_token)!==null&&i!==void 0?i:void 0,xform:Sa})})}catch(s){if(Fe(s))return wf(s)&&(await this._removeSession(),await ys(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:s});throw s}}async updateUser(t,s={}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(t,s))}async _updateUser(t,s={}){try{return await this._useSession(async r=>{const{data:a,error:i}=r;if(i)throw i;if(!a.session)throw new rn;const o=a.session;let l=null,c=null;this.flowType==="pkce"&&t.email!=null&&([l,c]=await yo(this.storage,this.storageKey));const{data:d,error:u}=await He(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:s==null?void 0:s.emailRedirectTo,body:Object.assign(Object.assign({},t),{code_challenge:l,code_challenge_method:c}),jwt:o.access_token,xform:Sa});if(u)throw u;return o.user=d.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),this._returnResult({data:{user:o.user},error:null})})}catch(r){if(await ys(this.storage,`${this.storageKey}-code-verifier`),Fe(r))return this._returnResult({data:{user:null},error:r});throw r}}async setSession(t){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(t))}async _setSession(t){try{if(!t.access_token||!t.refresh_token)throw new rn;const s=Date.now()/1e3;let r=s,a=!0,i=null;const{payload:o}=eh(t.access_token);if(o.exp&&(r=o.exp,a=r<=s),a){const{data:l,error:c}=await this._callRefreshToken(t.refresh_token);if(c)return this._returnResult({data:{user:null,session:null},error:c});if(!l)return{data:{user:null,session:null},error:null};i=l}else{const{data:l,error:c}=await this._getUser(t.access_token);if(c)return this._returnResult({data:{user:null,session:null},error:c});i={access_token:t.access_token,refresh_token:t.refresh_token,user:l.user,token_type:"bearer",expires_in:r-s,expires_at:r},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return this._returnResult({data:{user:i.user,session:i},error:null})}catch(s){if(Fe(s))return this._returnResult({data:{session:null,user:null},error:s});throw s}}async refreshSession(t){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(t))}async _refreshSession(t){try{return await this._useSession(async s=>{var r;if(!t){const{data:o,error:l}=s;if(l)throw l;t=(r=o.session)!==null&&r!==void 0?r:void 0}if(!(t!=null&&t.refresh_token))throw new rn;const{data:a,error:i}=await this._callRefreshToken(t.refresh_token);return i?this._returnResult({data:{user:null,session:null},error:i}):a?this._returnResult({data:{user:a.user,session:a},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(s){if(Fe(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async _getSessionFromURL(t,s){try{if(!bs())throw new Xu("No browser detected.");
95if(t.error||t.error_description||t.error_code)throw new Xu(t.error_description||"Error in URL with unspecified error_description",{error:t.error||"unspecified_error",code:t.error_code||"unspecified_code"});switch(s){case"implicit":if(this.flowType==="pkce")throw new gw("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new Xu("Not a valid implicit grant flow url.");break;default:}if(s==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!t.code)throw new gw("No code detected.");const{data:y,error:w}=await this._exchangeCodeForSession(t.code);if(w)throw w;const j=new URL(window.location.href);return j.searchParams.delete("code"),window.history.replaceState(window.history.state,"",j.toString()),{data:{session:y.session,redirectType:null},error:null}}const{provider_token:r,provider_refresh_token:a,access_token:i,refresh_token:o,expires_in:l,expires_at:c,token_type:d}=t;if(!i||!l||!o||!d)throw new Xu("No session defined in URL");const u=Math.round(Date.now()/1e3),m=parseInt(l);let p=u+m;c&&(p=parseInt(c));const f=p-u;f*1e3<=Lo&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${f}s, should have been closer to ${m}s`);const g=p-m;u-g>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",g,p,u):u-g<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",g,p,u);const{data:x,error:b}=await this._getUser(i);if(b)throw b;const v={provider_token:r,provider_refresh_token:a,access_token:i,expires_in:m,expires_at:p,refresh_token:o,token_type:d,user:x.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:v,redirectType:t.type},error:null})}catch(r){if(Fe(r))return this._returnResult({data:{session:null,redirectType:null},error:r});throw r}}_isImplicitGrantCallback(t){return typeof this.detectSessionInUrl=="function"?this.detectSessionInUrl(new URL(window.location.href),t):!!(t.access_token||t.error_description)}async _isPKCECallback(t){const s=await ki(this.storage,`${this.storageKey}-code-verifier`);return!!(t.code&&s)}async signOut(t={scope:"global"}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(t))}async _signOut({scope:t}={scope:"global"}){return await this._useSession(async s=>{var r;const{data:a,error:i}=s;if(i&&!wf(i))return this._returnResult({error:i});const o=(r=a.session)===null||r===void 0?void 0:r.access_token;if(o){const{error:l}=await this.admin.signOut(o,t);if(l&&!(TO(l)&&(l.status===404||l.status===401||l.status===403)||wf(l)))return this._returnResult({error:l})}return t!=="others"&&(await this._removeSession(),await ys(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(t){const s=DO(),r={id:s,callback:t,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",s),this.stateChangeEmitters.delete(s)}};return this._debug("#onAuthStateChange()","registered callback with id",s),this.stateChangeEmitters.set(s,r),(async()=>(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(s)})))(),{data:{subscription:r}}}async _emitInitialSession(t){return await this._useSession(async s=>{var r,a;try{const{data:{session:i},error:o}=s;if(o)throw o;await((r=this.stateChangeEmitters.get(t))===null||r===void 0?void 0:r.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",t,"session",i)}catch(i){await((a=this.stateChangeEmitters.get(t))===null||a===void 0?void 0:a.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",t,"error",i),console.error(i)}})}async resetPasswordForEmail(t,s={}){let r=null,a=null;this.flowType==="pkce"&&([r,a]=await yo(this.storage,this.storageKey,!0));try{return await He(this.fetch,"POST",`${this.url}/recover`,{body:{email:t,code_challenge:r,code_challenge_method:a,gotrue_meta_security:{captcha_token:s.captchaToken}},headers:this.headers,redirectTo:s.redirectTo})}catch(i){if(await ys(this.storage,`${this.storageKey}-code-verifier`),Fe(i))return this._returnResult({data:null,error:i});throw i}}async getUserIdentities(){var t;try{const{data:s,error:r}=await this.getUser();if(r)throw r;return this._returnResult({data:{identities:(t=s.user.identities)!==null&&t!==void 0?t:[]},error:null})}catch(s){if(Fe(s))return this._returnResult({data:null,error:s});throw s}}async linkIdentity(t){return"token"in t?this.linkIdentityIdToken(t):this.linkIdentityOAuth(t)}async linkIdentityOAuth(t){var s;try{const{data:r,error:a}=await this._useSession(async i=>{var o,l,c,d,u;const{data:m,error:p}=i;if(p)throw p;const f=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,t.provider,{redirectTo:(o=t.options)===null||o===void 0?void 0:o.redirectTo,scopes:(l=t.options)===null||l===void 0?void 0:l.scopes,queryParams:(c=t.options)===null||c===void 0?void 0:c.queryParams,skipBrowserRedirect:!0});return await He(this.fetch,"GET",f,{headers:this.headers,jwt:(u=(d=m.session)===null||d===void 0?void 0:d.access_token)!==null&&u!==void 0?u:void 0})});if(a)throw a;return bs()&&!(!((s=t.options)===null||s===void 0)&&s.skipBrowserRedirect)&&window.location.assign(r==null?void 0:r.url),this._returnResult({data:{provider:t.provider,url:r==null?void 0:r.url},error:null})}catch(r){if(Fe(r))return this._returnResult({data:{provider:t.provider,url:null},error:r});throw r}}async linkIdentityIdToken(t){return await this._useSession(async s=>{var r;try{const{error:a,data:{session:i}}=s;
95if(a)throw a;const{options:o,provider:l,token:c,access_token:d,nonce:u}=t,m=await He(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(r=i==null?void 0:i.access_token)!==null&&r!==void 0?r:void 0,body:{provider:l,id_token:c,access_token:d,nonce:u,link_identity:!0,gotrue_meta_security:{captcha_token:o==null?void 0:o.captchaToken}},xform:Fn}),{data:p,error:f}=m;return f?this._returnResult({data:{user:null,session:null},error:f}):!p||!p.session||!p.user?this._returnResult({data:{user:null,session:null},error:new vo}):(p.session&&(await this._saveSession(p.session),await this._notifyAllSubscribers("USER_UPDATED",p.session)),this._returnResult({data:p,error:f}))}catch(a){if(await ys(this.storage,`${this.storageKey}-code-verifier`),Fe(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}})}async unlinkIdentity(t){try{return await this._useSession(async s=>{var r,a;const{data:i,error:o}=s;if(o)throw o;return await He(this.fetch,"DELETE",`${this.url}/user/identities/${t.identity_id}`,{headers:this.headers,jwt:(a=(r=i.session)===null||r===void 0?void 0:r.access_token)!==null&&a!==void 0?a:void 0})})}catch(s){if(Fe(s))return this._returnResult({data:null,error:s});throw s}}async _refreshAccessToken(t){const s=`#_refreshAccessToken(${t.substring(0,5)}...)`;this._debug(s,"begin");try{const r=Date.now();return await UO(async a=>(a>0&&await FO(200*Math.pow(2,a-1)),this._debug(s,"refreshing attempt",a),await He(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:t},headers:this.headers,xform:Fn})),(a,i)=>{const o=200*Math.pow(2,a);return i&&jf(i)&&Date.now()+o-r<Lo})}catch(r){if(this._debug(s,"error",r),Fe(r))return this._returnResult({data:{session:null,user:null},error:r});throw r}finally{this._debug(s,"end")}}_isValidSession(t){return typeof t=="object"&&t!==null&&"access_token"in t&&"refresh_token"in t&&"expires_at"in t}async _handleProviderSignIn(t,s){const r=await this._getUrlForProvider(`${this.url}/authorize`,t,{redirectTo:s.redirectTo,scopes:s.scopes,queryParams:s.queryParams});return this._debug("#_handleProviderSignIn()","provider",t,"options",s,"url",r),bs()&&!s.skipBrowserRedirect&&window.location.assign(r),{data:{provider:t,url:r},error:null}}async _recoverAndRefresh(){var t,s;const r="#_recoverAndRefresh()";this._debug(r,"begin");try{const a=await ki(this.storage,this.storageKey);if(a&&this.userStorage){let o=await ki(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!o&&(o={user:a.user},await Io(this.userStorage,this.storageKey+"-user",o)),a.user=(t=o==null?void 0:o.user)!==null&&t!==void 0?t:_f()}else if(a&&!a.user&&!a.user){const o=await ki(this.storage,this.storageKey+"-user");o&&(o!=null&&o.user)?(a.user=o.user,await ys(this.storage,this.storageKey+"-user"),await Io(this.storage,this.storageKey,a)):a.user=_f()}if(this._debug(r,"session from storage",a),!this._isValidSession(a)){this._debug(r,"session is not valid"),a!==null&&await this._removeSession();return}const i=((s=a.expires_at)!==null&&s!==void 0?s:1/0)*1e3-Date.now()<bf;if(this._debug(r,`session has${i?"":" not"} expired with margin of ${bf}s`),i){if(this.autoRefreshToken&&a.refresh_token){const{error:o}=await this._callRefreshToken(a.refresh_token);o&&(console.error(o),jf(o)||(this._debug(r,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()))}}else if(a.user&&a.user.__isUserNotAvailableProxy===!0)try{const{data:o,error:l}=await this._getUser(a.access_token);!l&&(o!=null&&o.user)?(a.user=o.user,await this._saveSession(a),await this._notifyAllSubscribers("SIGNED_IN",a)):this._debug(r,"could not get user data, skipping SIGNED_IN notification")}catch(o){console.error("Error getting user data:",o),this._debug(r,"error getting user data, skipping SIGNED_IN notification",o)}else await this._notifyAllSubscribers("SIGNED_IN",a)}catch(a){this._debug(r,"error",a),console.error(a);return}finally{this._debug(r,"end")}}async _callRefreshToken(t){var s,r;if(!t)throw new rn;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const a=`#_callRefreshToken(${t.substring(0,5)}...)`;this._debug(a,"begin");try{this.refreshingDeferred=new cp;const{data:i,error:o}=await this._refreshAccessToken(t);if(o)throw o;if(!i.session)throw new rn;await this._saveSession(i.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",i.session);const l={data:i.session,error:null};return this.refreshingDeferred.resolve(l),l}catch(i){if(this._debug(a,"error",i),Fe(i)){const o={data:null,error:i};return jf(i)||await this._removeSession(),(s=this.refreshingDeferred)===null||s===void 0||s.resolve(o),o}throw(r=this.refreshingDeferred)===null||r===void 0||r.reject(i),i}finally{this.refreshingDeferred=null,this._debug(a,"end")}}async _notifyAllSubscribers(t,s,r=!0){const a=`#_notifyAllSubscribers(${t})`;this._debug(a,"begin",s,`broadcast = ${r}`);try{this.broadcastChannel&&r&&this.broadcastChannel.postMessage({event:t,session:s});const i=[],o=Array.from(this.stateChangeEmitters.values()).map(async l=>{try{await l.callback(t,s)}catch(c){i.push(c)}});if(await Promise.all(o),i.length>0){for(let l=0;l<i.length;l+=1)console.error(i[l]);throw i[0]}}finally{this._debug(a,"end")}}async _saveSession(t){this._debug("#_saveSession()",t),this.suppressGetSessionWarning=!0,await ys(this.storage,`${this.storageKey}-code-verifier`);const s=Object.assign({},t),r=s.user&&s.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!r&&s.user&&await Io(this.userStorage,this.storageKey+"-user",{user:s.user});const a=Object.assign({},s);delete a.user;const i=ww(a);await Io(this.storage,this.storageKey,i)}else{const a=ww(s);await Io(this.storage,this.storageKey,a)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await ys(this.storage,this.storageKey),await ys(this.storage,this.storageKey+"-code-verifier"),await ys(this.storage,this.storageKey+"-user"),this.userStorage&&await ys(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const t=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{t&&bs()&&(window!=null&&window.removeEventListener)&&window.removeEventListener("visibilitychange",t)}
95catch(s){console.error("removing visibilitychange callback failed",s)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const t=setInterval(()=>this._autoRefreshTokenTick(),Lo);this.autoRefreshTicker=t,t&&typeof t=="object"&&typeof t.unref=="function"?t.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(t);const s=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=s,s&&typeof s=="object"&&typeof s.unref=="function"?s.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(s)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const t=this.autoRefreshTicker;this.autoRefreshTicker=null,t&&clearInterval(t);const s=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,s&&clearTimeout(s)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{const t=Date.now();try{return await this._useSession(async s=>{const{data:{session:r}}=s;if(!r||!r.refresh_token||!r.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const a=Math.floor((r.expires_at*1e3-t)/Lo);this._debug("#_autoRefreshTokenTick()",`access token expires in ${a} ticks, a tick lasts ${Lo}ms, refresh threshold is ${Tx} ticks`),a<=Tx&&await this._callRefreshToken(r.refresh_token)})}catch(s){console.error("Auto refresh tick failed with error. This is likely a transient error.",s)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(t){if(t.isAcquireTimeout||t instanceof QN)this._debug("auto refresh token tick lock not available");else throw t}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!bs()||!(window!=null&&window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(t){this._debug("#visibilityChangedCallback","error",t)}},window==null||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(t){console.error("_handleVisibilityChange",t)}}async _onVisibilityChanged(t){const s=`#_onVisibilityChanged(${t})`;this._debug(s,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),t||(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{if(document.visibilityState!=="visible"){this._debug(s,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(t,s,r){const a=[`provider=${encodeURIComponent(s)}`];if(r!=null&&r.redirectTo&&a.push(`redirect_to=${encodeURIComponent(r.redirectTo)}`),r!=null&&r.scopes&&a.push(`scopes=${encodeURIComponent(r.scopes)}`),this.flowType==="pkce"){const[i,o]=await yo(this.storage,this.storageKey),l=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(o)}`});a.push(l.toString())}if(r!=null&&r.queryParams){const i=new URLSearchParams(r.queryParams);a.push(i.toString())}return r!=null&&r.skipBrowserRedirect&&a.push(`skip_http_redirect=${r.skipBrowserRedirect}`),`${t}?${a.join("&")}`}async _unenroll(t){try{return await this._useSession(async s=>{var r;const{data:a,error:i}=s;return i?this._returnResult({data:null,error:i}):await He(this.fetch,"DELETE",`${this.url}/factors/${t.factorId}`,{headers:this.headers,jwt:(r=a==null?void 0:a.session)===null||r===void 0?void 0:r.access_token})})}catch(s){if(Fe(s))return this._returnResult({data:null,error:s});throw s}}async _enroll(t){try{return await this._useSession(async s=>{var r,a;const{data:i,error:o}=s;
95if(o)return this._returnResult({data:null,error:o});const l=Object.assign({friendly_name:t.friendlyName,factor_type:t.factorType},t.factorType==="phone"?{phone:t.phone}:t.factorType==="totp"?{issuer:t.issuer}:{}),{data:c,error:d}=await He(this.fetch,"POST",`${this.url}/factors`,{body:l,headers:this.headers,jwt:(r=i==null?void 0:i.session)===null||r===void 0?void 0:r.access_token});return d?this._returnResult({data:null,error:d}):(t.factorType==="totp"&&c.type==="totp"&&(!((a=c==null?void 0:c.totp)===null||a===void 0)&&a.qr_code)&&(c.totp.qr_code=`data:image/svg+xml;utf-8,${c.totp.qr_code}`),this._returnResult({data:c,error:null}))})}catch(s){if(Fe(s))return this._returnResult({data:null,error:s});throw s}}async _verify(t){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async s=>{var r;const{data:a,error:i}=s;if(i)return this._returnResult({data:null,error:i});const o=Object.assign({challenge_id:t.challengeId},"webauthn"in t?{webauthn:Object.assign(Object.assign({},t.webauthn),{credential_response:t.webauthn.type==="create"?gD(t.webauthn.credential_response):xD(t.webauthn.credential_response)})}:{code:t.code}),{data:l,error:c}=await He(this.fetch,"POST",`${this.url}/factors/${t.factorId}/verify`,{body:o,headers:this.headers,jwt:(r=a==null?void 0:a.session)===null||r===void 0?void 0:r.access_token});return c?this._returnResult({data:null,error:c}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+l.expires_in},l)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",l),this._returnResult({data:l,error:c}))})}catch(s){if(Fe(s))return this._returnResult({data:null,error:s});throw s}})}async _challenge(t){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async s=>{var r;const{data:a,error:i}=s;if(i)return this._returnResult({data:null,error:i});const o=await He(this.fetch,"POST",`${this.url}/factors/${t.factorId}/challenge`,{body:t,headers:this.headers,jwt:(r=a==null?void 0:a.session)===null||r===void 0?void 0:r.access_token});if(o.error)return o;const{data:l}=o;if(l.type!=="webauthn")return{data:l,error:null};switch(l.webauthn.type){case"create":return{data:Object.assign(Object.assign({},l),{webauthn:Object.assign(Object.assign({},l.webauthn),{credential_options:Object.assign(Object.assign({},l.webauthn.credential_options),{publicKey:pD(l.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},l),{webauthn:Object.assign(Object.assign({},l.webauthn),{credential_options:Object.assign(Object.assign({},l.webauthn.credential_options),{publicKey:fD(l.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(s){if(Fe(s))return this._returnResult({data:null,error:s});throw s}})}async _challengeAndVerify(t){const{data:s,error:r}=await this._challenge({factorId:t.factorId});return r?this._returnResult({data:null,error:r}):await this._verify({factorId:t.factorId,challengeId:s.id,code:t.code})}async _listFactors(){var t;const{data:{user:s},error:r}=await this.getUser();if(r)return{data:null,error:r};const a={all:[],phone:[],totp:[],webauthn:[]};for(const i of(t=s==null?void 0:s.factors)!==null&&t!==void 0?t:[])a.all.push(i),i.status==="verified"&&a[i.factor_type].push(i);return{data:a,error:null}}async _getAuthenticatorAssuranceLevel(t){var s,r,a,i;if(t)try{const{payload:f}=eh(t);let g=null;f.aal&&(g=f.aal);let x=g;const{data:{user:b},error:v}=await this.getUser(t);if(v)return this._returnResult({data:null,error:v});((r=(s=b==null?void 0:b.factors)===null||s===void 0?void 0:s.filter(j=>j.status==="verified"))!==null&&r!==void 0?r:[]).length>0&&(x="aal2");const w=f.amr||[];return{data:{currentLevel:g,nextLevel:x,currentAuthenticationMethods:w},error:null}}catch(f){if(Fe(f))return this._returnResult({data:null,error:f});throw f}const{data:{session:o},error:l}
95=await this.getSession();if(l)return this._returnResult({data:null,error:l});if(!o)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:c}=eh(o.access_token);let d=null;c.aal&&(d=c.aal);let u=d;((i=(a=o.user.factors)===null||a===void 0?void 0:a.filter(f=>f.status==="verified"))!==null&&i!==void 0?i:[]).length>0&&(u="aal2");const p=c.amr||[];return{data:{currentLevel:d,nextLevel:u,currentAuthenticationMethods:p},error:null}}async _getAuthorizationDetails(t){try{return await this._useSession(async s=>{const{data:{session:r},error:a}=s;return a?this._returnResult({data:null,error:a}):r?await He(this.fetch,"GET",`${this.url}/oauth/authorizations/${t}`,{headers:this.headers,jwt:r.access_token,xform:i=>({data:i,error:null})}):this._returnResult({data:null,error:new rn})})}catch(s){if(Fe(s))return this._returnResult({data:null,error:s});throw s}}async _approveAuthorization(t,s){try{return await this._useSession(async r=>{const{data:{session:a},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!a)return this._returnResult({data:null,error:new rn});const o=await He(this.fetch,"POST",`${this.url}/oauth/authorizations/${t}/consent`,{headers:this.headers,jwt:a.access_token,body:{action:"approve"},xform:l=>({data:l,error:null})});return o.data&&o.data.redirect_url&&bs()&&!(s!=null&&s.skipBrowserRedirect)&&window.location.assign(o.data.redirect_url),o})}catch(r){if(Fe(r))return this._returnResult({data:null,error:r});throw r}}async _denyAuthorization(t,s){try{return await this._useSession(async r=>{const{data:{session:a},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!a)return this._returnResult({data:null,error:new rn});const o=await He(this.fetch,"POST",`${this.url}/oauth/authorizations/${t}/consent`,{headers:this.headers,jwt:a.access_token,body:{action:"deny"},xform:l=>({data:l,error:null})});return o.data&&o.data.redirect_url&&bs()&&!(s!=null&&s.skipBrowserRedirect)&&window.location.assign(o.data.redirect_url),o})}catch(r){if(Fe(r))return this._returnResult({data:null,error:r});throw r}}async _listOAuthGrants(){try{return await this._useSession(async t=>{const{data:{session:s},error:r}=t;return r?this._returnResult({data:null,error:r}):s?await He(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:s.access_token,xform:a=>({data:a,error:null})}):this._returnResult({data:null,error:new rn})})}catch(t){if(Fe(t))return this._returnResult({data:null,error:t});throw t}}async _revokeOAuthGrant(t){try{return await this._useSession(async s=>{const{data:{session:r},error:a}=s;return a?this._returnResult({data:null,error:a}):r?(await He(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,query:{client_id:t.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new rn})})}catch(s){if(Fe(s))return this._returnResult({data:null,error:s});throw s}}async fetchJwk(t,s={keys:[]}){let r=s.keys.find(l=>l.kid===t);if(r)return r;const a=Date.now();if(r=this.jwks.keys.find(l=>l.kid===t),r&&this.jwks_cached_at+SO>a)return r;const{data:i,error:o}=await He(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(o)throw o;return!i.keys||i.keys.length===0||(this.jwks=i,this.jwks_cached_at=a,r=i.keys.find(l=>l.kid===t),!r)?null:r}async getClaims(t,s={}){try{let r=t;if(!r){const{data:f,error:g}
95=await this.getSession();if(g||!f.session)return this._returnResult({data:null,error:g});r=f.session.access_token}const{header:a,payload:i,signature:o,raw:{header:l,payload:c}}=eh(r);s!=null&&s.allowExpired||YO(i.exp);const d=!a.alg||a.alg.startsWith("HS")||!a.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(a.kid,s!=null&&s.keys?{keys:s.keys}:s==null?void 0:s.jwks);if(!d){const{error:f}=await this.getUser(r);if(f)throw f;return{data:{claims:i,header:a,signature:o},error:null}}const u=KO(a.alg),m=await crypto.subtle.importKey("jwk",d,u,!0,["verify"]);if(!await crypto.subtle.verify(u,m,o,IO(`${l}.${c}`)))throw new Ax("Invalid JWT signature");return{data:{claims:i,header:a,signature:o},error:null}}catch(r){if(Fe(r))return this._returnResult({data:null,error:r});throw r}}}Td.nextInstanceID={};const SD=Td,CD="2.101.0";let Ac="";typeof Deno<"u"?Ac="deno":typeof document<"u"?Ac="web":typeof navigator<"u"&&navigator.product==="ReactNative"?Ac="react-native":Ac="node";const TD={"X-Client-Info":`supabase-js-${Ac}/${CD}`},PD={headers:TD},ED={schema:"public"},AD={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},RD={};function Pd(e){"@babel/helpers - typeof";return Pd=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},Pd(e)}function $D(e,t){if(Pd(e)!="object"||!e)return e;var s=e[Symbol.toPrimitive];if(s!==void 0){var r=s.call(e,t||"default");if(Pd(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function LD(e){var t=$D(e,"string");return Pd(t)=="symbol"?t:t+""}function ID(e,t,s){return(t=LD(t))in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s,e}function Pw(e,t){var s=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),s.push.apply(s,r)}return s}function Yt(e){for(var t=1;t<arguments.length;t++){var s=arguments[t]!=null?arguments[t]:{};t%2?Pw(Object(s),!0).forEach(function(r){ID(e,r,s[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(s)):Pw(Object(s)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(s,r))})}return e}const OD=e=>e?(...t)=>e(...t):(...t)=>fetch(...t),DD=()=>Headers,MD=(e,t,s)=>{const r=OD(s),a=DD();return async(i,o)=>{var l;const c=(l=await t())!==null&&l!==void 0?l:e;let d=new a(o==null?void 0:o.headers);return d.has("apikey")||d.set("apikey",e),d.has("Authorization")||d.set("Authorization",`Bearer ${c}`),r(i,Yt(Yt({},o),{},{headers:d}))}};function zD(e){return e.endsWith("/")?e:e+"/"}function FD(e,t){var s,r;const{db:a,auth:i,realtime:o,global:l}=e,{db:c,auth:d,realtime:u,global:m}=t,p={db:Yt(Yt({},c),a),auth:Yt(Yt({},d),i),realtime:Yt(Yt({},u),o),storage:{},global:Yt(Yt(Yt({},m),l),{},{headers:Yt(Yt({},(s=m==null?void 0:m.headers)!==null&&s!==void 0?s:{}),(r=l==null?void 0:l.headers)!==null&&r!==void 0?r:{})}),accessToken:async()=>""};return e.accessToken?p.accessToken=e.accessToken:delete p.accessToken,p}function UD(e){const t=e==null?void 0:e.trim();if(!t)throw new Error("supabaseUrl is required.");if(!t.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(zD(t))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var BD=class extends SD{constructor(e){super(e)}},VD=class{constructor(e,t,s){var r,a;this.supabaseUrl=e,this.supabaseKey=t;const i=UD(e);if(!t)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",i),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",i),this.storageUrl=new URL("storage/v1",i),this.functionsUrl=new URL("functions/v1",i);const o=`sb-${i.hostname.split(".")[0]}-auth-token`,l={db:ED,realtime:RD,auth:Yt(Yt({},AD),{},{storageKey:o}),global:PD},c=FD(s??{},l);if(this.storageKey=(r=c.auth.storageKey)!==null&&r!==void 0?r:"",this.headers=(a=c.global.headers)!==null&&a!==void 0?a:{},c.accessToken)this.accessToken=c.accessToken,this.auth=new Proxy({},{get:(u,m)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(m)} is not possible`)}});else{var d;this.auth=this._initSupabaseAuthClient((d=c.auth)!==null&&d!==void 0?d:{},this.headers,c.global.fetch)}this.fetch=MD(t,this._getAccessToken.bind(this),c.global.fetch),this.realtime=this._initRealtimeClient(Yt({headers:this.headers,accessToken:this._getAccessToken.bind(this)},c.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(u=>this.realtime.setAuth(u)).catch(u=>console.warn("Failed to set initial Realtime auth token:",u)),this.rest=new u3(new URL("rest/v1",i).href,{headers:this.headers,schema:c.db.schema,fetch:this.fetch,timeout:c.db.timeout,urlLengthLimit:c.db.urlLengthLimit}),this.storage=new wO(this.storageUrl.href,this.headers,this.fetch,s==null?void 0:s.storage),c.accessToken||this._listenForAuthEvents()}get functions(){return new n3(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},s={head:!1,get:!1,count:void 0}){return this.rest.rpc(e,t,s)}
95channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var e=this,t,s;if(e.accessToken)return await e.accessToken();const{data:r}=await e.auth.getSession();return(t=(s=r.session)===null||s===void 0?void 0:s.access_token)!==null&&t!==void 0?t:e.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:s,storage:r,userStorage:a,storageKey:i,flowType:o,lock:l,debug:c,throwOnError:d},u,m){const p={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new BD({url:this.authUrl.href,headers:Yt(Yt({},p),u),storageKey:i,autoRefreshToken:e,persistSession:t,detectSessionInUrl:s,storage:r,userStorage:a,flowType:o,lock:l,debug:c,throwOnError:d,fetch:m,hasCustomAuthorizationHeader:Object.keys(this.headers).some(f=>f.toLowerCase()==="authorization")})}_initRealtimeClient(e){return new H3(this.realtimeUrl.href,Yt(Yt({},e),{},{params:Yt(Yt({},{apikey:this.supabaseKey}),e==null?void 0:e.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((e,t)=>{this._handleTokenChanged(e,"CLIENT",t==null?void 0:t.access_token)})}_handleTokenChanged(e,t,s){(e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==s?(this.changedAccessToken=s,this.realtime.setAuth(s)):e==="SIGNED_OUT"&&(this.realtime.setAuth(),t=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};const qD=(e,t,s)=>new VD(e,t,s);function HD(){if(typeof window<"u")return!1;const e=globalThis.process;if(!e)return!1;const t=e.version;if(t==null)return!1;const s=t.match(/^v(\d+)\./);return s?parseInt(s[1],10)<=18:!1}HD()&&console.warn("⚠️  Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217");const WD="https://nfqxajdgklseicehjolk.supabase.co",GD="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Im5mcXhhamRna2xzZWljZWhqb2xrIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzQ4OTE1MzksImV4cCI6MjA5MDQ2NzUzOX0.6_j0QrbnSX8MwR-HqRHEG6jOotimefvkE_S9mchl3TE",I=qD(WD,GD,{auth:{storage:localStorage,persistSession:!0,autoRefreshToken:!0}}),XN=h.createContext({session:null,user:null,profile:null,loading:!0,accessBlocked:!1,signOut:async()=>{},refreshProfile:async()=>{}}),st=()=>h.useContext(XN);async function YD(e){const{data:t}=await I.from("user_profiles").select("onboarding_completed, selected_role, workspace_id").eq("user_id",e).maybeSingle();return t}async function KD(e){const{data:t}=await I.from("user_roles").select("role").eq("user_id",e).limit(1);return!!(t&&t.length>0)}function Ew(e){if(!e)return!1;try{const t=JSON.parse(atob(e.split(".")[1]));return!(t!=null&&t.sub)}catch{return!0}}async function Aw(){try{await I.auth.signOut()}catch{}window.location.reload()}function QD({children:e}){const[t,s]=h.useState(null),[r,a]=h.useState(null),[i,o]=h.useState(!0),[l,c]=h.useState(!1),d=async p=>{if(!await KD(p)){c(!0),a(null);try{await I.auth.signOut()}catch{}s(null);return}c(!1);const g=await YD(p);a(g)};h.useEffect(()=>{const{data:{subscription:p}}=I.auth.onAuthStateChange(async(f,g)=>{if(g!=null&&g.access_token&&Ew(g.access_token)){Aw();return}s(g),g!=null&&g.user?setTimeout(()=>d(g.user.id),0):a(null)});return I.auth.getSession().then(async({data:{session:f}})=>{if(f!=null&&f.access_token&&Ew(f.access_token)){Aw();return}s(f),f!=null&&f.user&&await d(f.user.id),o(!1)}),()=>p.unsubscribe()},[]);const u=async()=>{await I.auth.signOut(),s(null),a(null),c(!1)},m=async()=>{t!=null&&t.user&&await d(t.user.id)};return n.jsx(XN.Provider,{value:{session:t,user:(t==null?void 0:t.user)??null,profile:r,loading:i,accessBlocked:l,signOut:u,refreshProfile:m},children:e})}const eS=h.createContext({planKey:"free",subscribed:!1,status:"inactive",subscriptionEnd:null,loading:!0,refresh:async()=>{},startCheckout:async()=>{},openPortal:async()=>{},isAdmin:!1,overridePlan:()=>{}}),ar=()=>h.useContext(eS);function JD({children:e}){const{session:t}=st(),[s,r]=h.useState("free"),[a,i]=h.useState(!1),[o,l]=h.useState("inactive"),[c,d]=h.useState(null),[u,m]=h.useState(!0),[p,f]=h.useState(null),[g,x]=h.useState(!1),b=h.useCallback(_=>{g&&f(_)},[g]),v=p??s,y=h.useCallback(async()=>
95{if(!(t!=null&&t.access_token)){r("free"),i(!1),x(!1),m(!1);return}try{const{data:_,error:N}=await I.functions.invoke("check-subscription",{headers:{Authorization:`Bearer ${t.access_token}`}});if(N){console.error("check-subscription error:",N),m(!1);return}r((_==null?void 0:_.plan_key)||"free"),i((_==null?void 0:_.subscribed)??!1),l((_==null?void 0:_.status)??"inactive"),d((_==null?void 0:_.subscription_end)??null),x((_==null?void 0:_.is_admin)===!0)}catch(_){console.error("check-subscription failed:",_)}finally{m(!1)}},[t==null?void 0:t.access_token]);h.useEffect(()=>{y();const _=setInterval(y,6e4);return()=>clearInterval(_)},[y]);const w=h.useCallback(async _=>{if(!(t!=null&&t.access_token))return;const{data:N,error:k}=await I.functions.invoke("create-checkout",{body:{priceId:_},headers:{Authorization:`Bearer ${t.access_token}`}});if(k){console.error("create-checkout error:",k);return}N!=null&&N.url&&window.open(N.url,"_blank")},[t==null?void 0:t.access_token]),j=h.useCallback(async()=>{if(!(t!=null&&t.access_token))return;const{data:_,error:N}=await I.functions.invoke("customer-portal",{headers:{Authorization:`Bearer ${t.access_token}`}});if(N){console.error("customer-portal error:",N);return}_!=null&&_.url&&window.open(_.url,"_blank")},[t==null?void 0:t.access_token]);return n.jsx(eS.Provider,{value:{planKey:v,subscribed:v!=="free"||a,status:o,subscriptionEnd:c,loading:u,refresh:y,startCheckout:w,openPortal:j,isAdmin:g,overridePlan:b},children:e})}const tS=h.createContext({status:"not_connected",channel:null,loading:!0,error:null,startConnect:async()=>{},disconnect:async()=>{},refresh:async()=>{}}),lo=()=>h.useContext(tS);function ZD({children:e}){const{session:t,profile:s}=st(),[r,a]=h.useState("not_connected"),[i,o]=h.useState(null),[l,c]=h.useState(!0),[d,u]=h.useState(null),m=s==null?void 0:s.workspace_id,p=h.useCallback(async()=>{if(!m){c(!1);return}try{const{data:x,error:b}=await I.from("integrations").select("*").eq("workspace_id",m).eq("provider","youtube").maybeSingle();if(b){console.error("YouTube integration fetch error:",b),c(!1);return}if(!x||x.status==="not_connected")a("not_connected"),o(null);else if(x.status==="expired"||x.status==="error"){a(x.status);const v=x.metadata_json;v&&o({id:x.provider_channel_id||"",title:v.channel_title||"",thumbnail:v.channel_thumbnail||"",handle:v.channel_handle||"",subscriberCount:v.subscriber_count||"0",videoCount:v.video_count||"0"})}else if(x.status==="connected"){a("connected");const v=x.metadata_json;o({id:x.provider_channel_id||"",title:(v==null?void 0:v.channel_title)||"",thumbnail:(v==null?void 0:v.channel_thumbnail)||"",handle:(v==null?void 0:v.channel_handle)||"",subscriberCount:(v==null?void 0:v.subscriber_count)||"0",videoCount:(v==null?void 0:v.video_count)||"0"})}}catch(x){console.error("YouTube integration check failed:",x)}finally{c(!1)}},[m]);h.useEffect(()=>{p()},[p]),h.useEffect(()=>{const x=new URL(window.location.href),b=x.searchParams.get("code"),v=x.searchParams.get("state");if(b&&v&&(t!=null&&t.access_token)){x.searchParams.delete("code"),x.searchParams.delete("state"),x.searchParams.delete("scope"),window.history.replaceState({},"",x.pathname),a("connecting"),u(null);const y=`${window.location.origin}/app/integrations`;I.functions.invoke("youtube-callback",{body:{code:b,redirectUri:y},headers:{Authorization:`Bearer ${t.access_token}`}}).then(({data:w,error:j})=>{if(j||w!=null&&w.error){a("error"),u((w==null?void 0:w.error)||(j==null?void 0:j.message)||"Connection failed");return}w!=null&&w.channel&&(o(w.channel),a("connected"))})}},[t==null?void 0:t.access_token]);const f=h.useCallback(async()=>{if(!(t!=null&&t.access_token))return;a("connecting"),u(null);const{data:x,error:b}=await I.functions.invoke("youtube-auth-url",{headers:{Authorization:`Bearer ${t.access_token}`}});if(b||x!=null&&x.error){a("error"),u((x==null?void 0:x.error)||(b==null?void 0:b.message)||"Failed to get auth URL");return}x!=null&&x.url&&(window.location.href=x.url)},[t==null?void 0:t.access_token]),g=h.useCallback(async()=>{m&&(await I.from("integrations").update({status:"not_connected",access_token_encrypted:null,refresh_token_encrypted:null}).eq("workspace_id",m).eq("provider","youtube"),a("not_connected"),o(null))},[m]);return n.jsx(tS.Provider,{value:{status:r,channel:i,loading:l,error:d,startConnect:f,disconnect:g,refresh:p},children:e})}const sS=h.createContext({status:"not_connected",account:null,loading:!0,error:null,startConnect:async()=>{},disconnect:async()=>{},refresh:async()=>{}}),nS=()=>h.useContext(sS);function XD({children:e}){const{session:t,profile:s}=st(),[r,a]=h.useState("not_connected"),[i,o]=h.useState(null),[l,c]=h.useState(!0),[d,u]=
95h.useState(null),m=s==null?void 0:s.workspace_id,p=h.useCallback(async()=>{if(!m){c(!1);return}try{const{data:x}=await I.from("integrations").select("status, provider_account_id, expires_at, metadata_json").eq("workspace_id",m).eq("provider","restream").maybeSingle();if(!x||x.status==="not_connected")a("not_connected"),o(null);else{const b=x.metadata_json||{};o({username:b.username??null,providerAccountId:x.provider_account_id??null}),a(x.status)}}catch(x){console.error("Restream integration fetch failed",x)}finally{c(!1)}},[m]);h.useEffect(()=>{p()},[p]),h.useEffect(()=>{const x=new URL(window.location.href),b=x.searchParams.get("code"),v=x.searchParams.get("state");if(!b||!v||!(t!=null&&t.access_token))return;let y=!1;try{const j=JSON.parse(atob(v));y=(j==null?void 0:j.provider)==="restream"}catch{}if(!y)return;x.searchParams.delete("code"),x.searchParams.delete("state"),window.history.replaceState({},"",x.pathname),a("connecting"),u(null);const w=`${window.location.origin}/app/integrations`;I.functions.invoke("restream-callback",{body:{code:b,redirectUri:w},headers:{Authorization:`Bearer ${t.access_token}`}}).then(({data:j,error:_})=>{if(_||j!=null&&j.error){a("error"),u((j==null?void 0:j.error)||(_==null?void 0:_.message)||"Connection failed");return}a("connected"),p()})},[t==null?void 0:t.access_token,p]);const f=h.useCallback(async()=>{if(!(t!=null&&t.access_token))return;a("connecting"),u(null);const{data:x,error:b}=await I.functions.invoke("restream-auth-url",{headers:{Authorization:`Bearer ${t.access_token}`}});if(b||x!=null&&x.error){a("error"),u((x==null?void 0:x.error)||(b==null?void 0:b.message)||"Failed to get auth URL");return}x!=null&&x.url&&(window.location.href=x.url)},[t==null?void 0:t.access_token]),g=h.useCallback(async()=>{m&&(await I.from("integrations").update({status:"not_connected",access_token_encrypted:null,refresh_token_encrypted:null}).eq("workspace_id",m).eq("provider","restream"),a("not_connected"),o(null))},[m]);return n.jsx(sS.Provider,{value:{status:r,account:i,loading:l,error:d,startConnect:f,disconnect:g,refresh:p},children:e})}/**
96 * @license lucide-react v0.462.0 - ISC
97 *
98 * This source code is licensed under the ISC license.
99 * See the LICENSE file in the root directory of this source tree.
100 */const e4=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),rS=(...e)=>e.filter((t,s,r)=>!!t&&t.trim()!==""&&r.indexOf(t)===s).join(" ").trim();/**
101 * @license lucide-react v0.462.0 - ISC
102 *
103 * This source code is licensed under the ISC license.
104 * See the LICENSE file in the root directory of this source tree.
105 */var t4={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/**
106 * @license lucide-react v0.462.0 - ISC
107 *
108 * This source code is licensed under the ISC license.
109 * See the LICENSE file in the root directory of this source tree.
110 */const s4=h.forwardRef(({color:e="currentColor",size:t=24,strokeWidth:s=2,absoluteStrokeWidth:r,className:a="",children:i,iconNode:o,...l},c)=>h.createElement("svg",{ref:c,...t4,width:t,height:t,stroke:e,strokeWidth:r?Number(s)*24/Number(t):s,className:rS("lucide",a),...l},[...o.map(([d,u])=>h.createElement(d,u)),...Array.isArray(i)?i:[i]]));/**
111 * @license lucide-react v0.462.0 - ISC
112 *
113 * This source code is licensed under the ISC license.
114 * See the LICENSE file in the root directory of this source tree.
115 */const le=(e,t)=>{const s=h.forwardRef(({className:r,...a},i)=>h.createElement(s4,{ref:i,iconNode:t,className:rS(`lucide-${e4(e)}`,r),...a}));return s.displayName=`${e}`,s};/**
116 * @license lucide-react v0.462.0 - ISC
117 *
118 * This source code is licensed under the ISC license.
119 * See the LICENSE file in the root directory of this source tree.
120 */const Ed=le("Activity",[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]]);/**
121 * @license lucide-react v0.462.0 - ISC
122 *
123 * This source code is licensed under the ISC license.
124 * See the LICENSE file in the root directory of this source tree.
125 */const ii=le("Archive",[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8",key:"1s80jp"}],["path",{d:"M10 12h4",key:"a56b0p"}]]);/**
126 * @license lucide-react v0.462.0 - ISC
127 *
128 * This source code is licensed under the ISC license.
129 * See the LICENSE file in the root directory of this source tree.
130 */const Hi=le("ArrowLeft",[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]]);/**
131 * @license lucide-react v0.462.0 - ISC
132 *
133 * This source code is licensed under the ISC license.
134 * See the LICENSE file in the root directory of this source tree.
135 */const Tr=le("ArrowRight",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]]);/**
136 * @license lucide-react v0.462.0 - ISC
137 *
138 * This source code is licensed under the ISC license.
139 * See the LICENSE file in the root directory of this source tree.
140 */const iu=le("Ban",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m4.9 4.9 14.2 14.2",key:"1m5liu"}]]);/**
141 * @license lucide-react v0.462.0 - ISC
142 *
143 * This source code is licensed under the ISC license.
144 * See the LICENSE file in the root directory of this source tree.
145 */const n4=le("Bell",[["path",{d:"M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9",key:"1qo2s2"}],["path",{d:"M10.3 21a1.94 1.94 0 0 0 3.4 0",key:"qgo35s"}]]);/**
146 * @license lucide-react v0.462.0 - ISC
147 *
148 * This source code is licensed under the ISC license.
149 * See the LICENSE file in the root directory of this source tree.
150 */const dp=le("BookOpen",[["path",{d:"M12 7v14",key:"1akyts"}],["path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z",key:"ruj8y"}]]);/**
151 * @license lucide-react v0.462.0 - ISC
152 *
153 * This source code is licensed under the ISC license.
154 * See the LICENSE file in the root directory of this source tree.
155 */const r4=le("Bot",[["path",{d:"M12 8V4H8",key:"hb8ula"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2",key:"enze0r"}],["path",{d:"M2 14h2",key:"vft8re"}],["path",{d:"M20 14h2",key:"4cs60a"}],["path",{d:"M15 13v2",key:"1xurst"}],["path",{d:"M9 13v2",key:"rq6x2g"}]]);/**
156 * @license lucide-react v0.462.0 - ISC
157 *
158 * This source code is licensed under the ISC license.
159 * See the LICENSE file in the root directory of this source tree.
160 */const a4=le("BrainCircuit",[["path",{d:"M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z",key:"l5xja"}],["path",{d:"M9 13a4.5 4.5 0 0 0 3-4",key:"10igwf"}],["path",{d:"M6.003 5.125A3 3 0 0 0 6.401 6.5",key:"105sqy"}],["path",{d:"M3.477 10.896a4 4 0 0 1 .585-.396",key:"ql3yin"}],["path",{d:"M6 18a4 4 0 0 1-1.967-.516",key:"2e4loj"}],["path",{d:"M12 13h4",key:"1ku699"}],["path",{d:"M12 18h6a2 2 0 0 1 2 2v1",key:"105ag5"}],["path",{d:"M12 8h8",key:"1lhi5i"}
160],["path",{d:"M16 8V5a2 2 0 0 1 2-2",key:"u6izg6"}],["circle",{cx:"16",cy:"13",r:".5",key:"ry7gng"}],["circle",{cx:"18",cy:"3",r:".5",key:"1aiba7"}],["circle",{cx:"20",cy:"21",r:".5",key:"yhc1fs"}],["circle",{cx:"20",cy:"8",r:".5",key:"1e43v0"}]]);/**
161 * @license lucide-react v0.462.0 - ISC
162 *
163 * This source code is licensed under the ISC license.
164 * See the LICENSE file in the root directory of this source tree.
165 */const vy=le("Brain",[["path",{d:"M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z",key:"l5xja"}],["path",{d:"M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z",key:"ep3f8r"}],["path",{d:"M15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4",key:"1p4c4q"}],["path",{d:"M17.599 6.5a3 3 0 0 0 .399-1.375",key:"tmeiqw"}],["path",{d:"M6.003 5.125A3 3 0 0 0 6.401 6.5",key:"105sqy"}],["path",{d:"M3.477 10.896a4 4 0 0 1 .585-.396",key:"ql3yin"}],["path",{d:"M19.938 10.5a4 4 0 0 1 .585.396",key:"1qfode"}],["path",{d:"M6 18a4 4 0 0 1-1.967-.516",key:"2e4loj"}],["path",{d:"M19.967 17.484A4 4 0 0 1 18 18",key:"159ez6"}]]);/**
166 * @license lucide-react v0.462.0 - ISC
167 *
168 * This source code is licensed under the ISC license.
169 * See the LICENSE file in the root directory of this source tree.
170 */const i4=le("Briefcase",[["path",{d:"M16 20V4a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16",key:"jecpp"}],["rect",{width:"20",height:"14",x:"2",y:"6",rx:"2",key:"i6l2r4"}]]);/**
171 * @license lucide-react v0.462.0 - ISC
172 *
173 * This source code is licensed under the ISC license.
174 * See the LICENSE file in the root directory of this source tree.
175 */const yy=le("Calendar",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}]]);/**
176 * @license lucide-react v0.462.0 - ISC
177 *
178 * This source code is licensed under the ISC license.
179 * See the LICENSE file in the root directory of this source tree.
180 */const Rw=le("Camera",[["path",{d:"M14.5 4h-5L7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3l-2.5-3z",key:"1tc9qg"}],["circle",{cx:"12",cy:"13",r:"3",key:"1vg3eu"}]]);/**
181 * @license lucide-react v0.462.0 - ISC
182 *
183 * This source code is licensed under the ISC license.
184 * See the LICENSE file in the root directory of this source tree.
185 */const by=le("ChartColumn",[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"M18 17V9",key:"2bz60n"}],["path",{d:"M13 17V5",key:"1frdt8"}],["path",{d:"M8 17v-3",key:"17ska0"}]]);/**
186 * @license lucide-react v0.462.0 - ISC
187 *
188 * This source code is licensed under the ISC license.
189 * See the LICENSE file in the root directory of this source tree.
190 */const ms=le("Check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]);/**
191 * @license lucide-react v0.462.0 - ISC
192 *
193 * This source code is licensed under the ISC license.
194 * See the LICENSE file in the root directory of this source tree.
195 */const ps=le("ChevronDown",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]);/**
196 * @license lucide-react v0.462.0 - ISC
197 *
198 * This source code is licensed under the ISC license.
199 * See the LICENSE file in the root directory of this source tree.
200 */const ou=le("ChevronLeft",[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]]);/**
201 * @license lucide-react v0.462.0 - ISC
202 *
203 * This source code is licensed under the ISC license.
204 * See the LICENSE file in the root directory of this source tree.
205 */const yn=le("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]);/**
206 * @license lucide-react v0.462.0 - ISC
207 *
208 * This source code is licensed under the ISC license.
209 * See the LICENSE file in the root directory of this source tree.
210 */const wy=le("ChevronUp",[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]]);/**
211 * @license lucide-react v0.462.0 - ISC
212 *
213 * This source code is licensed under the ISC license.
214 * See the LICENSE file in the root directory of this source tree.
215 */const Ad=le("CircleAlert",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]]);/**
216 * @license lucide-react v0.462.0 - ISC
217 *
218 * This source code is licensed under the ISC license.
219 * See the LICENSE file in the root directory of this source tree.
220 */const aS=le("CircleCheckBig",[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]]);/**
221 * @license lucide-react v0.462.0 - ISC
222 *
223 * This source code is licensed under the ISC license.
224 * See the LICENSE file in the root directory of this source tree.
225 */const wt=le("CircleCheck",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);/**
226 * @license lucide-react v0.462.0 - ISC
227 *
228 * This source code is licensed under the ISC license.
229 * See the LICENSE file in the root directory of this source tree.
230 */const o4=le("CirclePlay",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polygon",{points:"10 8 16 12 10 16 10 8",key:"1cimsy"}]]);/**
231 * @license lucide-react v0.462.0 - ISC
232 *
233 * This source code is licensed under the ISC license.
234 * See the LICENSE file in the root directory of this source tree.
235 */const gn=le("CircleX",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]]);/**
236 * @license lucide-react v0.462.0 - ISC
237 *
238 * This source code is licensed under the ISC license.
239 * See the LICENSE file in the root directory of this source tree.
240 */const Ll=le("Circle",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]);/**
241 * @license lucide-react v0.462.0 - ISC
242 *
243 * This source code is licensed under the ISC license.
244 * See the LICENSE file in the root directory of this source tree.
245 */const l4=le("Clipboard",[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1",key:"tgr4d6"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2",key:"116196"}]]);/**
246 * @license lucide-react v0.462.0 - ISC
247 *
248 * This source code is licensed under the ISC license.
249 * See the LICENSE file in the root directory of this source tree.
250 */const ls=le("Clock",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 16 14",key:"68esgv"}]]);/**
251 * @license lucide-react v0.462.0 - ISC
252 *
253 * This source code is licensed under the ISC license.
254 * See the LICENSE file in the root directory of this source tree.
255 */const c4=le("Coins",[["circle",{cx:"8",cy:"8",r:"6",key:"3yglwk"}],["path",{d:"M18.09 10.37A6 6 0 1 1 10.34 18",key:"t5s6rm"}],["path",{d:"M7 6h1v4",key:"1obek4"}],["path",{d:"m16.71 13.88.7.71-2.82 2.82",key:"1rbuyh"}]]);/**
256 * @license lucide-react v0.462.0 - ISC
257 *
258 * This source code is licensed under the ISC license.
259 * See the LICENSE file in the root directory of this source tree.
260 */const jy=le("Compass",[["path",{d:"m16.24 7.76-1.804 5.411a2 2 0 0 1-1.265 1.265L7.76 16.24l1.804-5.411a2 2 0 0 1 1.265-1.265z",key:"9ktpf1"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]);/**
261 * @license lucide-react v0.462.0 - ISC
262 *
263 * This source code is licensed under the ISC license.
264 * See the LICENSE file in the root directory of this source tree.
265 */const d4=le("Cookie",[["path",{d:"M12 2a10 10 0 1 0 10 10 4 4 0 0 1-5-5 4 4 0 0 1-5-5",key:"laymnq"}],["path",{d:"M8.5 8.5v.01",key:"ue8clq"}],["path",{d:"M16 15.5v.01",key:"14dtrp"}],["path",{d:"M12 12v.01",key:"u5ubse"}],["path",{d:"M11 17v.01",key:"1hyl5a"}],["path",{d:"M7 14v.01",key:"uct60s"}]]);/**
266 * @license lucide-react v0.462.0 - ISC
267 *
268 * This source code is licensed under the ISC license.
269 * See the LICENSE file in the root directory of this source tree.
270 */const Ma=le("Copy",[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]);/**
271 * @license lucide-react v0.462.0 - ISC
272 *
273 * This source code is licensed under the ISC license.
274 * See the LICENSE file in the root directory of this source tree.
275 */const mm=le("Cpu",[["rect",{width:"16",height:"16",x:"4",y:"4",rx:"2",key:"14l7u7"}],["rect",{width:"6",height:"6",x:"9",y:"9",rx:"1",key:"5aljv4"}],["path",{d:"M15 2v2",key:"13l42r"}],["path",{d:"M15 20v2",key:"15mkzm"}],["path",{d:"M2 15h2",key:"1gxd5l"}],["path",{d:"M2 9h2",key:"1bbxkp"}],["path",{d:"M20 15h2",key:"19e6y8"}],["path",{d:"M20 9h2",key:"19tzq7"}
275],["path",{d:"M9 2v2",key:"165o2o"}],["path",{d:"M9 20v2",key:"i2bqo8"}]]);/**
276 * @license lucide-react v0.462.0 - ISC
277 *
278 * This source code is licensed under the ISC license.
279 * See the LICENSE file in the root directory of this source tree.
280 */const Il=le("CreditCard",[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]]);/**
281 * @license lucide-react v0.462.0 - ISC
282 *
283 * This source code is licensed under the ISC license.
284 * See the LICENSE file in the root directory of this source tree.
285 */const _y=le("Crown",[["path",{d:"M11.562 3.266a.5.5 0 0 1 .876 0L15.39 8.87a1 1 0 0 0 1.516.294L21.183 5.5a.5.5 0 0 1 .798.519l-2.834 10.246a1 1 0 0 1-.956.734H5.81a1 1 0 0 1-.957-.734L2.02 6.02a.5.5 0 0 1 .798-.519l4.276 3.664a1 1 0 0 0 1.516-.294z",key:"1vdc57"}],["path",{d:"M5 21h14",key:"11awu3"}]]);/**
286 * @license lucide-react v0.462.0 - ISC
287 *
288 * This source code is licensed under the ISC license.
289 * See the LICENSE file in the root directory of this source tree.
290 */const ky=le("DollarSign",[["line",{x1:"12",x2:"12",y1:"2",y2:"22",key:"7eqyqh"}],["path",{d:"M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6",key:"1b0p4s"}]]);/**
291 * @license lucide-react v0.462.0 - ISC
292 *
293 * This source code is licensed under the ISC license.
294 * See the LICENSE file in the root directory of this source tree.
295 */const Ny=le("Download",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"7 10 12 15 17 10",key:"2ggqvy"}],["line",{x1:"12",x2:"12",y1:"15",y2:"3",key:"1vk2je"}]]);/**
296 * @license lucide-react v0.462.0 - ISC
297 *
298 * This source code is licensed under the ISC license.
299 * See the LICENSE file in the root directory of this source tree.
300 */const u4=le("Earth",[["path",{d:"M21.54 15H17a2 2 0 0 0-2 2v4.54",key:"1djwo0"}],["path",{d:"M7 3.34V5a3 3 0 0 0 3 3a2 2 0 0 1 2 2c0 1.1.9 2 2 2a2 2 0 0 0 2-2c0-1.1.9-2 2-2h3.17",key:"1tzkfa"}],["path",{d:"M11 21.95V18a2 2 0 0 0-2-2a2 2 0 0 1-2-2v-1a2 2 0 0 0-2-2H2.05",key:"14pb5j"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]);/**
301 * @license lucide-react v0.462.0 - ISC
302 *
303 * This source code is licensed under the ISC license.
304 * See the LICENSE file in the root directory of this source tree.
305 */const h4=le("EllipsisVertical",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}]]);/**
306 * @license lucide-react v0.462.0 - ISC
307 *
308 * This source code is licensed under the ISC license.
309 * See the LICENSE file in the root directory of this source tree.
310 */const Rs=le("ExternalLink",[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]]);/**
311 * @license lucide-react v0.462.0 - ISC
312 *
313 * This source code is licensed under the ISC license.
314 * See the LICENSE file in the root directory of this source tree.
315 */const m4=le("EyeOff",[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49",key:"ct8e1f"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242",key:"151rxh"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143",key:"13bj9a"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]);/**
316 * @license lucide-react v0.462.0 - ISC
317 *
318 * This source code is licensed under the ISC license.
319 * See the LICENSE file in the root directory of this source tree.
320 */const oi=le("Eye",[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);/**
321 * @license lucide-react v0.462.0 - ISC
322 *
323 * This source code is licensed under the ISC license.
324 * See the LICENSE file in the root directory of this source tree.
325 */const Xi=le("FileText",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]]);/**
326 * @license lucide-react v0.462.0 - ISC
327 *
328 * This source code is licensed under the ISC license.
329 * See the LICENSE file in the root directory of this source tree.
330 */const Sy=le("Film",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M7 3v18",key:"bbkbws"}],["path",{d:"M3 7.5h4",key:"zfgn84"}],["path",{d:"M3 12h18",key:"1i2n21"}],["path",{d:"M3 16.5h4",key:"1230mu"}],["path",{d:"M17 3v18",key:"in4fa5"}],["path",{d:"M17 7.5h4",key:"myr1c1"}],["path",{d:"M17 16.5h4",key:"go4c1d"}]]);/**
331 * @license lucide-react v0.462.0 - ISC
332 *
333 * This source code is licensed under the ISC license.
334 * See the LICENSE file in the root directory of this source tree.
335 */const iS=le("Filter",[["polygon",{points:"22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3",key:"1yg77f"}]]);/**
336 * @license lucide-react v0.462.0 - ISC
337 *
338 * This source code is licensed under the ISC license.
339 * See the LICENSE file in the root directory of this source tree.
340 */const Ol=le("Flame",[["path",{d:"M8.5 14.5A2.5 2.5 0 0 0 11 12c0-1.38-.5-2-1-3-1.072-2.143-.224-4.054 2-6 .5 2.5 2 4.9 4 6.5 2 1.6 3 3.5 3 5.5a7 7 0 1 1-14 0c0-1.153.433-2.294 1-3a2.5 2.5 0 0 0 2.5 2.5z",key:"96xj49"}]]);/**
341 * @license lucide-react v0.462.0 - ISC
342 *
343 * This source code is licensed under the ISC license.
344 * See the LICENSE file in the root directory of this source tree.
345 */const Rx=le("FlaskConical",[["path",{d:"M10 2v7.527a2 2 0 0 1-.211.896L4.72 20.55a1 1 0 0 0 .9 1.45h12.76a1 1 0 0 0 .9-1.45l-5.069-10.127A2 2 0 0 1 14 9.527V2",key:"pzvekw"}],["path",{d:"M8.5 2h7",key:"csnxdl"}],["path",{d:"M7 16h10",key:"wp8him"}]]);/**
346 * @license lucide-react v0.462.0 - ISC
347 *
348 * This source code is licensed under the ISC license.
349 * See the LICENSE file in the root directory of this source tree.
350 */const p4=le("Gift",[["rect",{x:"3",y:"8",width:"18",height:"4",rx:"1",key:"bkv52"}],["path",{d:"M12 8v13",key:"1c76mn"}],["path",{d:"M19 12v7a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2v-7",key:"6wjy6b"}],["path",{d:"M7.5 8a2.5 2.5 0 0 1 0-5A4.8 8 0 0 1 12 8a4.8 8 0 0 1 4.5-5 2.5 2.5 0 0 1 0 5",key:"1ihvrl"}]]);/**
351 * @license lucide-react v0.462.0 - ISC
352 *
353 * This source code is licensed under the ISC license.
354 * See the LICENSE file in the root directory of this source tree.
355 */const Rd=le("Globe",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]]);/**
356 * @license lucide-react v0.462.0 - ISC
357 *
358 * This source code is licensed under the ISC license.
359 * See the LICENSE file in the root directory of this source tree.
360 */const Cy=le("GraduationCap",[["path",{d:"M21.42 10.922a1 1 0 0 0-.019-1.838L12.83 5.18a2 2 0 0 0-1.66 0L2.6 9.08a1 1 0 0 0 0 1.832l8.57 3.908a2 2 0 0 0 1.66 0z",key:"j76jl0"}],["path",{d:"M22 10v6",key:"1lu8f3"}],["path",{d:"M6 12.5V16a6 3 0 0 0 12 0v-3.5",key:"1r8lef"}]]);/**
361 * @license lucide-react v0.462.0 - ISC
362 *
363 * This source code is licensed under the ISC license.
364 * See the LICENSE file in the root directory of this source tree.
365 */const f4=le("Hash",[["line",{x1:"4",x2:"20",y1:"9",y2:"9",key:"4lhtct"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15",key:"vyu0kd"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21",key:"1ggp8o"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21",key:"weycgp"}
365]]);/**
366 * @license lucide-react v0.462.0 - ISC
367 *
368 * This source code is licensed under the ISC license.
369 * See the LICENSE file in the root directory of this source tree.
370 */const Zs=le("Headphones",[["path",{d:"M3 14h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-7a9 9 0 0 1 18 0v7a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3",key:"1xhozi"}]]);/**
371 * @license lucide-react v0.462.0 - ISC
372 *
373 * This source code is licensed under the ISC license.
374 * See the LICENSE file in the root directory of this source tree.
375 */const co=le("Heart",[["path",{d:"M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5l7 7Z",key:"c3ymky"}]]);/**
376 * @license lucide-react v0.462.0 - ISC
377 *
378 * This source code is licensed under the ISC license.
379 * See the LICENSE file in the root directory of this source tree.
380 */const oS=le("History",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]]);/**
381 * @license lucide-react v0.462.0 - ISC
382 *
383 * This source code is licensed under the ISC license.
384 * See the LICENSE file in the root directory of this source tree.
385 */const g4=le("Image",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]]);/**
386 * @license lucide-react v0.462.0 - ISC
387 *
388 * This source code is licensed under the ISC license.
389 * See the LICENSE file in the root directory of this source tree.
390 */const x4=le("Images",[["path",{d:"M18 22H4a2 2 0 0 1-2-2V6",key:"pblm9e"}],["path",{d:"m22 13-1.296-1.296a2.41 2.41 0 0 0-3.408 0L11 18",key:"nf6bnh"}],["circle",{cx:"12",cy:"8",r:"2",key:"1822b1"}],["rect",{width:"16",height:"16",x:"6",y:"2",rx:"2",key:"12espp"}]]);/**
391 * @license lucide-react v0.462.0 - ISC
392 *
393 * This source code is licensed under the ISC license.
394 * See the LICENSE file in the root directory of this source tree.
395 */const Ty=le("Info",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]]);/**
396 * @license lucide-react v0.462.0 - ISC
397 *
398 * This source code is licensed under the ISC license.
399 * See the LICENSE file in the root directory of this source tree.
400 */const Py=le("KeyRound",[["path",{d:"M2.586 17.414A2 2 0 0 0 2 18.828V21a1 1 0 0 0 1 1h3a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h1a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h.172a2 2 0 0 0 1.414-.586l.814-.814a6.5 6.5 0 1 0-4-4z",key:"1s6t7t"}],["circle",{cx:"16.5",cy:"7.5",r:".5",fill:"currentColor",key:"w0ekpg"}]]);/**
401 * @license lucide-react v0.462.0 - ISC
402 *
403 * This source code is licensed under the ISC license.
404 * See the LICENSE file in the root directory of this source tree.
405 */const v4=le("Languages",[["path",{d:"m5 8 6 6",key:"1wu5hv"}],["path",{d:"m4 14 6-6 2-3",key:"1k1g8d"}],["path",{d:"M2 5h12",key:"or177f"}],["path",{d:"M7 2h1",key:"1t2jsx"}],["path",{d:"m22 22-5-10-5 10",key:"don7ne"}],["path",{d:"M14 18h6",key:"1m8k6r"}]]);/**
406 * @license lucide-react v0.462.0 - ISC
407 *
408 * This source code is licensed under the ISC license.
409 * See the LICENSE file in the root directory of this source tree.
410 */const Ey=le("Layers",[["path",{d:"m12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83Z",key:"8b97xw"}],["path",{d:"m22 17.65-9.17 4.16a2 2 0 0 1-1.66 0L2 17.65",key:"dd6zsq"}],["path",{d:"m22 12.65-9.17 4.16a2 2 0 0 1-1.66 0L2 12.65",key:"ep9fru"}]]);/**
411 * @license lucide-react v0.462.0 - ISC
412 *
413 * This source code is licensed under the ISC license.
414 * See the LICENSE file in the root directory of this source tree.
415 */const y4=le("LayoutDashboard",[["rect",{width:"7",height:"9",x:"3",y:"3",rx:"1",key:"10lvy0"}],["rect",{width:"7",height:"5",x:"14",y:"3",rx:"1",key:"16une8"}],["rect",{width:"7",height:"9",x:"14",y:"12",rx:"1",key:"1hutg5"}],["rect",{width:"7",height:"5",x:"3",y:"16",rx:"1",key:"ldoo1y"}]]);/**
416 * @license lucide-react v0.462.0 - ISC
417 *
418 * This source code is licensed under the ISC license.
419 * See the LICENSE file in the root directory of this source tree.
420 */const b4=le("LayoutGrid",[["rect",{width:"7",height:"7",x:"3",y:"3",rx:"1",key:"1g98yp"}],["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["rect",{width:"7",height:"7",x:"14",y:"14",rx:"1",key:"nxv5o0"}],["rect",{width:"7",height:"7",x:"3",y:"14",rx:"1",key:"1bb6yr"}]]);/**
421 * @license lucide-react v0.462.0 - ISC
422 *
423 * This source code is licensed under the ISC license.
424 * See the LICENSE file in the root directory of this source tree.
425 */const Pr=le("Link2",[["path",{d:"M9 17H7A5 5 0 0 1 7 7h2",key:"8i5ue5"}],["path",{d:"M15 7h2a5 5 0 1 1 0 10h-2",key:"1b9ql8"}],["line",{x1:"8",x2:"16",y1:"12",y2:"12",key:"1jonct"}]]);/**
426 * @license lucide-react v0.462.0 - ISC
427 *
428 * This source code is licensed under the ISC license.
429 * See the LICENSE file in the root directory of this source tree.
430 */const w4=le("ListOrdered",[["path",{d:"M10 12h11",key:"6m4ad9"}],["path",{d:"M10 18h11",key:"11hvi2"}],["path",{d:"M10 6h11",key:"c7qv1k"}],["path",{d:"M4 10h2",key:"16xx2s"}],["path",{d:"M4 6h1v4",key:"cnovpq"}],["path",{d:"M6 18H4c0-1 2-2 2-3s-1-1.5-2-1",key:"m9a95d"}]]);/**
431 * @license lucide-react v0.462.0 - ISC
432 *
433 * This source code is licensed under the ISC license.
434 * See the LICENSE file in the root directory of this source tree.
435 */const xe=le("LoaderCircle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]);/**
436 * @license lucide-react v0.462.0 - ISC
437 *
438 * This source code is licensed under the ISC license.
439 * See the LICENSE file in the root directory of this source tree.
440 */const lS=le("Lock",[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]]);/**
441 * @license lucide-react v0.462.0 - ISC
442 *
443 * This source code is licensed under the ISC license.
444 * See the LICENSE file in the root directory of this source tree.
445 */const cS=le("LogOut",[["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}],["polyline",{points:"16 17 21 12 16 7",key:"1gabdz"}],["line",{x1:"21",x2:"9",y1:"12",y2:"12",key:"1uyos4"}]]);/**
446 * @license lucide-react v0.462.0 - ISC
447 *
448 * This source code is licensed under the ISC license.
449 * See the LICENSE file in the root directory of this source tree.
450 */const j4=le("Mail",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}]]);/**
451 * @license lucide-react v0.462.0 - ISC
452 *
453 * This source code is licensed under the ISC license.
454 * See the LICENSE file in the root directory of this source tree.
455 */const za=le("Megaphone",[["path",{d:"m3 11 18-5v12L3 14v-3z",key:"n962bs"}],["path",{d:"M11.6 16.8a3 3 0 1 1-5.8-1.6",key:"1yl0tm"}]]);/**
456 * @license lucide-react v0.462.0 - ISC
457 *
458 * This source code is licensed under the ISC license.
459 * See the LICENSE file in the root directory of this source tree.
460 */const lu=le("MessageCircle",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}]]);/**
461 * @license lucide-react v0.462.0 - ISC
462 *
463 * This source code is licensed under the ISC license.
464 * See the LICENSE file in the root directory of this source tree.
465 */const _4=le("MessageSquarePlus",[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}],["path",{d:"M12 7v6",key:"lw1j43"}],["path",{d:"M9 10h6",key:"9gxzsh"}]]);/**
466 * @license lucide-react v0.462.0 - ISC
467 *
468 * This source code is licensed under the ISC license.
469 * See the LICENSE file in the root directory of this source tree.
470 */const k4=le("MessageSquareQuote",[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}],["path",{d:"M8 12a2 2 0 0 0 2-2V8H8",key:"1jfesj"}],["path",{d:"M14 12a2 2 0 0 0 2-2V8h-2",key:"1dq9mh"}]]);/**
471 * @license lucide-react v0.462.0 - ISC
472 *
473 * This source code is licensed under the ISC license.
474 * See the LICENSE file in the root directory of this source tree.
475 */const up=le("MessageSquare",[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}]]);/**
476 * @license lucide-react v0.462.0 - ISC
477 *
478 * This source code is licensed under the ISC license.
479 * See the LICENSE file in the root directory of this source tree.
480 */const N4=le("MessagesSquare",[["path",{d:"M14 9a2 2 0 0 1-2 2H6l-4 4V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2z",key:"p1xzt8"}],["path",{d:"M18 9h2a2 2 0 0 1 2 2v11l-4-4h-6a2 2 0 0 1-2-2v-1",key:"1cx29u"}]]);/**
481 * @license lucide-react v0.462.0 - ISC
482 *
483 * This source code is licensed under the ISC license.
484 * See the LICENSE file in the root directory of this source tree.
485 */const cu=le("Mic",[["path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z",key:"131961"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2",key:"1vc78b"}],["line",{x1:"12",x2:"12",y1:"19",y2:"22",key:"x3vr5v"}]]);/**
486 * @license lucide-react v0.462.0 - ISC
487 *
488 * This source code is licensed under the ISC license.
489 * See the LICENSE file in the root directory of this source tree.
490 */const dS=le("Monitor",[["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}],["line",{x1:"8",x2:"16",y1:"21",y2:"21",key:"1svkeh"}],["line",{x1:"12",x2:"12",y1:"17",y2:"21",key:"vw1qmm"}]]);/**
491 * @license lucide-react v0.462.0 - ISC
492 *
493 * This source code is licensed under the ISC license.
494 * See the LICENSE file in the root directory of this source tree.
495 */const Qc=le("Newspaper",[["path",{d:"M4 22h16a2 2 0 0 0 2-2V4a2 2 0 0 0-2-2H8a2 2 0 0 0-2 2v16a2 2 0 0 1-2 2Zm0 0a2 2 0 0 1-2-2v-9c0-1.1.9-2 2-2h2",key:"7pis2x"}],["path",{d:"M18 14h-8",key:"sponae"}],["path",{d:"M15 18h-5",key:"95g1m2"}],["path",{d:"M10 6h8v4h-8V6Z",key:"smlsk5"}]]);/**
496 * @license lucide-react v0.462.0 - ISC
497 *
498 * This source code is licensed under the ISC license.
499 * See the LICENSE file in the root directory of this source tree.
500 */const S4=le("OctagonX",[["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"M2.586 16.726A2 2 0 0 1 2 15.312V8.688a2 2 0 0 1 .586-1.414l4.688-4.688A2 2 0 0 1 8.688 2h6.624a2 2 0 0 1 1.414.586l4.688 4.688A2 2 0 0 1 22 8.688v6.624a2 2 0 0 1-.586 1.414l-4.688 4.688a2 2 0 0 1-1.414.586H8.688a2 2 0 0 1-1.414-.586z",key:"2d38gg"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]]);/**
501 * @license lucide-react v0.462.0 - ISC
502 *
503 * This source code is licensed under the ISC license.
504 * See the LICENSE file in the root directory of this source tree.
505 */const C4=le("Palette",[["circle",{cx:"13.5",cy:"6.5",r:".5",fill:"currentColor",key:"1okk4w"}],["circle",{cx:"17.5",cy:"10.5",r:".5",fill:"currentColor",key:"f64h9f"}],["circle",{cx:"8.5",cy:"7.5",r:".5",fill:"currentColor",key:"fotxhn"}],["circle",{cx:"6.5",cy:"12.5",r:".5",fill:"currentColor",key:"qy21gx"}],["path",{d:"M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10c.926 0 1.648-.746 1.648-1.688 0-.437-.18-.835-.437-1.125-.29-.289-.438-.652-.438-1.125a1.64 1.64 0 0 1 1.668-1.668h1.996c3.051 0 5.555-2.503 5.555-5.554C21.965 6.012 17.461 2 12 2z",key:"12rzf8"}]]);/**
506 * @license lucide-react v0.462.0 - ISC
507 *
508 * This source code is licensed under the ISC license.
509 * See the LICENSE file in the root directory of this source tree.
510 */const T4=le("PanelLeft",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]]);/**
511 * @license lucide-react v0.462.0 - ISC
512 *
513 * This source code is licensed under the ISC license.
514 * See the LICENSE file in the root directory of this source tree.
515 */const $x=le("Pause",[["rect",{x:"14",y:"4",width:"4",height:"16",rx:"1",key:"zuxfzm"}],["rect",{x:"6",y:"4",width:"4",height:"16",rx:"1",key:"1okwgv"}]]);/**
516 * @license lucide-react v0.462.0 - ISC
517 *
518 * This source code is licensed under the ISC license.
519 * See the LICENSE file in the root directory of this source tree.
520 */const $d=le("Pencil",[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]]);/**
521 * @license lucide-react v0.462.0 - ISC
522 *
523 * This source code is licensed under the ISC license.
524 * See the LICENSE file in the root directory of this source tree.
525 */const en=le("Play",[["polygon",{points:"6 3 20 12 6 21 6 3",key:"1oa8hb"}]]);/**
526 * @license lucide-react v0.462.0 - ISC
527 *
528 * This source code is licensed under the ISC license.
529 * See the LICENSE file in the root directory of this source tree.
530 */const sr=le("Plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]);/**
531 * @license lucide-react v0.462.0 - ISC
532 *
533 * This source code is licensed under the ISC license.
534 * See the LICENSE file in the root directory of this source tree.
535 */const Ja=le("Presentation",[["path",{d:"M2 3h20",key:"91anmk"}],["path",{d:"M21 3v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V3",key:"2k9sn8"}],["path",{d:"m7 21 5-5 5 5",key:"bip4we"}]]);/**
536 * @license lucide-react v0.462.0 - ISC
537 *
538 * This source code is licensed under the ISC license.
539 * See the LICENSE file in the root directory of this source tree.
540 */const P4=le("Quote",[["path",{d:"M16 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z",key:"rib7q0"}],["path",{d:"M5 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z",key:"1ymkrd"}]]);/**
541 * @license lucide-react v0.462.0 - ISC
542 *
543 * This source code is licensed under the ISC license.
544 * See the LICENSE file in the root directory of this source tree.
545 */const St=le("Radio",[["path",{d:"M4.9 19.1C1 15.2 1 8.8 4.9 4.9",key:"1vaf9d"}],["path",{d:"M7.8 16.2c-2.3-2.3-2.3-6.1 0-8.5",key:"u1ii0m"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}],["path",{d:"M16.2 7.8c2.3 2.3 2.3 6.1 0 8.5",key:"1j5fej"}],["path",{d:"M19.1 4.9C23 8.8 23 15.1 19.1 19",key:"10b0cb"}]]);/**
546 * @license lucide-react v0.462.0 - ISC
547 *
548 * This source code is licensed under the ISC license.
549 * See the LICENSE file in the root directory of this source tree.
550 */const ss=le("RefreshCw",[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]]);/**
551 * @license lucide-react v0.462.0 - ISC
552 *
553 * This source code is licensed under the ISC license.
554 * See the LICENSE file in the root directory of this source tree.
555 */const uS=le("Repeat",[["path",{d:"m17 2 4 4-4 4",key:"nntrym"}],["path",{d:"M3 11v-1a4 4 0 0 1 4-4h14",key:"84bu3i"}],["path",{d:"m7 22-4-4 4-4",key:"1wqhfi"}],["path",{d:"M21 13v1a4 4 0 0 1-4 4H3",key:"1rx37r"}]]);/**
556 * @license lucide-react v0.462.0 - ISC
557 *
558 * This source code is licensed under the ISC license.
559 * See the LICENSE file in the root directory of this source tree.
560 */const Ld=le("Rocket",[["path",{d:"M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09z",key:"m3
560kijz"}],["path",{d:"m12 15-3-3a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.35 22.35 0 0 1-4 2z",key:"1fmvmk"}],["path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0",key:"1f8sc4"}],["path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5",key:"qeys4"}]]);/**
561 * @license lucide-react v0.462.0 - ISC
562 *
563 * This source code is licensed under the ISC license.
564 * See the LICENSE file in the root directory of this source tree.
565 */const hS=le("RotateCcw",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]]);/**
566 * @license lucide-react v0.462.0 - ISC
567 *
568 * This source code is licensed under the ISC license.
569 * See the LICENSE file in the root directory of this source tree.
570 */const E4=le("RotateCw",[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8",key:"1p45f6"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}]]);/**
571 * @license lucide-react v0.462.0 - ISC
572 *
573 * This source code is licensed under the ISC license.
574 * See the LICENSE file in the root directory of this source tree.
575 */const Id=le("Save",[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]]);/**
576 * @license lucide-react v0.462.0 - ISC
577 *
578 * This source code is licensed under the ISC license.
579 * See the LICENSE file in the root directory of this source tree.
580 */const mS=le("Scale",[["path",{d:"m16 16 3-8 3 8c-.87.65-1.92 1-3 1s-2.13-.35-3-1Z",key:"7g6ntu"}],["path",{d:"m2 16 3-8 3 8c-.87.65-1.92 1-3 1s-2.13-.35-3-1Z",key:"ijws7r"}],["path",{d:"M7 21h10",key:"1b0cd5"}],["path",{d:"M12 3v18",key:"108xh3"}],["path",{d:"M3 7h2c2 0 5-1 7-2 2 1 5 2 7 2h2",key:"3gwbw2"}]]);/**
581 * @license lucide-react v0.462.0 - ISC
582 *
583 * This source code is licensed under the ISC license.
584 * See the LICENSE file in the root directory of this source tree.
585 */const pm=le("Scissors",[["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["path",{d:"M8.12 8.12 12 12",key:"1alkpv"}],["path",{d:"M20 4 8.12 15.88",key:"xgtan2"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["path",{d:"M14.8 14.8 20 20",key:"ptml3r"}]]);/**
586 * @license lucide-react v0.462.0 - ISC
587 *
588 * This source code is licensed under the ISC license.
589 * See the LICENSE file in the root directory of this source tree.
590 */const bn=le("Search",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}]]);/**
591 * @license lucide-react v0.462.0 - ISC
592 *
593 * This source code is licensed under the ISC license.
594 * See the LICENSE file in the root directory of this source tree.
595 */const Za=le("Send",[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]]);/**
596 * @license lucide-react v0.462.0 - ISC
597 *
598 * This source code is licensed under the ISC license.
599 * See the LICENSE file in the root directory of this source tree.
600 */const A4=le("Server",[["rect",{width:"20",height:"8",x:"2",y:"2",rx:"2",ry:"2",key:"ngkwjq"}],["rect",{width:"20",height:"8",x:"2",y:"14",rx:"2",ry:"2",key:"iecqi9"}],["line",{x1:"6",x2:"6.01",y1:"6",y2:"6",key:"16zg32"}],["line",{x1:"6",x2:"6.01",y1:"18",y2:"18",key:"nzw8ys"}]]);/**
601 * @license lucide-react v0.462.0 - ISC
602 *
603 * This source code is licensed under the ISC license.
604 * See the LICENSE file in the root directory of this source tree.
605 */const R4=le("Settings2",[["path",{d:"M20 7h-9",key:"3s1dr2"}],["path",{d:"M14 17H5",key:"gfn3mx"}],["circle",{cx:"17",cy:"17",r:"3",key:"18b49y"}],["circle",{cx:"7",cy:"7",r:"3",key:"dfmy0x"}]]);/**
606 * @license lucide-react v0.462.0 - ISC
607 *
608 * This source code is licensed under the ISC license.
609 * See the LICENSE file in the root directory of this source tree.
610 */const pS=le("Settings",[["path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z",key:"1qme2f"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);/**
611 * @license lucide-react v0.462.0 - ISC
612 *
613 * This source code is licensed under the ISC license.
614 * See the LICENSE file in the root directory of this source tree.
615 */const fm=le("Share2",[["circle",{cx:"18",cy:"5",r:"3",key:"gq8acd"}],["circle",{cx:"6",cy:"12",r:"3",key:"w7nqdw"}],["circle",{cx:"18",cy:"19",r:"3",key:"1xt0gg"}],["line",{x1:"8.59",x2:"15.42",y1:"13.51",y2:"17.49",key:"47mynk"}],["line",{x1:"15.41",x2:"8.59",y1:"6.51",y2:"10.49",key:"1n3mei"}]]);/**
616 * @license lucide-react v0.462.0 - ISC
617 *
618 * This source code is licensed under the ISC license.
619 * See the LICENSE file in the root directory of this source tree.
620 */const fS=le("ShieldAlert",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",ke
620y:"oel41y"}],["path",{d:"M12 8v4",key:"1got3b"}],["path",{d:"M12 16h.01",key:"1drbdi"}]]);/**
621 * @license lucide-react v0.462.0 - ISC
622 *
623 * This source code is licensed under the ISC license.
624 * See the LICENSE file in the root directory of this source tree.
625 */const Od=le("ShieldCheck",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);/**
626 * @license lucide-react v0.462.0 - ISC
627 *
628 * This source code is licensed under the ISC license.
629 * See the LICENSE file in the root directory of this source tree.
630 */const li=le("Shield",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}]]);/**
631 * @license lucide-react v0.462.0 - ISC
632 *
633 * This source code is licensed under the ISC license.
634 * See the LICENSE file in the root directory of this source tree.
635 */const $4=le("SlidersVertical",[["line",{x1:"4",x2:"4",y1:"21",y2:"14",key:"1p332r"}],["line",{x1:"4",x2:"4",y1:"10",y2:"3",key:"gb41h5"}],["line",{x1:"12",x2:"12",y1:"21",y2:"12",key:"hf2csr"}],["line",{x1:"12",x2:"12",y1:"8",y2:"3",key:"1kfi7u"}],["line",{x1:"20",x2:"20",y1:"21",y2:"16",key:"1lhrwl"}],["line",{x1:"20",x2:"20",y1:"12",y2:"3",key:"16vvfq"}],["line",{x1:"2",x2:"6",y1:"14",y2:"14",key:"1uebub"}],["line",{x1:"10",x2:"14",y1:"8",y2:"8",key:"1yglbp"}],["line",{x1:"18",x2:"22",y1:"16",y2:"16",key:"1jxqpz"}]]);/**
636 * @license lucide-react v0.462.0 - ISC
637 *
638 * This source code is licensed under the ISC license.
639 * See the LICENSE file in the root directory of this source tree.
640 */const L4=le("Smartphone",[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2",key:"1yt0o3"}],["path",{d:"M12 18h.01",key:"mhygvu"}]]);/**
641 * @license lucide-react v0.462.0 - ISC
642 *
643 * This source code is licensed under the ISC license.
644 * See the LICENSE file in the root directory of this source tree.
645 */const tt=le("Sparkles",[["path",{d:"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z",key:"4pj2yx"}],["path",{d:"M20 3v4",key:"1olli1"}],["path",{d:"M22 5h-4",key:"1gvqau"}],["path",{d:"M4 17v2",key:"vumght"}],["path",{d:"M5 18H3",key:"zchphs"}]]);/**
646 * @license lucide-react v0.462.0 - ISC
647 *
648 * This source code is licensed under the ISC license.
649 * See the LICENSE file in the root directory of this source tree.
650 */const du=le("Square",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]]);/**
651 * @license lucide-react v0.462.0 - ISC
652 *
653 * This source code is licensed under the ISC license.
654 * See the LICENSE file in the root directory of this source tree.
655 */const gS=le("Star",[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z",key:"r04s7s"}]]);/**
656 * @license lucide-react v0.462.0 - ISC
657 *
658 * This source code is licensed under the ISC license.
659 * See the LICENSE file in the root directory of this source tree.
660 */const I4=le("ThumbsUp",[["path",{d:"M7 10v12",key:"1qc93n"}],["path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z",key:"emmmcr"}]]);/**
661 * @license lucide-react v0.462.0 - ISC
662 *
663 * This source code is licensed under the ISC license.
664 * See the LICENSE file in the root directory of this source tree.
665 */const O4=le("Timer",[["line",{x1:"10",x2:"14",y1:"2",y2:"2",key:"14vaq8"}],["line",{x1:"12",x2:"15",y1:"14",y2:"11",key:"17fdiu"}],["circle",{cx:"12",cy:"14",r:"8",key:"1e1u0o"}]]);/**
666 * @license lucide-react v0.462.0 - ISC
667 *
668 * This source code is licensed under the ISC license.
669 * See the LICENSE file in the root directory of this source tree.
670 */const ci=le("Trash2",[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6",key:"4alrt4"}
670],["path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2",key:"v07s0e"}],["line",{x1:"10",x2:"10",y1:"11",y2:"17",key:"1uufr5"}],["line",{x1:"14",x2:"14",y1:"11",y2:"17",key:"xtxkd"}]]);/**
671 * @license lucide-react v0.462.0 - ISC
672 *
673 * This source code is licensed under the ISC license.
674 * See the LICENSE file in the root directory of this source tree.
675 */const uu=le("TrendingUp",[["polyline",{points:"22 7 13.5 15.5 8.5 10.5 2 17",key:"126l90"}],["polyline",{points:"16 7 22 7 22 13",key:"kwv8wd"}]]);/**
676 * @license lucide-react v0.462.0 - ISC
677 *
678 * This source code is licensed under the ISC license.
679 * See the LICENSE file in the root directory of this source tree.
680 */const ft=le("TriangleAlert",[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);/**
681 * @license lucide-react v0.462.0 - ISC
682 *
683 * This source code is licensed under the ISC license.
684 * See the LICENSE file in the root directory of this source tree.
685 */const hp=le("Undo2",[["path",{d:"M9 14 4 9l5-5",key:"102s5s"}],["path",{d:"M4 9h10.5a5.5 5.5 0 0 1 5.5 5.5a5.5 5.5 0 0 1-5.5 5.5H11",key:"f3b9sd"}]]);/**
686 * @license lucide-react v0.462.0 - ISC
687 *
688 * This source code is licensed under the ISC license.
689 * See the LICENSE file in the root directory of this source tree.
690 */const jo=le("Unplug",[["path",{d:"m19 5 3-3",key:"yk6iyv"}],["path",{d:"m2 22 3-3",key:"19mgm9"}],["path",{d:"M6.3 20.3a2.4 2.4 0 0 0 3.4 0L12 18l-6-6-2.3 2.3a2.4 2.4 0 0 0 0 3.4Z",key:"goz73y"}],["path",{d:"M7.5 13.5 10 11",key:"7xgeeb"}],["path",{d:"M10.5 16.5 13 14",key:"10btkg"}],["path",{d:"m12 6 6 6 2.3-2.3a2.4 2.4 0 0 0 0-3.4l-2.6-2.6a2.4 2.4 0 0 0-3.4 0Z",key:"1snsnr"}]]);/**
691 * @license lucide-react v0.462.0 - ISC
692 *
693 * This source code is licensed under the ISC license.
694 * See the LICENSE file in the root directory of this source tree.
695 */const Ay=le("Upload",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"17 8 12 3 7 8",key:"t8dd8p"}],["line",{x1:"12",x2:"12",y1:"3",y2:"15",key:"widbto"}]]);/**
696 * @license lucide-react v0.462.0 - ISC
697 *
698 * This source code is licensed under the ISC license.
699 * See the LICENSE file in the root directory of this source tree.
700 */const D4=le("UserCog",[["circle",{cx:"18",cy:"15",r:"3",key:"gjjjvw"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M10 15H6a4 4 0 0 0-4 4v2",key:"1nfge6"}],["path",{d:"m21.7 16.4-.9-.3",key:"12j9ji"}],["path",{d:"m15.2 13.9-.9-.3",key:"1fdjdi"}],["path",{d:"m16.6 18.7.3-.9",key:"heedtr"}],["path",{d:"m19.1 12.2.3-.9",key:"1af3ki"}],["path",{d:"m19.6 18.7-.4-1",key:"1x9vze"}],["path",{d:"m16.8 12.3-.4-1",key:"vqeiwj"}],["path",{d:"m14.3 16.6 1-.4",key:"1qlj63"}],["path",{d:"m20.7 13.8 1-.4",key:"1v5t8k"}]]);/**
701 * @license lucide-react v0.462.0 - ISC
702 *
703 * This source code is licensed under the ISC license.
704 * See the LICENSE file in the root directory of this source tree.
705 */const Xs=le("User",[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2",key:"975kel"}],["circle",{cx:"12",cy:"7",r:"4",key:"17ys0d"}]]);/**
706 * @license lucide-react v0.462.0 - ISC
707 *
708 * This source code is licensed under the ISC license.
709 * See the LICENSE file in the root directory of this source tree.
710 */const eo=le("Users",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["path",{d:"M16 3.13a4 4 0 0 1 0 7.75",key:"1da9ce"}]]);/**
711 * @license lucide-react v0.462.0 - ISC
712 *
713 * This source code is licensed under the ISC license.
714 * See the LICENSE file in the root directory of this source tree.
715 */const Ns=le("Video",[["path",{d:"m16 13 5.223 3.482a.5.5 0 0 0 .777-.416V7.87a.5.5 0 0 0-.752-.432L16 10.5",key:"ftymec"}],["rect",{x:"2",y:"6",width:"14",height:"12",rx:"2",key:"158x01"}]]);/**
716 * @license lucide-react v0.462.0 - ISC
717 *
718 * This source code is licensed under the ISC license.
719 * See the LICENSE file in the root directory of this source tree.
720 */const M4=le("Volume2",[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",key:"uqj9uw"}],["path",{d:"M16 9a5 5 0 0 1 0 6",key:"1q6k2b"}],["path",{d:"M19.364 18.364a9 9 0 0 0 0-12.728",key:"ijwkga"}]]);/**
721 * @license lucide-react v0.462.0 - ISC
722 *
723 * This source code is licensed under the ISC license.
724 * See the LICENSE file in the root directory of this source tree.
725 */const xi=le("WandSparkles",[["path",{d:"m21.64 3.64-1.28-1.28a1.21 1.21 0 0 0-1.72 0L2.36 18.64a1.21 1.21 0 0 0 0 1.72l1.28 1.28a1.2 1.2 0 0 0 1.72 0L21.64 5.36a1.2 1.2 0 0 0 0-1.72",key:"ul74o6"}],["path",{d:"m14 7 3 3",key:"1r5n42"}],["path",{d:"M5 6v4",key:"ilb8ba"}],["path",{d:"M19 14v4",key:"blhpug"}],["path",{d:"M10 2v2",key:"7u0qdc"}],["path",{d:"M7 8H3",key:"zfb6yr"}],["path",{d:"M21 16h-4",key:"1cnmox"}],["path",{d:"M11 3H9",key:"1obp7u"}]]);/**
726 * @license lucide-react v0.462.0 - ISC
727 *
728 * This source code is licensed under the ISC license.
729 * See the LICENSE file in the root directory of this source tree.
730 */const Qn=le("X",[["path",{d:"M18 6 6 18",key:"1bl5f8"}
730],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]);/**
731 * @license lucide-react v0.462.0 - ISC
732 *
733 * This source code is licensed under the ISC license.
734 * See the LICENSE file in the root directory of this source tree.
735 */const Ls=le("Youtube",[["path",{d:"M2.5 17a24.12 24.12 0 0 1 0-10 2 2 0 0 1 1.4-1.4 49.56 49.56 0 0 1 16.2 0A2 2 0 0 1 21.5 7a24.12 24.12 0 0 1 0 10 2 2 0 0 1-1.4 1.4 49.55 49.55 0 0 1-16.2 0A2 2 0 0 1 2.5 17",key:"1q2vi4"}],["path",{d:"m10 15 5-3-5-3z",key:"1jp15x"}]]);/**
736 * @license lucide-react v0.462.0 - ISC
737 *
738 * This source code is licensed under the ISC license.
739 * See the LICENSE file in the root directory of this source tree.
740 */const nr=le("Zap",[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]]);function $w({children:e}){const{session:t,profile:s,loading:r}=st();return r?n.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:n.jsx(xe,{className:"w-6 h-6 animate-spin text-primary"})}):t?s&&!s.onboarding_completed?n.jsx(Al,{to:"/app/onboarding",replace:!0}):n.jsx(n.Fragment,{children:e}):n.jsx(Al,{to:"/login",replace:!0})}function z4({children:e}){const{session:t,profile:s,loading:r}=st();return r?n.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:n.jsx(xe,{className:"w-6 h-6 animate-spin text-primary"})}):t?s!=null&&s.onboarding_completed?n.jsx(Al,{to:"/app",replace:!0}):n.jsx(n.Fragment,{children:e}):n.jsx(Al,{to:"/login",replace:!0})}const Lw=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,Iw=CN,hu=(e,t)=>s=>{var r;if((t==null?void 0:t.variants)==null)return Iw(e,s==null?void 0:s.class,s==null?void 0:s.className);const{variants:a,defaultVariants:i}=t,o=Object.keys(a).map(d=>{const u=s==null?void 0:s[d],m=i==null?void 0:i[d];if(u===null)return null;const p=Lw(u)||Lw(m);return a[d][p]}),l=s&&Object.entries(s).reduce((d,u)=>{let[m,p]=u;return p===void 0||(d[m]=p),d},{}),c=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((d,u)=>{let{class:m,className:p,...f}=u;return Object.entries(f).every(g=>{let[x,b]=g;return Array.isArray(b)?b.includes({...i,...l}[x]):{...i,...l}[x]===b})?[...d,m,p]:d},[]);return Iw(e,o,c,s==null?void 0:s.class,s==null?void 0:s.className)},Ry=hu("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline",hero:"bg-gradient-primary text-primary-foreground shadow-glow hover:opacity-90 transition-all duration-300 font-semibold","hero-outline":"border-2 border-primary/20 bg-background text-foreground hover:border-primary/40 hover:bg-primary/5 transition-all duration-300 font-semibold",nav:"text-muted-foreground hover:text-foreground transition-colors font-medium"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8",icon:"h-10 w-10"}},defaultVariants:{variant:"default",size:"default"}}),L=h.forwardRef(({className:e,variant:t,size:s,asChild:r=!1,...a},i)=>{const o=r?ec:"button";return n.jsx(o,{className:_e(Ry({variant:t,size:s,className:e})),ref:i,...a})});L.displayName="Button";const et=e=>typeof e=="string",jc=()=>{let e,t;const s=new Promise((r,a)=>{e=r,t=a});return s.resolve=e,s.reject=t,s},Ow=e=>e==null?"":String(e),F4=(e,t,s)=>{e.forEach(r=>{t[r]&&(s[r]=t[r])})},U4=/###/g,Dw=e=>e&&e.includes("###")?e.replace(U4,"."):e,Mw=e=>!e||et(e),Jc=(e,t,s)=>{const r=et(t)?t.split("."):t;let a=0;for(;a<r.length-1;){if(Mw(e))return{};const i=Dw(r[a]);!e[i]&&s&&(e[i]=new s),Object.prototype.hasOwnProperty.call(e,i)?e=e[i]:e={},++a}return Mw(e)?{}:{obj:e,k:Dw(r[a])}},zw=(e,t,s)=>{const{obj:r,k:a}=Jc(e,t,Object);if(r!==void 0||t.length===1){r[a]=s;return}let i=t[t.length-1],o=t.slice(0,t.length-1),l=Jc(e,o,Object);for(;l.obj===void 0&&o.length;)i=`${o[o.length-1]}.${i}`,o=o.slice(0,o.length-1),l=Jc(e,o,Object),l!=null&&l.obj&&typeof l.obj[`${l.k}.${i}`]<"u"&&(l.obj=void 0);l.obj[`${l.k}.${i}`]=s},B4=(e,t,s,r)=>{const{obj:a,k:i}=Jc(e,t,Object);a[i]=a[i]||[],a[i].push(s)},gm=(e,t)=>
vendor: 6,154 bytes, line 740
740{const{obj:s,k:r}=Jc(e,t);if(s&&Object.prototype.hasOwnProperty.call(s,r))return s[r]},V4=(e,t,s)=>{const r=gm(e,s);return r!==void 0?r:gm(t,s)},xS=(e,t,s)=>{for(const r in t)r!=="__proto__"&&r!=="constructor"&&(r in e?et(e[r])||e[r]instanceof String||et(t[r])||t[r]instanceof String?s&&(e[r]=t[r]):xS(e[r],t[r],s):e[r]=t[r]);return e},Ir=e=>e.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&"),q4={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;"},H4=e=>et(e)?e.replace(/[&<>"'\/]/g,t=>q4[t]):e;class W4{constructor(t){this.capacity=t,this.regExpMap=new Map,this.regExpQueue=[]}getRegExp(t){const s=this.regExpMap.get(t);if(s!==void 0)return s;const r=new RegExp(t);return this.regExpQueue.length===this.capacity&&this.regExpMap.delete(this.regExpQueue.shift()),this.regExpMap.set(t,r),this.regExpQueue.push(t),r}}const G4=[" ",",","?","!",";"],Y4=new W4(20),K4=(e,t,s)=>{t=t||"",s=s||"";const r=G4.filter(o=>!t.includes(o)&&!s.includes(o));if(r.length===0)return!0;const a=Y4.getRegExp(`(${r.map(o=>o==="?"?"\\?":o).join("|")})`);let i=!a.test(e);if(!i){const o=e.indexOf(s);o>0&&!a.test(e.substring(0,o))&&(i=!0)}return i},Lx=(e,t,s=".")=>{if(!e)return;if(e[t])return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0;const r=t.split(s);let a=e;for(let i=0;i<r.length;){if(!a||typeof a!="object")return;let o,l="";for(let c=i;c<r.length;++c)if(c!==i&&(l+=s),l+=r[c],o=a[l],o!==void 0){if(["string","number","boolean"].includes(typeof o)&&c<r.length-1)continue;i+=c-i+1;break}a=o}return a},Dd=e=>e==null?void 0:e.replace(/_/g,"-"),Q4={type:"logger",log(e){this.output("log",e)},warn(e){this.output("warn",e)},error(e){this.output("error",e)},output(e,t){var s,r;(r=(s=console==null?void 0:console[e])==null?void 0:s.apply)==null||r.call(s,console,t)}};class xm{constructor(t,s={}){this.init(t,s)}init(t,s={}){this.prefix=s.prefix||"i18next:",this.logger=t||Q4,this.options=s,this.debug=s.debug}log(...t){return this.forward(t,"log","",!0)}warn(...t){return this.forward(t,"warn","",!0)}error(...t){return this.forward(t,"error","")}deprecate(...t){return this.forward(t,"warn","WARNING DEPRECATED: ",!0)}forward(t,s,r,a){return a&&!this.debug?null:(t=t.map(i=>et(i)?i.replace(/[\r\n\x00-\x1F\x7F]/g," "):i),et(t[0])&&(t[0]=`${r}${this.prefix} ${t[0]}`),this.logger[s](t))}create(t){return new xm(this.logger,{prefix:`${this.prefix}:${t}:`,...this.options})}clone(t){return t=t||this.options,t.prefix=t.prefix||this.prefix,new xm(this.logger,t)}}var jr=new xm;class mp{constructor(){this.observers={}}on(t,s){return t.split(" ").forEach(r=>{this.observers[r]||(this.observers[r]=new Map);const a=this.observers[r].get(s)||0;this.observers[r].set(s,a+1)}),this}off(t,s){if(this.observers[t]){if(!s){delete this.observers[t];return}this.observers[t].delete(s)}}once(t,s){const r=(...a)=>{s(...a),this.off(t,r)};return this.on(t,r),this}emit(t,...s){this.observers[t]&&Array.from(this.observers[t].entries()).forEach(([a,i])=>{for(let o=0;o<i;o++)a(...s)}),this.observers["*"]&&Array.from(this.observers["*"].entries()).forEach(([a,i])=>{for(let o=0;o<i;o++)a(t,...s)})}}class Fw extends mp{constructor(t,s={ns:["translation"],defaultNS:"translation"}){super(),this.data=t||{},this.options=s,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.options.ignoreJSONStructure===void 0&&(this.options.ignoreJSONStructure=!0)}addNamespaces(t){this.options.ns.includes(t)||this.options.ns.push(t)}removeNamespaces(t){const s=this.options.ns.indexOf(t);s>-1&&this.options.ns.splice(s,1)}getResource(t,s,r,a={}){var d,u;const i=a.keySeparator!==void 0?a.keySeparator:this.options.keySeparator,o=a.ignoreJSONStructure!==void 0?a.ignoreJSONStructure:this.options.ignoreJSONStructure;let l;t.includes(".")?l=t.split("."):(l=[t,s],r&&(Array.isArray(r)?l.push(...r):et(r)&&i?l.push(...r.split(i)):l.push(r)));const c=gm(this.data,l);return!c&&!s&&!r&&t.includes(".")&&(t=l[0],s=l[1],r=l.slice(2).join(".")),c||!o||!et(r)?c:Lx((u=(d=this.data)==null?void 0:d[t])==null?void 0:u[s],r,i)}addResource(t,s,r,a,i={silent:!1}){const o=i.keySeparator!==void 0?i.keySeparator:this.options.keySeparator;let l=[t,s];r&&(l=l.concat(o?r.split(o):r)),t.includes(".")&&(l=t.split("."),a=s,s=l[1]),this.addNamespaces(s),zw(this.data,l,a),i.silent||this.emit("added",t,s,r,a)}addResources(t,s,r,a={silent:!1}){for(const i in r)(et(r[i])||Array.isArray(r[i]))&&this.addResource(t,s,i,r[i],{silent:!0});a.silent||this.emit("added",t,s,r)}addResourceBundle(t,s,r,a,i,o={silent:!1,skipCopy:!1}){let l=[t,s];t.includes(".")&&(l=t.split("."),a=r,r=s,s=l[1]),this.addNamespaces(s);let c=gm(this.data,l)||{};o.skipCopy||(r=JSON.parse(JSON.stringify(r))),a?xS(c,r,i):c={...c,...r},zw(this.data,l,c),o.silent||this.emit("added",t,s,r)}removeResourceBundle(t,s){this.hasResourceBundle(t,s)&&delete this.data[t][s],this.removeNamespaces(s),this.emit("removed",t,s)}hasResourceBundle(t,s){return this.getResource(t,s)!==void 0}getResourceBundle(t,s){return s||(s=this.options.defaultNS),this.getResource(t,s)}getDataByLanguage(t){return this.data[t]}hasLanguageSomeTranslations(t){const s=this.getDataByLanguage(t);return!!(s&&Object.keys(s)||[]).find(a=>s[a]&&Object.keys(s[a]).length>0)}toJSON(){return this.data}}var vS={processors:{},addPostProcessor(e){this.processors[e.name]=e},handle(e,t,s,r,a){return e.forEach(i=>{var o;t=((o=this.processors[i])==null?void 0:o.process(t,s,r,a))??t}),t}};const yS=Symbol("i18next/PATH_KEY");function J4(){const e=[],t=Object.create(null);let s;return t.get=(r,a)=>{var i;return(i=s==null?void 0:s.revoke)==null||i.call(s),a===yS?e:(e.push(a),s=Proxy.revocable(r,t),s.proxy)},Proxy.revocable(Object.create(null),t).proxy}function ll(e,t){const{[yS]:s}=e(J4()),r=(t==null?void 0:t.keySeparator)??".",a=(t==null?void 0:t.nsSeparator)??":";if(s.length>1&&a){const i=t==null?void 0:t.ns,o=Array.isArray(i)?i:null;if(o&&o.length>1&&o.slice(1).includes(s[0]))return`${s[0]}${a}${s.slice(1).join(r)}`}return s.join(r)}const Nf=e=>!et(e)&&typeof e!="boolean"&&typeof e!="number";class vm extends mp{constructor(t,s={}){super(),F4(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","
740i18nFormat","utils"],t,this),this.options=s,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.logger=jr.create("translator"),this.checkedLoadedFor={}}changeLanguage(t){t&&(this.language=t)}exists(t,s={interpolation:{}}){const r={...s};if(t==null)return!1;const a=this.resolve(t,r);if((a==null?void 0:a.res)===void 0)return!1;const i=Nf(a.res);return!(r.returnObjects===!1&&i)}extractFromKey(t,s){let r=s.nsSeparator!==void 0?s.nsSeparator:this.options.nsSeparator;r===void 0&&(r=":");const a=s.keySeparator!==void 0?s.keySeparator:this.options.keySeparator;let i=s.ns||this.options.defaultNS||[];const o=r&&t.includes(r),l=!this.options.userDefinedKeySeparator&&!s.keySeparator&&!this.options.userDefinedNsSeparator&&!s.nsSeparator&&!K4(t,r,a);if(o&&!l){const c=t.match(this.interpolator.nestingRegexp);if(c&&c.length>0)return{key:t,namespaces:et(i)?[i]:i};const d=t.split(r);(r!==a||r===a&&this.options.ns.includes(d[0]))&&(i=d.shift()),t=d.join(a)}return{key:t,namespaces:et(i)?[i]:i}}translate(t,s,r){let a=typeof s=="object"?{...s}:s;if(typeof a!="object"&&this.options.overloadTranslationOptionHandler&&(a=this.options.overloadTranslationOptionHandler(arguments)),typeof a=="object"&&(a={...a}),a||(a={}),t==null)return"";typeof t=="function"&&(t=ll(t,{...this.options,...a})),Array.isArray(t)||(t=[String(t)]),t=t.map(H=>typeof H=="function"?ll(H,{...this.options,...a}):String(H));const i=a.returnDetails!==void 0?a.returnDetails:this.options.returnDetails,o=a.keySeparator!==void 0?a.keySeparator:this.options.keySeparator,{key:l,namespaces:c}=this.extractFromKey(t[t.length-1],a),d=c[c.length-1];let u=a.nsSeparator!==void 0?a.nsSeparator:this.options.nsSeparator;u===void 0&&(u=":");const m=a.lng||this.language,p=a.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if((m==null?void 0:m.toLowerCase())==="cimode")return p?i?{res:`${d}${u}${l}`,usedKey:l,exactUsedKey:l,usedLng:m,usedNS:d,usedParams:this.getUsedParamsDetails(a)}:`${d}${u}${l}`:i?{res:l,usedKey:l,exactUsedKey:l,usedLng:m,usedNS:d,usedParams:this.getUsedParamsDetails(a)}:l;const f=this.resolve(t,a);let g=f==null?void 0:f.res;const x=(f==null?void 0:f.usedKey)||l,b=(f==null?void 0:f.exactUsedKey)||l,v=["[object Number]","[object Function]","[object RegExp]"],y=a.joinArrays!==void 0?a.joinArrays:this.options.joinArrays,w=!this.i18nFormat||this.i18nFormat.handleAsObject,j=a.count!==void 0&&!et(a.count),_=vm.hasDefaultValue(a),N=j?this.pluralResolver.getSuffix(m,a.count,a):"",k=a.ordinal&&j?this.pluralResolver.getSuffix(m,a.count,{ordinal:!1}):"",S=j&&!a.ordinal&&a.count===0,T=S&&a[`defaultValue${this.options.pluralSeparator}zero`]||a[`defaultValue${N}`]||a[`defaultValue${k}`]||a.defaultValue;let C=g;w&&!g&&_&&(C=T);const B=Nf(C),E=Object.prototype.toString.apply(C);if(w&&C&&B&&!v.includes(E)&&!(et(y)&&Array.isArray(C))){if(!a.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");const H=this.options.returnedObjectHandler?this.options.returnedObjectHandler(x,C,{...a,ns:c}):`key '${l} (${this.language})' returned an object instead of string.`;return i?(f.res=H,f.usedParams=this.getUsedParamsDetails(a),f):H}if(o){const H=Array.isArray(C),z=H?[]:{},ne=H?b:x;for(const V in C)if(Object.prototype.hasOwnProperty.call(C,V)){const te=`${ne}${o}${V}`;_&&!g?z[V]=this.translate(te,{...a,defaultValue:Nf(T)?T[V]:void 0,joinArrays:!1,ns:c}):z[V]=this.translate(te,{...a,joinArrays:!1,ns:c}),z[V]===te&&(z[V]=C[V])}g=z}}else if(w&&et(y)&&Array.isArray(g))g=g.join(y),g&&(g=this.extendTranslation(g,t,a,r));else{let H=!1,z=!1;!this.isValidLookup(g)&&_&&(H=!0,g=T),this.isValidLookup(g)||(z=!0,g=l);const V=(a.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&z?void 0:g,te=_&&T!==g&&this.options.updateMissing;if(z||H||te){if(this.logger.log(te?"updateKey":"missingKey",m,d,l,te?T:g),o){const J=this.resolve(l,{...a,keySeparator:!1});J&&J.res&&this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.")}let R=[];const F=this.languageUtils.getFallbackCodes(this.options.fallbackLng,a.lng||this.language);if(this.options.saveMissingTo==="fallback"&&F&&F[0])for(let J=0;J<F.length;J++)R.push(F[J]);else this.options.saveMissingTo==="all"?R=this.languageUtils.toResolveHierarchy(a.lng||this.language):R.push(a.lng||this.language);const $=(J,Y,re)=>{var O;const G=_&&re!==g?re:V;this.options.missingKeyHandler?this.options.missingKeyHandler(J,d,Y,G,te,a):(O=this.backendConnector)!=null&&O.saveMissing&&this.backendConnector.saveMissing(J,d,Y,G,te,a),this.emit
vendor: 28,937 bytes, line 740
740("missingKey",J,d,Y,g)};this.options.saveMissing&&(this.options.saveMissingPlurals&&j?R.forEach(J=>{const Y=this.pluralResolver.getSuffixes(J,a);S&&a[`defaultValue${this.options.pluralSeparator}zero`]&&!Y.includes(`${this.options.pluralSeparator}zero`)&&Y.push(`${this.options.pluralSeparator}zero`),Y.forEach(re=>{$([J],l+re,a[`defaultValue${re}`]||T)})}):$(R,l,T))}g=this.extendTranslation(g,t,a,f,r),z&&g===l&&this.options.appendNamespaceToMissingKey&&(g=`${d}${u}${l}`),(z||H)&&this.options.parseMissingKeyHandler&&(g=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${d}${u}${l}`:l,H?g:void 0,a))}return i?(f.res=g,f.usedParams=this.getUsedParamsDetails(a),f):g}extendTranslation(t,s,r,a,i){var c,d;if((c=this.i18nFormat)!=null&&c.parse)t=this.i18nFormat.parse(t,{...this.options.interpolation.defaultVariables,...r},r.lng||this.language||a.usedLng,a.usedNS,a.usedKey,{resolved:a});else if(!r.skipInterpolation){r.interpolation&&this.interpolator.init({...r,interpolation:{...this.options.interpolation,...r.interpolation}});const u=et(t)&&(((d=r==null?void 0:r.interpolation)==null?void 0:d.skipOnVariables)!==void 0?r.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables);let m;if(u){const f=t.match(this.interpolator.nestingRegexp);m=f&&f.length}let p=r.replace&&!et(r.replace)?r.replace:r;if(this.options.interpolation.defaultVariables&&(p={...this.options.interpolation.defaultVariables,...p}),t=this.interpolator.interpolate(t,p,r.lng||this.language||a.usedLng,r),u){const f=t.match(this.interpolator.nestingRegexp),g=f&&f.length;m<g&&(r.nest=!1)}!r.lng&&a&&a.res&&(r.lng=this.language||a.usedLng),r.nest!==!1&&(t=this.interpolator.nest(t,(...f)=>(i==null?void 0:i[0])===f[0]&&!r.context?(this.logger.warn(`It seems you are nesting recursively key: ${f[0]} in key: ${s[0]}`),null):this.translate(...f,s),r)),r.interpolation&&this.interpolator.reset()}const o=r.postProcess||this.options.postProcess,l=et(o)?[o]:o;return t!=null&&(l!=null&&l.length)&&r.applyPostProcessor!==!1&&(t=vS.handle(l,t,s,this.options&&this.options.postProcessPassResolved?{i18nResolved:{...a,usedParams:this.getUsedParamsDetails(r)},...r}:r,this)),t}resolve(t,s={}){let r,a,i,o,l;return et(t)&&(t=[t]),Array.isArray(t)&&(t=t.map(c=>typeof c=="function"?ll(c,{...this.options,...s}):c)),t.forEach(c=>{if(this.isValidLookup(r))return;const d=this.extractFromKey(c,s),u=d.key;a=u;let m=d.namespaces;this.options.fallbackNS&&(m=m.concat(this.options.fallbackNS));const p=s.count!==void 0&&!et(s.count),f=p&&!s.ordinal&&s.count===0,g=s.context!==void 0&&(et(s.context)||typeof s.context=="number")&&s.context!=="",x=s.lngs?s.lngs:this.languageUtils.toResolveHierarchy(s.lng||this.language,s.fallbackLng);m.forEach(b=>{var v,y;this.isValidLookup(r)||(l=b,!this.checkedLoadedFor[`${x[0]}-${b}`]&&((v=this.utils)!=null&&v.hasLoadedNamespace)&&!((y=this.utils)!=null&&y.hasLoadedNamespace(l))&&(this.checkedLoadedFor[`${x[0]}-${b}`]=!0,this.logger.warn(`key "${a}" for languages "${x.join(", ")}" won't get resolved as namespace "${l}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!")),x.forEach(w=>{var N;if(this.isValidLookup(r))return;o=w;const j=[u];if((N=this.i18nFormat)!=null&&N.addLookupKeys)this.i18nFormat.addLookupKeys(j,u,w,b,s);else{let k;p&&(k=this.pluralResolver.getSuffix(w,s.count,s));const S=`${this.options.pluralSeparator}zero`,T=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(p&&(s.ordinal&&k.startsWith(T)&&j.push(u+k.replace(T,this.options.pluralSeparator)),j.push(u+k),f&&j.push(u+S)),g){const C=`${u}${this.options.contextSeparator||"_"}${s.context}`;j.push(C),p&&(s.ordinal&&k.startsWith(T)&&j.push(C+k.replace(T,this.options.pluralSeparator)),j.push(C+k),f&&j.push(C+S))}}let _;for(;_=j.pop();)this.isValidLookup(r)||(i=_,r=this.getResource(w,b,_,s))}))})}),{res:r,usedKey:a,exactUsedKey:i,usedLng:o,usedNS:l}}isValidLookup(t){return t!==void 0&&!(!this.options.returnNull&&t===null)&&!(!this.options.returnEmptyString&&t==="")}getResource(t,s,r,a={}){var i;return(i=this.i18nFormat)!=null&&i.getResource?this.i18nFormat.getResource(t,s,r,a):this.resourceStore.getResource(t,s,r,a)}getUsedParamsDetails(t={}){const s=["defaultValue","ordinal","context","replace","lng","lngs","fallbackLng","ns","keySeparator","nsSeparator","returnObjects","returnDetails","joinArrays","postProcess","interpolation"],r=t.replace&&!et(t.replace);let a=r?t.replace:t;if(r&&typeof t.count<"u"&&(a.count=t.count),this.options.interpolation.defaultVariables&&(a={...this.options.interpolation.defaultVariables,...a}),!r){a={...a};for(const i of s)delete a[i]}return a}static hasDefaultValue(t){const s="defaultValue";for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)&&r.startsWith(s)&&t[r]!==void 0)return!0;return!1}}class Uw{constructor(t){this.options=t,this.supportedLngs=this.options.supportedLngs||!1,this.logger=jr.create("languageUtils")}getScriptPartFromCode(t){if(t=Dd(t),!t||!t.includes("-"))return null;const s=t.split("-");return s.length===2||(s.pop(),s[s.length-1].toLowerCase()==="x")?null:this.formatLanguageCode(s.join("-"))}getLanguagePartFromCode(t){if(t=Dd(t),!t||!t.includes("-"))return t;const s=t.split("-");return this.formatLanguageCode(s[0])}formatLanguageCode(t){if(et(t)&&t.includes("-")){let s;try{s=Intl.getCanonicalLocales(t)[0]}catch{}return s&&this.options.lowerCaseLng&&(s=s.toLowerCase()),s||(this.options.lowerCaseLng?t.toLowerCase():t)}return this.options.cleanCode||this.options.lowerCaseLng?t.toLowerCase():t}isSupportedCode(t){return(this.options.load==="languageOnly"||this.options.nonExplicitSupportedLngs)&&(t=this.getLanguagePartFromCode(t)),!this.supportedLngs||!this.supportedLngs.length||this.supportedLngs.includes(t)}getBestMatchFromCodes(t){if(!t)return null;let s;return t.forEach(r=>{if(s)return;const a=this.formatLanguageCode(r);(!this.options.supportedLngs||this.isSupportedCode(a))&&(s=a)}),!s&&this.options.supportedLngs&&t.forEach(r=>{if(s)return;const a=this.getScriptPartFromCode(r);if(this.isSupportedCode(a))return s=a;const i=this.getLanguagePartFromCode(r);if(this.isSupportedCode(i))return s=i;s=this.options.supportedLngs.find(o=>o===i?!0:!o.includes("-")&&!i.includes("-")?!1:!!(o.includes("-")&&!i.includes("-")&&o.slice(0,o.indexOf("-"))===i||o.startsWith(i)&&i.length>1))}),s||(s=this.getFallbackCodes(this.options.fallbackLng)[0]),s}getFallbackCodes(t,s){if(!t)return[];if(typeof t=="function"&&(t=t(s)),et(t)&&(t=[t]),Array.isArray(t))return t;if(!s)return t.default||[];let r=t[s];return r||(r=t[this.getScriptPartFromCode(s)]),r||(r=t[this.formatLanguageCode(s)]),r||(r=t[this.getLanguagePartFromCode(s)]),r||(r=t.default),r||[]}toResolveHierarchy(t,s){const r=this.getFallbackCodes((s===!1?[]:s)||this.options.fallbackLng||[],t),a=[],i=o=>{o&&(this.isSupportedCode(o)?a.push(o):this.logger.warn(`rejecting language code not found in supportedLngs: ${o}`))};return et(t)&&(t.includes("-")||t.includes("_"))?(this.options.load!=="languageOnly"&&i(this.formatLanguageCode(t)),this.options.load!=="languageOnly"&&this.options.load!=="currentOnly"&&i(this.getScriptPartFromCode(t)),this.options.load!=="currentOnly"&&i(this.getLanguagePartFromCode(t))):et(t)&&i(this.formatLanguageCode(t)),r.forEach(o=>{a.includes(o)||i(this.formatLanguageCode(o))}),a}}const Bw={zero:0,one:1,two:2,few:3,many:4,other:5},Vw={select:e=>e===1?"one":"other",resolvedOptions:()=>({pluralCategories:["one","other"]})};class Z4{constructor(t,s={}){this.languageUtils=t,this.options=s,this.logger=jr.create("pluralResolver"),this.pluralRulesCache={}}clearCache(){this.pluralRulesCache={}}getRule(t,s={}){const r=Dd(t==="dev"?"en":t),a=s.ordinal?"ordinal":"cardinal",i=JSON.stringify({cleanedCode:r,type:a});if(i in this.pluralRulesCache)return this.pluralRulesCache[i];let o;try{o=new Intl.PluralRules(r,{type:a})}catch{if(typeof Intl>"u")return this.logger.error("No Intl support, please use an Intl polyfill!"),Vw;if(!t.match(/-|_/))return Vw;const c=this.languageUtils.getLanguagePartFromCode(t);o=this.getRule(c,s)}return this.pluralRulesCache[i]=o,o}needsPlural(t,s={}){let r=this.getRule(t,s);return r||(r=this.getRule("dev",s)),(r==null?void 0:r.resolvedOptions().pluralCategories.length)>1}getPluralFormsOfKey(t,s,r={}){return this.getSuffixes(t,r).map(a=>`${s}${a}`)}getSuffixes(t,s={}){let r=this.getRule(t,s);return r||(r=this.getRule("dev",s)),r?r.resolvedOptions().pluralCategories.sort((a,i)=>Bw[a]-Bw[i]).map(a=>`${this.options.prepend}${s.ordinal?`ordinal${this.options.prepend}`:""}${a}`):[]}getSuffix(t,s,r={}){const a=this.getRule(t,r);return a?`${this.options.prepend}${r.ordinal?`ordinal${this.options.prepend}`:""}${a.select(s)}`:(this.logger.warn(`no plural rule found for: ${t}`),this.getSuffix("dev",s,r))}}const qw=(e,t,s,r=".",a=!0)=>{let i=V4(e,t,s);return!i&&a&&et(s)&&(i=Lx(e,s,r),i===void 0&&(i=Lx(t,s,r))),i},Sf=e=>e.replace(/\$/g,"$$$$");class Hw{constructor(t={}){var s;this.logger=jr.create("interpolator"),this.options=t,this.format=((s=t==null?void 0:t.interpolation)==null?void 0:s.format)||(r=>r),this.init(t)}init(t={}){t.interpolation||(t.interpolation={escapeValue:!0});const{escape:s,escapeValue:r,useRawValueToEscape:a,prefix:i,prefixEscaped:o,suffix:l,suffixEscaped:c,formatSeparator:d,unescapeSuffix:u,unescapePrefix:m,nestingPrefix:p,nestingPrefixEscaped:f,nestingSuffix:g,nestingSuffixEscaped:x,nestingOptionsSeparator:b,maxReplaces:v,alwaysFormat:y}=t.interpolation;this.escape=s!==void 0?s:H4,this.escapeValue=r!==void 0?r:!0,this.useRawValueToEscape=a!==void 0?a:!1,this.prefix=i?Ir(i):o||"{{",this.suffix=l?Ir(l):c||"}}",this.formatSeparator=d||",",this.unescapePrefix=u?"":m?Ir(m):"-",this.unescapeSuffix=this.unescapePrefix?"":u?Ir(u):"",this.nestingPrefix=p?Ir(p):f||Ir("$t("),this.nestingSuffix=g?Ir(g):x||Ir(")"),this.nestingOptionsSeparator=b||",",this.maxReplaces=v||1e3,this.alwaysFormat=y!==void 0?y:!1,this.resetRegExp()}reset(){this.options&&this.init(this.options)}resetRegExp(){const t=(s,r)=>(s==null?void 0:s.source)===r?(s.lastIndex=0,s):new RegExp(r,"g");this.regexp=t(this.regexp,`${this.prefix}(.+?)${this.suffix}`),this.regexpUnescape=t(this.regexpUnescape,`${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`),this.nestingRegexp=t(this.nestingRegexp,`${this.nestingPrefix}((?:[^()"']+|"[^"]*"|'[^']*'|\\((?:[^()]|"[^"]*"|'[^']*')*\\))*?)${this.nestingSuffix}`)}interpolate(t,s,r,a){var f;let i,o,l;const c=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},d=g=>{if(!g.includes(this.formatSeparator)){const y=qw(s,c,g,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(y,void 0,r,{...a,...s,interpolationkey:g}):y}const x=g.split(this.formatSeparator),b=x.shift().trim(),v=x.join(this.formatSeparator).trim();return this.format(qw(s,c,b,this.options.keySeparator,this.options.ignoreJSONStructure),v,r,{...a,...s,interpolationkey:b})};this.resetRegExp(),!this.escapeValue&&typeof t=="string"&&/\$t\([^)]*\{[^}]*\{\{/.test(t)&&this.logger.warn("nesting options string contains interpolated variables with escapeValue: false — if any of those values are attacker-controlled they can inject additional nesting options (e.g. redirect lng/ns). Sanitise untrusted input before passing it to t(), or keep escapeValue: true.");const u=(a==null?void 0:a.missingInterpolationHandler)||this.options.missingInterpolationHandler,m=((f=a==null?void 0:a.interpolation)==null?void 0:f.skipOnVariables)!==void 0?a.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:g=>Sf(g)},{regex:this.regexp,safeValue:g=>this.escapeValue?Sf(this.escape(g)):Sf(g)}].forEach(g=>{for(l=0;i=g.regex.exec(t);){const x=i[1].trim();if(o=d(x),o===void 0)if(typeof u=="function"){const v=u(t,i,a);o=et(v)?v:""}else if(a&&Object.prototype.hasOwnProperty.call(a,x))o="";else if(m){o=i[0];continue}else this.logger.warn(`missed to pass in variable ${x} for interpolating ${t}`),o="";else!et(o)&&!this.useRawValueToEscape&&(o=Ow(o));const b=g.safeValue(o);if(t=t.replace(i[0],b),m?(g.regex.lastIndex+=o.length,g.regex.lastIndex-=i[0].length):g.regex.lastIndex=0,l++,l>=this.maxReplaces)break}}),t}nest(t,s,r={}){let a,i,o;const l=(c,d)=>{const u=this.nestingOptionsSeparator;if(!c.includes(u))return c;const m=c.split(new RegExp(`${Ir(u)}[ ]*{`));let p=`{${m[1]}`;c=m[0],p=this.interpolate(p,o);const f=p.match(/'/g),g=p.match(/"/g);(((f==null?void 0:f.length)??0)%2===0&&!g||((g==null?void 0:g.length)??0)%2!==0)&&(p=p.replace(/'/g,'"'));try{o=JSON.parse(p),d&&(o={...d,...o})}catch(x){return this.logger.warn(`failed parsing options string in nesting for key ${c}`,x),`${c}${u}${p}`}return o.defaultValue&&o.defaultValue.includes(this.prefix)&&delete o.defaultValue,c};for(;a=this.nestingRegexp.exec(t);){let c=[];o={...r},o=o.replace&&!et(o.replace)?o.replace:o,o.applyPostProcessor=!1,delete o.defaultValue;const d=/{.*}/.test(a[1])?a[1].lastIndexOf("}")+1:a[1].indexOf(this.formatSeparator);if(d!==-1&&(c=a[1].slice(d).split(this.formatSeparator).map(u=>u.trim()).filter(Boolean),a[1]=a[1].slice(0,d)),i=s(l.call(this,a[1].trim(),o),o),i&&a[0]===t&&!et(i))return i;et(i)||(i=Ow(i)),i||(this.logger.warn(`missed to resolve ${a[1]} for nesting ${t}`),i=""),c.length&&(i=c.reduce((u,m)=>this.format(u,m,r.lng,{...r,interpolationkey:a[1].trim()}),i.trim())),t=t.replace(a[0],i),this.regexp.lastIndex=0}return t}}const X4=e=>{let t=e.toLowerCase().trim();const s={};if(e.includes("(")){const r=e.split("(");t=r[0].toLowerCase().trim();const a=r[1].slice(0,-1);t==="currency"&&!a.includes(":")?s.currency||(s.currency=a.trim()):t==="relativetime"&&!a.includes(":")?s.range||(s.range=a.trim()):a.split(";").forEach(o=>{if(o){const[l,...c]=o.split(":"),d=c.join(":").trim().replace(/^'+|'+$/g,""),u=l.trim();s[u]||(s[u]=d),d==="false"&&(s[u]=!1),d==="true"&&(s[u]=!0),isNaN(d)||(s[u]=parseInt(d,10))}})}return{formatName:t,formatOptions:s}},Ww=e=>{const t={};return(s,r,a)=>{let i=a;a&&a.interpolationkey&&a.formatParams&&a.formatParams[a.interpolationkey]&&a[a.interpolationkey]&&(i={...i,[a.interpolationkey]:void 0});const o=r+JSON.stringify(i);let l=t[o];return l||(l=e(Dd(r),a),t[o]=l),l(s)}},eM=e=>(t,s,r)=>e(Dd(s),r)(t);class tM{constructor(t={}){this.logger=jr.create("formatter"),this.options=t,this.init(t)}init(t,s={interpolation:{}}){this.formatSeparator=s.interpolation.formatSeparator||",";const r=s.cacheInBuiltFormats?Ww:eM;this.formats={number:r((a,i)=>{const o=new Intl.NumberFormat(a,{...i});return l=>o.format(l)}),currency:r((a,i)=>{const o=new Intl.NumberFormat(a,{...i,style:"currency"});return l=>o.format(l)}),datetime:r((a,i)=>{const o=new Intl.DateTimeFormat(a,{...i});return l=>o.format(l)}),relativetime:r((a,i)=>{const o=new Intl.RelativeTimeFormat(a,{...i});return l=>o.format(l,i.range||"day")}),list:r((a,i)=>{const o=new Intl.ListFormat(a,{...i});return l=>o.format(l)})}}add(t,s){this.formats[t.toLowerCase().trim()]=s}addCached(t,s){this.formats[t.toLowerCase().trim()]=Ww(s)}format(t,s,r,a={}){if(!s||t==null)return t;const i=s.split(this.formatSeparator);if(i.length>1&&i[0].indexOf("(")>1&&!i[0].includes(")")&&i.find(l=>l.includes(")"))){const l=i.findIndex(c=>c.includes(")"));i[0]=[i[0],...i.splice(1,l)].join(this.formatSeparator)}return i.reduce((l,c)=>{var m;const{formatName:d,formatOptions:u}=X4(c);if(this.formats[d]){let p=l;try{const f=((m=a==null?void 0:a.formatParams)==null?void 0:m[a.interpolationkey])||{},g=f.locale||f.lng||a.locale||a.lng||r;p=this.formats[d](l,g,{...u,...a,...f})}catch(f){this.logger.warn(f)}return p}else this.logger.warn(`there was no format function for ${d}`);return l},t)}}const sM=(e,t)=>{e.pending[t]!==void 0&&(delete e.pending[t],e.pendingCount--)};class nM extends mp{constructor(t,s,r,a={}){var i,o;super(),this.backend=t,this.store=s,this.services=r,this.languageUtils=r.languageUtils,this.options=a,this.logger=jr.create("backendConnector"),this.waitingReads=[],this.maxParallelReads=a.maxParallelReads||10,this.readingCalls=0,this.maxRetries=a.maxRetries>=0?a.maxRetries:5,this.retryTimeout=a.retryTimeout>=1?a.retryTimeout:350,this.state={},this.queue=[],(o=(i=this.backend)==null?void 0:i.init)==null||o.call(i,r,a.backend,a)}queueLoad(t,s,r,a){const i={},o={},l={},c={};return t.forEach(d=>{let u=!0;s.forEach(m=>{const p=`${d}|${m}`;!r.reload&&this.store.hasResourceBundle(d,m)?this.state[p]=2:this.state[p]<0||(this.state[p]===1?o[p]===void 0&&(o[p]=!0):(this.state[p]=1,u=!1,o[p]===void 0&&(o[p]=!0),i[p]===void 0&&(i[p]=!0),c[m]===void 0&&(c[m]=!0)))}),u||(l[d]=!0)}),(Object.keys(i).length||Object.keys(o).length)&&this.queue.push({pending:o,pendingCount:Object.keys(o).length,loaded:{},errors:[],callback:a}),{toLoad:Object.keys(i),pending:Object.keys(o),toLoadLanguages:Object.keys(l),toLoadNamespaces:Object.keys(c)}}loaded(t,s,r){const a=t.split("|"),i=a[0],o=a[1];s&&this.emit("failedLoading",i,o,s),!s&&r&&this.store.addResourceBundle(i,o,r,void 0,void 0,{skipCopy:!0}),this.state[t]=s?-1:2,s&&r&&(this.state[t]=0);const l={};this.queue.forEach(c=>{B4(c.loaded,[i],o),sM(c,t),s&&c.errors.push(s),c.pendingCount===0&&!c.done&&(Object.keys(c.loaded).forEach(d=>{l[d]||(l[d]={});const u=c.loaded[d];u.length&&u.forEach(m=>{l[d][m]===void 0&&(l[d][m]=!0)})}),c.done=!0,c.errors.length?c.callback(c.errors):c.callback())}),this.emit("loaded",l),this.queue=this.queue.filter(c=>!c.done)}read(t,s,r,a=0,i=this.retryTimeout,o){if(!t.length)return o(null,{});if(this.readingCalls>=this.maxParallelReads){this.waitingReads.push({lng:t,ns:s,fcName:r,tried:a,wait:i,callback:o});return}this.readingCalls++;const l=(d,u)=>{if(this.readingCalls--,this.waitingReads.length>0){const m=this.waitingReads.shift();this.read(m.lng,m.ns,m.fcName,m.tried,m.wait,m.callback)}if(d&&u&&a<this.maxRetries){setTimeout(()=>{this.read(t,s,r,a+1,i*2,o)},i);return}o(d,u)},c=this.backend[r].bind(this.backend);if(c.length===2){try{const d=c(t,s);d&&typeof d.then=="function"?d.then(u=>l(null,u)).catch(l):l(null,d)}catch(d){l(d)}return}return c(t,s,l)}prepareLoading(t,s,r={},a){if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),a&&a();et(t)&&(t=this.languageUtils.toResolveHierarchy(t)),et(s)&&(s=[s]);const i=this.queueLoad(t,s,r,a);if(!i.toLoad.length)return i.pending.length||a(),null;i.toLoad.forEach(o=>{this.loadOne(o)})}load(t,s,r){this.prepareLoading(t,s,{},r)}reload(t,s,r){this.prepareLoading(t,s,{reload:!0},r)}loadOne(t,s=""){const r=t.split("|"),a=r[0],i=r[1];this.read(a,i,"read",void 0,void 0,(o,l)=>{o&&this.logger.warn(`${s}loading namespace ${i} for language ${a} failed`,o),!o&&l&&this.logger.log(`${s}loaded namespace ${i} for language ${a}`,l),this.loaded(t,o,l)})}saveMissing(t,s,r,a,i,o={},l=()=>{}){var c,d,u,m,p;if((d=(c=this.services)==null?void 0:c.utils)!=null&&d.hasLoadedNamespace&&!((m=(u=this.services)==null?void 0:u.utils)!=null&&m.hasLoadedNamespace(s))){this.logger.warn(`did not save key "${r}" as the namespace "${s}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");return}if(!(r==null||r==="")){if((p=this.backend)!=null&&p.create){const f={...o,isUpdate:i},g=this.backend.create.bind(this.backend);if(g.length<6)try{let x;g.length===5?x=g(t,s,r,a,f):x=g(t,s,r,a),x&&typeof x.then=="function"?x.then(b=>l(null,b)).catch(l):l(null,x)}catch(x){l(x)}else g(t,s,r,a,l,f)}!t||!t[0]||this.store.addResource(t[0],s,r,a)}}}const Cf=()=>({debug:!1,initAsync:!0,ns:["translation"],defaultNS:["translation"],fallbackLng:["dev"],fallbackNS:!1,supportedLngs:!1,nonExplicitSupportedLngs:!1,load:"all",preload:!1,keySeparator:".",nsSeparator:":",pluralSeparator:"_",contextSeparator:"_",partialBundledLanguages:!1,saveMissing:!1,updateMissing:!1,saveMissingTo:"fallback",saveMissingPlurals:!0,missingKeyHandler:!1,missingInterpolationHandler:!1,postProcess:!1,postProcessPassResolved:!1,returnNull:!1,returnEmptyString:!0,returnObjects:!1,joinArrays:!1,returnedObjectHandler:!1,parseMissingKeyHandler:!1,appendNamespaceToMissingKey:!1,appendNamespaceToCIMode:!1,overloadTranslationOptionHandler:e=>{let t={};if(typeof e[1]=="object"&&(t=e[1]),et(e[1])&&(t.defaultValue=e[1]),et(e[2])&&(t.tDescription=e[2]),typeof e[2]=="object"||typeof e[3]=="object"){const s=e[3]||e[2];Object.keys(s).forEach(r=>{t[r]=s[r]})}return t},interpolation:{escapeValue:!0,prefix:"{{",suffix:"}}",formatSeparator:",",unescapePrefix:"-",nestingPrefix:"$t(",nestingSuffix:")",nestingOptionsSeparator:",",maxReplaces:1e3,skipOnVariables:!0},cacheInBuiltFormats:!0}),Gw=e=>(et(e.ns)&&(e.ns=[e.ns]),et(e.fallbackLng)&&(e.fallbackLng=[e.fallbackLng]),et(e.fallbackNS)&&(e.fallbackNS=[e.fallbackNS]),e.supportedLngs&&!e.supportedLngs.includes("cimode")&&(e.supportedLngs=e.supportedLngs.concat(["cimode"])),e),th=()=>{},rM=e=>{Object.getOwnPropertyNames(Object.getPrototypeOf(e)).forEach(s=>{typeof e[s]=="function"&&(e[s]=e[s].bind(e))})};class Zc extends mp{constructor(t={},s){if(super(),this.options=Gw(t),this.services={},this.logger=jr,this.modules={external:[]},rM(this),s&&!this.isInitialized&&!t.isClone){if(!this.options.initAsync)return this.init(t,s),this;setTimeout(()=>{this.init(t,s)},0)}}init(t={},s){this.isInitializing=!0,typeof t=="function"&&(s=t,t={}),t.defaultNS==null&&t.ns&&(et(t.ns)?t.defaultNS=t.ns:t.ns.includes("translation")||(t.defaultNS=t.ns[0]));const r=Cf();this.options={...r,...this.options,...Gw(t)},this.options.interpolation={...r.interpolation,...this.options.interpolation},t.keySeparator!==void 0&&(this.options.userDefinedKeySeparator=t.keySeparator),t.nsSeparator!==void 0&&(this.options.userDefinedNsSeparator=t.nsSeparator),typeof this.options.overloadTranslationOptionHandler!="function"&&(this.options.overloadTranslationOptionHandler=r.overloadTranslationOptionHandler);const a=d=>d?typeof d=="function"?new d:d:null;if(!this.options.isClone){this.modules.logger?jr.init(a(this.modules.logger),this.options):jr.init(null,this.options);let d;this.modules.formatter?d=this.modules.formatter:d=tM;const u=new Uw(this.options);this.store=new Fw(this.options.resources,this.options);const m=this.services;m.logger=jr,m.resourceStore=this.store,m.languageUtils=u,m.pluralResolver=new Z4(u,{prepend:this.options.pluralSeparator}),d&&(m.formatter=a(d),m.formatter.init&&m.formatter.init(m,this.options),this.options.interpolation.format=m.formatter.format.bind(m.formatter)),m.interpolator=new Hw(this.options),m.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},m.backendConnector=new nM(a(this.modules.backend),m.resourceStore,m,this.options),m.backendConnector.on("*",(p,...f)=>{this.emit(p,...f)}),this.modules.languageDetector&&(m.languageDetector=a(this.modules.languageDetector),m.languageDetector.init&&m.languageDetector.init(m,this.options.detection,this.options)),this.modules.i18nFormat&&(m.i18nFormat=a(this.modules.i18nFormat),m.i18nFormat.init&&m.i18nFormat.init(this)),this.translator=new vm(this.services,this.options),this.translator.on("*",(p,...f)=>{this.emit(p,...f)}),this.modules.external.forEach(p=>{p.init&&p.init(this)})}if(this.format=this.options.interpolation.format,s||(s=th),this.options.fallbackLng&&!this.services.languageDetector&&!this.options.lng){const d=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);d.length>0&&d[0]!=="dev"&&(this.options.lng=d[0])}!this.services.languageDetector&&!this.options.lng&&this.logger.warn("init: no languageDetector is used and no lng is defined"),["getResource","hasResourceBundle","getResourceBundle","getDataByLanguage"].forEach(d=>{this[d]=(...u)=>this.store[d](...u)}),["addResource","addResources","addResourceBundle","removeResourceBundle"].forEach(d=>{this[d]=(...u)=>(this.store[d](...u),this)});const l=jc(),c=()=>{const d=(u,m)=>{this.isInitializing=!1,this.isInitialized&&!this.initializedStoreOnce&&this.logger.warn("init: i18next is already initialized. You should call init just once!"),this.isInitialized=!0,this.options.isClone||this.logger.log("initialized",this.options),this.emit("initialized",this.options),l.resolve(m),s(u,m)};if((this.languages||this.isLanguageChangingTo)&&!this.isInitialized)return d(null,this.t.bind(this));this.changeLanguage(this.options.lng,d)};return this.options.resources||!this.options.initAsync?c():setTimeout(c,0),l}loadResources(t,s=th){var i,o;let r=s;const a=et(t)?t:this.language;if(typeof t=="function"&&(r=t),!this.options.resources||this.options.partialBundledLanguages){if((a==null?void 0:a.toLowerCase())==="cimode"&&(!this.options.preload||this.options.preload.length===0))return r();const l=[],c=d=>{if(!d||d==="cimode")return;this.services.languageUtils.toResolveHierarchy(d).forEach(m=>{m!=="cimode"&&(l.includes(m)||l.push(m))})};a?c(a):this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach(u=>c(u)),(o=(i=this.options.preload)==null?void 0:i.forEach)==null||o.call(i,d=>c(d)),this.services.backendConnector.load(l,this.options.ns,d=>{!d&&!this.resolvedLanguage&&this.language&&this.setResolvedLanguage(this.language),r(d)})}else r(null)}reloadResources(t,s,r){const a=jc();return typeof t=="function"&&(r=t,t=void 0),typeof s=="function"&&(r=s,s=void 0),t||(t=this.languages),s||(s=this.options.ns),r||(r=th),this.services.backendConnector.reload(t,s,i=>{a.resolve(),r(i)}),a}use(t){if(!t)throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");if(!t.type)throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");return t.type==="backend"&&(this.modules.backend=t),(t.type==="logger"||t.log&&t.warn&&t.error)&&(this.modules.logger=t),t.type==="languageDetector"&&(this.modules.languageDetector=t),t.type==="i18nFormat"&&(this.modules.i18nFormat=t),t.type==="postProcessor"&&vS.addPostProcessor(t),t.type==="formatter"&&(this.modules.formatter=t),t.type==="3rdParty"&&this.modules.external.push(t),this}setResolvedLanguage(t){if(!(!t||!this.languages)&&!["cimode","dev"].includes(t)){for(let s=0;s<this.languages.length;s++){const r=this.languages[s];if(!["cimode","dev"].includes(r)&&this.store.hasLanguageSomeTranslations(r)){this.resolvedLanguage=r;break}}!this.resolvedLanguage&&!this.languages.includes(t)&&this.store.hasLanguageSomeTranslations(t)&&(this.resolvedLanguage=t,this.languages.unshift(t))}}changeLanguage(t,s){this.isLanguageChangingTo=t;const r=jc();this.emit("languageChanging",t);const a=l=>{this.language=l,this.languages=this.services.languageUtils.toResolveHierarchy(l),this.resolvedLanguage=void 0,this.setResolvedLanguage(l)},i=(l,c)=>{c?this.isLanguageChangingTo===t&&(a(c),this.translator.changeLanguage(c),this.isLanguageChangingTo=void 0,this.emit("languageChanged",c),this.logger.log("languageChanged",c)):this.isLanguageChangingTo=void 0,r.resolve((...d)=>this.t(...d)),s&&s(l,(...d)=>this.t(...d))},o=l=>{var u,m;!t&&!l&&this.services.languageDetector&&(l=[]);const c=et(l)?l:l&&l[0],d=this.store.hasLanguageSomeTranslations(c)?c:this.services.languageUtils.getBestMatchFromCodes(et(l)?[l]:l);d&&(this.language||a(d),this.translator.language||this.translator.changeLanguage(d),(m=(u=this.services.languageDetector)==null?void 0:u.cacheUserLanguage)==null||m.call(u,d)),this.loadResources(d,p=>{i(p,d)})};return!t&&this.services.languageDetector&&!this.services.languageDetector.async?o(this.services.languageDetector.detect()):!t&&this.services.languageDetector&&this.services.languageDetector.async?this.services.languageDetector.detect.length===0?this.services.languageDetector.detect().then(o):this.services.languageDetector.detect(o):o(t),r}getFixedT(t,s,r){const a=(i,o,...l)=>{let c;typeof o!="object"?c=this.options.overloadTranslationOptionHandler([i,o].concat(l)):c={...o},c.lng=c.lng||a.lng,c.lngs=c.lngs||a.lngs,c.ns=c.ns||a.ns,c.keyPrefix!==""&&(c.keyPrefix=c.keyPrefix||r||a.keyPrefix);const d={...this.options,...c};typeof c.keyPrefix=="function"&&(c.keyPrefix=ll(c.keyPrefix,d));const u=this.options.keySeparator||".";let m;return c.keyPrefix&&Array.isArray(i)?m=i.map(p=>(typeof p=="function"&&(p=ll(p,d)),`${c.keyPrefix}${u}${p}`)):(typeof i=="function"&&(i=ll(i,d)),m=c.keyPrefix?`${c.keyPrefix}${u}${i}`:i),this.t(m,c)};return et(t)?a.lng=t:a.lngs=t,a.ns=s,a.keyPrefix=r,a}t(...t){var s;return(s=this.translator)==null?void 0:s.translate(...t)}exists(...t){var s;return(s=this.translator)==null?void 0:s.exists(...t)}setDefaultNamespace(t){this.options.defaultNS=t}hasLoadedNamespace(t,s={}){if(!this.isInitialized)return this.logger.warn("hasLoadedNamespace: i18next was not initialized",this.languages),!1;
740if(!this.languages||!this.languages.length)return this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty",this.languages),!1;const r=s.lng||this.resolvedLanguage||this.languages[0],a=this.options?this.options.fallbackLng:!1,i=this.languages[this.languages.length-1];if(r.toLowerCase()==="cimode")return!0;const o=(l,c)=>{const d=this.services.backendConnector.state[`${l}|${c}`];return d===-1||d===0||d===2};if(s.precheck){const l=s.precheck(this,o);if(l!==void 0)return l}return!!(this.hasResourceBundle(r,t)||!this.services.backendConnector.backend||this.options.resources&&!this.options.partialBundledLanguages||o(r,t)&&(!a||o(i,t)))}loadNamespaces(t,s){const r=jc();return this.options.ns?(et(t)&&(t=[t]),t.forEach(a=>{this.options.ns.includes(a)||this.options.ns.push(a)}),this.loadResources(a=>{r.resolve(),s&&s(a)}),r):(s&&s(),Promise.resolve())}loadLanguages(t,s){const r=jc();et(t)&&(t=[t]);const a=this.options.preload||[],i=t.filter(o=>!a.includes(o)&&this.services.languageUtils.isSupportedCode(o));return i.length?(this.options.preload=a.concat(i),this.loadResources(o=>{r.resolve(),s&&s(o)}),r):(s&&s(),Promise.resolve())}dir(t){var a,i;if(t||(t=this.resolvedLanguage||(((a=this.languages)==null?void 0:a.length)>0?this.languages[0]:this.language)),!t)return"rtl";try{const o=new Intl.Locale(t);if(o&&o.getTextInfo){const l=o.getTextInfo();if(l&&l.direction)return l.direction}}catch{}const s=["ar","shu","sqr","ssh","xaa","yhd","yud","aao","abh","abv","acm","acq","acw","acx","acy","adf","ads","aeb","aec","afb","ajp","apc","apd","arb","arq","ars","ary","arz","auz","avl","ayh","ayl","ayn","ayp","bbz","pga","he","iw","ps","pbt","pbu","pst","prp","prd","ug","ur","ydd","yds","yih","ji","yi","hbo","men","xmn","fa","jpr","peo","pes","prs","dv","sam","ckb"],r=((i=this.services)==null?void 0:i.languageUtils)||new Uw(Cf());return t.toLowerCase().indexOf("-latn")>1?"ltr":s.includes(r.getLanguagePartFromCode(t))||t.toLowerCase().indexOf("-arab")>1?"rtl":"ltr"}static createInstance(t={},s){const r=new Zc(t,s);return r.createInstance=Zc.createInstance,r}cloneInstance(t={},s=th){const r=t.forkResourceStore;r&&delete t.forkResourceStore;const a={...this.options,...t,isClone:!0},i=new Zc(a);if((t.debug!==void 0||t.prefix!==void 0)&&(i.logger=i.logger.clone(t)),["store","services","language"].forEach(l=>{i[l]=this[l]}),i.services={...this.services},i.services.utils={hasLoadedNamespace:i.hasLoadedNamespace.bind(i)},r){const l=Object.keys(this.store.data).reduce((c,d)=>(c[d]={...this.store.data[d]},c[d]=Object.keys(c[d]).reduce((u,m)=>(u[m]={...c[d][m]},u),c[d]),c),{});i.store=new Fw(l,a),i.services.resourceStore=i.store}if(t.interpolation){const c={...Cf().interpolation,...this.options.interpolation,...t.interpolation},d={...a,interpolation:c};i.services.interpolator=new Hw(d)}return i.translator=new vm(i.services,a),i.translator.on("*",(l,...c)=>{i.emit(l,...c)}),i.init(a,s),i.translator.options=a,i.translator.backendConnector.services.utils={hasLoadedNamespace:i.hasLoadedNamespace.bind(i)},i}toJSON(){return{options:this.options,store:this.store,language:this.language,languages:this.languages,resolvedLanguage:this.resolvedLanguage}}}const xs=Zc.createInstance();xs.createInstance;xs.dir;xs.init;xs.loadResources;xs.reloadResources;xs.use;xs.changeLanguage;xs.getFixedT;xs.t;xs.exists;xs.setDefaultNamespace;xs.hasLoadedNamespace;xs.loadNamespaces;xs.loadLanguages;const aM=(e,t,s,r)=>{var i,o,l,c;const a=[s,{code:t,...r||{}}];if((o=(i=e==null?void 0:e.services)==null?void 0:i.logger)!=null&&o.forward)return e.services.logger.forward(a,"warn","react-i18next::",!0);to(a[0])&&(a[0]=`react-i18next:: ${a[0]}`),(c=(l=e==null?void 0:e.services)==null?void 0:l.logger)!=null&&c.warn?e.services.logger.warn(...a):console!=null&&console.warn&&console.warn(...a)},Yw={},Ix=(e,t,s,r)=>{to(s)&&Yw[s]||(to(s)&&(Yw[s]=new Date),aM(e,t,s,r))},bS=(e,t)=>()=>{if(e.isInitialized)t();else{const s=()=>{setTimeout(()=>{e.off("initialized",s)},0),t()};e.on("initialized",s)}},Ox=(e,t,s)=>{e.loadNamespaces(t,bS(e,s))},Kw=(e,t,s,r)=>{if(to(s)&&(s=[s]),e.options.preload&&e.options.preload.indexOf(t)>-1)return Ox(e,s,r);
740s.forEach(a=>{e.options.ns.indexOf(a)<0&&e.options.ns.push(a)}),e.loadLanguages(t,bS(e,r))},iM=(e,t,s={})=>!t.languages||!t.languages.length?(Ix(t,"NO_LANGUAGES","i18n.languages were undefined or empty",{languages:t.languages}),!0):t.hasLoadedNamespace(e,{lng:s.lng,precheck:(r,a)=>{if(s.bindI18n&&s.bindI18n.indexOf("languageChanging")>-1&&r.services.backendConnector.backend&&r.isLanguageChangingTo&&!a(r.isLanguageChangingTo,e))return!1}}),to=e=>typeof e=="string",oM=e=>typeof e=="object"&&e!==null,lM=/&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34|nbsp|#160|copy|#169|reg|#174|hellip|#8230|#x2F|#47);/g,cM={"&amp;":"&","&#38;":"&","&lt;":"<","&#60;":"<","&gt;":">","&#62;":">","&apos;":"'","&#39;":"'","&quot;":'"',"&#34;":'"',"&nbsp;":" ","&#160;":" ","&copy;":"©","&#169;":"©","&reg;":"®","&#174;":"®","&hellip;":"…","&#8230;":"…","&#x2F;":"/","&#47;":"/"},dM=e=>cM[e],uM=e=>e.replace(lM,dM);let Dx={bindI18n:"languageChanged",bindI18nStore:"",transEmptyNodeValue:"",transSupportBasicHtmlNodes:!0,transWrapTextNodes:"",transKeepBasicHtmlNodesFor:["br","strong","i","p"],useSuspense:!0,unescape:uM,transDefaultProps:void 0};const hM=(e={})=>{Dx={...Dx,...e}},mM=()=>Dx;let wS;const pM=e=>{wS=e},fM=()=>wS,gM={type:"3rdParty",init(e){hM(e.options.react),pM(e)}},xM=h.createContext();class vM{constructor(){this.usedNamespaces={}}addUsedNamespaces(t){t.forEach(s=>{this.usedNamespaces[s]||(this.usedNamespaces[s]=!0)})}getUsedNamespaces(){return Object.keys(this.usedNamespaces)}}var jS={exports:{}},_S={};/**
741 * @license React
742 * use-sync-external-store-shim.production.js
743 *
744 * Copyright (c) Meta Platforms, Inc. and affiliates.
745 *
746 * This source code is licensed under the MIT license found in the
747 * LICENSE file in the root directory of this source tree.
748 */var Dl=h;function yM(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var bM=typeof Object.is=="function"?Object.is:yM,wM=Dl.useState,jM=Dl.useEffect,_M=Dl.useLayoutEffect,kM=Dl.useDebugValue;function NM(e,t){var s=t(),r=wM({inst:{value:s,getSnapshot:t}}),a=r[0].inst,i=r[1];return _M(function(){a.value=s,a.getSnapshot=t,Tf(a)&&i({inst:a})},[e,s,t]),jM(function(){return Tf(a)&&i({inst:a}),e(function(){Tf(a)&&i({inst:a})})},[e]),kM(s),s}function Tf(e){var t=e.getSnapshot;e=e.value;try{var s=t();return!bM(e,s)}catch{return!0}}function SM(e,t){return t()}var CM=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?SM:NM;_S.useSyncExternalStore=Dl.useSyncExternalStore!==void 0?Dl.useSyncExternalStore:CM;jS.exports=_S;var TM=jS.exports;const PM=(e,t)=>{if(to(t))return t;if(oM(t)&&to(t.defaultValue))return t.defaultValue;if(typeof e=="function")return"";if(Array.isArray(e)){const s=e[e.length-1];return typeof s=="function"?"":s}return e},EM={t:PM,ready:!1},AM=()=>()=>{},Oe=(e,t={})=>{var T,C,B;const{i18n:s}=t,{i18n:r,defaultNS:a}=h.useContext(xM)||{},i=s||r||fM();i&&!i.reportNamespaces&&(i.reportNamespaces=new vM),i||Ix(i,"NO_I18NEXT_INSTANCE","useTranslation: You will need to pass in an i18next instance by using initReactI18next");const o=h.useMemo(()=>{var E;return{...mM(),...(E=i==null?void 0:i.options)==null?void 0:E.react,...t}},[i,t]),{useSuspense:l,keyPrefix:c}=o,d=e||a||((T=i==null?void 0:i.options)==null?void 0:T.defaultNS),u=to(d)?[d]:d||["translation"],m=h.useMemo(()=>u,u);(B=(C=i==null?void 0:i.reportNamespaces)==null?void 0:C.addUsedNamespaces)==null||B.call(C,m);const p=h.useRef(0),f=h.useCallback(E=>{if(!i)return AM;const{bindI18n:H,bindI18nStore:z}=o,ne=()=>{p.current+=1,E()};return H&&i.on(H,ne),z&&i.store.on(z,ne),()=>{H&&H.split(" ").forEach(V=>i.off(V,ne)),z&&z.split(" ").forEach(V=>i.store.off(V,ne))}},[i,o]),g=h.useRef(),x=h.useCallback(()=>{if(!i)return EM;const E=!!(i.isInitialized||i.initializedStoreOnce)&&m.every(R=>iM(R,i,o)),H=t.lng||i.language,z=p.current,ne=g.current;if(ne&&ne.ready===E&&ne.lng===H&&ne.keyPrefix===c&&ne.revision===z)return ne;const te={t:i.getFixedT(H,o.nsMode==="fallback"?m:m[0],c),ready:E,lng:H,keyPrefix:c,revision:z};return g.current=te,te},[i,m,c,o,t.lng]),[b,v]=h.useState(0),{t:y,ready:w}=TM.useSyncExternalStore(f,x,x);h.useEffect(()=>{if(i&&!w&&!l){const E=()=>v(H=>H+1);t.lng?Kw(i,t.lng,m,E):Ox(i,m,E)}},[i,t.lng,m,w,l,b]);const j=i||{},_=h.useRef(null),N=h.useRef(),k=E=>{const H=Object.getOwnPropertyDescriptors(E);H.__original&&delete H.__original;const z=Object.create(Object.getPrototypeOf(E),H);if(!Object.prototype.hasOwnProperty.call(z,"__original"))try{Object.defineProperty(z,"__original",{value:E,writable:!1,enumerable:!1,
748configurable:!1})}catch{}return z},S=h.useMemo(()=>{const E=j,H=E==null?void 0:E.language;let z=E;E&&(_.current&&_.current.__original===E?N.current!==H?(z=k(E),_.current=z,N.current=H):z=_.current:(z=k(E),_.current=z,N.current=H));const ne=!w&&!l?(...te)=>(Ix(i,"USE_T_BEFORE_READY","useTranslation: t was called before ready. When using useSuspense: false, make sure to check the ready flag before using t."),y(...te)):y,V=[ne,z,w];return V.t=ne,V.i18n=z,V.ready=w,V},[y,j,w,j.resolvedLanguage,j.language,j.languages]);if(i&&l&&!w)throw new Promise(E=>{const H=()=>E();t.lng?Kw(i,t.lng,m,H):Ox(i,m,H)});return S};function Or({children:e}){const{profile:t}=st(),s=fi(),{t:r}=Oe("common"),[a,i]=h.useState("loading");return h.useEffect(()=>{if(!(t!=null&&t.workspace_id)){i("loading");return}I.from("personas").select("id",{count:"exact",head:!0}).eq("workspace_id",t.workspace_id).then(({count:o})=>{i((o??0)>0?"ok":"empty")})},[t==null?void 0:t.workspace_id]),a==="loading"?n.jsx("div",{className:"flex items-center justify-center min-h-[400px]",children:n.jsx(xe,{className:"w-6 h-6 animate-spin text-primary"})}):a==="empty"?n.jsxs("div",{className:"flex flex-col items-center justify-center min-h-[400px] text-center px-4 space-y-4",children:[n.jsx("div",{className:"w-14 h-14 rounded-2xl bg-primary/10 flex items-center justify-center",children:n.jsx(Xs,{className:"w-7 h-7 text-primary"})}),n.jsx("h2",{className:"font-heading font-bold text-xl text-foreground",children:r("personaGate.title")}),n.jsx("p",{className:"text-muted-foreground text-sm max-w-md",children:r("personaGate.description")}),n.jsxs(L,{variant:"hero",className:"gap-2",onClick:()=>s("/app/persona"),children:[r("personaGate.createButton")," ",n.jsx(Tr,{size:16})]})]}):n.jsx(n.Fragment,{children:e})}const Pf="smartblog_cookie_consent";function RM(){const{t:e}=Oe("common"),[t,s]=h.useState(!1);h.useEffect(()=>{if(!localStorage.getItem(Pf)){const o=setTimeout(()=>s(!0),1500);return()=>clearTimeout(o)}},[]);const r=()=>{localStorage.setItem(Pf,"accepted"),s(!1)},a=()=>{localStorage.setItem(Pf,"declined"),s(!1)};return t?n.jsx("div",{className:"fixed bottom-0 inset-x-0 z-50 p-4 pointer-events-none",children:n.jsx("div",{className:"max-w-lg mx-auto md:mx-4 md:ml-auto bg-card border border-border/60 rounded-2xl shadow-premium-lg p-5 pointer-events-auto animate-in slide-in-from-bottom-4 fade-in duration-500",children:n.jsxs("div",{className:"flex items-start gap-3",children:[n.jsx("div",{className:"w-9 h-9 rounded-xl bg-primary/10 flex items-center justify-center shrink-0 mt-0.5",children:n.jsx(d4,{size:16,className:"text-primary"})}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("p",{className:"text-sm text-foreground font-medium mb-1",children:e("cookie.title")}),n.jsxs("p",{className:"text-xs text-muted-foreground leading-relaxed",children:[e("cookie.desc")," ",n.jsx(zt,{to:"/cookies",className:"text-primary hover:underline",children:e("cookie.more")})]}),n.jsxs("div",{className:"flex items-center gap-2 mt-3",children:[n.jsx(L,{size:"sm",onClick:r,className:"h-8 text-xs px-4",children:e("cookie.accept")}),n.jsx(L,{size:"sm",variant:"outline",onClick:a,className:"h-8 text-xs px-4",children:e("cookie.decline")})]})]}),n.jsx("button",{onClick:a,className:"text-muted-foreground hover:text-foreground transition-colors shrink-0",children:n.jsx(Qn,{size:16})})]})})}):null}const $M="AW-18158846056";function LM(){const{pathname:e}=rr();return h.useEffect(()=>{if(e==="/admin"||e.startsWith("/admin/"))return;const t=window;t.dataLayer=t.dataLayer||[],t.gtag=function(){t.dataLayer.push(arguments)},t.gtag("js",new Date),t.gtag("config",$M,{send_page_view:!0})},[e]),null}const IM=2e3,kS=20,Qw=5e3,OM=200;let $i=[],Ef=null;const _c=new Map;let Jw=!1;function DM(e){return e.fingerprint??`${e.severity}|${e.source}|${e.message.slice(0,200)}`}function MM(e){const t=Date.now(),s=_c.get(e);if(s&&t-s<Qw)return!0;if(_c.set(e,t),_c.size>500){const r=t-Qw*4;for(const[a,i]of _c)i<r&&_c.delete(a)}return!1}function NS(){Ef==null&&(Ef=window.setTimeout(()=>{Ef=null,$y()},IM))}async function $y(){if($i.length===0)return;const e=$i.splice(0,kS);try{await I.functions.invoke("log-event",{body:{events:e}})}catch(t){console.warn("[error-logger] flush failed",t)}$i.length>0&&NS()}function Mx(e){try{const t=DM(e);if(MM(t))return;$i.length>=OM&&$i.shift(),$i.push({...e,fingerprint:t}),$i.length>=kS?$y():NS()}catch{}}function zM(e,t,s){const r=t;Mx({severity:"error",source:e,message:(r==null?void 0:r.message)??String(t??"unknown_error"),stack:(r==null?void 0:r.stack)??null,...s})}function FM(){Jw||(Jw=!0,window.addEventListener("error",e=>{var t;Mx({severity:"error",source:"frontend",category:"window.onerror",message:e.message||"window.onerror",stack:((t=e.error)==null?void 0:t.stack)??null,context_json:{url:window.location.href,filename:e.filename,lineno:e.lineno,colno:e.colno,user_agent:navigator.userAgent}})}),window.addEventListener("unhandledrejection",e=>{const t=e.reason,s=typeof t=="string"?t:(t==null?void 0:t.message)??"unhandledrejection";Mx({severity:"error",source:"frontend",category:"unhandledrejection",message:s,stack:typeof t=="object"?(t==null?void 0:t.stack)??null:null,context_json:{url:window.location.href,user_agent:navigator.userAgent}})}),window.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&$y()}))}class UM extends h.Component{constructor(){super(...arguments);Cu(this,"state",{error:null});Cu(this,"handleRetry",()=>{this.setState({error:null})});Cu(this,"handleGoHome",()=>{this.setState({error:null}),window.location.href=this.props.fallbackRoute??"/app"})}static getDerivedStateFromError(s){return{error:s}}componentDidCatch(s,r){console.error("[ErrorBoundary]",s,r.componentStack),zM("frontend",s,{category:"react.ErrorBoundary",context_json:{url:typeof window<"u"?window.location.href:null,component_stack:r.componentStack??null}})}
vendor: 5,830 bytes, line 748
748render(){if(!this.state.error)return this.props.children;const s=r=>xs.t(r,{ns:"common"});return n.jsxs("div",{className:"flex flex-col items-center justify-center min-h-[60vh] gap-4 p-8 text-center",children:[n.jsx(ft,{className:"w-12 h-12 text-destructive"}),n.jsx("h2",{className:"text-xl font-semibold text-foreground",children:s("errorBoundary.title")}),n.jsx("p",{className:"text-muted-foreground max-w-md text-sm",children:this.state.error.message||s("errorBoundary.fallback")}),n.jsxs("div",{className:"flex gap-3 mt-2",children:[n.jsxs(L,{variant:"outline",onClick:this.handleRetry,children:[n.jsx(ss,{className:"w-4 h-4 mr-2"}),s("errorBoundary.retry")]}),n.jsx(L,{onClick:this.handleGoHome,children:s("errorBoundary.home")})]})]})}}const Af=768;function BM(){const[e,t]=h.useState(void 0);return h.useEffect(()=>{const s=window.matchMedia(`(max-width: ${Af-1}px)`),r=()=>{t(window.innerWidth<Af)};return s.addEventListener("change",r),t(window.innerWidth<Af),()=>s.removeEventListener("change",r)},[]),!!e}const gt=h.forwardRef(({className:e,type:t,...s},r)=>n.jsx("input",{type:t,className:_e("flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",e),ref:r,...s}));gt.displayName="Input";var VM="Separator",Zw="horizontal",qM=["horizontal","vertical"],SS=h.forwardRef((e,t)=>{const{decorative:s,orientation:r=Zw,...a}=e,i=HM(r)?r:Zw,l=s?{role:"none"}:{"aria-orientation":i==="vertical"?i:void 0,role:"separator"};return n.jsx(qe.div,{"data-orientation":i,...l,...a,ref:t})});SS.displayName=VM;function HM(e){return qM.includes(e)}var CS=SS;const TS=h.forwardRef(({className:e,orientation:t="horizontal",decorative:s=!0,...r},a)=>n.jsx(CS,{ref:a,decorative:s,orientation:t,className:_e("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",e),...r}));TS.displayName=CS.displayName;var Rf="focusScope.autoFocusOnMount",$f="focusScope.autoFocusOnUnmount",Xw={bubbles:!1,cancelable:!0},WM="FocusScope",mu=h.forwardRef((e,t)=>{const{loop:s=!1,trapped:r=!1,onMountAutoFocus:a,onUnmountAutoFocus:i,...o}=e,[l,c]=h.useState(null),d=Zn(a),u=Zn(i),m=h.useRef(null),p=bt(t,x=>c(x)),f=h.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;h.useEffect(()=>{if(r){let x=function(w){if(f.paused||!l)return;const j=w.target;l.contains(j)?m.current=j:ya(m.current,{select:!0})},b=function(w){if(f.paused||!l)return;const j=w.relatedTarget;j!==null&&(l.contains(j)||ya(m.current,{select:!0}))},v=function(w){if(document.activeElement===document.body)for(const _ of w)_.removedNodes.length>0&&ya(l)};document.addEventListener("focusin",x),document.addEventListener("focusout",b);const y=new MutationObserver(v);return l&&y.observe(l,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",x),document.removeEventListener("focusout",b),y.disconnect()}}},[r,l,f.paused]),h.useEffect(()=>{if(l){t1.add(f);const x=document.activeElement;if(!l.contains(x)){const v=new CustomEvent(Rf,Xw);l.addEventListener(Rf,d),l.dispatchEvent(v),v.defaultPrevented||(GM(ZM(PS(l)),{select:!0}),document.activeElement===x&&ya(l))}return()=>{l.removeEventListener(Rf,d),setTimeout(()=>{const v=new CustomEvent($f,Xw);l.addEventListener($f,u),l.dispatchEvent(v),v.defaultPrevented||ya(x??document.body,{select:!0}),l.removeEventListener($f,u),t1.remove(f)},0)}}},[l,d,u,f]);const g=h.useCallback(x=>{if(!s&&!r||f.paused)return;const b=x.key==="Tab"&&!x.altKey&&!x.ctrlKey&&!x.metaKey,v=document.activeElement;if(b&&v){const y=x.currentTarget,[w,j]=YM(y);w&&j?!x.shiftKey&&v===j?(x.preventDefault(),s&&ya(w,{select:!0})):x.shiftKey&&v===w&&(x.preventDefault(),s&&ya(j,{select:!0})):v===y&&x.preventDefault()}},[s,r,f.paused]);return n.jsx(qe.div,{tabIndex:-1,...o,ref:p,onKeyDown:g})});mu.displayName=WM;function GM(e,{select:t=!1}={}){const s=document.activeElement;for(const r of e)if(ya(r,{select:t}),document.activeElement!==s)return}function YM(e){const t=PS(e),s=e1(t,e),r=e1(t.reverse(),e);return[s,r]}function PS(e){const t=[],s=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const a=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||a?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;s.nextNode();)t.push(s.currentNode);return t}function e1(e,t){for(const s of e)if(!KM(s,{upTo:t}))return s}function KM(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function QM(e){return e instanceof HTMLInputElement&&"select"in e}function ya(e,{select:t=!1}={}){if(e&&e.focus){const s=document.activeElement;e.focus({preventScroll:!0}),e!==s&&QM(e)&&t&&e.select()}}var t1=JM();function JM(){let e=[];return{add(t){const s=e[0];t!==s&&(s==null||s.pause()),e=s1(e,t),e.unshift(t)},remove(t){var s;e=s1(e,t),(s=e[0])==null||s.resume()}}}function s1(e,t){const s=[...e],r=s.indexOf(t);return r!==-1&&s.splice(r,1),s}function ZM(e){return e.filter(t=>t.tagName!=="A")}var Lf=0;function pp(){h.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??n1()),document.body.insertAdjacentElement("beforeend",e[1]??n1()),Lf++,()=>{Lf===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),Lf--}},[])}function n1(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.
vendor: 4,904 bytes, lines 748-763
748style.position="fixed",e.style.pointerEvents="none",e}var Nh="right-scroll-bar-position",Sh="width-before-scroll-bar",XM="with-scroll-bars-hidden",ez="--removed-body-scroll-bar-size";function If(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function tz(e,t){var s=h.useState(function(){return{value:e,callback:t,facade:{get current(){return s.value},set current(r){var a=s.value;a!==r&&(s.value=r,s.callback(r,a))}}}})[0];return s.callback=t,s.facade}var sz=typeof window<"u"?h.useLayoutEffect:h.useEffect,r1=new WeakMap;function nz(e,t){var s=tz(null,function(r){return e.forEach(function(a){return If(a,r)})});return sz(function(){var r=r1.get(s);if(r){var a=new Set(r),i=new Set(e),o=s.current;a.forEach(function(l){i.has(l)||If(l,null)}),i.forEach(function(l){a.has(l)||If(l,o)})}r1.set(s,e)},[e]),s}function rz(e){return e}function az(e,t){t===void 0&&(t=rz);var s=[],r=!1,a={read:function(){if(r)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return s.length?s[s.length-1]:e},useMedium:function(i){var o=t(i,r);return s.push(o),function(){s=s.filter(function(l){return l!==o})}},assignSyncMedium:function(i){for(r=!0;s.length;){var o=s;s=[],o.forEach(i)}s={push:function(l){return i(l)},filter:function(){return s}}},assignMedium:function(i){r=!0;var o=[];if(s.length){var l=s;s=[],l.forEach(i),o=s}var c=function(){var u=o;o=[],u.forEach(i)},d=function(){return Promise.resolve().then(c)};d(),s={push:function(u){o.push(u),d()},filter:function(u){return o=o.filter(u),s}}}};return a}function iz(e){e===void 0&&(e={});var t=az(null);return t.options=vr({async:!0,ssr:!1},e),t}var ES=function(e){var t=e.sideCar,s=ac(e,["sideCar"]);if(!t)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var r=t.read();if(!r)throw new Error("Sidecar medium not found");return h.createElement(r,vr({},s))};ES.isSideCarExport=!0;function oz(e,t){return e.useMedium(t),ES}var AS=iz(),Of=function(){},fp=h.forwardRef(function(e,t){var s=h.useRef(null),r=h.useState({onScrollCapture:Of,onWheelCapture:Of,onTouchMoveCapture:Of}),a=r[0],i=r[1],o=e.forwardProps,l=e.children,c=e.className,d=e.removeScrollBar,u=e.enabled,m=e.shards,p=e.sideCar,f=e.noRelative,g=e.noIsolation,x=e.inert,b=e.allowPinchZoom,v=e.as,y=v===void 0?"div":v,w=e.gapMode,j=ac(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),_=p,N=nz([s,t]),k=vr(vr({},j),a);return h.createElement(h.Fragment,null,u&&h.createElement(_,{sideCar:AS,removeScrollBar:d,shards:m,noRelative:f,noIsolation:g,inert:x,setCallbacks:i,allowPinchZoom:!!b,lockRef:s,gapMode:w}),o?h.cloneElement(h.Children.only(l),vr(vr({},k),{ref:N})):h.createElement(y,vr({},k,{className:c,ref:N}),l))});fp.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1};fp.classNames={fullWidth:Sh,zeroRight:Nh};var lz=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function cz(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=lz();return t&&e.setAttribute("nonce",t),e}function dz(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function uz(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var hz=function(){var e=0,t=null;return{add:function(s){e==0&&(t=cz())&&(dz(t,s),uz(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},mz=function(){var e=hz();return function(t,s){h.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&s])}},RS=function(){var e=mz(),t=function(s){var r=s.styles,a=s.dynamic;return e(r,a),null};return t},pz={left:0,top:0,right:0,gap:0},Df=function(e){return parseInt(e||"",10)||0},fz=function(e){var t=window.getComputedStyle(document.body),s=t[e==="padding"?"paddingLeft":"marginLeft"],r=t[e==="padding"?"paddingTop":"marginTop"],a=t[e==="padding"?"paddingRight":"marginRight"];return[Df(s),Df(r),Df(a)]},gz=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return pz;var t=fz(e),s=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-s+t[2]-t[0])}},xz=RS(),cl="data-scroll-locked",vz=function(e,t,s,r){var a=e.left,i=e.top,o=e.right,l=e.gap;return s===void 0&&(s="margin"),`
749  .`.concat(XM,` {
750   overflow: hidden `).concat(r,`;
751   padding-right: `).concat(l,"px ").concat(r,`;
752  }
753  body[`).concat(cl,`] {
754    overflow: hidden `).concat(r,`;
755    overscroll-behavior: contain;
756    `).concat([t&&"position: relative ".concat(r,";"),s==="margin"&&`
757    padding-left: `.concat(a,`px;
758    padding-top: `).concat(i,`px;
759    padding-right: `).concat(o,`px;
760    margin-left:0;
761    margin-top:0;
762    margin-right: `).concat(l,"px ").concat(r,`;
763    `),s==="padding"&&"padding-right: ".concat(l,"px ").concat(r,";
763")].filter(Boolean).join(""),`
764  }
765  
766  .`).concat(Nh,` {
767    right: `).concat(l,"px ").concat(r,`;
768  }
769  
770  .`).concat(Sh,` {
771    margin-right: `).concat(l,"px ").concat(r,`;
772  }
773  
774  .`).concat(Nh," .").concat(Nh,` {
775    right: 0 `).concat(r,`;
776  }
777  
778  .`).concat(Sh," .").concat(Sh,` {
779    margin-right: 0 `).concat(r,`;
780  }
781  
782  body[`).concat(cl,`] {
783    `).concat(ez,": ").concat(l,`px;
784  }
785`)},a1=function(){var e=parseInt(document.body.getAttribute(cl)||"0",10);return isFinite(e)?e:0},yz=function(){h.useEffect(function(){return document.body.setAttribute(cl,(a1()+1).toString()),function(){var e=a1()-1;e<=0?document.body.removeAttribute(cl):document.body.setAttribute(cl,e.toString())}},[])},bz=function(e){var t=e.noRelative,s=e.noImportant,r=e.gapMode,a=r===void 0?"margin":r;yz();var i=h.useMemo(function(){return gz(a)},[a]);return h.createElement(xz,{styles:vz(i,!t,a,s?"":"!important")})},zx=!1;if(typeof window<"u")try{var sh=Object.defineProperty({},"passive",{get:function(){return zx=!0,!0}});window.addEventListener("test",sh,sh),window.removeEventListener("test",sh,sh)}catch{zx=!1}var _o=zx?{passive:!1}:!1,wz=function(e){return e.tagName==="TEXTAREA"},$S=function(e,t){if(!(e instanceof Element))return!1;var s=window.getComputedStyle(e);return s[t]!=="hidden"&&!(s.overflowY===s.overflowX&&!wz(e)&&s[t]==="visible")},jz=function(e){return $S(e,"overflowY")},_z=function(e){return $S(e,"overflowX")},i1=function(e,t){var s=t.ownerDocument,r=t;do{typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host);var a=LS(e,r);if(a){var i=IS(e,r),o=i[1],l=i[2];if(o>l)return!0}r=r.parentNode}while(r&&r!==s.body);return!1},kz=function(e){var t=e.scrollTop,s=e.scrollHeight,r=e.clientHeight;return[t,s,r]},Nz=function(e){var t=e.scrollLeft,s=e.scrollWidth,r=e.clientWidth;return[t,s,r]},LS=function(e,t){return e==="v"?jz(t):_z(t)},IS=function(e,t){return e==="v"?kz(t):Nz(t)},Sz=function(e,t){return e==="h"&&t==="rtl"?-1:1},Cz=function(e,t,s,r,a){var i=Sz(e,window.getComputedStyle(t).direction),o=i*r,l=s.target,c=t.contains(l),d=!1,u=o>0,m=0,p=0;do{if(!l)break;var f=IS(e,l),g=f[0],x=f[1],b=f[2],v=x-b-i*g;(g||v)&&LS(e,l)&&(m+=v,p+=g);var y=l.parentNode;l=y&&y.nodeType===Node.DOCUMENT_FRAGMENT_NODE?y.host:y}while(!c&&l!==document.body||c&&(t.contains(l)||t===l));return(u&&(Math.abs(m)<1||!a)||!u&&(Math.abs(p)<1||!a))&&(d=!0),d},nh=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},o1=function(e){return[e.deltaX,e.deltaY]},l1=function(e){return e&&"current"in e?e.current:e},Tz=function(e,t){return e[0]===t[0]&&e[1]===t[1]},Pz=function(e){return`
786  .block-interactivity-`.concat(e,` {pointer-events: none;}
787  .allow-interactivity-`).concat(e,` {pointer-events: all;}
788`)},Ez=0,ko=[];function Az(e){var t=h.useRef([]),s=h.useRef([0,0]),r=h.useRef(),a=h.useState(Ez++)[0],i=h.useState(RS)[0],o=h.useRef(e);h.useEffect(function(){o.current=e},[e]),h.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(a));var x=e3([e.lockRef.current],(e.shards||[]).map(l1),!0).filter(Boolean);return x.forEach(function(b){return b.classList.add("allow-interactivity-".concat(a))}),function(){document.body.classList.remove("block-interactivity-".concat(a)),x.forEach(function(b){return b.classList.remove("allow-interactivity-".concat(a))})}}},[e.inert,e.lockRef.current,e.shards]);var l=h.useCallback(function(x,b){if("touches"in x&&x.touches.length===2||x.type==="wheel"&&x.ctrlKey)return!o.current.allowPinchZoom;var v=nh(x),y=s.current,w="deltaX"in x?x.deltaX:y[0]-v[0],j="deltaY"in x?x.deltaY:y[1]-v[1],_,N=x.target,k=Math.abs(w)>Math.abs(j)?"h":"v";if("touches"in x&&k==="h"&&N.type==="range")return!1;var S=i1(k,N);if(!S)return!0;if(S?_=k:(_=k==="v"?"h":"v",S=i1(k,N)),!S)return!1;if(!r.current&&"changedTouches"in x&&(w||j)&&(r.current=_),!_)return!0;var T=r.current||_;return Cz(T,b,x,T==="h"?w:j,!0)},[]),c=h.useCallback(function(x){var b=x;if(!(!ko.length||ko[ko.length-1]!==i)){var v="deltaY"in b?o1(b):nh(b),y=t.current.filter(function(_){return _.name===b.type&&(_.target===b.target||b.target===_.shadowParent)&&Tz(_.delta,v)}
vendor: 4,137 bytes, line 788
788)[0];if(y&&y.should){b.cancelable&&b.preventDefault();return}if(!y){var w=(o.current.shards||[]).map(l1).filter(Boolean).filter(function(_){return _.contains(b.target)}),j=w.length>0?l(b,w[0]):!o.current.noIsolation;j&&b.cancelable&&b.preventDefault()}}},[]),d=h.useCallback(function(x,b,v,y){var w={name:x,delta:b,target:v,should:y,shadowParent:Rz(v)};t.current.push(w),setTimeout(function(){t.current=t.current.filter(function(j){return j!==w})},1)},[]),u=h.useCallback(function(x){s.current=nh(x),r.current=void 0},[]),m=h.useCallback(function(x){d(x.type,o1(x),x.target,l(x,e.lockRef.current))},[]),p=h.useCallback(function(x){d(x.type,nh(x),x.target,l(x,e.lockRef.current))},[]);h.useEffect(function(){return ko.push(i),e.setCallbacks({onScrollCapture:m,onWheelCapture:m,onTouchMoveCapture:p}),document.addEventListener("wheel",c,_o),document.addEventListener("touchmove",c,_o),document.addEventListener("touchstart",u,_o),function(){ko=ko.filter(function(x){return x!==i}),document.removeEventListener("wheel",c,_o),document.removeEventListener("touchmove",c,_o),document.removeEventListener("touchstart",u,_o)}},[]);var f=e.removeScrollBar,g=e.inert;return h.createElement(h.Fragment,null,g?h.createElement(i,{styles:Pz(a)}):null,f?h.createElement(bz,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function Rz(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const $z=oz(AS,Az);var pu=h.forwardRef(function(e,t){return h.createElement(fp,vr({},e,{ref:t,sideCar:$z}))});pu.classNames=fp.classNames;var Lz=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},No=new WeakMap,rh=new WeakMap,ah={},Mf=0,OS=function(e){return e&&(e.host||OS(e.parentNode))},Iz=function(e,t){return t.map(function(s){if(e.contains(s))return s;var r=OS(s);return r&&e.contains(r)?r:(console.error("aria-hidden",s,"in not contained inside",e,". Doing nothing"),null)}).filter(function(s){return!!s})},Oz=function(e,t,s,r){var a=Iz(t,Array.isArray(e)?e:[e]);ah[s]||(ah[s]=new WeakMap);var i=ah[s],o=[],l=new Set,c=new Set(a),d=function(m){!m||l.has(m)||(l.add(m),d(m.parentNode))};a.forEach(d);var u=function(m){!m||c.has(m)||Array.prototype.forEach.call(m.children,function(p){if(l.has(p))u(p);else try{var f=p.getAttribute(r),g=f!==null&&f!=="false",x=(No.get(p)||0)+1,b=(i.get(p)||0)+1;No.set(p,x),i.set(p,b),o.push(p),x===1&&g&&rh.set(p,!0),b===1&&p.setAttribute(s,"true"),g||p.setAttribute(r,"true")}catch(v){console.error("aria-hidden: cannot operate on ",p,v)}})};return u(t),l.clear(),Mf++,function(){o.forEach(function(m){var p=No.get(m)-1,f=i.get(m)-1;No.set(m,p),i.set(m,f),p||(rh.has(m)||m.removeAttribute(r),rh.delete(m)),f||m.removeAttribute(s)}),Mf--,Mf||(No=new WeakMap,No=new WeakMap,rh=new WeakMap,ah={})}},gp=function(e,t,s){s===void 0&&(s="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),a=Lz(e);return a?(r.push.apply(r,Array.from(a.querySelectorAll("[aria-live]"))),Oz(r,a,s,"aria-hidden")):function(){return null}},xp="Dialog",[DS,MS]=Is(xp),[Dz,ir]=DS(xp),zS=e=>{const{__scopeDialog:t,children:s,open:r,defaultOpen:a,onOpenChange:i,modal:o=!0}=e,l=h.useRef(null),c=h.useRef(null),[d,u]=tr({prop:r,defaultProp:a??!1,onChange:i,caller:xp});return n.jsx(Dz,{scope:t,triggerRef:l,contentRef:c,contentId:pn(),titleId:pn(),descriptionId:pn(),open:d,onOpenChange:u,onOpenToggle:h.useCallback(()=>u(m=>!m),[u]),modal:o,children:s})};zS.displayName=xp;var FS="DialogTrigger",US=h.forwardRef((e,t)=>{const{__scopeDialog:s,...r}=e,a=ir(FS,s),i=bt(t,a.triggerRef);return n.jsx(qe.button,{type:"button","aria-haspopup":"dialog","aria-expanded":a.open,"aria-controls":a.contentId,"data-state":Oy(a.open),...r,ref:i,onClick:Ee(e.onClick,a.onOpenToggle)})});US.displayName=FS;var Ly="DialogPortal",[Mz,BS]=DS(Ly,{forceMount:void 0}),VS=e=>{const{__scopeDialog:t,forceMount:s,children:r,container:a}=e,i=ir(Ly,t);return n.jsx(Mz,{scope:t,forceMount:s,children:h.Children.map(r,o=>n.jsx(sn,{present:s||i.open,children:n.jsx(ru,{asChild:!0,container:a,children:o})}))})};VS.displayName=Ly;var ym="DialogOverlay",qS=h.forwardRef((e,t)=>
vendor: 5,231 bytes, lines 788-792
788{const s=BS(ym,e.__scopeDialog),{forceMount:r=s.forceMount,...a}=e,i=ir(ym,e.__scopeDialog);return i.modal?n.jsx(sn,{present:r||i.open,children:n.jsx(Fz,{...a,ref:t})}):null});qS.displayName=ym;var zz=ni("DialogOverlay.RemoveScroll"),Fz=h.forwardRef((e,t)=>{const{__scopeDialog:s,...r}=e,a=ir(ym,s);return n.jsx(pu,{as:zz,allowPinchZoom:!0,shards:[a.contentRef],children:n.jsx(qe.div,{"data-state":Oy(a.open),...r,ref:t,style:{pointerEvents:"auto",...r.style}})})}),so="DialogContent",HS=h.forwardRef((e,t)=>{const s=BS(so,e.__scopeDialog),{forceMount:r=s.forceMount,...a}=e,i=ir(so,e.__scopeDialog);return n.jsx(sn,{present:r||i.open,children:i.modal?n.jsx(Uz,{...a,ref:t}):n.jsx(Bz,{...a,ref:t})})});HS.displayName=so;var Uz=h.forwardRef((e,t)=>{const s=ir(so,e.__scopeDialog),r=h.useRef(null),a=bt(t,s.contentRef,r);return h.useEffect(()=>{const i=r.current;if(i)return gp(i)},[]),n.jsx(WS,{...e,ref:a,trapFocus:s.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Ee(e.onCloseAutoFocus,i=>{var o;i.preventDefault(),(o=s.triggerRef.current)==null||o.focus()}),onPointerDownOutside:Ee(e.onPointerDownOutside,i=>{const o=i.detail.originalEvent,l=o.button===0&&o.ctrlKey===!0;(o.button===2||l)&&i.preventDefault()}),onFocusOutside:Ee(e.onFocusOutside,i=>i.preventDefault())})}),Bz=h.forwardRef((e,t)=>{const s=ir(so,e.__scopeDialog),r=h.useRef(!1),a=h.useRef(!1);return n.jsx(WS,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var o,l;(o=e.onCloseAutoFocus)==null||o.call(e,i),i.defaultPrevented||(r.current||(l=s.triggerRef.current)==null||l.focus(),i.preventDefault()),r.current=!1,a.current=!1},onInteractOutside:i=>{var c,d;(c=e.onInteractOutside)==null||c.call(e,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(a.current=!0));const o=i.target;((d=s.triggerRef.current)==null?void 0:d.contains(o))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&a.current&&i.preventDefault()}})}),WS=h.forwardRef((e,t)=>{const{__scopeDialog:s,trapFocus:r,onOpenAutoFocus:a,onCloseAutoFocus:i,...o}=e,l=ir(so,s),c=h.useRef(null),d=bt(t,c);return pp(),n.jsxs(n.Fragment,{children:[n.jsx(mu,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:a,onUnmountAutoFocus:i,children:n.jsx(tc,{role:"dialog",id:l.contentId,"aria-describedby":l.descriptionId,"aria-labelledby":l.titleId,"data-state":Oy(l.open),...o,ref:d,onDismiss:()=>l.onOpenChange(!1)})}),n.jsxs(n.Fragment,{children:[n.jsx(qz,{titleId:l.titleId}),n.jsx(Wz,{contentRef:c,descriptionId:l.descriptionId})]})]})}),Iy="DialogTitle",GS=h.forwardRef((e,t)=>{const{__scopeDialog:s,...r}=e,a=ir(Iy,s);return n.jsx(qe.h2,{id:a.titleId,...r,ref:t})});GS.displayName=Iy;var YS="DialogDescription",KS=h.forwardRef((e,t)=>{const{__scopeDialog:s,...r}=e,a=ir(YS,s);return n.jsx(qe.p,{id:a.descriptionId,...r,ref:t})});KS.displayName=YS;var QS="DialogClose",JS=h.forwardRef((e,t)=>{const{__scopeDialog:s,...r}=e,a=ir(QS,s);return n.jsx(qe.button,{type:"button",...r,ref:t,onClick:Ee(e.onClick,()=>a.onOpenChange(!1))})});JS.displayName=QS;function Oy(e){return e?"open":"closed"}var ZS="DialogTitleWarning",[Vz,XS]=hL(ZS,{contentName:so,titleName:Iy,docsSlug:"dialog"}),qz=({titleId:e})=>{const t=XS(ZS),s=`\`${t.contentName}\` requires a \`${t.titleName}\` for the component to be accessible for screen reader users.
789
790If you want to hide the \`${t.titleName}\`, you can wrap it with our VisuallyHidden component.
791
792For more information, see https://radix-ui.com/primitives/docs/components/${t.docsSlug}`;return h.useEffect(()=>{e&&(document.getElementById(e)||console.error(s))},[s,e]),null},Hz="DialogDescriptionWarning",Wz=({contentRef:e,descriptionId:t})=>{const r=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${XS(Hz).contentName}}.`;return h.useEffect(()=>{var i;const a=(i=e.current)==null?void 0:i.getAttribute("aria-describedby");t&&a&&(document.getElementById(t)||console.warn(r))},[r,e,t]),null},Dy=zS,Gz=US,My=VS,fu=qS,gu=HS,xu=GS,vu=KS,vp=JS;const Yz=Dy,Kz=My,eC=h.forwardRef(({className:e,...t},s)=>n.jsx(fu,{className:_e("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:s}));eC.displayName=fu.displayName;const Qz=hu("fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:duration-500",{variants:{side:{top:"inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",right:"inset-y-0 right-0 h-full w-3/4  border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm"}},defaultVariants:{side:"right"}}),tC=h.forwardRef(({side:e="right",className:t,children:s,...r},a)=>n.jsxs(Kz,{children:[n.jsx(eC,{}),n.jsxs(gu,{ref:a,className:_e(Qz({side:e}),t),...r,children:[s,n.jsxs(vp,{className:"absolute right-4 top-4 roun
792ded-sm opacity-70 ring-offset-background transition-opacity data-[state=open]:bg-secondary hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none",children:[n.jsx(Qn,{className:"h-4 w-4"}),n.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));tC.displayName=gu.displayName;const Jz=h.forwardRef(({className:e,...t},s)=>n.jsx(xu,{ref:s,className:_e("text-lg font-semibold text-foreground",e),...t}));Jz.displayName=xu.displayName;const Zz=h.forwardRef(({className:e,...t},s)=>n.jsx(vu,{ref:s,className:_e("text-sm text-muted-foreground",e),...t}));Zz.displayName=vu.displayName;function c1({className:e,...t}){return n.jsx("div",{className:_e("animate-pulse rounded-md bg-muted",e),...t})}const Xz="sidebar:state",eF=60*60*24*7,tF="16rem",sF="18rem",nF="3rem",rF="b",sC=h.createContext(null);function yu(){const e=h.useContext(sC);if(!e)throw new Error("useSidebar must be used within a SidebarProvider.");return e}const nC=h.forwardRef(({defaultOpen:e=!0,open:t,onOpenChange:s,className:r,style:a,children:i,...o},l)=>{const c=BM(),[d,u]=h.useState(!1),[m,p]=h.useState(e),f=t??m,g=h.useCallback(y=>{const w=typeof y=="function"?y(f):y;s?s(w):p(w),document.cookie=`${Xz}=${w}; path=/; max-age=${eF}`},[s,f]),x=h.useCallback(()=>c?u(y=>!y):g(y=>!y),[c,g,u]);h.useEffect(()=>{const y=w=>{w.key===rF&&(w.metaKey||w.ctrlKey)&&(w.preventDefault(),x())};return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)},[x]);const b=f?"expanded":"collapsed",v=h.useMemo(()=>({state:b,open:f,setOpen:g,isMobile:c,openMobile:d,setOpenMobile:u,toggleSidebar:x}),[b,f,g,c,d,u,x]);return n.jsx(sC.Provider,{value:v,children:n.jsx($N,{delayDuration:0,children:n.jsx("div",{style:{"--sidebar-width":tF,"--sidebar-width-icon":nF,...a},className:_e("group/sidebar-wrapper flex min-h-svh w-full has-[[data-variant=inset]]:bg-sidebar",r),ref:l,...o,children:i})})})});nC.displayName="SidebarProvider";const rC=h.forwardRef(({side:e="left",variant:t="sidebar",collapsible:s="offcanvas",className:r,children:a,...i},o)=>{const{isMobile:l,state:c,openMobile:d,setOpenMobile:u}=yu();return s==="none"?n.jsx("div",{className:_e("flex h-full w-[--sidebar-width] flex-col bg-sidebar text-sidebar-foreground",r),ref:o,...i,children:a}):l?n.jsx(Yz,{open:d,onOpenChange:u,...i,children:n.jsx(tC,{"data-sidebar":"sidebar","data-mobile":"true",className:"w-[--sidebar-width] bg-sidebar p-0 text-sidebar-foreground [&>button]:hidden",style:{"--sidebar-width":sF},side:e,children:n.jsx("div",{className:"flex h-full w-full flex-col",children:a})})}):n.jsxs("div",{ref:o,className:"group peer hidden text-sidebar-foreground md:block","data-state":c,"data-collapsible":c==="collapsed"?s:"","data-variant":t,"data-side":e,children:[n.jsx("div",{className:_e("relative h-svh w-[--sidebar-width] bg-transparent transition-[width] duration-200 ease-linear","group-data-[collapsible=offcanvas]:w-0","group-data-[side=right]:rotate-180",t==="floating"||t==="inset"?"group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4))]":"group-data-[collapsible=icon]:w-[--sidebar-width-icon]")}),n.jsx("div",{className:_e("fixed inset-y-0 z-10 hidden h-svh w-[--sidebar-width] transition-[left,right,width] duration-200 ease-linear md:flex",e==="left"?"left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]":"right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]",t==="floating"||t==="inset"?"p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4)_+2px)]":"group-data-[collapsible=icon]:w-[--sidebar-width-icon] group-data-[side=left]:border-r group-data-[side=right]:border-l",r),...i,children:n.jsx("div",{"data-sidebar":"sidebar",className:"flex h-full w-full flex-col bg-sidebar group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:border-sidebar-border group-data-[variant=floating]:shadow",children:a})})]})});rC.displayName="Sidebar";const aC=h.forwardRef(({className:e,onClick:t,...s},r)=>{const{toggleSidebar:a}=yu();return n.jsxs(L,{ref:r,"data-sidebar":"trigger",variant:"ghost",size:"icon",className:_e("h-7 w-7",e),onClick:i=>{t==null||t(i),a()},...s,children:[n.jsx(T4,{}),n.jsx("span",{className:"sr-only",children:"Toggle Sidebar"})]})});aC.displayName="SidebarTrigger";const aF=h.forwardRef(({className:e,...t},s)=>{const{toggleSidebar:r}=yu();return n.jsx("button",{ref:s,"data-sidebar":"rail","aria-label":"Toggle Sidebar",tabIndex:-1,onClick:r,title:"Toggle Sidebar",className:_e("absolute inset-y-0 z-20 hidden w-4 -translate-x-1/2 transition-all ease-linear after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] group-data-[side=left]:-right-4 group-data-[side=right]:left-0 hover:after:bg-sidebar-border sm:flex","[[data-side=left]_&]:cursor-w-resize [[data-side=right]_&]:cursor-e-resize","[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize","group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full group-data-[collapsible=offcanvas]:hover:bg-sidebar","[[data-side=left][data-collapsible=offcanvas]_&]:-right-2","[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",e),...t})});aF.displayName="SidebarRail";const iF=h.forwardRef(({className:e,...t},s)=>n.jsx("main",{ref:s,className:_e("relative flex min-h-svh flex-1 flex-col bg-background","peer-data-[variant=inset]:min-
792h-[calc(100svh-theme(spacing.4))] md:peer-data-[variant=inset]:m-2 md:peer-data-[state=collapsed]:peer-data-[variant=inset]:ml-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow",e),...t}));iF.displayName="SidebarInset";const oF=h.forwardRef(({className:e,...t},s)=>n.jsx(gt,{ref:s,"data-sidebar":"input",className:_e("h-8 w-full bg-background shadow-none focus-visible:ring-2 focus-visible:ring-sidebar-ring",e),...t}));oF.displayName="SidebarInput";const iC=h.forwardRef(({className:e,...t},s)=>n.jsx("div",{ref:s,"data-sidebar":"header",className:_e("flex flex-col gap-2 p-2",e),...t}));iC.displayName="SidebarHeader";const oC=h.forwardRef(({className:e,...t},s)=>n.jsx("div",{ref:s,"data-sidebar":"footer",className:_e("flex flex-col gap-2 p-2",e),...t}));oC.displayName="SidebarFooter";const lF=h.forwardRef(({className:e,...t},s)=>n.jsx(TS,{ref:s,"data-sidebar":"separator",className:_e("mx-2 w-auto bg-sidebar-border",e),...t}));lF.displayName="SidebarSeparator";const lC=h.forwardRef(({className:e,...t},s)=>n.jsx("div",{ref:s,"data-sidebar":"content",className:_e("flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",e),...t}));lC.displayName="SidebarContent";const cC=h.forwardRef(({className:e,...t},s)=>n.jsx("div",{ref:s,"data-sidebar":"group",className:_e("relative flex w-full min-w-0 flex-col p-2",e),...t}));cC.displayName="SidebarGroup";const dC=h.forwardRef(({className:e,asChild:t=!1,...s},r)=>{const a=t?ec:"div";return n.jsx(a,{ref:r,"data-sidebar":"group-label",className:_e("flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium text-sidebar-foreground/70 outline-none ring-sidebar-ring transition-[margin,opa] duration-200 ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0","group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",e),...s})});dC.displayName="SidebarGroupLabel";const cF=h.forwardRef(({className:e,asChild:t=!1,...s},r)=>{const a=t?ec:"button";return n.jsx(a,{ref:r,"data-sidebar":"group-action",className:_e("absolute right-3 top-3.5 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground outline-none ring-sidebar-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0","after:absolute after:-inset-2 after:md:hidden","group-data-[collapsible=icon]:hidden",e),...s})});cF.displayName="SidebarGroupAction";const uC=h.forwardRef(({className:e,...t},s)=>n.jsx("div",{ref:s,"data-sidebar":"group-content",className:_e("w-full text-sm",e),...t}));uC.displayName="SidebarGroupContent";const Ch=h.forwardRef(({className:e,...t},s)=>n.jsx("ul",{ref:s,"data-sidebar":"menu",className:_e("flex w-full min-w-0 flex-col gap-1",e),...t}));Ch.displayName="SidebarMenu";const Rc=h.forwardRef(({className:e,...t},s)=>n.jsx("li",{ref:s,"data-sidebar":"menu-item",className:_e("group/menu-item relative",e),...t}));Rc.displayName="SidebarMenuItem";const dF=hu("peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-none ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-[[data-sidebar=menu-action]]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:!size-8 group-data-[collapsible=icon]:!p-2 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",{variants:{variant:{default:"hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",outline:"bg-background shadow-[0_0_0_1px_hsl(var(--sidebar-border))] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_hsl(var(--sidebar-accent))]"},size:{default:"h-8 text-sm",sm:"h-7 text-xs",lg:"h-12 text-sm group-data-[collapsible=icon]:!p-0"}},defaultVariants:{variant:"default",size:"default"}}),$c=h.forwardRef(({asChild:e=!1,isActive:t=!1,variant:s="default",size:r="default",tooltip:a,className:i,...o},l)=>{const c=e?ec:"button",{isMobile:d,state:u}=yu(),m=n.jsx(c,{ref:l,"data-sidebar":"menu-button","data-size":r,"data-active":t,className:_e(dF({variant:s,size:r}),i),...o});
792return a?(typeof a=="string"&&(a={children:a}),n.jsxs(LN,{children:[n.jsx(IN,{asChild:!0,children:m}),n.jsx(fy,{side:"right",align:"center",hidden:u!=="collapsed"||d,...a})]})):m});$c.displayName="SidebarMenuButton";const uF=h.forwardRef(({className:e,asChild:t=!1,showOnHover:s=!1,...r},a)=>{const i=t?ec:"button";return n.jsx(i,{ref:a,"data-sidebar":"menu-action",className:_e("absolute right-1 top-1.5 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground outline-none ring-sidebar-ring transition-transform peer-hover/menu-button:text-sidebar-accent-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0","after:absolute after:-inset-2 after:md:hidden","peer-data-[size=sm]/menu-button:top-1","peer-data-[size=default]/menu-button:top-1.5","peer-data-[size=lg]/menu-button:top-2.5","group-data-[collapsible=icon]:hidden",s&&"group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 peer-data-[active=true]/menu-button:text-sidebar-accent-foreground md:opacity-0",e),...r})});uF.displayName="SidebarMenuAction";const hF=h.forwardRef(({className:e,...t},s)=>n.jsx("div",{ref:s,"data-sidebar":"menu-badge",className:_e("pointer-events-none absolute right-1 flex h-5 min-w-5 select-none items-center justify-center rounded-md px-1 text-xs font-medium tabular-nums text-sidebar-foreground","peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[active=true]/menu-button:text-sidebar-accent-foreground","peer-data-[size=sm]/menu-button:top-1","peer-data-[size=default]/menu-button:top-1.5","peer-data-[size=lg]/menu-button:top-2.5","group-data-[collapsible=icon]:hidden",e),...t}));hF.displayName="SidebarMenuBadge";const mF=h.forwardRef(({className:e,showIcon:t=!1,...s},r)=>{const a=h.useMemo(()=>`${Math.floor(Math.random()*40)+50}%`,[]);return n.jsxs("div",{ref:r,"data-sidebar":"menu-skeleton",className:_e("flex h-8 items-center gap-2 rounded-md px-2",e),...s,children:[t&&n.jsx(c1,{className:"size-4 rounded-md","data-sidebar":"menu-skeleton-icon"}),n.jsx(c1,{className:"h-4 max-w-[--skeleton-width] flex-1","data-sidebar":"menu-skeleton-text",style:{"--skeleton-width":a}})]})});mF.displayName="SidebarMenuSkeleton";const pF=h.forwardRef(({className:e,...t},s)=>n.jsx("ul",{ref:s,"data-sidebar":"menu-sub",className:_e("mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l border-sidebar-border px-2.5 py-0.5","group-data-[collapsible=icon]:hidden",e),...t}));pF.displayName="SidebarMenuSub";const fF=h.forwardRef(({...e},t)=>n.jsx("li",{ref:t,...e}));fF.displayName="SidebarMenuSubItem";const gF=h.forwardRef(({asChild:e=!1,size:t="md",isActive:s,className:r,...a},i)=>{const o=e?ec:"a";return n.jsx(o,{ref:i,"data-sidebar":"menu-sub-button","data-size":t,"data-active":s,className:_e("flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 text-sidebar-foreground outline-none ring-sidebar-ring aria-disabled:pointer-events-none aria-disabled:opacity-50 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0 [&>svg]:text-sidebar-accent-foreground","data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground",t==="sm"&&"text-xs",t==="md"&&"text-sm","group-data-[collapsible=icon]:hidden",r),...a})});gF.displayName="SidebarMenuSubButton";const Th=h.forwardRef(({className:e,activeClassName:t,pendingClassName:s,to:r,...a},i)=>n.jsx(iL,{ref:i,to:r,className:({isActive:o,isPending:l})=>_e(e,o&&t,l&&s),...a}));Th.displayName="NavLink";const xF=[{key:"dashboard",url:"/app",icon:y4},{key:"persona",url:"/app/persona",icon:Xs},{key:"contentStudio",url:"/app/content",icon:Sy},{key:"live",url:"/app/live",icon:St},{key:"simulator",url:"/app/simulator",icon:Rx},{key:"webinars",url:"/app/webinars",icon:Ja},{key:"trends",url:"/app/trends",icon:uu},{key:"news",url:"/app/news",icon:Qc},{key:"topicDiscovery",url:"/app/topic-discovery",icon:jy},{key:"consultations",url:"/app/consultations",icon:Zs},{key:"integrations",url:"/app/integrations",icon:Pr},{key:"ads",url:"/app/ads",icon:za},{key:"monetization",url:"/app/monetization",icon:ky},{key:"analytics",url:"/app/analytics",icon:by}],vF=[{key:"billing",url:"/app/billing",icon:Il}
792,{key:"settings",url:"/app/settings",icon:pS}];function yF(){const{state:e,setOpenMobile:t,isMobile:s}=yu(),r=e==="collapsed";rr();const{signOut:a}=st(),{isAdmin:i}=ar(),{t:o}=Oe("common"),l=i?[{key:"operations",url:"/admin/operations",icon:Ed},{key:"prompts",url:"/admin/prompts",icon:tt},{key:"admin",url:"/admin",icon:Od}]:[],c=()=>{s&&t(!1)};return n.jsxs(rC,{collapsible:"icon",className:"border-r border-border/50",children:[n.jsx(iC,{className:"p-4 border-b border-border/30",children:n.jsxs("a",{href:"/app",className:"font-heading font-bold text-lg tracking-tight text-foreground flex items-center gap-2",children:[!r&&n.jsxs(n.Fragment,{children:["SmartBlog",n.jsx("span",{className:"text-gradient",children:"AI"})]}),r&&n.jsx("span",{className:"text-gradient font-extrabold text-xl",children:"S"})]})}),n.jsx(lC,{className:"py-2",children:n.jsxs(cC,{children:[n.jsx(dC,{className:"text-[10px] uppercase tracking-wider text-muted-foreground/60 px-4 mb-1",children:o("sidebar.main")}),n.jsx(uC,{children:n.jsx(Ch,{children:xF.map(d=>n.jsx(Rc,{children:n.jsx($c,{asChild:!0,children:n.jsxs(Th,{to:d.url,end:d.url==="/app",onClick:c,className:"flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium text-muted-foreground hover:text-foreground hover:bg-muted/50 transition-colors",activeClassName:"bg-primary/8 text-primary",children:[n.jsx(d.icon,{className:"h-[18px] w-[18px] shrink-0"}),!r&&n.jsx("span",{children:o(`sidebar.${d.key}`)})]})})},d.key))})})]})}),n.jsxs(oC,{className:"border-t border-border/30 py-2",children:[l.length>0&&n.jsx(Ch,{children:l.map(d=>n.jsx(Rc,{children:n.jsx($c,{asChild:!0,children:n.jsxs(Th,{to:d.url,onClick:c,className:"flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium text-red-500/80 hover:text-red-600 hover:bg-red-50 dark:hover:bg-red-950/20 transition-colors",activeClassName:"bg-red-50 dark:bg-red-950/30 text-red-600",children:[n.jsx(d.icon,{className:"h-[18px] w-[18px] shrink-0"}),!r&&n.jsx("span",{children:o(`sidebar.${d.key}`,"Admin")})]})})},d.key))}),n.jsxs(Ch,{children:[vF.map(d=>n.jsx(Rc,{children:n.jsx($c,{asChild:!0,children:n.jsxs(Th,{to:d.url,onClick:c,className:"flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium text-muted-foreground hover:text-foreground hover:bg-muted/50 transition-colors",activeClassName:"bg-primary/8 text-primary",children:[n.jsx(d.icon,{className:"h-[18px] w-[18px] shrink-0"}),!r&&n.jsx("span",{children:o(`sidebar.${d.key}`)})]})})},d.key)),n.jsx(Rc,{children:n.jsx($c,{asChild:!0,children:n.jsxs("button",{onClick:a,className:"flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium text-muted-foreground hover:text-destructive hover:bg-destructive/5 transition-colors w-full",children:[n.jsx(cS,{className:"h-[18px] w-[18px] shrink-0"}),!r&&n.jsx("span",{children:o("sidebar.signOut")})]})})})]})]})]})}const bF=hu("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",destructive:"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",outline:"text-foreground"}},defaultVariants:{variant:"default"}});function fe({className:e,variant:t,...s}){return n.jsx("div",{className:_e(bF({variant:t}),e),...s})}const ih={video_per_second:1,live_per_second:2},hC=[{key:"free",name:"Free",tagline:"Try it and build the foundation",desc:"Create your first AI character and explore the platform.",monthly:null,yearly:null,credits_monthly:500},{key:"pro",name:"Pro",tagline:"Build and monetize",desc:"Active channel development, live formats, and monetization stack.",monthly:{priceId:"price_1TIUdcJWaDwanPCA5sMrnrAu",productId:"prod_UH2jK9X2TTTcHt",amount:99,interval:"month"},yearly:{priceId:"price_1TIUrLJWaDwanPCAdlCu0JLT",productId:"prod_UH2xThmb9e9iYC",amount:79,interval:"year"},credits_monthly:24e3},{key:"business",name:"Business",tagline:"Scale as a system",desc:"For brands, teams, and large launches.",monthly:{priceId:"price_1TIUreJWaDwanPCAV7ZrLHem",productId:"prod_UH2xa2v0Pg4V6y",amount:399,interval:"month"},yearly:{priceId:"price_1TIV6mJWaDwanPCAuVLj21JU",productId:"prod_UH3DR4z7M1kbbR",amount:349,interval:"year"},credits_monthly:1e5}],Md=Object.fromEntries(hC.map(e=>[e.key,e]));function d1(e,[t,s]){return Math.min(s,Math.max(t,e))}function zy(e){const t=e+"CollectionProvider",[s,r]=Is(t),[a,i]=s(t,{collectionRef:{current:null},itemMap:new Map}),o=x=>{const{scope:b,children:v}=x,y=Se.useRef(null),w=Se.useRef(new Map).current;return n.jsx(a,{scope:b,itemMap:w,collectionRef:y,children:v})};o.displayName=t;const l=e+"CollectionSlot",c=ni(l),d=Se.forwardRef((x,b)=>{const{scope:v,children:y}=x,w=i(l,v),j=bt(b,w.collectionRef);return n.jsx(c,{ref:j,children:y})});d.displayName=l;const u=e+"CollectionItemSlot",m="data-radix-collection-item",p=ni(u),f=Se.forwardRef((x,b)=>{const{scope:v,children:y,...w}=x,j=Se.useRef(null),_=bt(b,j),N=i(u,v);return Se.useEffect(()=>(N.itemMap.set(j,{ref:j,...w}),()=>void N.itemMap.delete(j))),n.jsx(p,{[m]:"",ref:_,children:y})});f.displayName=u;function g(x){const b=i(e+"CollectionConsumer",x);return Se.useCallback(()=>{const y=b.collectionRef.current;if(!y)return[];const w=Array.from(y.querySelectorAll(`[${m}]`));return Array.from(b.itemMap.values()).sort((N,k)=>w.indexOf(N.ref.current)-w.indexOf(k.ref.current))},[b.collectionRef,b.itemMap])}return[{Provider:o,Slot:d,ItemSlot:f},g,r]}var wF=h.createContext(void 0);function yp(e){const t=h.useContext(wF);return e||t||"ltr"}function Fy(e){const t=h.useRef({value:e,previous:e});return h.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}var jF=[" ","Enter","ArrowUp","ArrowDown"],_F=[" ","Enter"],no="Select",[bp,wp,kF]=zy(no),[oc,K1e]=Is(no,[kF,gi]),jp=gi(),[NF,vi]=oc(no),[SF,CF]=oc(no),mC=e=>{const{__scopeSelect:t,children:s,open:r,defaultOpen:a,onOpenChange:i,value:o,defaultValue:l,onValueChange:c,dir:d,name:u,autoComplete:m,disabled:p,required:f,form:g}=e,x=jp(t),[b,v]=h.useState(null),[y,w]=h.useState(null),[j,_]=h.useState(!1),N=yp(d),[k,S]=tr({prop:r,defaultProp:a??!1,onChange:i,caller:no}),[T,C]=tr({prop:o,defaultProp:l,onChange:c,caller:no}),B=h.useRef(null),E=b?g||!!b.closest("form"):!0,[H,z]=h.useState(new Set),ne=Array.from(H).map(V=>V.props.value).join(";");return n.jsx(tp,{...x,children:n.jsxs(NF,{required:f,scope:t,trigger:b,onTriggerChange:v,valueNode:y,onValueNodeChange:w,valueNodeHasChildren:j,onValueNodeHasChildrenChange:_,contentId:pn(),value:T,onValueChange:C,open:k,onOpenChange:S,dir:N,triggerPointerDownPosRef:B,disabled:p,children:[n.jsx(bp.Provider,{scope:t,children:n.jsx(SF,{scope:e.__scopeSelect,onNativeOptionAdd:h.useCallback(V=>{z(te=>new Set(te).add(V))},[]),onNativeOptionRemove:h.useCallback(V=>{z(te=>{const R=new Set(te);return R.delete(V),R})},[]),children:s})}),E?n.jsxs(DC,{"aria-hidden":!0,required:f,tabIndex:-1,name:u,autoComplete:m,value:T,onChange:V=>C(V.target.value),disabled:p,form:g,children:[T===void 0?n.jsx("option",{value:""}):null,Array.from(H)]},ne):null]})})};mC.displayName=no;var pC="SelectTrigger",fC=h.forwardRef((e,t)=>
vendor: 16,816 bytes, line 792
792{const{__scopeSelect:s,disabled:r=!1,...a}=e,i=jp(s),o=vi(pC,s),l=o.disabled||r,c=bt(t,o.onTriggerChange),d=wp(s),u=h.useRef("touch"),[m,p,f]=zC(x=>{const b=d().filter(w=>!w.disabled),v=b.find(w=>w.value===o.value),y=FC(b,x,v);y!==void 0&&o.onValueChange(y.value)}),g=x=>{l||(o.onOpenChange(!0),f()),x&&(o.triggerPointerDownPosRef.current={x:Math.round(x.pageX),y:Math.round(x.pageY)})};return n.jsx(nu,{asChild:!0,...i,children:n.jsx(qe.button,{type:"button",role:"combobox","aria-controls":o.contentId,"aria-expanded":o.open,"aria-required":o.required,"aria-autocomplete":"none",dir:o.dir,"data-state":o.open?"open":"closed",disabled:l,"data-disabled":l?"":void 0,"data-placeholder":MC(o.value)?"":void 0,...a,ref:c,onClick:Ee(a.onClick,x=>{x.currentTarget.focus(),u.current!=="mouse"&&g(x)}),onPointerDown:Ee(a.onPointerDown,x=>{u.current=x.pointerType;const b=x.target;b.hasPointerCapture(x.pointerId)&&b.releasePointerCapture(x.pointerId),x.button===0&&x.ctrlKey===!1&&x.pointerType==="mouse"&&(g(x),x.preventDefault())}),onKeyDown:Ee(a.onKeyDown,x=>{const b=m.current!=="";!(x.ctrlKey||x.altKey||x.metaKey)&&x.key.length===1&&p(x.key),!(b&&x.key===" ")&&jF.includes(x.key)&&(g(),x.preventDefault())})})})});fC.displayName=pC;var gC="SelectValue",xC=h.forwardRef((e,t)=>{const{__scopeSelect:s,className:r,style:a,children:i,placeholder:o="",...l}=e,c=vi(gC,s),{onValueNodeHasChildrenChange:d}=c,u=i!==void 0,m=bt(t,c.onValueNodeChange);return cs(()=>{d(u)},[d,u]),n.jsx(qe.span,{...l,ref:m,style:{pointerEvents:"none"},children:MC(c.value)?n.jsx(n.Fragment,{children:o}):i})});xC.displayName=gC;var TF="SelectIcon",vC=h.forwardRef((e,t)=>{const{__scopeSelect:s,children:r,...a}=e;return n.jsx(qe.span,{"aria-hidden":!0,...a,ref:t,children:r||"▼"})});vC.displayName=TF;var PF="SelectPortal",yC=e=>n.jsx(ru,{asChild:!0,...e});yC.displayName=PF;var ro="SelectContent",bC=h.forwardRef((e,t)=>{const s=vi(ro,e.__scopeSelect),[r,a]=h.useState();if(cs(()=>{a(new DocumentFragment)},[]),!s.open){const i=r;return i?Jl.createPortal(n.jsx(wC,{scope:e.__scopeSelect,children:n.jsx(bp.Slot,{scope:e.__scopeSelect,children:n.jsx("div",{children:e.children})})}),i):null}return n.jsx(jC,{...e,ref:t})});bC.displayName=ro;var Un=10,[wC,yi]=oc(ro),EF="SelectContentImpl",AF=ni("SelectContent.RemoveScroll"),jC=h.forwardRef((e,t)=>{const{__scopeSelect:s,position:r="item-aligned",onCloseAutoFocus:a,onEscapeKeyDown:i,onPointerDownOutside:o,side:l,sideOffset:c,align:d,alignOffset:u,arrowPadding:m,collisionBoundary:p,collisionPadding:f,sticky:g,hideWhenDetached:x,avoidCollisions:b,...v}=e,y=vi(ro,s),[w,j]=h.useState(null),[_,N]=h.useState(null),k=bt(t,A=>j(A)),[S,T]=h.useState(null),[C,B]=h.useState(null),E=wp(s),[H,z]=h.useState(!1),ne=h.useRef(!1);h.useEffect(()=>{if(w)return gp(w)},[w]),pp();const V=h.useCallback(A=>{const[oe,...ue]=E().map(ie=>ie.ref.current),[je]=ue.slice(-1),ae=document.activeElement;for(const ie of A)if(ie===ae||(ie==null||ie.scrollIntoView({block:"nearest"}),ie===oe&&_&&(_.scrollTop=0),ie===je&&_&&(_.scrollTop=_.scrollHeight),ie==null||ie.focus(),document.activeElement!==ae))return},[E,_]),te=h.useCallback(()=>V([S,w]),[V,S,w]);h.useEffect(()=>{H&&te()},[H,te]);const{onOpenChange:R,triggerPointerDownPosRef:F}=y;h.useEffect(()=>{if(w){let A={x:0,y:0};const oe=je=>{var ae,ie;A={x:Math.abs(Math.round(je.pageX)-(((ae=F.current)==null?void 0:ae.x)??0)),y:Math.abs(Math.round(je.pageY)-(((ie=F.current)==null?void 0:ie.y)??0))}},ue=je=>{A.x<=10&&A.y<=10?je.preventDefault():w.contains(je.target)||R(!1),document.removeEventListener("pointermove",oe),F.current=null};return F.current!==null&&(document.addEventListener("pointermove",oe),document.addEventListener("pointerup",ue,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",oe),document.removeEventListener("pointerup",ue,{capture:!0})}}},[w,R,F]),h.useEffect(()=>{const A=()=>R(!1);return window.addEventListener("blur",A),window.addEventListener("resize",A),()=>{window.removeEventListener("blur",A),window.removeEventListener("resize",A)}},[R]);const[$,J]=zC(A=>{const oe=E().filter(ae=>!ae.disabled),ue=oe.find(ae=>ae.ref.current===document.activeElement),je=FC(oe,A,ue);je&&setTimeout(()=>je.ref.current.focus())}),Y=h.useCallback((A,oe,ue)=>{const je=!ne.current&&!ue;(y.value!==void 0&&y.value===oe||je)&&(T(A),je&&(ne.current=!0))},[y.value]),re=h.useCallback(()=>w==null?void 0:w.focus(),[w]),G=h.useCallback((A,oe,ue)=>{const je=!ne.current&&!ue;(y.value!==void 0&&y.value===oe||je)&&B(A)},[y.value]),O=r==="popper"?Fx:_C,Z=O===Fx?{side:l,sideOffset:c,align:d,alignOffset:u,arrowPadding:m,collisionBoundary:p,collisionPadding:f,sticky:g,hideWhenDetached:x,avoidCollisions:b}:{};return n.jsx(wC,{scope:s,content:w,viewport:_,onViewportChange:N,itemRefCallback:Y,selectedItem:S,onItemLeave:re,itemTextRefCallback:G,focusSelectedItem:te,selectedItemText:C,position:r,isPositioned:H,searchRef:$,children:n.jsx(pu,{as:AF,allowPinchZoom:!0,children:n.jsx(mu,{asChild:!0,trapped:y.open,onMountAutoFocus:A=>{A.preventDefault()},onUnmountAutoFocus:Ee(a,A=>{var oe;(oe=y.trigger)==null||oe.focus({preventScroll:!0}),A.preventDefault()}),children:n.jsx(tc,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:i,onPointerDownOutside:o,onFocusOutside:A=>A.preventDefault(),onDismiss:()=>y.onOpenChange(!1),children:n.jsx(O,{role:"listbox",id:y.contentId,"data-state":y.open?"open":"closed",dir:y.dir,onContextMenu:A=>A.preventDefault(),...v,...Z,onPlaced:()=>z(!0),ref:k,style:{display:"flex",flexDirection:"column",outline:"none",...v.style},onKeyDown:Ee(v.onKeyDown,A=>{const oe=A.ctrlKey||A.altKey||A.metaKey;if(A.key==="Tab"&&A.preventDefault(),!oe&&A.key.length===1&&J(A.key),["ArrowUp","ArrowDown","Home","End"].includes(A.key)){let je=E().filter(ae=>!ae.disabled).map(ae=>ae.ref.current);if(["ArrowUp","End"].includes(A.key)&&(je=je.slice().reverse()),["ArrowUp","ArrowDown"].includes(A.key)){const ae=A.target,ie=je.indexOf(ae);je=je.slice(ie+1)}setTimeout(()=>V(je)),A.preventDefault()}})})})})})})});jC.displayName=EF;var RF="SelectItemAlignedPosition",_C=h.forwardRef((e,t)=>{const{__scopeSelect:s,onPlaced:r,...a}=e,i=vi(ro,s),o=yi(ro,s),[l,c]=h.useState(null),[d,u]=h.useState(null),m=bt(t,k=>u(k)),p=wp(s),f=h.useRef(!1),g=h.useRef(!0),{viewport:x,selectedItem:b,selectedItemText:v,focusSelectedItem:y}=o,w=h.useCallback(()=>{if(i.trigger&&i.valueNode&&l&&d&&x&&b&&v){const k=i.trigger.getBoundingClientRect(),S=d.getBoundingClientRect(),T=i.valueNode.getBoundingClientRect(),C=v.getBoundingClientRect();if(i.dir!=="rtl"){const ae=C.left-S.left,ie=T.left-ae,we=k.left-ie,Ae=k.width+we,nt=Math.max(Ae,S.width),Qe=window.innerWidth-Un,P=d1(ie,[Un,Math.max(Un,Qe-nt)]);l.style.minWidth=Ae+"px",l.style.left=P+"px"}else{const ae=S.right-C.right,ie=window.innerWidth-T.right-ae,we=window.innerWidth-k.right-ie,Ae=k.width+we,nt=Math.max(Ae,S.width),Qe=window.innerWidth-Un,P=d1(ie,[Un,Math.max(Un,Qe-nt)]);l.style.minWidth=Ae+"px",l.style.right=P+"px"}const B=p(),E=window.innerHeight-Un*2,H=x.scrollHeight,z=window.getComputedStyle(d),ne=parseInt(z.borderTopWidth,10),V=parseInt(z.paddingTop,10),te=parseInt(z.borderBottomWidth,10),R=parseInt(z.paddingBottom,10),F=ne+V+H+R+te,$=Math.min(b.offsetHeight*5,F),J=window.getComputedStyle(x),Y=parseInt(J.paddingTop,10),re=parseInt(J.paddingBottom,10),G=k.top+k.height/2-Un,O=E-G,Z=b.offsetHeight/2,A=b.offsetTop+Z,oe=ne+V+A,ue=F-oe;if(oe<=G){const ae=B.length>0&&b===B[B.length-1].ref.current;l.style.bottom="0px";const ie=d.clientHeight-x.offsetTop-x.offsetHeight,we=Math.max(O,Z+(ae?re:0)+ie+te),Ae=oe+we;l.style.height=Ae+"px"}else{const ae=B.length>0&&b===B[0].ref.current;l.style.top="0px";const we=Math.max(G,ne+x.offsetTop+(ae?Y:0)+Z)+ue;l.style.height=we+"px",x.scrollTop=oe-G+x.offsetTop}l.style.margin=`${Un}px 0`,l.style.minHeight=$+"px",l.style.maxHeight=E+"px",r==null||r(),requestAnimationFrame(()=>f.current=!0)}},[p,i.trigger,i.valueNode,l,d,x,b,v,i.dir,r]);cs(()=>w(),[w]);const[j,_]=h.useState();cs(()=>{d&&_(window.getComputedStyle(d).zIndex)},[d]);const N=h.useCallback(k=>{k&&g.current===!0&&(w(),y==null||y(),g.current=!1)},[w,y]);return n.jsx(LF,{scope:s,contentWrapper:l,shouldExpandOnScrollRef:f,onScrollButtonChange:N,children:n.jsx("div",{ref:c,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:j},children:n.jsx(qe.div,{...a,ref:m,style:{boxSizing:"border-box",maxHeight:"100%",...a.style}})})})});_C.displayName=RF;var $F="SelectPopperPosition",Fx=h.forwardRef((e,t)=>{const{__scopeSelect:s,align:r="start",collisionPadding:a=Un,...i}=e,o=jp(s);return n.jsx(sp,{...o,...i,ref:t,align:r,collisionPadding:a,style:{boxSizing:"border-box",...i.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}})});Fx.displayName=$F;var[LF,Uy]=oc(ro,{}),Ux="SelectViewport",kC=h.forwardRef((e,t)=>{const{__scopeSelect:s,nonce:r,...a}=e,i=yi(Ux,s),o=Uy(Ux,s),l=bt(t,i.onViewportChange),c=h.useRef(0);return n.jsxs(n.Fragment,{children:[n.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:r}),n.jsx(bp.Slot,{scope:s,children:n.jsx(qe.div,{"data-radix-select-viewport":"",role:"presentation",...a,ref:l,style:{position:"relative",flex:1,overflow:"hidden auto",...a.style},onScroll:Ee(a.onScroll,d=>{const u=d.currentTarget,{contentWrapper:m,shouldExpandOnScrollRef:p}=o;if(p!=null&&p.current&&m){const f=Math.abs(c.current-u.scrollTop);if(f>0){const g=window.innerHeight-Un*2,x=parseFloat(m.style.minHeight),b=parseFloat(m.style.height),v=Math.max(x,b);if(v<g){const y=v+f,w=Math.min(g,y),j=y-w;m.style.height=w+"px",m.style.bottom==="0px"&&(u.scrollTop=j>0?j:0,m.style.justifyContent="flex-end")}}}c.current=u.scrollTop})})})]})});kC.displayName=Ux;var NC="SelectGroup",[IF,OF]=oc(NC),DF=h.forwardRef((e,t)=>{const{__scopeSelect:s,...r}=e,a=pn();return n.jsx(IF,{scope:s,id:a,children:n.jsx(qe.div,{role:"group","aria-labelledby":a,...r,ref:t})})});DF.displayName=NC;var SC="SelectLabel",CC=h.forwardRef((e,t)=>{const{__scopeSelect:s,...r}=e,a=OF(SC,s);return n.jsx(qe.div,{id:a.id,...r,ref:t})});CC.displayName=SC;var bm="SelectItem",[MF,TC]=oc(bm),PC=h.forwardRef((e,t)=>{const{__scopeSelect:s,value:r,disabled:a=!1,textValue:i,...o}=e,l=vi(bm,s),c=yi(bm,s),d=l.value===r,[u,m]=h.useState(i??""),[p,f]=h.useState(!1),g=bt(t,y=>{var w;return(w=c.itemRefCallback)==null?void 0:w.call(c,y,r,a)}),x=pn(),b=h.useRef("touch"),v=()=>{a||(l.onValueChange(r),l.onOpenChange(!1))};if(r==="")throw new Error("A <Select.Item /> must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return n.jsx(MF,{scope:s,value:r,disabled:a,textId:x,isSelected:d,onItemTextChange:h.useCallback(y=>{m(w=>w||((y==null?void 0:y.textContent)??"").trim())},[]),children:n.jsx(bp.ItemSlot,{scope:s,value:r,disabled:a,textValue:u,children:n.jsx(qe.div,{role:"option","aria-labelledby":x,"data-highlighted":p?"":void 0,"aria-selected":d&&p,"data-state":d?"checked":"unchecked","aria-disabled":a||void 0,"data-disabled":a?"":void 0,tabIndex:a?void 0:-1,...o,ref:g,onFocus:Ee(o.onFocus,()=>f(!0)),onBlur:Ee(o.onBlur,()=>f(!1)),onClick:Ee(o.onClick,()=>{b.current!=="mouse"&&v()}),onPointerUp:Ee(o.onPointerUp,()=>{b.current==="mouse"&&v()}),onPointerDown:Ee(o.onPointerDown,y=>{b.current=y.pointerType}),onPointerMove:Ee(o.onPointerMove,y=>{var w;b.current=y.pointerType,a?(w=c.onItemLeave)==null||w.call(c):b.current==="mouse"&&y.currentTarget.focus({preventScroll:!0})}),onPointerLeave:Ee(o.onPointerLeave,y=>{var w;y.currentTarget===document.activeElement&&((w=c.onItemLeave)==null||w.call(c))}),onKeyDown:Ee(o.onKeyDown,y=>{var j;((j=c.searchRef)==null?void 0:j.current)!==""&&y.key===" "||(_F.includes(y.key)&&v(),y.key===" "&&y.preventDefault())})})})})});PC.displayName=bm;var Lc="SelectItemText",EC=h.forwardRef((e,t)=>{const{__scopeSelect:s,className:r,style:a,...i}=e,o=vi(Lc,s),l=yi(Lc,s),c=TC(Lc,s),d=CF(Lc,s),[u,m]=h.useState(null),p=bt(t,v=>m(v),c.onItemTextChange,v=>{var y;return(y=l.itemTextRefCallback)==null?void 0:y.call(l,v,c.value,c.disabled)}),f=u==null?void 0:u.textContent,g=h.useMemo(()=>n.jsx("option",{value:c.value,disabled:c.disabled,children:f},c.value),[c.disabled,c.value,f]),{onNativeOptionAdd:x,onNativeOptionRemove:b}=d;return cs(()=>(x(g),()=>b(g)),[x,b,g]),n.jsxs(n.Fragment,{children:[n.jsx(qe.span,{id:c.textId,...i,ref:p}),c.isSelected&&o.valueNode&&!o.valueNodeHasChildren?Jl.createPortal(i.children,o.valueNode):null]})});EC.displayName=Lc;var AC="SelectItemIndicator",RC=h.forwardRef((e,t)=>{const{__scopeSelect:s,...r}=e;return TC(AC,s).isSelected?n.jsx(qe.span,{"aria-hidden":!0,...r,ref:t}):null});RC.displayName=AC;var Bx="SelectScrollUpButton",$C=h.forwardRef((e,t)=>{const s=yi(Bx,e.__scopeSelect),r=Uy(Bx,e.__scopeSelect),[a,i]=h.useState(!1),o=bt(t,r.onScrollButtonChange);return cs(()=>{if(s.viewport&&s.isPositioned){let l=function(){const d=c.scrollTop>0;i(d)};const c=s.viewport;return l(),c.addEventListener("scroll",l),()=>c.removeEventListener("scroll",l)}},[s.viewport,s.isPositioned]),a?n.jsx(IC,{...e,ref:o,onAutoScroll:()=>{const{viewport:l,selectedItem:c}=s;l&&c&&(l.scrollTop=l.scrollTop-c.offsetHeight)}}):null});$C.displayName=Bx;var Vx="SelectScrollDownButton",LC=h.forwardRef((e,t)=>{const s=yi(Vx,e.__scopeSelect),r=Uy(Vx,e.__scopeSelect),[a,i]=h.useState(!1),o=bt(t,r.onScrollButtonChange);return cs(()=>{if(s.viewport&&s.isPositioned){let l=function(){const d=c.scrollHeight-c.clientHeight,u=Math.ceil(c.scrollTop)<d;i(u)};const c=s.viewport;return l(),c.addEventListener("scroll",l),()=>c.removeEventListener("scroll",l)}},[s.viewport,s.isPositioned]),a?n.jsx(IC,{...e,ref:o,onAutoScroll:()=>{const{viewport:l,selectedItem:c}=s;l&&c&&(l.scrollTop=l.scrollTop+c.offsetHeight)}}):null});LC.displayName=Vx;var IC=h.forwardRef((e,t)=>{const{__scopeSelect:s,onAutoScroll:r,...a}=e,i=yi("SelectScrollButton",s),o=h.useRef(null),l=wp(s),c=h.useCallback(()=>{o.current!==null&&(window.clearInterval(o.current),o.current=null)},[]);return h.useEffect(()=>()=>c(),[c]),cs(()=>{var u;const d=l().find(m=>m.ref.current===document.activeElement);(u=d==null?void 0:d.ref.current)==null||u.scrollIntoView({block:"nearest"})},[l]),n.jsx(qe.div,{"aria-hidden":!0,...a,ref:t,style:{flexShrink:0,...a.style},onPointerDown:Ee(a.onPointerDown,()=>{o.current===null&&(o.current=window.setInterval(r,50))}),onPointerMove:Ee(a.onPointerMove,()=>{var d;(d=i.onItemLeave)==null||d.call(i),o.current===null&&(o.current=window.setInterval(r,50))}),onPointerLeave:Ee(a.onPointerLeave,()=>{c()})})}),zF="SelectSeparator",OC=h.forwardRef((e,t)=>{const{__scopeSelect:s,...r}=e;return n.jsx(qe.div,{"aria-hidden":!0,...r,ref:t})});OC.displayName=zF;var qx="SelectArrow",FF=h.forwardRef((e,t)=>{const{__scopeSelect:s,...r}=e,a=jp(s),i=vi(qx,s),o=yi(qx,s);return i.open&&o.position==="popper"?n.jsx(np,{...a,...r,ref:t}):null});FF.displayName=qx;var UF="SelectBubbleInput",DC=h.forwardRef(({__scopeSelect:e,value:t,...s},r)=>{const a=h.useRef(null),i=bt(r,a),o=Fy(t);return h.useEffect(()=>{const l=a.current;if(!l)return;const c=window.HTMLSelectElement.prototype,u=Object.getOwnPropertyDescriptor(c,"value").set;if(o!==t&&u){const m=new Event("change",{bubbles:!0});u.call(l,t),l.dispatchEvent(m)}},[o,t]),n.jsx(qe.select,{...s,style:{...gN,...s.style},ref:i,defaultValue:t})});DC.displayName=UF;function MC(e){return e===""||e===void 0}function zC(e){const t=Zn(e),s=h.useRef(""),r=h.useRef(0),a=h.useCallback(o=>{const l=s.current+o;t(l),function c(d){s.current=d,window.clearTimeout(r.current),d!==""&&(r.current=window.setTimeout(()=>c(""),1e3))}(l)},[t]),i=h.useCallback(()=>{s.current="",window.clearTimeout(r.current)},[]);return h.useEffect(()=>()=>window.clearTimeout(r.current),[]),[s,a,i]}function FC(e,t,s){const a=t.length>1&&Array.from(t).every(d=>d===t[0])?t[0]:t,i=s?e.indexOf(s):-1;let o=BF(e,Math.max(i,0));a.length===1&&(o=o.filter(d=>d!==s));const c=o.find(d=>d.textValue.toLowerCase().startsWith(a.toLowerCase()));return c!==s?c:void 0}function BF(e,t){return e.map((s,r)=>e[(t+r)%e.length])}var VF=mC,UC=fC,qF=xC,HF=vC,WF=yC,BC=bC,GF=kC,VC=CC,qC=PC,YF=EC,KF=RC,HC=$C,WC=LC,GC=OC;const ut=VF,ht=qF,ct=h.forwardRef(({className:e,children:t,...s},r)=>n.jsxs(UC,{ref:r,className:_e("flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm r
792ing-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",e),...s,children:[t,n.jsx(HF,{asChild:!0,children:n.jsx(ps,{className:"h-4 w-4 opacity-50"})})]}));ct.displayName=UC.displayName;const YC=h.forwardRef(({className:e,...t},s)=>n.jsx(HC,{ref:s,className:_e("flex cursor-default items-center justify-center py-1",e),...t,children:n.jsx(wy,{className:"h-4 w-4"})}));YC.displayName=HC.displayName;const KC=h.forwardRef(({className:e,...t},s)=>n.jsx(WC,{ref:s,className:_e("flex cursor-default items-center justify-center py-1",e),...t,children:n.jsx(ps,{className:"h-4 w-4"})}));KC.displayName=WC.displayName;const dt=h.forwardRef(({className:e,children:t,position:s="popper",...r},a)=>n.jsx(WF,{children:n.jsxs(BC,{ref:a,className:_e("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",s==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:s,...r,children:[n.jsx(YC,{}),n.jsx(GF,{className:_e("p-1",s==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),n.jsx(KC,{})]})}));dt.displayName=BC.displayName;const QF=h.forwardRef(({className:e,...t},s)=>n.jsx(VC,{ref:s,className:_e("py-1.5 pl-8 pr-2 text-sm font-semibold",e),...t}));QF.displayName=VC.displayName;const ce=h.forwardRef(({className:e,children:t,...s},r)=>n.jsxs(qC,{ref:r,className:_e("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 focus:bg-accent focus:text-accent-foreground",e),...s,children:[n.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:n.jsx(KF,{children:n.jsx(ms,{className:"h-4 w-4"})})}),n.jsx(YF,{children:t})]}));ce.displayName=qC.displayName;const JF=h.forwardRef(({className:e,...t},s)=>n.jsx(GC,{ref:s,className:_e("-mx-1 my-1 h-px bg-muted",e),...t}));JF.displayName=GC.displayName;const ZF=[{code:"ru",label:"Русский"},{code:"en",label:"English"}];function XF({className:e=""}){var r;const{i18n:t}=Oe(),s=(r=t.language)!=null&&r.startsWith("en")?"en":"ru";return n.jsxs(ut,{value:s,onValueChange:a=>t.changeLanguage(a),children:[n.jsxs(ct,{className:`h-8 w-auto gap-1.5 px-2.5 text-xs font-medium text-muted-foreground border-border/50 bg-transparent hover:bg-muted/50 ${e}`,children:[n.jsx(Rd,{size:14,className:"shrink-0"}),n.jsx(ht,{})]}),n.jsx(dt,{children:ZF.map(a=>n.jsx(ce,{value:a.code,children:a.label},a.code))})]})}const e6=["free","pro","business"];function t6(){var c,d,u;const{t:e}=Oe("common"),{planKey:t,startCheckout:s,isAdmin:r,overridePlan:a}=ar(),{user:i}=st(),o=(c=i==null?void 0:i.user_metadata)!=null&&c.full_name?i.user_metadata.full_name.charAt(0).toUpperCase():((d=i==null?void 0:i.email)==null?void 0:d.charAt(0).toUpperCase())??"U",l=(u=i==null?void 0:i.user_metadata)==null?void 0:u.avatar_url;return n.jsx(n.Fragment,{children:n.jsxs("header",{className:"h-14 border-b border-border/50 bg-surface-elevated flex items-center gap-3 px-4 shrink-0",children:[n.jsx(aC,{className:"text-muted-foreground hover:text-foreground"}),n.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[n.jsx("span",{className:"font-heading font-semibold text-foreground",children:e("topBar.myProject")}),r?n.jsxs(ut,{value:t,onValueChange:m=>a(m),children:[n.jsx(ct,{className:"h-6 w-auto gap-1 px-2 text-[10px] font-semibold border-border/50 bg-secondary text-secondary-foreground rounded-full",children:n.jsx(ht,{})}),n.jsx(dt,{children:e6.map(m=>n.jsx(ce,{value:m,children:e(`plans.${m}`,m)},m))})]}):n.jsx(fe,{variant:"secondary",className:"text-[10px] font-semibold",children:e(`plans.${t}`,t)})]}),n.jsx("div",{className:"flex-1 max-w-md mx-auto hidden md:block",children:n.jsxs("div",{className:"relative",children:[n.jsx(bn,{size:15,className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground
792/50"}),n.jsx("input",{type:"text",placeholder:e("topBar.searchPlaceholder"),className:"w-full h-9 pl-9 pr-4 rounded-lg bg-muted/50 border border-border/50 text-sm text-foreground placeholder:text-muted-foreground/50 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary/30 transition-all"})]})}),n.jsxs("div",{className:"flex items-center gap-2 ml-auto",children:[n.jsx(XF,{}),t==="free"&&!r&&n.jsxs(L,{variant:"hero",size:"sm",className:"h-8 text-xs gap-1.5",onClick:()=>{var p;const m=(p=Md.pro.monthly)==null?void 0:p.priceId;m&&s(m)},children:[n.jsx(tt,{size:13}),e("topBar.upgrade")]}),n.jsxs("button",{className:"flex items-center gap-2 px-2 py-1.5 rounded-lg hover:bg-muted/50 transition-colors",children:[l?n.jsx("img",{src:l,alt:"",className:"w-7 h-7 rounded-full object-cover"}):n.jsx("div",{className:"w-7 h-7 rounded-full bg-gradient-primary flex items-center justify-center text-primary-foreground text-xs font-bold",children:o}),n.jsx(ps,{size:14,className:"text-muted-foreground hidden sm:block"})]})]})]})})}const s6={initial:{opacity:0,y:8},animate:{opacity:1,y:0,transition:{duration:.25,ease:"easeOut"}},exit:{opacity:0,y:-6,transition:{duration:.15,ease:"easeIn"}}},u1=()=>{const{pathname:e}=rr();return n.jsx(nC,{children:n.jsxs("div",{className:"min-h-screen flex w-full bg-surface",children:[n.jsx(yF,{}),n.jsxs("div",{className:"flex-1 flex flex-col min-w-0",children:[n.jsx(t6,{}),n.jsx("main",{className:"flex-1 p-6 md:p-8 overflow-auto",children:n.jsx(xn,{mode:"wait",children:n.jsx(de.div,{variants:s6,initial:"initial",animate:"animate",exit:"exit",children:n.jsx(W$,{})},e)})})]})]})})},n6=["blogger","host","consultant","teacher","lawyer","mixed"],r6={blogger:Ns,host:St,consultant:Zs,teacher:Cy,lawyer:mS,mixed:Ey},a6=["ai","business","education","languages","commentary","news","expert","brand"],i6={ai:vy,business:i4,education:dp,languages:v4,commentary:up,news:Qc,expert:bn,brand:Xs},o6=["shorts","live","consult","subscription","gradual"],l6={shorts:en,live:cu,consult:Zs,subscription:Il,gradual:Ld},c6=[tt,en,St,Ns,Il],zf=6,d6=()=>{const{t:e}=Oe("onboarding-app"),[t,s]=h.useState(0),[r,a]=h.useState(null),[i,o]=h.useState([]),[l,c]=h.useState(null),[d,u]=h.useState(!1),[m,p]=h.useState(!1),f=fi(),{user:g,refreshProfile:x}=st(),b=k=>o(S=>S.includes(k)?S.filter(T=>T!==k):[...S,k]),v=async()=>{if(!(!g||m)){p(!0);try{await I.from("user_profiles").update({onboarding_completed:!0,selected_role:r,selected_niche:i.join(","),selected_start_mode:l}).eq("user_id",g.id),await I.from("onboarding_progress").update({completed_at:new Date().toISOString(),role_selected:r,niche_selected:i.join(","),start_mode_selected:l,youtube_connect_skipped:!d,current_step:"done"}).eq("user_id",g.id),await x()}catch(k){console.error("Onboarding save error:",k)}finally{p(!1)}}},y=()=>t===0?!!r:t===1?i.length>0:t===2?!!l:!0,w=()=>t<zf-1&&s(t+1),j=()=>t>0&&s(t-1),_={enter:{opacity:0,x:40},center:{opacity:1,x:0},exit:{opacity:0,x:-40}},N=e("roadmap",{returnObjects:!0});return n.jsxs("div",{className:"min-h-screen bg-surface flex flex-col",children:[n.jsxs("header",{className:"h-14 border-b border-border/50 bg-surface-elevated flex items-center px-6 shrink-0",children:[n.jsxs("span",{className:"font-heading font-bold text-lg text-foreground",children:["SmartBlog",n.jsx("span",{className:"text-gradient",children:"AI"})]}),n.jsx("span",{className:"ml-auto text-xs text-muted-foreground",children:e("stepOf",{step:t+1,total:zf})})]}),n.jsx("div",{className:"h-1 bg-muted/50",children:n.jsx(de.div,{className:"h-full bg-gradient-primary rounded-r-full",initial:!1,animate:{width:`${(t+1)/zf*100}%`},transition:{duration:.4,ease:"easeInOut"}})}),n.jsx("div",{className:"flex-1 flex items-start justify-center px-4 py-10 md:py-16 overflow-auto",children:n.jsx("div",{className:"w-full max-w-2xl",children:n.jsx(xn,{mode:"wait",children:n.jsxs(de.div,{variants:_,initial:"enter",animate:"center",exit:"exit",transition:{duration:.35},children:[t===0&&n.jsxs("div",{children:[n.jsx("h1",{className:"font-heading font-extrabold text-2xl md:text-3xl text-foreground mb-2",children:e("step0Title")}),n.jsx("p",{className:"text-muted-foreground text-sm mb-8",children:e("step0Desc")}),n.jsx("div",{className:"grid gap-3",children:n6.map(k=>{const S=r6[k],T=r===k;return n.jsxs("button",{onClick:()=>a(k),className:`flex items-start gap-4 p-5 rounded-xl border text-left transition-all duration-200 ${T?"border-primary/40 bg-primary/5 shadow-premium-sm":"border-border/50 bg-surface-elevated hover:border-border hover:shadow-
792premium-sm"}`,children:[n.jsx("div",{className:`w-10 h-10 rounded-lg flex items-center justify-center shrink-0 ${T?"bg-primary/12":"bg-muted/50"}`,children:n.jsx(S,{size:18,className:T?"text-primary":"text-muted-foreground"})}),n.jsxs("div",{children:[n.jsx("h3",{className:"font-heading font-semibold text-foreground text-sm",children:e(`roles.${k}.title`)}),n.jsx("p",{className:"text-muted-foreground text-xs mt-0.5",children:e(`roles.${k}.text`)})]}),T&&n.jsx(wt,{size:18,className:"text-primary shrink-0 ml-auto mt-1"})]},k)})})]}),t===1&&n.jsxs("div",{children:[n.jsx("h1",{className:"font-heading font-extrabold text-2xl md:text-3xl text-foreground mb-2",children:e("step1Title")}),n.jsx("p",{className:"text-muted-foreground text-sm mb-8",children:e("step1Desc")}),n.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3",children:a6.map(k=>{const S=i6[k],T=i.includes(k);return n.jsxs("button",{onClick:()=>b(k),className:`flex flex-col items-center gap-2.5 p-5 rounded-xl border text-center transition-all duration-200 ${T?"border-primary/40 bg-primary/5 shadow-premium-sm":"border-border/50 bg-surface-elevated hover:border-border hover:shadow-premium-sm"}`,children:[n.jsx("div",{className:`w-10 h-10 rounded-lg flex items-center justify-center ${T?"bg-primary/12":"bg-muted/50"}`,children:n.jsx(S,{size:18,className:T?"text-primary":"text-muted-foreground"})}),n.jsx("span",{className:"text-xs font-medium text-foreground",children:e(`topics.${k}`)})]},k)})})]}),t===2&&n.jsxs("div",{children:[n.jsx("h1",{className:"font-heading font-extrabold text-2xl md:text-3xl text-foreground mb-2",children:e("step2Title")}),n.jsx("p",{className:"text-muted-foreground text-sm mb-8",children:e("step2Desc")}),n.jsx("div",{className:"grid gap-3",children:o6.map(k=>{const S=l6[k],T=l===k;return n.jsxs("button",{onClick:()=>c(k),className:`flex items-start gap-4 p-5 rounded-xl border text-left transition-all duration-200 ${T?"border-primary/40 bg-primary/5 shadow-premium-sm":"border-border/50 bg-surface-elevated hover:border-border hover:shadow-premium-sm"}`,children:[n.jsx("div",{className:`w-10 h-10 rounded-lg flex items-center justify-center shrink-0 ${T?"bg-primary/12":"bg-muted/50"}`,children:n.jsx(S,{size:18,className:T?"text-primary":"text-muted-foreground"})}),n.jsxs("div",{children:[n.jsx("h3",{className:"font-heading font-semibold text-foreground text-sm",children:e(`startModels.${k}.title`)}),n.jsx("p",{className:"text-muted-foreground text-xs mt-0.5",children:e(`startModels.${k}.text`)})]}),T&&n.jsx(wt,{size:18,className:"text-primary shrink-0 ml-auto mt-1"})]},k)})})]}),t===3&&n.jsxs("div",{className:"text-center",children:[n.jsx("div",{className:"w-16 h-16 rounded-2xl bg-destructive/10 flex items-center justify-center mx-auto mb-6",children:n.jsx(Ls,{size:30,className:"text-destructive"})}),n.jsx("h1",{className:"font-heading font-extrabold text-2xl md:text-3xl text-foreground mb-3",children:e("step3Title")}),n.jsx("p",{className:"text-muted-foreground text-sm max-w-md mx-auto mb-8 leading-relaxed",children:e("step3Desc")}),d?n.jsxs("div",{className:"inline-flex items-center gap-2 px-5 py-3 rounded-xl bg-primary/5 border border-primary/20 text-primary font-medium text-sm",children:[n.jsx(wt,{size:18})," ",e("ytConnected")]}):n.jsxs(L,{variant:"hero",size:"lg",className:"gap-2 text-base px-8",onClick:()=>u(!0),children:[n.jsx(Ls,{size:18})," ",e("connectYt")]}),n.jsx("p",{className:"text-xs text-muted-foreground/60 mt-4",children:e("ytSkipNote")})]}),t===4&&n.jsxs("div",{children:[n.jsx("h1",{className:"font-heading font-extrabold text-2xl md:text-3xl text-foreground mb-2 text-center",children:e("step4Title")}),n.jsx("p",{className:"text-muted-foreground text-sm mb-10 text-center",children:e("step4Desc")}),n.jsx("div",{className:"space-y-0",children:Array.isArray(N)&&N.map((k,S)=>{const T=c6[S]||tt;return n.jsxs("div",{className:"flex gap-4",children:[n.jsxs("div",{className:"flex flex-col items-center",children:[n.jsx("div",{className:"w-10 h-10 rounded-xl bg-primary/10 border-2 border-primary/25 flex items-center justify-center text-primary shrink-0",children:n.jsx(T,{size:17})}),S<N.length-1&&n.jsx("div",{className:"w-px flex-1 bg-primary/15 my-1"})]}),n.jsxs("div",{className:"pb-6",children:[n.jsx("h3",{className:"font-heading font-semibold text-foreground text-sm",children:k.label}),n.jsx("p",{className:"text-muted-foreground text-xs mt-0.5",children:k.desc})]})]},k.label)})})]}),t===5&&n.jsxs("div",{className:"text-center",children:[n.jsx(de.div,{initial:{scale:.8,opacity:0}
792,animate:{scale:1,opacity:1},transition:{duration:.5,type:"spring"},className:"w-20 h-20 rounded-2xl bg-gradient-primary flex items-center justify-center mx-auto mb-6",children:n.jsx(tt,{size:36,className:"text-primary-foreground"})}),n.jsx("h1",{className:"font-heading font-extrabold text-2xl md:text-3xl text-foreground mb-3",children:e("step5Title")}),n.jsx("p",{className:"text-muted-foreground text-sm max-w-md mx-auto mb-8 leading-relaxed",children:e("step5Desc")}),n.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 justify-center",children:[n.jsxs(L,{variant:"hero",size:"lg",className:"gap-2 text-base px-8",disabled:m,onClick:async()=>{await v(),f("/app")},children:[e(m?"saving":"goToDashboard")," ",n.jsx(Tr,{size:16})]}),n.jsxs(L,{variant:"hero-outline",size:"lg",className:"gap-2 text-base px-8",disabled:m,onClick:async()=>{await v(),f("/app/persona")},children:[n.jsx(tt,{size:16})," ",e("createFirstPersona")]})]})]})]},t)})})}),t<5&&n.jsxs("footer",{className:"border-t border-border/50 bg-surface-elevated px-6 py-4 flex items-center justify-between shrink-0",children:[n.jsxs(L,{variant:"ghost",onClick:j,disabled:t===0,className:"gap-1.5 text-muted-foreground",children:[n.jsx(Hi,{size:15})," ",e("back")]}),n.jsxs(L,{variant:"hero",onClick:w,disabled:!y(),className:"gap-1.5 px-6",children:[e(t===3&&!d?"skip":"continue")," ",n.jsx(Tr,{size:15})]})]})]})},h1={ru:"ru-RU",en:"en-US"};function or(){const{i18n:e,t}=Oe("common"),s=h1[e.language]||h1.ru,r=h.useCallback(c=>c?new Date(c).toLocaleDateString(s):"—",[s]),a=h.useCallback(c=>c?new Date(c).toLocaleString(s,{day:"numeric",month:"short",hour:"2-digit",minute:"2-digit"}):"—",[s]),i=h.useCallback(c=>c?new Date(c).toLocaleString(s,{day:"2-digit",month:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}):"—",[s]),o=h.useCallback(c=>{const d=Date.now()-new Date(c).getTime(),u=Math.floor(d/1e3);if(u<60)return t("timeAgo.seconds",{count:u});const m=Math.floor(u/60);if(m<60)return t("timeAgo.minutes",{count:m});const p=Math.floor(m/60);return p<24?t("timeAgo.hours",{count:p}):t("timeAgo.days",{count:Math.floor(p/24)})},[t]),l=h.useCallback(c=>c.toLocaleString(s),[s]);return{formatDate:r,formatDateShort:a,formatDateTime:i,timeAgo:o,formatNumber:l,locale:s}}function Ln({message:e}){const{t}=Oe("common");return n.jsxs("div",{className:"flex flex-col items-center justify-center py-24 gap-3",children:[n.jsx(xe,{size:28,className:"animate-spin text-primary"}),n.jsx("p",{className:"text-sm text-muted-foreground",children:e??t("system.loading")})]})}function Er({icon:e,title:t,description:s,actionLabel:r,onAction:a,actionLink:i,secondaryLabel:o,onSecondary:l}){return n.jsxs(de.div,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},className:"text-center py-12 px-6",children:[n.jsx("div",{className:"w-16 h-16 rounded-2xl bg-muted/40 flex items-center justify-center mx-auto mb-4",children:n.jsx(e,{size:28,className:"text-muted-foreground"})}),n.jsx("h3",{className:"font-heading font-semibold text-base text-foreground mb-1.5",children:t}),n.jsx("p",{className:"text-sm text-muted-foreground max-w-sm mx-auto leading-relaxed",children:s}),n.jsxs("div",{className:"flex items-center justify-center gap-2 mt-5",children:[r&&i&&n.jsx(L,{variant:"hero",size:"sm",className:"gap-1.5",asChild:!0,children:n.jsxs(zt,{to:i,children:[n.jsx(sr,{size:14})," ",r]})}),r&&a&&!i&&n.jsxs(L,{variant:"hero",size:"sm",className:"gap-1.5",onClick:a,children:[n.jsx(sr,{size:14})," ",r]}),o&&l&&n.jsx(L,{variant:"hero-outline",size:"sm",className:"gap-1.5",onClick:l,children:o})]})]})}const m1={idea:{icon:nr,className:"bg-muted/50 text-muted-foreground border-border/40"},draft:{icon:$d,className:"bg-muted/60 text-muted-foreground border-border/40"},generating:{icon:xe,className:"bg-amber-50 text-amber-600 border-amber-200/50"},queued:{icon:ls,className:"bg-blue-50 text-blue-600 border-blue-200/50"},running:{icon:xe,className:"bg-primary/10 text-primary border-primary/20"},ready:{icon:wt,className:"bg-emerald-50 text-emerald-600 border-emerald-200/50"},scheduled:{icon:ls,className:"bg-amber-50 text-amber-600 border-amber-200/50"},published:{icon:Ay,className:"bg-primary/10 text-primary border-primary/20"},live:{icon:St,className:"bg-red-50 text-red-500 border-red-200/50"},ended:{icon:wt,className:"bg-emerald-50 text-emerald-600 border-emerald-200/50"},canceled:{icon:iu,className:"bg-muted/50 text-muted-foreground border-border/40"},failed:{icon:gn,className:"bg-red-50 text-red-500 border-red-200/50"},timed_out:{icon:ls,className:"bg-amber-50 text-amber-600 border-amber-200/50"},completed:{icon:wt,className:"bg-emerald-50 text-emerald-600 border-emerald-200/50"},review:{icon:oi,className:"bg-orange-50 text-orange-600 border-orange-200/50"},approved:{icon:Od,className:"bg-emerald-50 text-emerald-600 border-emerald-200/50"},active:{icon:wt,className:"bg-emerald-50 text-emerald-600 border-emerald-200/50"},inactive:{icon:Ll,className:"bg-muted/50 text-muted-foreground border-border/40"},past_due:{icon:ft,className:"bg-amber-50 text-amber-600 border-amber-200/50"},trialing:{icon:nr,className:"bg-blue-50 text-blue-600 border-blue-200/50"},connected:{icon:wt,className:"bg-emerald-50 text-emerald-600 border-emerald-200/50"},not_connected:{icon:Ll,className:"bg-muted/50 text-muted-foreground border-border/40"},connecting:{icon:xe,className:"bg-amber-50 text-amber-600 border-amber-200/50"},expired:{icon:ft,className:"bg-amber-50 text-amber-600 border-amber-200/50"},error:{icon:gn,className:"bg-red-50 text-red-500 border-red-200/50"}};function yr({status:e,size:t="sm",animate:s=!1}){const{t:r}=Oe("common"),a=m1[e]??m1.draft,i=a.icon,o=s||e==="generating"||e==="running"||e==="connecting",l=r(`system.status.${e}`,e);return n.jsxs("span",{className:`inline-flex items-center gap-1 px-2 py-0.5 rounded-full border font-semibold ${t==="sm"?"text-[10px]":"text-xs"} ${a.className}`,children:[n.jsx(i,{size:t==="sm"?10:12,className:o?"animate-spin":""}),l]})}function Ff({icon:e=ft,title:t,description:s,actionLabel:r,onAction:a,variant:i="warning"}){const o={warning:"border-amber-200/50 bg-amber-50/30 text-amber-600",error:"border-red-200/50 bg-red-50/30 text-red-500",info:"border-primary/15 bg-primary/[0.03] text-primary"};return n.jsxs("div",{className:`flex items-start gap-3 rounded-xl border px-4 py-3 ${o[i]}`,children:[n.jsx(e,{size:18,className:"shrink-0 mt-0.5"}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("p",{className:"text-sm font-semibold text-foreground",children:t}),n.jsx("p",{className:"text-[11px] text-muted-foreground mt-0.5",children:s})]}),r&&a&&n.jsx(L,{variant:"outline",size:"sm",className:"shrink-0 text-xs h-7",onClick:a,children:r})]})}function QC({status:e,planKey:t,subscriptionEnd:s,onUpgrade:r,onManage:a}){const{formatDate:i}=or(),{t:o}=Oe("common");
792if(e==="past_due")return n.jsx(Ff,{variant:"error",title:o("system.subscription.pastDueTitle"),description:o("system.subscription.pastDueDesc"),actionLabel:o("system.subscription.pastDueAction"),onAction:a});if(e==="canceled"||e==="active"&&s){const l=s?i(s):"";return n.jsx(Ff,{variant:"warning",title:o("system.subscription.canceledTitle"),description:o("system.subscription.canceledDesc",{date:l}),actionLabel:o("system.subscription.canceledAction"),onAction:a})}return t==="free"&&r?n.jsx(Ff,{variant:"info",icon:nr,title:o("system.subscription.freeTitle"),description:o("system.subscription.freeDesc"),actionLabel:o("system.subscription.freeAction"),onAction:r}):null}function u6({alert:e}){const{t}=Oe("common"),s=e.icon??(e.severity==="error"?gn:e.severity==="warning"?ft:nr),r=e.severity==="error"?"border-red-200/50":e.severity==="warning"?"border-amber-200/50":"border-primary/15",a=e.severity==="error"?"bg-red-50/20":e.severity==="warning"?"bg-amber-50/20":"bg-primary/[0.02]",i=e.severity==="error"?"text-red-500":e.severity==="warning"?"text-amber-500":"text-primary";return n.jsxs(de.div,{initial:{opacity:0,y:8},animate:{opacity:1,y:0},exit:{opacity:0,height:0,marginBottom:0},className:`rounded-xl border ${r} ${a} px-4 py-3.5 flex items-start gap-3 relative`,children:[e.dismissable&&e.onDismiss&&n.jsx("button",{onClick:e.onDismiss,className:"absolute top-2.5 right-2.5 w-6 h-6 rounded-md flex items-center justify-center text-muted-foreground hover:text-foreground hover:bg-muted/40 transition-colors",title:t("system.dismiss"),children:n.jsx(Qn,{size:14})}),n.jsx("div",{className:`w-8 h-8 rounded-lg flex items-center justify-center shrink-0 ${e.severity==="error"?"bg-red-100/60":e.severity==="warning"?"bg-amber-100/60":"bg-primary/10"}`,children:n.jsx(s,{size:16,className:i})}),n.jsxs("div",{className:"flex-1 min-w-0 pr-4",children:[n.jsx("p",{className:"text-sm font-semibold text-foreground",children:e.title}),n.jsx("p",{className:"text-[11px] text-muted-foreground mt-0.5 leading-relaxed",children:e.description}),e.reason&&n.jsx("p",{className:"text-[10px] text-muted-foreground/70 mt-1 font-mono",children:t("system.reason",{reason:e.reason})}),n.jsxs("div",{className:"flex flex-wrap gap-2 mt-2.5",children:[e.actionLink?n.jsx(L,{variant:e.severity==="error"?"default":"outline",size:"sm",className:"h-7 text-[11px] gap-1.5",asChild:!0,children:n.jsxs(zt,{to:e.actionLink,children:[n.jsx(ss,{size:11})," ",e.actionLabel]})}):e.onAction?n.jsxs(L,{variant:e.severity==="error"?"default":"outline",size:"sm",className:"h-7 text-[11px] gap-1.5",onClick:e.onAction,children:[n.jsx(ss,{size:11})," ",e.actionLabel]}):null,e.secondaryLink?n.jsx(L,{variant:"ghost",size:"sm",className:"h-7 text-[11px] gap-1",asChild:!0,children:n.jsx(zt,{to:e.secondaryLink,children:e.secondaryLabel})}):e.onSecondary?n.jsx(L,{variant:"ghost",size:"sm",className:"h-7 text-[11px] gap-1",onClick:e.onSecondary,children:e.secondaryLabel}):null]})]})]})}function _p({alerts:e,title:t}){return e.length===0?null:n.jsxs(de.div,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},className:"space-y-3",children:[t&&n.jsxs("h3",{className:"font-heading font-semibold text-sm text-foreground flex items-center gap-2",children:[n.jsx(ft,{size:14,className:"text-amber-500"})," ",t,n.jsx(fe,{variant:"outline",className:"text-[9px] ml-1",children:e.length})]}),n.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:n.jsx(xn,{children:e.map(s=>n.jsx(u6,{alert:s},s.id))})})]})}function kp(e){var r,a;const{t}=e,s=[];return e.ytStatus==="expired"&&s.push({id:"yt-expired",severity:"warning",title:t("system.recovery.ytExpiredTitle"),description:t("system.recovery.ytExpiredDesc"),actionLabel:t("system.recovery.ytExpiredAction"),onAction:e.onYtReconnect,actionLink:e.onYtReconnect?void 0:"/app/integrations",icon:ft}),e.ytStatus==="error"&&s.push({id:"yt-error",severity:"error",title:t("system.recovery.ytErrorTitle"),description:t("system.recovery.ytErrorDesc"),reason:e.ytError||t("system.recovery.unknownError"),actionLabel:t("system.recovery.ytErrorAction"),onAction:e.onYtReconnect,actionLink:e.onYtReconnect?void 0:"/app/integrations",secondaryLabel:t("system.recovery.ytErrorSecondary"),secondaryLink:"/app/integrations"}),e.patreonStatus==="expired"&&s.push({id:"patreon-expired",severity:"warning",title:t("system.recovery.patreonExpiredTitle"),description:t("system.recovery.patreonExpiredDesc"),actionLabel:t
792("system.recovery.patreonExpiredAction"),onAction:e.onPatreonReconnect,actionLink:e.onPatreonReconnect?void 0:"/app/integrations"}),e.patreonStatus==="error"&&s.push({id:"patreon-error",severity:"error",title:t("system.recovery.patreonErrorTitle"),description:t("system.recovery.patreonErrorDesc"),reason:e.patreonError||t("system.recovery.unknownError"),actionLabel:t("system.recovery.patreonErrorAction"),onAction:e.onPatreonReconnect,actionLink:e.onPatreonReconnect?void 0:"/app/integrations",secondaryLabel:t("system.recovery.patreonErrorSecondary"),secondaryLink:"/app/integrations"}),e.subStatus==="past_due"&&s.push({id:"billing-past-due",severity:"error",title:t("system.recovery.billingPastDueTitle"),description:t("system.recovery.billingPastDueDesc"),actionLabel:t("system.recovery.billingPastDueAction"),onAction:e.onManageBilling,actionLink:e.onManageBilling?void 0:"/app/billing",icon:Il}),e.subStatus==="canceled"&&s.push({id:"billing-canceled",severity:"warning",title:t("system.recovery.billingCanceledTitle"),description:t("system.recovery.billingCanceledDesc"),actionLabel:t("system.recovery.billingCanceledAction"),onAction:e.onManageBilling,actionLink:e.onManageBilling?void 0:"/app/billing",icon:Il}),(r=e.failedJobs)!=null&&r.length&&e.failedJobs.slice(0,5).forEach(i=>{const o=t(`system.recovery.jobTypes.${i.job_type}`,i.job_type);s.push({id:`job-failed-${i.id}`,severity:"error",title:`${o}: ${t("system.recovery.jobErrorSuffix")}`,description:i.error_text||t("system.recovery.jobErrorFallback"),actionLabel:"",dismissable:!0,onDismiss:e.onDismissJob?()=>e.onDismissJob(i.id):void 0})}),(a=e.failedLiveSessions)!=null&&a.length&&e.failedLiveSessions.slice(0,2).forEach(i=>{s.push({id:`live-failed-${i.id}`,severity:"error",title:t("system.recovery.liveFailedTitle",{title:i.title}),description:t("system.recovery.liveFailedDesc"),actionLabel:t("system.recovery.liveFailedAction"),actionLink:"/app/live",icon:St})}),s}function h6(e,t,s){return s&&e===t?"failed":e<t?"done":e===t?"active":"pending"}function m6(e){const t=e.job_type==="render_video"||e.job_type==="video_test";return e.status==="completed"?e.job_type==="generate_short_script"?3:e.job_type==="generate_voice"||e.job_type==="render_short_video"?4:6:e.status==="failed"||e.status==="running"?e.job_type==="generate_short_script"?3:e.job_type==="generate_voice"||e.job_type==="render_short_video"?4:5:e.status==="queued"?1:0}function p6(e){switch(e){case"draft":return 0;case"scheduled":case"ready":return 1;case"review":case"approved":return 2;case"live":return 4;case"ended":return 4;default:return 0}}function f6({step:e,status:t,isLast:s,executingLabel:r,errorLabel:a}){const i=e.icon,o={done:"bg-emerald-100 text-emerald-600 border-emerald-200",active:"bg-primary/15 text-primary border-primary/30",pending:"bg-muted/30 text-muted-foreground/50 border-border/30",failed:"bg-red-100 text-red-500 border-red-200"},l={done:"bg-emerald-300",active:"bg-primary/40",pending:"bg-border/30",failed:"bg-red-300"},c={done:"text-foreground",active:"text-foreground font-semibold",pending:"text-muted-foreground/50",failed:"text-red-500 font-semibold"};return n.jsxs("div",{className:"flex items-start gap-2 relative",children:[!s&&n.jsx("div",{className:`absolute left-[13px] top-[26px] w-[2px] h-[calc(100%+4px)] ${l[t]}`}),n.jsx("div",{className:`relative z-10 w-[28px] h-[28px] rounded-lg border flex items-center justify-center shrink-0 ${o[t]}`,children:t==="active"?n.jsx(xe,{size:13,className:"animate-spin"}):n.jsx(i,{size:13})}),n.jsxs("div",{className:"pb-4 pt-0.5",children:[n.jsx("p",{className:`text-[11px] leading-tight ${c[t]}`,children:e.label}),t==="active"&&n.jsx("span",{className:"text-[9px] text-primary/70 font-medium",children:r}),t==="failed"&&n.jsx("span",{className:"text-[9px] text-red-400 font-medium",children:a})]})]})}function JC({title:e,steps:t,currentStep:s,failed:r=!1,compact:a=!1,doneLabel:i,executingLabel:o,errorLabel:l}){return n.jsxs(de.div,{initial:{opacity:0,y:8},animate:{opacity:1,y:0},className:`rounded-xl border border-border/40 bg-muted/5 ${a?"p-3":"p-4"}`,children:[n.jsxs("div",{className:"flex items-center justify-between mb-3",children:[n.jsx("p",{className:"text-xs font-semibold text-foreground",children:e}),n.jsx(fe,{variant:"outline",className:"text-[9px]",children:s>
792=t.length?i:`${s+1} / ${t.length}`})]}),n.jsx("div",{className:"h-1 rounded-full bg-muted/40 mb-3 overflow-hidden",children:n.jsx("div",{className:`h-full rounded-full transition-all duration-500 ${r?"bg-red-400":"bg-primary"}`,style:{width:`${Math.min(100,(s+(r?0:.5))/t.length*100)}%`}})}),n.jsx("div",{className:"space-y-0",children:t.map((c,d)=>n.jsx(f6,{step:c,status:h6(d,s,r),isLast:d===t.length-1,executingLabel:o,errorLabel:l},c.key))})]})}function g6({job:e,compact:t}){const{t:s}=Oe("content-studio"),r=[{key:"request",label:s("timeline.stepRequestCreated"),icon:nr},{key:"queued",label:s("timeline.stepQueued"),icon:ls},{key:"worker",label:s("timeline.stepWorkerClaimed"),icon:mm},{key:"script",label:s("timeline.stepScriptGen"),icon:nr},{key:"voice",label:s("timeline.stepVoiceGen"),icon:Zs},{key:"render",label:s("timeline.stepRender"),icon:dS},{key:"ready",label:s("timeline.stepAssetReady"),icon:wt}];return n.jsx(JC,{title:s("timeline.shortTitle"),steps:r,currentStep:m6(e),failed:e.status==="failed",compact:t,doneLabel:s("timeline.done"),executingLabel:s("timeline.executing"),errorLabel:s("timeline.error")})}function x6({sessionStatus:e,compact:t}){const{t:s}=Oe("content-studio"),r=[{key:"created",label:s("timeline.stepSessionCreated"),icon:nr},{key:"yt_objects",label:s("timeline.stepYTObjects"),icon:Ns},{key:"preparing",label:s("timeline.stepPrepRuntime"),icon:mm},{key:"active",label:s("timeline.stepWorkerLive"),icon:St},{key:"chat",label:s("timeline.stepMonitorChat"),icon:lu}];return n.jsx(JC,{title:s("timeline.livePrepTitle"),steps:r,currentStep:p6(e),failed:e==="failed",compact:t,doneLabel:s("timeline.done"),executingLabel:s("timeline.executing"),errorLabel:s("timeline.error")})}function ZC({job:e}){var i;const{t}=Oe("content-studio"),s={generate_short_script:t("jobs.typeGenerateScript"),render_short_video:t("jobs.typeRenderVideo"),generate_clip_set:t("jobs.typeGenerateClipSet"),extract_live_highlights:t("jobs.typeExtractHighlights"),repurpose_live_to_shorts:t("jobs.typeRepurposeLive"),create_youtube_live_objects:t("jobs.typeCreateYTLiveObjects"),prepare_live_assets:t("jobs.typePrepareLiveAssets"),ingest_live_chat:t("jobs.typeIngestChat"),generate_chat_reply_suggestions:t("jobs.typeGenerateReplies"),upload_video_to_youtube:t("jobs.typeUploadYouTube")};if(["generate_short_script","generate_voice","render_video","render_short_video","video_test"].includes(e.job_type))return n.jsx(g6,{job:e,compact:!0});const a={queued:"border-blue-200/40 bg-blue-50/10",running:"border-primary/20 bg-primary/[0.03]",completed:"border-emerald-200/40 bg-emerald-50/10",failed:"border-red-200/40 bg-red-50/10"};return n.jsx(de.div,{initial:{opacity:0,y:6},animate:{opacity:1,y:0},className:`rounded-xl border p-3 ${a[e.status]||"border-border/40"}`,children:n.jsxs("div",{className:"flex items-center gap-2.5",children:[n.jsx("div",{className:`w-8 h-8 rounded-lg flex items-center justify-center shrink-0 ${e.status==="running"?"bg-primary/10":e.status==="failed"?"bg-red-100":"bg-muted/30"}`,children:e.status==="running"?n.jsx(xe,{size:14,className:"text-primary animate-spin"}):e.status==="failed"?n.jsx(Ll,{size:14,className:"text-red-500"}):e.status==="completed"?n.jsx(wt,{size:14,className:"text-emerald-500"}):n.jsx(ls,{size:14,className:"text-muted-foreground"})}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("p",{className:"text-[11px] font-semibold text-foreground truncate",children:s[e.job_type]||e.job_type}),n.jsxs("p",{className:"text-[9px] text-muted-foreground",children:[e.status==="queued"&&t("jobs.runtimeWaiting"),e.status==="running"&&t("jobs.runtimeProcessing"),e.status==="completed"&&t("jobs.runtimeDone"),e.status==="failed"&&(((i=e.error_text)==null?void 0:i.slice(0,50))||t("jobs.runtimeError"))]})]}),n.jsx(fe,{variant:"outline",className:`text-[9px] shrink-0 ${e.status==="running"?"border-primary/30 text-primary":e.status==="failed"?"border-red-200 text-red-500":e.status==="completed"?"border-emerald-200 text-emerald-600":"border-border/40 text-muted-foreground"}`,children:e.status==="queued"?t("jobs.badgeQueued"):e.status==="running"?t("jobs.badgeRunning"):e.status==="completed"?t("jobs.badgeCompleted"):e.status==="failed"?t("jobs.badgeFailed"):e.status})]})})}const v6=8e3,y6=3e4,b6=2e3,Ic=new Map;let w6=0;function j6(e,t,s){return`${e}::${t??""}::${s??""}`}function zd(e,t){for(const s of e.listeners.values())try{s.onChange(t)}
792catch(r){console.warn("[realtime-manager] listener threw:",r)}}function _6(e){for(const t of e.listeners.values())if(t.onHealth)try{t.onHealth(e.health)}catch(s){console.warn("[realtime-manager] health listener threw:",s)}}function XC(e,t){e.health!==t&&(e.health=t,_6(e))}function k6(e){e.recoveryPollTimer||(e.recoveryPollTimer=setInterval(()=>{e.listeners.size!==0&&zd(e)},b6))}function e2(e){e.recoveryPollTimer&&(clearInterval(e.recoveryPollTimer),e.recoveryPollTimer=null)}function Hx(e){e.subscribeTimer&&(clearTimeout(e.subscribeTimer),e.subscribeTimer=null)}function N6(e){e.retryTimer&&(clearTimeout(e.retryTimer),e.retryTimer=null)}function Np(e){if(Hx(e),e.channel){try{I.removeChannel(e.channel)}catch{}e.channel=null}}function p1(e){e.status!=="broken"&&(e.status="broken",e.wasBroken=!0,XC(e,"recovering"),zd(e),k6(e),S6(e))}function S6(e){if(e.retryTimer)return;const t=Math.min(y6,1e3*2**e.retryAttempt);e.retryAttempt+=1,e.retryTimer=setTimeout(()=>{e.retryTimer=null,e.listeners.size!==0&&(Np(e),By(e))},t)}function By(e){if(e.listeners.size===0)return;e.status="connecting";const t=`${e.table}-${e.filter??"all"}-${Math.random().toString(36).slice(2,8)}`,s=I.channel(`rt-${t}`);e.channel=s,e.subscribeTimer=setTimeout(()=>{e.subscribeTimer=null,Np(e),p1(e)},v6),s.on("postgres_changes",{event:"*",schema:"public",table:e.table,...e.filter?{filter:e.filter}:{}},r=>zd(e,r)).subscribe(r=>{if(r==="SUBSCRIBED"){Hx(e);const a=e.wasBroken;e.status="subscribed",e.retryAttempt=0,e.wasBroken=!1,e2(e),XC(e,"healthy"),a&&zd(e)}else(r==="CHANNEL_ERROR"||r==="TIMED_OUT"||r==="CLOSED")&&(Hx(e),p1(e))})}function Sp(e){const t=j6(e.table,e.filter,e.channelKey);let s=Ic.get(t);s||(s={key:t,table:e.table,filter:e.filter,listeners:new Map,channel:null,status:"idle",health:"recovering",wasBroken:!1,retryAttempt:0,subscribeTimer:null,retryTimer:null,recoveryPollTimer:null},Ic.set(t,s));const r=++w6;if(s.listeners.set(r,{id:r,onChange:e.onChange,onHealth:e.onHealth}),e.onHealth)try{e.onHealth(s.health)}catch{}return s.status==="idle"&&By(s),()=>{const a=Ic.get(t);a&&(a.listeners.delete(r),a.listeners.size===0&&(N6(a),e2(a),Np(a),Ic.delete(t)))}}function C6(){for(const e of Ic.values())zd(e),e.status!=="subscribed"&&!e.retryTimer&&!e.subscribeTimer&&(e.retryAttempt=0,Np(e),By(e))}function lc({table:e,filter:t,queryKey:s,channelKey:r,enabled:a=!0}){const i=na(),o=h.useRef(s);o.current=s;const[l,c]=h.useState(!0);return h.useEffect(()=>{if(!a)return;const d=()=>i.invalidateQueries({queryKey:o.current});d();const u=Sp({table:e,filter:t,channelKey:r,onChange:d,onHealth:g=>c(g==="healthy")}),m=()=>d(),p=()=>{d(),C6()},f=()=>{document.visibilityState==="visible"&&d()};return window.addEventListener("focus",m),window.addEventListener("online",p),document.addEventListener("visibilitychange",f),()=>{window.removeEventListener("focus",m),window.removeEventListener("online",p),document.removeEventListener("visibilitychange",f),u()}},[a,e,t,r,i]),{isHealthy:l}}const t2=new Set(["render_video","video_test","conduct_live_session","conduct_consultation"]);function s2(e){return t2.has(e)}var Tt;(function(e){e.assertEqual=a=>{};function t(a){}e.assertIs=t;function s(a){throw new Error}e.assertNever=s,e.arrayToEnum=a=>{const i={};for(const o of a)i[o]=o;return i},e.getValidEnumValues=a=>{const i=e.objectKeys(a).filter(l=>typeof a[a[l]]!="number"),o={};for(const l of i)o[l]=a[l];return e.objectValues(o)},e.objectValues=a=>e.objectKeys(a).map(function(i){return a[i]}),e.objectKeys=typeof Object.keys=="function"?a=>Object.keys(a):a=>{const i=[];for(const o in a)Object.prototype.hasOwnProperty.call(a,o)&&i.push(o);return i},e.find=(a,i)=>{for(const o of a)if(i(o))return o},e.isInteger=typeof Number.isInteger=="function"?a=>Number.isInteger(a):a=>typeof a=="number"&&Number.isFinite(a)&&Math.floor(a)===a;function r(a,i=" | "){return a.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}e.joinValues=r,e.jsonStringifyReplacer=(a,i)=>typeof i=="bigint"?i.toString():i})(Tt||(Tt={}));var f1;(function(e){e.mergeShapes=(t,s)=>({...t,...s})})(f1||(f1={}));const Ue=Tt.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ja=e=>{switch(typeof e){case"undefined":return Ue.undefined;case"string":return Ue.string;case"number":return Number.isNaN(e)?Ue.nan:Ue.number;case"boolean":return Ue.boolean;case"function":return Ue.function;case"bigint":return Ue.bigint;case"symbol":return Ue.symbol;case"object":return Array.isArray(e)?Ue.array:e===null?Ue.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?Ue.promise:typeof Map<"u"&&e instanceof Map?Ue.map:typeof Set<"u"&&e instanceof Set?Ue.set:typeof Date<"u"&&e instanceof Date?Ue.date:Ue.object;default:return Ue.unknown}}
vendor: 4,703 bytes, line 792
792,ke=Tt.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class ta extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const s=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,s):this.__proto__=s,this.name="ZodError",this.issues=t}format(t){const s=t||function(i){return i.message},r={_errors:[]},a=i=>{for(const o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(a);else if(o.code==="invalid_return_type")a(o.returnTypeError);else if(o.code==="invalid_arguments")a(o.argumentsError);else if(o.path.length===0)r._errors.push(s(o));else{let l=r,c=0;for(;c<o.path.length;){const d=o.path[c];c===o.path.length-1?(l[d]=l[d]||{_errors:[]},l[d]._errors.push(s(o))):l[d]=l[d]||{_errors:[]},l=l[d],c++}}};return a(this),r}static assert(t){if(!(t instanceof ta))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Tt.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=s=>s.message){const s={},r=[];for(const a of this.issues)if(a.path.length>0){const i=a.path[0];s[i]=s[i]||[],s[i].push(t(a))}else r.push(t(a));return{formErrors:r,fieldErrors:s}}get formErrors(){return this.flatten()}}ta.create=e=>new ta(e);const Wx=(e,t)=>{let s;switch(e.code){case ke.invalid_type:e.received===Ue.undefined?s="Required":s=`Expected ${e.expected}, received ${e.received}`;break;case ke.invalid_literal:s=`Invalid literal value, expected ${JSON.stringify(e.expected,Tt.jsonStringifyReplacer)}`;break;case ke.unrecognized_keys:s=`Unrecognized key(s) in object: ${Tt.joinValues(e.keys,", ")}`;break;case ke.invalid_union:s="Invalid input";break;case ke.invalid_union_discriminator:s=`Invalid discriminator value. Expected ${Tt.joinValues(e.options)}`;break;case ke.invalid_enum_value:s=`Invalid enum value. Expected ${Tt.joinValues(e.options)}, received '${e.received}'`;break;case ke.invalid_arguments:s="Invalid function arguments";break;case ke.invalid_return_type:s="Invalid function return type";break;case ke.invalid_date:s="Invalid date";break;case ke.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(s=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(s=`${s} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?s=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?s=`Invalid input: must end with "${e.validation.endsWith}"`:Tt.assertNever(e.validation):e.validation!=="regex"?s=`Invalid ${e.validation}`:s="Invalid";break;case ke.too_small:e.type==="array"?s=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?s=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?s=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?s=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?s=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:s="Invalid input";break;case ke.too_big:e.type==="array"?s=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?s=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?s=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?s=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?s=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:s="Invalid input";break;case ke.custom:s="Invalid input";break;case ke.invalid_intersection_types:s="Intersection results could not be merged";break;case ke.not_multiple_of:s=`Number must be a multiple of ${e.multipleOf}`;break;case ke.not_finite:s="Number must be finite";break;default:s=t.defaultError,Tt.assertNever(e)}return{message:s}};let T6=Wx;function P6(){return T6}const E6=e=>
vendor: 30,561 bytes, line 792
792{const{data:t,path:s,errorMaps:r,issueData:a}=e,i=[...s,...a.path||[]],o={...a,path:i};if(a.message!==void 0)return{...a,path:i,message:a.message};let l="";const c=r.filter(d=>!!d).slice().reverse();for(const d of c)l=d(o,{data:t,defaultError:l}).message;return{...a,path:i,message:l}};function $e(e,t){const s=P6(),r=E6({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,s,s===Wx?void 0:Wx].filter(a=>!!a)});e.common.issues.push(r)}class wn{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,s){const r=[];for(const a of s){if(a.status==="aborted")return it;a.status==="dirty"&&t.dirty(),r.push(a.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,s){const r=[];for(const a of s){const i=await a.key,o=await a.value;r.push({key:i,value:o})}return wn.mergeObjectSync(t,r)}static mergeObjectSync(t,s){const r={};for(const a of s){const{key:i,value:o}=a;if(i.status==="aborted"||o.status==="aborted")return it;i.status==="dirty"&&t.dirty(),o.status==="dirty"&&t.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||a.alwaysSet)&&(r[i.value]=o.value)}return{status:t.value,value:r}}}const it=Object.freeze({status:"aborted"}),Oc=e=>({status:"dirty",value:e}),In=e=>({status:"valid",value:e}),g1=e=>e.status==="aborted",x1=e=>e.status==="dirty",Ml=e=>e.status==="valid",wm=e=>typeof Promise<"u"&&e instanceof Promise;var Be;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t==null?void 0:t.message})(Be||(Be={}));class di{constructor(t,s,r,a){this._cachedPath=[],this.parent=t,this.data=s,this._path=r,this._key=a}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const v1=(e,t)=>{if(Ml(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const s=new ta(e.common.issues);return this._error=s,this._error}}};function yt(e){if(!e)return{};const{errorMap:t,invalid_type_error:s,required_error:r,description:a}=e;if(t&&(s||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:a}:{errorMap:(o,l)=>{const{message:c}=e;return o.code==="invalid_enum_value"?{message:c??l.defaultError}:typeof l.data>"u"?{message:c??r??l.defaultError}:o.code!=="invalid_type"?{message:l.defaultError}:{message:c??s??l.defaultError}},description:a}}class Ct{get description(){return this._def.description}_getType(t){return ja(t.data)}_getOrReturnCtx(t,s){return s||{common:t.parent.common,data:t.data,parsedType:ja(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new wn,ctx:{common:t.parent.common,data:t.data,parsedType:ja(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const s=this._parse(t);if(wm(s))throw new Error("Synchronous parse encountered promise.");return s}_parseAsync(t){const s=this._parse(t);return Promise.resolve(s)}parse(t,s){const r=this.safeParse(t,s);if(r.success)return r.data;throw r.error}safeParse(t,s){const r={common:{issues:[],async:(s==null?void 0:s.async)??!1,contextualErrorMap:s==null?void 0:s.errorMap},path:(s==null?void 0:s.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:ja(t)},a=this._parseSync({data:t,path:r.path,parent:r});return v1(r,a)}"~validate"(t){var r,a;const s={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:ja(t)};if(!this["~standard"].async)try{const i=this._parseSync({data:t,path:[],parent:s});return Ml(i)?{value:i.value}:{issues:s.common.issues}}catch(i){(a=(r=i==null?void 0:i.message)==null?void 0:r.toLowerCase())!=null&&a.includes("encountered")&&(this["~standard"].async=!0),s.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:s}).then(i=>Ml(i)?{value:i.value}:{issues:s.common.issues})}async parseAsync(t,s){const r=await this.safeParseAsync(t,s);if(r.success)return r.data;throw r.error}async safeParseAsync(t,s){const r={common:{issues:[],contextualErrorMap:s==null?void 0:s.errorMap,async:!0},path:(s==null?void 0:s.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:ja(t)},a=this._parse({data:t,path:r.path,parent:r}),i=await(wm(a)?a:Promise.resolve(a));return v1(r,i)}refine(t,s){const r=a=>typeof s=="string"||typeof s>"u"?{message:s}:typeof s=="function"?s(a):s;return this._refinement((a,i)=>{const o=t(a),l=()=>i.addIssue({code:ke.custom,...r(a)});return typeof Promise<"u"&&o instanceof Promise?o.then(c=>c?!0:(l(),!1)):o?!0:(l(),!1)})}refinement(t,s){return this._refinement((r,a)=>t(r)?!0:(a.addIssue(typeof s=="function"?s(r,a):s),!1))}_refinement(t){return new Ul({schema:this,typeName:ot.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:s=>this["~validate"](s)}}optional(){return Xa.create(this,this._def)}nullable(){return Bl.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Sr.create(this)}promise(){return Nm.create(this,this._def)}or(t){return _m.create([this,t],this._def)}and(t){return km.create(this,t,this._def)}transform(t){return new Ul({...yt(this._def),schema:this,typeName:ot.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const s=typeof t=="function"?t:()=>t;return new Kx({...yt(this._def),innerType:this,defaultValue:s,typeName:ot.ZodDefault})}brand(){return new X6({typeName:ot.ZodBranded,type:this,...yt(this._def)})}catch(t){const s=typeof t=="function"?t:()=>t;return new Qx({...yt(this._def),innerType:this,catchValue:s,typeName:ot.ZodCatch})}describe(t){const s=this.constructor;return new s({...this._def,description:t})}pipe(t){return Vy.create(this,t)}readonly(){return Jx.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const A6=/^c[^\s-]{8,}$/i,R6=/^[0-9a-z]+$/,$6=/^[0-9A-HJKMNP-TV-Z]{26}$/i,L6=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,I6=/^[a-z0-9_-]{21}$/i,O6=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,D6=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,M6=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,z6="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Uf;const F6=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,U6=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,B6=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,V6=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,q6=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,H6=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,n2="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",W6=new RegExp(`^${n2}$`);function r2(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);const s=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${s}`}function G6(e){return new RegExp(`^${r2(e)}$`)}function Y6(e){let t=`${n2}T${r2(e)}`;const s=[];return s.push(e.local?"Z?":"Z"),e.offset&&s.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${s.join("|")})`,new RegExp(`^${t}$`)}function K6(e,t){return!!((t==="v4"||!t)&&F6.test(e)||(t==="v6"||!t)&&B6.test(e))}function Q6(e,t){if(!O6.test(e))return!1;try{const[s]=e.split(".");if(!s)return!1;const r=s.replace(/-/g,"+").replace(/_/g,"/").padEnd(s.length+(4-s.length%4)%4,"="),a=JSON.parse(atob(r));return!(typeof a!="object"||a===null||"typ"in a&&(a==null?void 0:a.typ)!=="JWT"||!a.alg||t&&a.alg!==t)}catch{return!1}}function J6(e,t){return!!((t==="v4"||!t)&&U6.test(e)||(t==="v6"||!t)&&V6.test(e))}class Fa extends Ct{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==Ue.string){const i=this._getOrReturnCtx(t);return $e(i,{code:ke.invalid_type,expected:Ue.string,received:i.parsedType}),it}const r=new wn;let a;for(const i of this._def.checks)if(i.kind==="min")t.data.length<i.value&&(a=this._getOrReturnCtx(t,a),$e(a,{code:ke.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="max")t.data.length>i.value&&(a=this._getOrReturnCtx(t,a),$e(a,{code:ke.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){const o=t.data.length>i.value,l=t.data.length<i.value;(o||l)&&(a=this._getOrReturnCtx(t,a),o?$e(a,{code:ke.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):l&&$e(a,{code:ke.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")M6.test(t.data)||(a=this._getOrReturnCtx(t,a),$e(a,{validation:"email",code:ke.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")Uf||(Uf=new RegExp(z6,"u")),Uf.test(t.data)||(a=this._getOrReturnCtx(t,a),$e(a,{validation:"emoji",code:ke.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")L6.test(t.data)||(a=this._getOrReturnCtx(t,a),$e(a,{validation:"uuid",code:ke.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")I6.test(t.data)||(a=this._getOrReturnCtx(t,a),$e(a,{validation:"nanoid",code:ke.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")A6.test(t.data)||(a=this._getOrReturnCtx(t,a),$e(a,{validation:"cuid",code:ke.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")R6.test(t.data)||(a=this._getOrReturnCtx(t,a),$e(a,{validation:"cuid2",code:ke.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")$6.test(t.data)||(a=this._getOrReturnCtx(t,a),$e(a,{validation:"ulid",code:ke.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(t.data)}catch{a=this._getOrReturnCtx(t,a),$e(a,{validation:"url",code:ke.invalid_string,message:i.message}),r.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(t.data)||(a=this._getOrReturnCtx(t,a),$e(a,{validation:"regex",code:ke.invalid_string,message:i.message}),r.dirty())):i.kind==="trim"?t.data=t.data.trim():i.kind==="includes"?t.data.includes(i.value,i.position)||(a=this._getOrReturnCtx(t,a),$e(a,{code:ke.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()):i.kind==="toLowerCase"?t.data=t.data.toLowerCase():i.kind==="toUpperCase"?t.data=t.data.toUpperCase():i.kind==="startsWith"?t.data.startsWith(i.value)||(a=this._getOrReturnCtx(t,a),$e(a,{code:ke.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?t.data.endsWith(i.value)||(a=this._getOrReturnCtx(t,a),$e(a,{code:ke.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?Y6(i).test(t.data)||(a=this._getOrReturnCtx(t,a),$e(a,{code:ke.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?W6.test(t.data)||(a=this._getOrReturnCtx(t,a),$e(a,{code:ke.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?G6(i).test(t.data)||(a=this._getOrReturnCtx(t,a),$e(a,{code:ke.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?D6.test(t.data)||(a=this._getOrReturnCtx(t,a),$e(a,{validation:"duration",code:ke.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?K6(t.data,i.version)||(a=this._getOrReturnCtx(t,a),$e(a,{validation:"ip",code:ke.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?Q6(t.data,i.alg)||(a=this._getOrReturnCtx(t,a),$e(a,{validation:"jwt",code:ke.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?J6(t.data,i.version)||(a=this._getOrReturnCtx(t,a),$e(a,{validation:"cidr",code:ke.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?q6.test(t.data)||(a=this._getOrReturnCtx(t,a),$e(a,{validation:"base64",code:ke.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?H6.test(t.data)||(a=this._getOrReturnCtx(t,a),$e(a,{validation:"base64url",code:ke.invalid_string,message:i.message}),r.dirty()):Tt.assertNever(i);return{status:r.value,value:t.data}}_regex(t,s,r){return this.refinement(a=>t.test(a),{validation:s,code:ke.invalid_string,...Be.errToObj(r)})}_addCheck(t){return new Fa({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...Be.errToObj(t)})}url(t){return this._addCheck({kind:"url",...Be.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...Be.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...Be.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...Be.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...Be.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...Be.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...Be.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...Be.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...Be.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...Be.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...Be.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...Be.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof(t==null?void 0:t.precision)>"u"?null:t==null?void 0:t.precision,offset:(t==null?void 0:t.offset)??!1,local:(t==null?void 0:t.local)??!1,...Be.errToObj(t==null?void 0:t.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof(t==null?void 0:t.precision)>"u"?null:t==null?void 0:t.precision,...Be.errToObj(t==null?void 0:t.message)})}duration(t){return this._addCheck({kind:"duration",...Be.errToObj(t)})}regex(t,s){return this._addCheck({kind:"regex",regex:t,...Be.errToObj(s)})}includes(t,s){return this._addCheck({kind:"includes",value:t,position:s==null?void 0:s.position,...Be.errToObj(s==null?void 0:s.message)})}startsWith(t,s){return this._addCheck({kind:"startsWith",value:t,...Be.errToObj(s)})}endsWith(t,s){return this._addCheck({kind:"endsWith",value:t,...Be.errToObj(s)})}min(t,s){return this._addCheck({kind:"min",value:t,...Be.errToObj(s)})}max(t,s){return this._addCheck({kind:"max",value:t,...Be.errToObj(s)})}length(t,s){return this._addCheck({kind:"length",value:t,...Be.errToObj(s)})}nonempty(t){return this.min(1,Be.errToObj(t))}trim(){return new Fa({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Fa({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Fa({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(const s of this._def.checks)s.kind==="min"&&(t===null||s.value>t)&&(t=s.value);return t}get maxLength(){let t=null;for(const s of this._def.checks)s.kind==="max"&&(t===null||s.value<t)&&(t=s.value);return t}}Fa.create=e=>new Fa({checks:[],typeName:ot.ZodString,coerce:(e==null?void 0:e.coerce)??!1,...yt(e)});function Z6(e,t){const s=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,a=s>r?s:r,i=Number.parseInt(e.toFixed(a).replace(".","")),o=Number.parseInt(t.toFixed(a).replace(".",""));return i%o/10**a}class zl extends Ct{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==Ue.number){const i=this._getOrReturnCtx(t);return $e(i,{code:ke.invalid_type,expected:Ue.number,received:i.parsedType}),it}let r;const a=new wn;for(const i of this._def.checks)i.kind==="int"?Tt.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),$e(r,{code:ke.invalid_type,expected:"integer",received:"float",message:i.message}),a.dirty()):i.kind==="min"?(i.inclusive?t.data<i.value:t.data<=i.value)&&(r=this._getOrReturnCtx(t,r),$e(r,{code:ke.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),a.dirty()):i.kind==="max"?(i.inclusive?t.data>i.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),$e(r,{code:ke.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),a.dirty()):i.kind==="multipleOf"?Z6(t.data,i.value)!==0&&(r=this._getOrReturnCtx(t,r),$e(r,{code:ke.not_multiple_of,multipleOf:i.value,message:i.message}),a.dirty()):i.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),$e(r,{code:ke.not_finite,message:i.message}),a.dirty()):Tt.assertNever(i);return{status:a.value,value:t.data}}gte(t,s){return this.setLimit("min",t,!0,Be.toString(s))}gt(t,s){return this.setLimit("min",t,!1,Be.toString(s))}lte(t,s){return this.setLimit("max",t,!0,Be.toString(s))}lt(t,s){return this.setLimit("max",t,!1,Be.toString(s))}setLimit(t,s,r,a){return new zl({...this._def,checks:[...this._def.checks,{kind:t,value:s,inclusive:r,message:Be.toString(a)}]})}_addCheck(t){return new zl({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:Be.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Be.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Be.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Be.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Be.toString(t)})}multipleOf(t,s){return this._addCheck({kind:"multipleOf",value:t,message:Be.toString(s)})}finite(t){return this._addCheck({kind:"finite",message:Be.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Be.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Be.toString(t)})}get minValue(){let t=null;for(const s of this._def.checks)s.kind==="min"&&(t===null||s.value>t)&&(t=s.value);return t}get maxValue(){let t=null;for(const s of this._def.checks)s.kind==="max"&&(t===null||s.value<t)&&(t=s.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&Tt.isInteger(t.value))}get isFinite(){let t=null,s=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(s===null||r.value>s)&&(s=r.value):r.kind==="max"&&(t===null||r.value<t)&&(t=r.value)}return Number.isFinite(s)&&Number.isFinite(t)}}zl.create=e=>new zl({checks:[],typeName:ot.ZodNumber,coerce:(e==null?void 0:e.coerce)||!1,...yt(e)});class Fd extends Ct{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==Ue.bigint)return this._getInvalidInput(t);let r;const a=new wn;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?t.data<i.value:t.data<=i.value)&&(r=this._getOrReturnCtx(t,r),$e(r,{code:ke.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),a.dirty()):i.kind==="max"?(i.inclusive?t.data>i.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),$e(r,{code:ke.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),a.dirty()):i.kind==="multipleOf"?t.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),$e(r,{code:ke.not_multiple_of,multipleOf:i.value,message:i.message}),a.dirty()):Tt.assertNever(i);return{status:a.value,value:t.data}}_getInvalidInput(t){const s=this._getOrReturnCtx(t);return $e(s,{code:ke.invalid_type,expected:Ue.bigint,received:s.parsedType}),it}gte(t,s){return this.setLimit("min",t,!0,Be.toString(s))}gt(t,s){return this.setLimit("min",t,!1,Be.toString(s))}lte(t,s){return this.setLimit("max",t,!0,Be.toString(s))}lt(t,s){return this.setLimit("max",t,!1,Be.toString(s))}setLimit(t,s,r,a){return new Fd({...this._def,checks:[...this._def.checks,{kind:t,value:s,inclusive:r,message:Be.toString(a)}]})}_addCheck(t){return new Fd({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Be.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Be.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Be.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Be.toString(t)})}multipleOf(t,s){return this._addCheck({kind:"multipleOf",value:t,message:Be.toString(s)})}get minValue(){let t=null;for(const s of this._def.checks)s.kind==="min"&&(t===null||s.value>t)&&(t=s.value);return t}get maxValue(){let t=null;for(const s of this._def.checks)s.kind==="max"&&(t===null||s.value<t)&&(t=s.value);return t}}Fd.create=e=>new Fd({checks:[],typeName:ot.ZodBigInt,coerce:(e==null?void 0:e.coerce)??!1,...yt(e)});class Gx extends Ct{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==Ue.boolean){const r=this._getOrReturnCtx(t);return $e(r,{code:ke.invalid_type,expected:Ue.boolean,received:r.parsedType}),it}return In(t.data)}}Gx.create=e=>new Gx({typeName:ot.ZodBoolean,coerce:(e==null?void 0:e.coerce)||!1,...yt(e)});class jm extends Ct{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==Ue.date){const i=this._getOrReturnCtx(t);return $e(i,{code:ke.invalid_type,expected:Ue.date,received:i.parsedType}),it}if(Number.isNaN(t.data.getTime())){const i=this._getOrReturnCtx(t);return $e(i,{code:ke.invalid_date}),it}const r=new wn;let a;for(const i of this._def.checks)i.kind==="min"?t.data.getTime()<i.value&&(a=this._getOrReturnCtx(t,a),$e(a,{code:ke.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):i.kind==="max"?t.data.getTime()>i.value&&(a=this._getOrReturnCtx(t,a),$e(a,{code:ke.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):Tt.assertNever(i);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new jm({...this._def,checks:[...this._def.checks,t]})}min(t,s){return this._addCheck({kind:"min",value:t.getTime(),message:Be.toString(s)})}max(t,s){return this._addCheck({kind:"max",value:t.getTime(),message:Be.toString(s)})}get minDate(){let t=null;for(const s of this._def.checks)s.kind==="min"&&(t===null||s.value>t)&&(t=s.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const s of this._def.checks)s.kind==="max"&&(t===null||s.value<t)&&(t=s.value);return t!=null?new Date(t):null}}jm.create=e=>new jm({checks:[],coerce:(e==null?void 0:e.coerce)||!1,typeName:ot.ZodDate,...yt(e)});class y1 extends Ct{_parse(t){if(this._getType(t)!==Ue.symbol){const r=this._getOrReturnCtx(t);return $e(r,{code:ke.invalid_type,expected:Ue.symbol,received:r.parsedType}),it}return In(t.data)}}y1.create=e=>new y1({typeName:ot.ZodSymbol,...yt(e)});class b1 extends Ct{_parse(t){if(this._getType(t)!==Ue.undefined){const r=this._getOrReturnCtx(t);return $e(r,{code:ke.invalid_type,expected:Ue.undefined,received:r.parsedType}),it}return In(t.data)}}b1.create=e=>new b1({typeName:ot.ZodUndefined,...yt(e)});class w1 extends Ct{_parse(t){if(this._getType(t)!==Ue.null){const r=this._getOrReturnCtx(t);return $e(r,{code:ke.invalid_type,expected:Ue.null,received:r.parsedType}),it}return In(t.data)}}w1.create=e=>new w1({typeName:ot.ZodNull,...yt(e)});class j1 extends Ct{constructor(){super(...arguments),this._any=!0}_parse(t){return In(t.data)}}j1.create=e=>new j1({typeName:ot.ZodAny,...yt(e)});class _1 extends Ct{constructor(){super(...arguments),this._unknown=!0}_parse(t){return In(t.data)}}_1.create=e=>new _1({typeName:ot.ZodUnknown,...yt(e)});class ui extends Ct{_parse(t){const s=this._getOrReturnCtx(t);return $e(s,{code:ke.invalid_type,expected:Ue.never,received:s.parsedType}),it}}ui.create=e=>new ui({typeName:ot.ZodNever,...yt(e)});class k1 extends Ct{_parse(t){if(this._getType(t)!==Ue.undefined){const r=this._getOrReturnCtx(t);return $e(r,{code:ke.invalid_type,expected:Ue.void,received:r.parsedType}),it}return In(t.data)}}k1.create=e=>new k1({typeName:ot.ZodVoid,...yt(e)});class Sr extends Ct{_parse(t){const{ctx:s,status:r}=this._processInputParams(t),a=this._def;if(s.parsedType!==Ue.array)return $e(s,{code:ke.invalid_type,expected:Ue.array,received:s.parsedType}),it;if(a.exactLength!==null){const o=s.data.length>a.exactLength.value,l=s.data.length<a.exactLength.value;(o||l)&&($e(s,{code:o?ke.too_big:ke.too_small,minimum:l?a.exactLength.value:void 0,maximum:o?a.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:a.exactLength.message}),r.dirty())}if(a.minLength!==null&&s.data.length<a.minLength.value&&($e(s,{code:ke.too_small,minimum:a.minLength.value,type:"array",inclusive:!0,exact:!1,message:a.minLength.message}),r.dirty()),a.maxLength!==null&&s.data.length>a.maxLength.value&&($e(s,{code:ke.too_big,maximum:a.maxLength.value,type:"array",inclusive:!0,exact:!1,message:a.maxLength.message}),r.dirty()),s.common.async)return Promise.all([...s.data].map((o,l)=>a.type._parseAsync(new di(s,o,s.path,l)))).then(o=>wn.mergeArray(r,o));const i=[...s.data].map((o,l)=>a.type._parseSync(new di(s,o,s.path,l)));return wn.mergeArray(r,i)}get element(){return this._def.type}min(t,s){return new Sr({...this._def,minLength:{value:t,message:Be.toString(s)}})}max(t,s){return new Sr({...this._def,maxLength:{value:t,message:Be.toString(s)}})}length(t,s){return new Sr({...this._def,exactLength:{value:t,message:Be.toString(s)}})}nonempty(t){return this.min(1,t)}}Sr.create=(e,t)=>new Sr({type:e,minLength:null,maxLength:null,exactLength:null,typeName:ot.ZodArray,...yt(t)});function Oo(e){if(e instanceof Kt){const t={};for(const s in e.shape){const r=e.shape[s];t[s]=Xa.create(Oo(r))}return new Kt({...e._def,shape:()=>t})}else return e instanceof Sr?new Sr({...e._def,type:Oo(e.element)}):e instanceof Xa?Xa.create(Oo(e.unwrap())):e instanceof Bl?Bl.create(Oo(e.unwrap())):e instanceof ao?ao.create(e.items.map(t=>Oo(t))):e}class Kt extends Ct{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),s=Tt.objectKeys(t);return this._cached={shape:t,keys:s},this._cached}_parse(t){if(this._getType(t)!==Ue.object){const d=this._getOrReturnCtx(t);return $e(d,{code:ke.invalid_type,expected:Ue.object,received:d.parsedType}),it}const{status:r,ctx:a}=this._processInputParams(t),{shape:i,keys:o}=this._getCached(),l=[];
vendor: 4,642 bytes, line 792
792if(!(this._def.catchall instanceof ui&&this._def.unknownKeys==="strip"))for(const d in a.data)o.includes(d)||l.push(d);const c=[];for(const d of o){const u=i[d],m=a.data[d];c.push({key:{status:"valid",value:d},value:u._parse(new di(a,m,a.path,d)),alwaysSet:d in a.data})}if(this._def.catchall instanceof ui){const d=this._def.unknownKeys;if(d==="passthrough")for(const u of l)c.push({key:{status:"valid",value:u},value:{status:"valid",value:a.data[u]}});else if(d==="strict")l.length>0&&($e(a,{code:ke.unrecognized_keys,keys:l}),r.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const d=this._def.catchall;for(const u of l){const m=a.data[u];c.push({key:{status:"valid",value:u},value:d._parse(new di(a,m,a.path,u)),alwaysSet:u in a.data})}}return a.common.async?Promise.resolve().then(async()=>{const d=[];for(const u of c){const m=await u.key,p=await u.value;d.push({key:m,value:p,alwaysSet:u.alwaysSet})}return d}).then(d=>wn.mergeObjectSync(r,d)):wn.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(t){return Be.errToObj,new Kt({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(s,r)=>{var i,o;const a=((o=(i=this._def).errorMap)==null?void 0:o.call(i,s,r).message)??r.defaultError;return s.code==="unrecognized_keys"?{message:Be.errToObj(t).message??a}:{message:a}}}:{}})}strip(){return new Kt({...this._def,unknownKeys:"strip"})}passthrough(){return new Kt({...this._def,unknownKeys:"passthrough"})}extend(t){return new Kt({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Kt({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:ot.ZodObject})}setKey(t,s){return this.augment({[t]:s})}catchall(t){return new Kt({...this._def,catchall:t})}pick(t){const s={};for(const r of Tt.objectKeys(t))t[r]&&this.shape[r]&&(s[r]=this.shape[r]);return new Kt({...this._def,shape:()=>s})}omit(t){const s={};for(const r of Tt.objectKeys(this.shape))t[r]||(s[r]=this.shape[r]);return new Kt({...this._def,shape:()=>s})}deepPartial(){return Oo(this)}partial(t){const s={};for(const r of Tt.objectKeys(this.shape)){const a=this.shape[r];t&&!t[r]?s[r]=a:s[r]=a.optional()}return new Kt({...this._def,shape:()=>s})}required(t){const s={};for(const r of Tt.objectKeys(this.shape))if(t&&!t[r])s[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof Xa;)i=i._def.innerType;s[r]=i}return new Kt({...this._def,shape:()=>s})}keyof(){return a2(Tt.objectKeys(this.shape))}}Kt.create=(e,t)=>new Kt({shape:()=>e,unknownKeys:"strip",catchall:ui.create(),typeName:ot.ZodObject,...yt(t)});Kt.strictCreate=(e,t)=>new Kt({shape:()=>e,unknownKeys:"strict",catchall:ui.create(),typeName:ot.ZodObject,...yt(t)});Kt.lazycreate=(e,t)=>new Kt({shape:e,unknownKeys:"strip",catchall:ui.create(),typeName:ot.ZodObject,...yt(t)});class _m extends Ct{_parse(t){const{ctx:s}=this._processInputParams(t),r=this._def.options;function a(i){for(const l of i)if(l.result.status==="valid")return l.result;for(const l of i)if(l.result.status==="dirty")return s.common.issues.push(...l.ctx.common.issues),l.result;const o=i.map(l=>new ta(l.ctx.common.issues));return $e(s,{code:ke.invalid_union,unionErrors:o}),it}if(s.common.async)return Promise.all(r.map(async i=>{const o={...s,common:{...s.common,issues:[]},parent:null};return{result:await i._parseAsync({data:s.data,path:s.path,parent:o}),ctx:o}})).then(a);{let i;const o=[];for(const c of r){const d={...s,common:{...s.common,issues:[]},parent:null},u=c._parseSync({data:s.data,path:s.path,parent:d});if(u.status==="valid")return u;u.status==="dirty"&&!i&&(i={result:u,ctx:d}),d.common.issues.length&&o.push(d.common.issues)}if(i)return s.common.issues.push(...i.ctx.common.issues),i.result;const l=o.map(c=>new ta(c));return $e(s,{code:ke.invalid_union,unionErrors:l}),it}}get options(){return this._def.options}}_m.create=(e,t)=>new _m({options:e,typeName:ot.ZodUnion,...yt(t)});function Yx(e,t){const s=ja(e),r=ja(t);if(e===t)return{valid:!0,data:e};if(s===Ue.object&&r===Ue.object){const a=Tt.objectKeys(t),i=Tt.objectKeys(e).filter(l=>a.indexOf(l)!==-1),o={...e,...t};for(const l of i){const c=Yx(e[l],t[l]);if(!c.valid)return{valid:!1};o[l]=c.data}return{valid:!0,data:o}}else if(s===Ue.array&&r===Ue.array){if(e.length!==t.length)return{valid:!1};const a=[];for(let i=0;i<e.length;i++){const o=e[i],l=t[i],c=Yx(o,l);if(!c.valid)return{valid:!1};a.push(c.data)}return{valid:!0,data:a}}else return s===Ue.date&&r===Ue.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}class km extends Ct{_parse(t){const{status:s,ctx:r}=this._processInputParams(t),a=(i,o)=>
vendor: 4,181 bytes, line 792
792{if(g1(i)||g1(o))return it;const l=Yx(i.value,o.value);return l.valid?((x1(i)||x1(o))&&s.dirty(),{status:s.value,value:l.data}):($e(r,{code:ke.invalid_intersection_types}),it)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([i,o])=>a(i,o)):a(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}km.create=(e,t,s)=>new km({left:e,right:t,typeName:ot.ZodIntersection,...yt(s)});class ao extends Ct{_parse(t){const{status:s,ctx:r}=this._processInputParams(t);if(r.parsedType!==Ue.array)return $e(r,{code:ke.invalid_type,expected:Ue.array,received:r.parsedType}),it;if(r.data.length<this._def.items.length)return $e(r,{code:ke.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),it;!this._def.rest&&r.data.length>this._def.items.length&&($e(r,{code:ke.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),s.dirty());const i=[...r.data].map((o,l)=>{const c=this._def.items[l]||this._def.rest;return c?c._parse(new di(r,o,r.path,l)):null}).filter(o=>!!o);return r.common.async?Promise.all(i).then(o=>wn.mergeArray(s,o)):wn.mergeArray(s,i)}get items(){return this._def.items}rest(t){return new ao({...this._def,rest:t})}}ao.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ao({items:e,typeName:ot.ZodTuple,rest:null,...yt(t)})};class N1 extends Ct{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:s,ctx:r}=this._processInputParams(t);if(r.parsedType!==Ue.map)return $e(r,{code:ke.invalid_type,expected:Ue.map,received:r.parsedType}),it;const a=this._def.keyType,i=this._def.valueType,o=[...r.data.entries()].map(([l,c],d)=>({key:a._parse(new di(r,l,r.path,[d,"key"])),value:i._parse(new di(r,c,r.path,[d,"value"]))}));if(r.common.async){const l=new Map;return Promise.resolve().then(async()=>{for(const c of o){const d=await c.key,u=await c.value;if(d.status==="aborted"||u.status==="aborted")return it;(d.status==="dirty"||u.status==="dirty")&&s.dirty(),l.set(d.value,u.value)}return{status:s.value,value:l}})}else{const l=new Map;for(const c of o){const d=c.key,u=c.value;if(d.status==="aborted"||u.status==="aborted")return it;(d.status==="dirty"||u.status==="dirty")&&s.dirty(),l.set(d.value,u.value)}return{status:s.value,value:l}}}}N1.create=(e,t,s)=>new N1({valueType:t,keyType:e,typeName:ot.ZodMap,...yt(s)});class Ud extends Ct{_parse(t){const{status:s,ctx:r}=this._processInputParams(t);if(r.parsedType!==Ue.set)return $e(r,{code:ke.invalid_type,expected:Ue.set,received:r.parsedType}),it;const a=this._def;a.minSize!==null&&r.data.size<a.minSize.value&&($e(r,{code:ke.too_small,minimum:a.minSize.value,type:"set",inclusive:!0,exact:!1,message:a.minSize.message}),s.dirty()),a.maxSize!==null&&r.data.size>a.maxSize.value&&($e(r,{code:ke.too_big,maximum:a.maxSize.value,type:"set",inclusive:!0,exact:!1,message:a.maxSize.message}),s.dirty());const i=this._def.valueType;function o(c){const d=new Set;for(const u of c){if(u.status==="aborted")return it;u.status==="dirty"&&s.dirty(),d.add(u.value)}return{status:s.value,value:d}}const l=[...r.data.values()].map((c,d)=>i._parse(new di(r,c,r.path,d)));return r.common.async?Promise.all(l).then(c=>o(c)):o(l)}min(t,s){return new Ud({...this._def,minSize:{value:t,message:Be.toString(s)}})}max(t,s){return new Ud({...this._def,maxSize:{value:t,message:Be.toString(s)}})}size(t,s){return this.min(t,s).max(t,s)}nonempty(t){return this.min(1,t)}}Ud.create=(e,t)=>new Ud({valueType:e,minSize:null,maxSize:null,typeName:ot.ZodSet,...yt(t)});class S1 extends Ct{get schema(){return this._def.getter()}_parse(t){const{ctx:s}=this._processInputParams(t);return this._def.getter()._parse({data:s.data,path:s.path,parent:s})}}S1.create=(e,t)=>new S1({getter:e,typeName:ot.ZodLazy,...yt(t)});class C1 extends Ct{_parse(t){if(t.data!==this._def.value){const s=this._getOrReturnCtx(t);return $e(s,{received:s.data,code:ke.invalid_literal,expected:this._def.value}),it}
vendor: 4,526 bytes, line 792
792return{status:"valid",value:t.data}}get value(){return this._def.value}}C1.create=(e,t)=>new C1({value:e,typeName:ot.ZodLiteral,...yt(t)});function a2(e,t){return new Fl({values:e,typeName:ot.ZodEnum,...yt(t)})}class Fl extends Ct{_parse(t){if(typeof t.data!="string"){const s=this._getOrReturnCtx(t),r=this._def.values;return $e(s,{expected:Tt.joinValues(r),received:s.parsedType,code:ke.invalid_type}),it}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){const s=this._getOrReturnCtx(t),r=this._def.values;return $e(s,{received:s.data,code:ke.invalid_enum_value,options:r}),it}return In(t.data)}get options(){return this._def.values}get enum(){const t={};for(const s of this._def.values)t[s]=s;return t}get Values(){const t={};for(const s of this._def.values)t[s]=s;return t}get Enum(){const t={};for(const s of this._def.values)t[s]=s;return t}extract(t,s=this._def){return Fl.create(t,{...this._def,...s})}exclude(t,s=this._def){return Fl.create(this.options.filter(r=>!t.includes(r)),{...this._def,...s})}}Fl.create=a2;class T1 extends Ct{_parse(t){const s=Tt.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==Ue.string&&r.parsedType!==Ue.number){const a=Tt.objectValues(s);return $e(r,{expected:Tt.joinValues(a),received:r.parsedType,code:ke.invalid_type}),it}if(this._cache||(this._cache=new Set(Tt.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){const a=Tt.objectValues(s);return $e(r,{received:r.data,code:ke.invalid_enum_value,options:a}),it}return In(t.data)}get enum(){return this._def.values}}T1.create=(e,t)=>new T1({values:e,typeName:ot.ZodNativeEnum,...yt(t)});class Nm extends Ct{unwrap(){return this._def.type}_parse(t){const{ctx:s}=this._processInputParams(t);if(s.parsedType!==Ue.promise&&s.common.async===!1)return $e(s,{code:ke.invalid_type,expected:Ue.promise,received:s.parsedType}),it;const r=s.parsedType===Ue.promise?s.data:Promise.resolve(s.data);return In(r.then(a=>this._def.type.parseAsync(a,{path:s.path,errorMap:s.common.contextualErrorMap})))}}Nm.create=(e,t)=>new Nm({type:e,typeName:ot.ZodPromise,...yt(t)});class Ul extends Ct{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ot.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:s,ctx:r}=this._processInputParams(t),a=this._def.effect||null,i={addIssue:o=>{$e(r,o),o.fatal?s.abort():s.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),a.type==="preprocess"){const o=a.transform(r.data,i);if(r.common.async)return Promise.resolve(o).then(async l=>{if(s.value==="aborted")return it;const c=await this._def.schema._parseAsync({data:l,path:r.path,parent:r});return c.status==="aborted"?it:c.status==="dirty"||s.value==="dirty"?Oc(c.value):c});{if(s.value==="aborted")return it;const l=this._def.schema._parseSync({data:o,path:r.path,parent:r});return l.status==="aborted"?it:l.status==="dirty"||s.value==="dirty"?Oc(l.value):l}}if(a.type==="refinement"){const o=l=>{const c=a.refinement(l,i);if(r.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return l};if(r.common.async===!1){const l=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return l.status==="aborted"?it:(l.status==="dirty"&&s.dirty(),o(l.value),{status:s.value,value:l.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(l=>l.status==="aborted"?it:(l.status==="dirty"&&s.dirty(),o(l.value).then(()=>({status:s.value,value:l.value}))))}if(a.type==="transform")if(r.common.async===!1){const o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Ml(o))return it;const l=a.transform(o.value,i);if(l instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:s.value,value:l}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(o=>Ml(o)?Promise.resolve(a.transform(o.value,i)).then(l=>({status:s.value,value:l})):it);Tt.assertNever(a)}}Ul.create=(e,t,s)=>new Ul({schema:e,typeName:ot.ZodEffects,effect:t,...yt(s)});Ul.createWithPreprocess=(e,t,s)=>new Ul({schema:t,effect:{type:"preprocess",transform:e},typeName:ot.ZodEffects,...yt(s)});class Xa extends Ct{_parse(t){return this._getType(t)===Ue.undefined?In(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Xa.create=(e,t)=>
vendor: 3,637 bytes, line 792
792new Xa({innerType:e,typeName:ot.ZodOptional,...yt(t)});class Bl extends Ct{_parse(t){return this._getType(t)===Ue.null?In(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Bl.create=(e,t)=>new Bl({innerType:e,typeName:ot.ZodNullable,...yt(t)});class Kx extends Ct{_parse(t){const{ctx:s}=this._processInputParams(t);let r=s.data;return s.parsedType===Ue.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:s.path,parent:s})}removeDefault(){return this._def.innerType}}Kx.create=(e,t)=>new Kx({innerType:e,typeName:ot.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...yt(t)});class Qx extends Ct{_parse(t){const{ctx:s}=this._processInputParams(t),r={...s,common:{...s.common,issues:[]}},a=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return wm(a)?a.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new ta(r.common.issues)},input:r.data})})):{status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new ta(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}Qx.create=(e,t)=>new Qx({innerType:e,typeName:ot.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...yt(t)});class P1 extends Ct{_parse(t){if(this._getType(t)!==Ue.nan){const r=this._getOrReturnCtx(t);return $e(r,{code:ke.invalid_type,expected:Ue.nan,received:r.parsedType}),it}return{status:"valid",value:t.data}}}P1.create=e=>new P1({typeName:ot.ZodNaN,...yt(e)});class X6 extends Ct{_parse(t){const{ctx:s}=this._processInputParams(t),r=s.data;return this._def.type._parse({data:r,path:s.path,parent:s})}unwrap(){return this._def.type}}class Vy extends Ct{_parse(t){const{status:s,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?it:i.status==="dirty"?(s.dirty(),Oc(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{const a=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?it:a.status==="dirty"?(s.dirty(),{status:"dirty",value:a.value}):this._def.out._parseSync({data:a.value,path:r.path,parent:r})}}static create(t,s){return new Vy({in:t,out:s,typeName:ot.ZodPipeline})}}class Jx extends Ct{_parse(t){const s=this._def.innerType._parse(t),r=a=>(Ml(a)&&(a.value=Object.freeze(a.value)),a);return wm(s)?s.then(a=>r(a)):r(s)}unwrap(){return this._def.innerType}}Jx.create=(e,t)=>new Jx({innerType:e,typeName:ot.ZodReadonly,...yt(t)});Kt.lazycreate;var ot;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(ot||(ot={}));const Jo=Fa.create,Zx=zl.create,i2=Gx.create;ui.create;Sr.create;const bu=Kt.create;
792Kt.strictCreate;_m.create;km.create;ao.create;const eU=Fl.create;Nm.create;Xa.create;Bl.create;const Vl=Jo().uuid(),tU=eU(["free","starter","pro","business"]).optional(),o2=bu({background_restore:Zx().min(0).max(1).optional(),face_restore:Zx().min(0).max(1).optional()}).partial().nullable().optional(),sU=bu({live_session_id:Vl,plan_key:tU,filters:o2,live_subtitles:i2().optional(),watermark_text:Jo().max(120).optional()}).passthrough(),nU=bu({content_item_id:Vl.optional(),audio_url:Jo().min(1).nullable().optional(),filters:o2,subtitles:i2().optional(),sample_steps:Zx().int().min(4).max(12).optional(),video_prompt:Jo().min(1).max(4e3).optional(),video_negative_prompt:Jo().min(1).max(4e3).optional(),watermark_text:Jo().max(120).optional()}).passthrough().refine(e=>{const t=e.frames;return!!(e.content_item_id||e.audio_url||Array.isArray(t)&&t.length>0)},{message:"Either content_item_id, audio_url, or frames is required"}),rU=bu({workspace_id:Vl,persona_id:Vl}),aU=bu({workspace_id:Vl,persona_id:Vl.optional().nullable()});function l2(e){const t=e.payload_json??{},s={workspace_id:e.workspace_id,persona_id:e.persona_id};let r=null,a=null;switch(e.job_type){case"conduct_live_session":r=sU,a=rU;break;case"render_video":r=nU,a=aU;break;default:return{ok:!0}}const i=[],o=a.safeParse(s);if(!o.success)for(const c of o.error.issues)i.push(`context.${c.path.join(".")||"(root)"}: ${c.message}`);const l=r.safeParse(t);if(!l.success)for(const c of l.error.issues)i.push(`payload.${c.path.join(".")||"(root)"}: ${c.message}`);return i.length>0?{ok:!1,details:i}:{ok:!0}}const iU=24*60*60*1e3;async function oU(e){const t=new Date(Date.now()-iU).toISOString(),{data:s,error:r}=await I.from("jobs").select("*").eq("workspace_id",e).eq("status","failed").is("dismissed_at",null).gte("created_at",t).order("created_at",{ascending:!1}).limit(20);if(r)throw r;return s??[]}function lU(){const{t:e}=Oe("dashboard"),{t}=Oe("content-studio"),{profile:s}=st(),r=s==null?void 0:s.workspace_id,a=na(),i=h.useMemo(()=>["failed-jobs-24h",r],[r]),{data:o=[]}=Zr({queryKey:i,queryFn:()=>oU(r),enabled:!!r,refetchInterval:3e4});lc({table:"jobs",filter:r?`workspace_id=eq.${r}`:void 0,queryKey:i,channelKey:`failed-jobs-${r}`,enabled:!!r});const l={generate_short_script:t("jobs.typeGenerateScript"),generate_voice:t("jobs.typeGenerateVoice"),render_video:t("jobs.typeRenderVideo"),render_short_video:t("jobs.typeRenderShortLegacy"),upload_video_to_youtube:t("jobs.typeUploadYouTube"),create_youtube_live_objects:t("jobs.typeCreateLive"),prepare_live_assets:t("jobs.typePrepareAssets"),ingest_live_chat:t("jobs.typeIngestChat"),generate_chat_reply_suggestions:t("jobs.typeGenerateReplies"),extract_live_highlights:t("jobs.typeExtractHighlights"),repurpose_live_to_shorts:t("jobs.typeRepurposeLive"),generate_consultation_summary:t("jobs.typeConsultationSummary")},[c,d]=h.useState(null),u="failedJobsAlert.collapsed",[m,p]=h.useState(()=>typeof window>"u"?!1:sessionStorage.getItem(u)==="1");h.useEffect(()=>{typeof window>"u"||sessionStorage.setItem(u,m?"1":"0")},[m]);const f=async b=>{a.setQueryData(i,y=>(y??[]).filter(w=>w.id!==b));const{error:v}=await I.from("jobs").update({dismissed_at:new Date().toISOString()}).eq("id",b);v&&(console.error("[FailedJobsAlert] dismiss error:",v),a.invalidateQueries({queryKey:i}))},g=async b=>{if(r){d(b.id);try{const v=l2({job_type:b.job_type,workspace_id:r,persona_id:b.persona_id,payload_json:b.payload_json});if(v.ok===!1){console.error("[FailedJobsAlert] retry invalid_payload:",b.job_type,v.details);return}const{data:y,error:w}=await I.from("jobs").insert({workspace_id:r,persona_id:b.persona_id,job_type:b.job_type,payload_json:b.payload_json??{}}).select().single();if(w||!y){console.error("[FailedJobsAlert] retry insert error:",w);return}s2(y.job_type)||I.functions.invoke("process-job",{body:{job_id:y.id}}).then(({error:_})=>{_&&console.error("[FailedJobsAlert] retry dispatch error:",_)}),a.setQueryData(i,_=>(_??[]).filter(N=>N.id!==b.id));const{error:j}=await I.from("jobs").update({dismissed_at:new Date().toISOString()}).eq("id",b.id);j&&(console.error("[FailedJobsAlert] retry dismiss error:",j),a.invalidateQueries({queryKey:i}))}finally{d(null)}}},x=async()=>
792{if(o.length===0)return;const b=o.map(y=>y.id);a.setQueryData(i,[]);const{error:v}=await I.from("jobs").update({dismissed_at:new Date().toISOString()}).in("id",b);v&&(console.error("[FailedJobsAlert] dismissAll error:",v),a.invalidateQueries({queryKey:i}))};return o.length===0?null:n.jsxs("section",{className:"rounded-2xl border border-destructive/25 bg-destructive/5 shadow-premium-sm p-5 md:p-6",children:[n.jsxs("div",{className:"flex items-start justify-between gap-3",children:[n.jsxs("button",{type:"button",onClick:()=>p(b=>!b),className:"flex items-center gap-2 min-w-0 flex-1 text-left -m-1 p-1 rounded-md hover:bg-destructive/5 transition-colors","aria-expanded":!m,"aria-controls":"failed-jobs-content",children:[n.jsx(ft,{size:16,className:"text-destructive shrink-0"}),n.jsx("h2",{className:"font-heading font-semibold text-sm md:text-base text-foreground",children:e("failedJobs.title")}),n.jsx(fe,{variant:"outline",className:"text-[10px] border-destructive/30 text-destructive",children:o.length}),m?n.jsx(ps,{size:14,className:"text-muted-foreground ml-auto","aria-hidden":!0}):n.jsx(wy,{size:14,className:"text-muted-foreground ml-auto","aria-hidden":!0})]}),!m&&n.jsx(L,{variant:"ghost",size:"sm",onClick:x,className:"h-7 text-[11px] text-muted-foreground hover:text-foreground shrink-0",children:e("failedJobs.dismissAll")})]}),!m&&n.jsxs("div",{id:"failed-jobs-content",className:"mt-3",children:[n.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:e("failedJobs.subtitle")}),n.jsx("ul",{className:"space-y-2",children:o.slice(0,5).map(b=>{const v=l[b.job_type]??b.job_type;return n.jsxs("li",{className:"flex items-center gap-3 rounded-lg border border-destructive/15 bg-background/60 px-3 py-2",children:[n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("p",{className:"text-xs font-semibold text-foreground truncate",children:v}),b.error_text&&n.jsx("p",{className:"text-[11px] text-muted-foreground truncate mt-0.5",children:b.error_text})]}),n.jsxs(L,{variant:"ghost",size:"sm",onClick:()=>g(b),disabled:c===b.id,className:"h-7 px-2 text-[11px] text-muted-foreground hover:text-foreground","aria-label":e("failedJobs.retry"),title:e("failedJobs.retry"),children:[c===b.id?n.jsx(xe,{size:12,className:"animate-spin mr-1"}):n.jsx(hS,{size:12,className:"mr-1"}),c===b.id?e("failedJobs.retrying"):e("failedJobs.retry")]}),n.jsx(L,{variant:"ghost",size:"sm",onClick:()=>f(b.id),disabled:c===b.id,className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground","aria-label":e("failedJobs.dismiss"),title:e("failedJobs.dismiss"),children:n.jsx(Qn,{size:14})})]},b.id)})}),o.length>5&&n.jsx(zt,{to:"/app/content",className:"mt-3 inline-block text-[11px] font-medium text-primary hover:text-primary/80",children:e("failedJobs.viewAll",{count:o.length})})]})]})}var c2="AlertDialog",[cU,Q1e]=Is(c2,[MS]),ia=MS(),d2=e=>{const{__scopeAlertDialog:t,...s}=e,r=ia(t);return n.jsx(Dy,{...r,...s,modal:!0})};d2.displayName=c2;var dU="AlertDialogTrigger",u2=h.forwardRef((e,t)=>{const{__scopeAlertDialog:s,...r}=e,a=ia(s);return n.jsx(Gz,{...a,...r,ref:t})});u2.displayName=dU;var uU="AlertDialogPortal",h2=e=>{const{__scopeAlertDialog:t,...s}=e,r=ia(t);return n.jsx(My,{...r,...s})};h2.displayName=uU;var hU="AlertDialogOverlay",m2=h.forwardRef((e,t)=>{const{__scopeAlertDialog:s,...r}=e,a=ia(s);return n.jsx(fu,{...a,...r,ref:t})});m2.displayName=hU;var dl="AlertDialogContent",[mU,pU]=cU(dl),fU=Hk("AlertDialogContent"),p2=h.forwardRef((e,t)=>{const{__scopeAlertDialog:s,children:r,...a}=e,i=ia(s),o=h.useRef(null),l=bt(t,o),c=h.useRef(null);return n.jsx(Vz,{contentName:dl,titleName:f2,docsSlug:"alert-dialog",children:n.jsx(mU,{scope:s,cancelRef:c,children:n.jsxs(gu,{role:"alertdialog",...i,...a,ref:l,onOpenAutoFocus:Ee(a.onOpenAutoFocus,d=>{var u;d.preventDefault(),(u=c.current)==null||u.focus({preventScroll:!0})}),onPointerDownOutside:d=>d.preventDefault(),onInteractOutside:d=>d.preventDefault(),children:[n.jsx(fU,{children:r}),n.jsx(xU,{contentRef:o})]})})})});p2.displayName=dl;var f2="AlertDialogTitle",g2=h.forwardRef((e,t)=>{const{__scopeAlertDialog:s,...r}=e,a=ia(s);return n.jsx(xu,{...a,...r,ref:t})});g2.displayName=f2;var x2="AlertDialogDescription",v2=h.forwardRef((e,t)=>
792{const{__scopeAlertDialog:s,...r}=e,a=ia(s);return n.jsx(vu,{...a,...r,ref:t})});v2.displayName=x2;var gU="AlertDialogAction",y2=h.forwardRef((e,t)=>{const{__scopeAlertDialog:s,...r}=e,a=ia(s);return n.jsx(vp,{...a,...r,ref:t})});y2.displayName=gU;var b2="AlertDialogCancel",w2=h.forwardRef((e,t)=>{const{__scopeAlertDialog:s,...r}=e,{cancelRef:a}=pU(b2,s),i=ia(s),o=bt(t,a);return n.jsx(vp,{...i,...r,ref:o})});w2.displayName=b2;var xU=({contentRef:e})=>{const t=`\`${dl}\` requires a description for the component to be accessible for screen reader users.
793
794You can add a description to the \`${dl}\` by passing a \`${x2}\` component as a child, which also benefits sighted users by adding visible context to the dialog.
795
796Alternatively, you can use your own component as a description by assigning it an \`id\` and passing the same value to the \`aria-describedby\` prop in \`${dl}\`. If the description is confusing or duplicative for sighted users, you can use the \`@radix-ui/react-visually-hidden\` primitive as a wrapper around your description component.
797
798For more information, see https://radix-ui.com/primitives/docs/components/alert-dialog`;return h.useEffect(()=>{var r;document.getElementById((r=e.current)==null?void 0:r.getAttribute("aria-describedby"))||console.warn(t)},[t,e]),null},vU=d2,yU=u2,bU=h2,j2=m2,_2=p2,k2=y2,N2=w2,S2=g2,C2=v2;const bi=vU,T2=yU,wU=bU,P2=h.forwardRef(({className:e,...t},s)=>n.jsx(j2,{className:_e("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:s}));P2.displayName=j2.displayName;const oa=h.forwardRef(({className:e,...t},s)=>n.jsxs(wU,{children:[n.jsx(P2,{}),n.jsx(_2,{ref:s,className:_e("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",e),...t})]}));oa.displayName=_2.displayName;const la=({className:e,...t})=>n.jsx("div",{className:_e("flex flex-col space-y-2 text-center sm:text-left",e),...t});la.displayName="AlertDialogHeader";const ca=({className:e,...t})=>n.jsx("div",{className:_e("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",e),...t});ca.displayName="AlertDialogFooter";const da=h.forwardRef(({className:e,...t},s)=>n.jsx(S2,{ref:s,className:_e("text-lg font-semibold",e),...t}));da.displayName=S2.displayName;const ua=h.forwardRef(({className:e,...t},s)=>n.jsx(C2,{ref:s,className:_e("text-sm text-muted-foreground",e),...t}));ua.displayName=C2.displayName;const ha=h.forwardRef(({className:e,...t},s)=>n.jsx(k2,{ref:s,className:_e(Ry(),e),...t}));ha.displayName=k2.displayName;const ma=h.forwardRef(({className:e,...t},s)=>n.jsx(N2,{ref:s,className:_e(Ry({variant:"outline"}),"mt-2 sm:mt-0",e),...t}));ma.displayName=N2.displayName;const Te=(e=0)=>({initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{duration:.35,delay:e}}),br={initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{duration:.4}};function E2({session:e,onCreateClick:t,onSendToReview:s,onEndLive:r,onLaunch:a,acting:i}){const{formatDateShort:o}=or(),{t:l}=Oe("live-center");return n.jsxs(de.div,{...Te(.05),className:"rounded-2xl border border-border/50 shadow-premium-md overflow-hidden",children:[n.jsxs("div",{className:"bg-gradient-primary p-6 relative",children:[n.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(circle_at_80%_20%,hsl(195_85%_48%/0.3),transparent_60%)]"}),n.jsxs("div",{className:"relative z-10 flex flex-col md:flex-row md:items-center md:justify-between gap-4",children:[e?n.jsxs("div",{children:[n.jsx("p",{className:"text-primary-foreground/60 text-xs font-medium uppercase tracking-wider mb-1",children:e.status==="live"?l("hero.nowLive"):l("hero.nextStream")}),n.jsx("h2",{className:"font-heading font-bold text-xl text-primary-foreground",children:e.title}),n.jsxs("div",{className:"flex flex-wrap items-center gap-3 mt-2.5 text-primary-foreground
798/70 text-xs",children:[e.scheduled_at&&n.jsxs("span",{className:"flex items-center gap-1",children:[n.jsx(yy,{size:12}),o(e.scheduled_at)]}),n.jsxs("span",{className:"flex items-center gap-1",children:[n.jsx(Xs,{size:12})," ",l("hero.aiPersona")]}),(()=>{var d;const c=(d=e.metadata_json)==null?void 0:d.stream_source;return c==="custom_rtmp"?n.jsxs("span",{className:"flex items-center gap-1",children:[n.jsx(St,{size:12})," Custom RTMP"]}):c==="restream"||e.platform==="restream"?n.jsxs("span",{className:"flex items-center gap-1",children:[n.jsx(St,{size:12})," Restream"]}):n.jsxs("span",{className:"flex items-center gap-1",children:[n.jsx(Ls,{size:12})," ",e.platform??"YouTube"]})})(),e.live_mode&&n.jsxs("span",{className:"flex items-center gap-1",children:[n.jsx(ls,{size:12})," ",l(`modes.${e.live_mode}`,e.live_mode)]})]})]}):n.jsxs("div",{children:[n.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[n.jsx(St,{size:16,className:"text-primary-foreground/60"}),n.jsx("p",{className:"text-primary-foreground/60 text-xs font-medium uppercase tracking-wider",children:l("hero.noScheduled")})]}),n.jsx("h2",{className:"font-heading font-bold text-xl text-primary-foreground",children:l("hero.createFirst")}),n.jsx("p",{className:"text-primary-foreground/50 text-sm mt-1",children:l("hero.createFirstDesc")})]}),e&&n.jsx(yr,{status:e.status,size:"md"})]})]}),n.jsxs("div",{className:"bg-surface-elevated p-4 flex flex-wrap gap-2",children:[a&&n.jsxs(L,{variant:"hero",className:"gap-2",onClick:a,disabled:i,children:[i?n.jsx(xe,{size:15,className:"animate-spin"}):n.jsx(Ld,{size:15}),i?l("hero.launching","Запуск..."):l("hero.launchStream","Запустить эфир")]}),n.jsxs(L,{variant:a?"hero-outline":"hero",className:"gap-2",onClick:t,children:[n.jsx(sr,{size:15})," ",l("hero.createStream")]}),s&&n.jsxs(L,{variant:"hero-outline",className:"gap-2",onClick:s,children:[n.jsx(oi,{size:15})," ",l("hero.toReview")]}),r&&n.jsxs(bi,{children:[n.jsx(T2,{asChild:!0,children:n.jsxs(L,{variant:"destructive",className:"gap-2",disabled:i,children:[i?n.jsx(xe,{size:15,className:"animate-spin"}):n.jsx(du,{size:15}),l(i?"hero.endingStream":"hero.endStream")]})}),n.jsxs(oa,{children:[n.jsxs(la,{children:[n.jsx(da,{children:l("hero.endStreamConfirmTitle")}),n.jsx(ua,{children:l("hero.endStreamConfirm")})]}),n.jsxs(ca,{children:[n.jsx(ma,{children:l("hero.endStreamCancel")}),n.jsx(ha,{onClick:r,children:l("hero.endStreamConfirmBtn")})]})]})]}),n.jsxs(L,{variant:"hero-outline",className:"gap-2",children:[n.jsx(en,{size:15})," ",l("hero.testStream")]})]})]})}function Cp(){const{session:e,profile:t}=st(),s=t==null?void 0:t.workspace_id,[r,a]=h.useState("not_connected"),[i,o]=h.useState(null),[l,c]=h.useState(!0),[d,u]=h.useState(null);h.useEffect(()=>{if(!s){c(!1);return}(async()=>{const{data:g,error:x}=await I.from("integrations").select("status, metadata_json, expires_at").eq("workspace_id",s).eq("provider","patreon").maybeSingle();if(x){console.error("Patreon integration fetch error:",x),c(!1);return}if(!g){a("not_connected"),c(!1);return}g.expires_at&&new Date(g.expires_at)<new Date?a("expired"):a(g.status);const b=g.metadata_json;b&&o({name:b.full_name||null,imageUrl:b.image_url||null,patreonUrl:b.patreon_url||null,campaignId:b.campaign_id||null,campaignTitle:b.campaign_title||null,patronCount:b.patron_count||0}),c(!1)})()},[s]),h.useEffect(()=>{const f=new URL(window.location.href),g=f.searchParams.get("code"),x=f.searchParams.get("state");if(!g||!x||!e)return;try{if(JSON.parse(atob(x)).provider!=="patreon")return}catch{return}f.searchParams.delete("code"),f.searchParams.delete("state"),window.history.replaceState({},"",f.pathname),a("connecting"),(async()=>{try{const{data:v,error:y}=await I.functions.invoke("patreon-callback",{body:{code:g,redirectUri:`${window.location.origin}/app/integrations`}});if(y)throw y;if(v!=null&&v.error)throw new Error(v.error);a("connected"),v!=null&&v.creator&&o(v.creator)}catch(v){console.error("Patreon callback error:",v),a("error"),u(v instanceof Error?v.message:"patreon_connect_error")}})()},[e]);const m=h.useCallback(async()=>{try{a("connecting"),u(null);const{data:f,error:g}=await I.functions.invoke("patreon-auth-url");if(g)throw g;if(f!=null&&f.error)throw new Error(f.error);if(!(f!=null&&f.url))throw new Error("No auth URL returned");window.location.href=f.url}catch(f){console.error("Patreon connect error:",f),a("error"),u(f instanceof Error?f.message:"patreon_start_error")}},[]),p=h.useCallback(async()=>
798{if(s)try{await I.from("integrations").update({status:"not_connected",access_token_encrypted:null,refresh_token_encrypted:null}).eq("workspace_id",s).eq("provider","patreon"),a("not_connected"),o(null)}catch(f){console.error("Patreon disconnect error:",f)}},[s]);return{status:r,creator:i,loading:l,error:d,startConnect:m,disconnect:p}}async function jU(e){const{data:t,error:s}=await I.from("personas").select("id, name, role, language, status, prompt_config").eq("workspace_id",e).eq("status","active");if(s)throw s;return t??[]}function wi(){const{profile:e}=st(),t=e==null?void 0:e.workspace_id,{data:s=[],isLoading:r}=Zr({queryKey:["personas",t],queryFn:()=>jU(t),enabled:!!t,staleTime:6e4});return{personas:s,loading:r}}async function _U(e){const{data:t,error:s}=await I.from("live_sessions").select("*").eq("workspace_id",e).order("created_at",{ascending:!1});if(s)throw s;return t??[]}function uo(){const{profile:e}=st(),t=e==null?void 0:e.workspace_id,s=na(),r=["live_sessions",t],{data:a=[],isLoading:i}=Zr({queryKey:r,queryFn:()=>_U(t),enabled:!!t}),o=h.useCallback(()=>{s.invalidateQueries({queryKey:r})},[s,r]);lc({table:"live_sessions",filter:t?`workspace_id=eq.${t}`:void 0,queryKey:r,enabled:!!t});const l=h.useCallback(g=>{I.functions.invoke("sync-live-meta",{body:{live_session_id:g}}).then(({data:x,error:b})=>{b?console.warn("[sync-live-meta] invoke error:",b):x&&!x.ok&&console.warn("[sync-live-meta] failed:",x)}).catch(x=>console.warn("[sync-live-meta] threw:",x))},[]),c=h.useCallback(async g=>{if(!t)return null;const{data:x,error:b}=await I.from("live_sessions").insert({...g,workspace_id:t}).select().single();return b?(console.error("Create live session error:",b),null):(s.setQueryData(r,v=>[x,...v??[]]),l(x.id),x)},[t,s,r,l]),d=h.useCallback(async(g,x)=>{const{error:b}=await I.from("live_sessions").update({status:x}).eq("id",g);if(b){console.error("Update live status error:",b);return}s.setQueryData(r,v=>(v??[]).map(y=>y.id===g?{...y,status:x}:y))},[s,r]),u=h.useCallback((g,x)=>{s.setQueryData(r,b=>(b??[]).map(v=>v.id===g?{...v,...x}:v))},[s,r]),m=a.find(g=>["draft","scheduled","ready"].includes(g.status)),p=a.find(g=>g.status==="live"),f=a.filter(g=>["ended","canceled","failed"].includes(g.status));return{sessions:a,upcoming:m,active:p,history:f,loading:i,refresh:o,create:c,updateStatus:d,patchSession:u,syncMeta:l}}const ql={GENERATE_SHORT_SCRIPT:"generate_short_script",GENERATE_VOICE:"generate_voice",RENDER_VIDEO:"render_video",UPLOAD_VIDEO_YOUTUBE:"upload_video_to_youtube",CONDUCT_LIVE_SESSION:"conduct_live_session",CONDUCT_CONSULTATION:"conduct_consultation",CREATE_YOUTUBE_LIVE:"create_youtube_live_objects",PREPARE_LIVE_ASSETS:"prepare_live_assets",INGEST_LIVE_CHAT:"ingest_live_chat",GENERATE_CHAT_SUGGESTIONS:"generate_chat_reply_suggestions",EXTRACT_LIVE_HIGHLIGHTS:"extract_live_highlights",REPURPOSE_LIVE:"repurpose_live_to_shorts",GENERATE_CONSULTATION_SUMMARY:"generate_consultation_summary",RENDER_SHORT_VIDEO:"render_short_video"};async function kU(e){const{data:t,error:s}=await I.from("jobs").select("*").eq("workspace_id",e).is("dismissed_at",null).order("created_at",{ascending:!1}).limit(50);if(s)throw s;return t??[]}function ho(e){const{profile:t}=st(),s=t==null?void 0:t.workspace_id,r=na(),a=["jobs",s],{data:i=[],isLoading:o}=Zr({queryKey:a,queryFn:()=>kU(s),enabled:!!s}),l=h.useCallback(()=>{r.invalidateQueries({queryKey:a})},[r,a]);lc({table:"jobs",filter:s?`workspace_id=eq.${s}`:void 0,queryKey:a,enabled:!!s});const c=h.useCallback(async g=>{if(!s)return null;const x=l2({job_type:g.job_type,workspace_id:s,persona_id:g.persona_id,payload_json:g.payload_json});if(x.ok===!1)return console.error("[useJobs.create] invalid_payload:",g.job_type,x.details),null;const{data:b,error:v}=await I.from("jobs").insert({...g,workspace_id:s}).select().single();return v?(console.error("Create job error:",v),null):(r.setQueryData(a,y=>[b,...y??[]]),b)},[s,r,a]),d=h.useCallback(async g=>{const x=await c(g);return x?(s2(x.job_type)||I.functions.invoke("process-job",{body:{job_id:x.id}}).then(({error:b})=>{b&&(console.error("Worker dispatch error:",b),l())}),x):null},[c,l]),u=i.filter(g=>["queued","running"].includes(g.status)),m=i.filter(g=>["completed","failed"].includes(g.status)).slice(0,10),p=h.useCallback(g=>i.filter(x=>x.job_type===g),[i]),f=h.useCallback((g,x)=>i.filter(b=>b.payload_json&&b.payload_json[g]===x),[i]);return{jobs:i,active:u,recent:m,loading:o,refresh:l,create:c,dispatch:d,jobsForType:p,jobsForEntity:f}}const NU=5*60*1e3,E1={status:"not_connected",profileKey:null,linkedPlatforms:[],displayNames:{},loading:!1,error:null};function Tp(){const{profile:e}=st(),t=e==null?void 0:e.workspace_id,[s,r]=h.useState(E1),a=h.useCallback(async()=>
798{if(!t)return;r(m=>({...m,loading:!0,error:null}));const{data:u}=await I.from("integrations").select("provider_account_id, metadata_json, status").eq("workspace_id",t).eq("provider","ayrshare").maybeSingle();if(u!=null&&u.provider_account_id&&u.status==="connected"){const m=u.metadata_json||{};r({status:"connected",profileKey:u.provider_account_id,linkedPlatforms:Array.isArray(m.linked_platforms)?m.linked_platforms:[],displayNames:m.display_names||{},loading:!1,error:null})}else r({...E1,loading:!1})},[t]);h.useEffect(()=>{a()},[a]);const i=h.useCallback(async()=>{r(u=>({...u,loading:!0,error:null}));try{const{data:u,error:m}=await I.functions.invoke("ayrshare-create-profile",{body:{}});if(m)throw m;if(u!=null&&u.error)throw new Error(u.error);return await a(),u}catch(u){throw r(m=>({...m,loading:!1,error:(u==null?void 0:u.message)||"Failed to create Ayrshare profile"})),u}},[a]),o=h.useCallback(async()=>{r(u=>({...u,loading:!0,error:null}));try{s.profileKey||await i();const{data:u,error:m}=await I.functions.invoke("ayrshare-link-url",{body:{}});if(m)throw m;const p=u;if(p!=null&&p.error)throw new Error(p.error);if(!(p!=null&&p.url))throw new Error("No URL returned");return window.open(p.url,"_blank","noopener,noreferrer"),r(f=>({...f,loading:!1})),p.url}catch(u){throw r(m=>({...m,loading:!1,error:(u==null?void 0:u.message)||"Failed to open link page"})),u}},[s.profileKey,i]),l=h.useCallback(async()=>{r(u=>({...u,loading:!0,error:null}));try{const{data:u,error:m}=await I.functions.invoke("ayrshare-status",{body:{}});if(m)throw m;const p=u;if(p!=null&&p.error)throw new Error(p.error);return await a(),p.linked_platforms}catch(u){throw r(m=>({...m,loading:!1,error:(u==null?void 0:u.message)||"Failed to refresh status"})),u}},[a]),c=h.useCallback(async()=>{if(!t)return!1;const{data:u}=await I.from("integrations").select("metadata_json, status").eq("workspace_id",t).eq("provider","ayrshare").maybeSingle(),m=(u==null?void 0:u.metadata_json)||{},p=typeof m.last_synced_at=="string"?Date.parse(m.last_synced_at):0;return(u==null?void 0:u.status)==="connected"&&(!p||Date.now()-p>NU)},[t]);h.useEffect(()=>{if(!t)return;let u=0;const m=()=>{const f=Date.now();f-u<3e3||(u=f,c().then(g=>g?l():void 0).catch(()=>{}))},p=()=>{document.visibilityState==="visible"&&m()};return window.addEventListener("focus",m),document.addEventListener("visibilitychange",p),()=>{window.removeEventListener("focus",m),document.removeEventListener("visibilitychange",p)}},[t,l,c]);const d=h.useCallback(async u=>{r(m=>({...m,loading:!0,error:null}));try{const{data:m,error:p}=await I.functions.invoke("ayrshare-disconnect",{body:u?{platform:u}:{}});if(p)throw p;const f=m;if(f!=null&&f.error)throw new Error(f.error);await a()}catch(m){throw r(p=>({...p,loading:!1,error:(m==null?void 0:m.message)||"Failed to disconnect"})),m}},[a]);return{...s,createProfile:i,openLinkPage:o,refreshStatus:l,disconnect:d,reload:a}}const qy="social-schedule-prefs:v1",Xx={enabled:!1,hours:24};function Bf(){try{const e=localStorage.getItem(qy);if(!e)return Xx;const t=JSON.parse(e),s=Math.max(1,Math.min(720,Number(t==null?void 0:t.hours)||24));return{enabled:!!(t!=null&&t.enabled),hours:s}}catch{return Xx}}function A1(e){try{localStorage.setItem(qy,JSON.stringify(e))}catch{}}function Hy(){const[e,t]=h.useState(()=>typeof window>"u"?Xx:Bf());h.useEffect(()=>{const a=o=>{o.key===qy&&t(Bf())},i=()=>t(Bf());return window.addEventListener("storage",a),window.addEventListener("social-schedule-prefs:change",i),()=>{window.removeEventListener("storage",a),window.removeEventListener("social-schedule-prefs:change",i)}},[]);const s=h.useCallback(a=>{t(i=>{const o={...i,enabled:a};return A1(o),window.dispatchEvent(new Event("social-schedule-prefs:change")),o})},[]),r=h.useCallback(a=>{const i=Math.max(1,Math.min(720,Math.floor(a)||1));t(o=>{const l={...o,hours:i};return A1(l),window.dispatchEvent(new Event("social-schedule-prefs:change")),l})},[]);return{enabled:e.enabled,hours:e.hours,setEnabled:s,setHours:r}}const Pp="generated-assets",A2=3600,R1=`/storage/v1/object/public/${Pp}/`,$1=`/storage/v1/object/sign/${Pp}/`;function R2(e){if(!e)return e;const t=e.indexOf($1);if(t!==-1)return e.substring(t+$1.length).split("?")[0];const s=e.indexOf(R1);if(s!==-1)return e.substring(s+R1.length).split("?")[0];const r=`/storage/v1/object/authenticated/${Pp}/`,a=e.indexOf(r);return a!==-1?e.substring(a+r.length).split("?")[0]:e}async function Bd(e,t=A2){if(!e)return null;const s=R2(e);
798if(/^https?:\/\//i.test(s))return e;const{data:r,error:a}=await I.storage.from(Pp).createSignedUrl(s,t);return a?(console.error("Failed to create signed URL:",a.message,s),null):r.signedUrl}const Vf=new Map;async function SU(e,t=!1){if(!e)return null;const s=R2(e);if(/^https?:\/\//i.test(s))return s;const r=Vf.get(s);if(!t&&r&&r.expiresAt>Date.now()+3e5)return r.url;const a=await Bd(e);return a?Vf.set(s,{url:a,expiresAt:Date.now()+A2*1e3}):Vf.delete(s),a}const CU=45*60*1e3;function cc(e){const[t,s]=h.useState(null),r=h.useRef(void 0);return h.useEffect(()=>{if(r.current=e,!e){s(null);return}let a=!1;const i=()=>{SU(e).then(l=>{a||s(l)})};i();const o=setInterval(i,CU);return()=>{a=!0,clearInterval(o)}},[e]),t}const TU=3*60*1e3;function Sm(e){return e.publish_started_at?Date.now()-new Date(e.publish_started_at).getTime()<TU:!1}const PU={youtube:"youtube",tiktok:"tiktok",instagram:"instagram",facebook:"facebook",x:"twitter",twitter:"twitter",linkedin:"linkedin"};function js(e){return PU[e.toLowerCase()]||e.toLowerCase()}function Wy(e){const t=new Set,s=e.published_targets;if(s&&typeof s=="object")for(const[r,a]of Object.entries(s))a!=null&&a.ok&&t.add(js(r));else e.published_at&&e.published_url&&t.add("youtube");return t}function $2(e,t){const s=Wy(e);return t.map(js).filter((r,a,i)=>i.indexOf(r)===a&&!s.has(r))}const Br={youtube:"YouTube",tiktok:"TikTok",instagram:"Instagram",facebook:"Facebook",twitter:"X",linkedin:"LinkedIn"};function EU(e){const{profile:t}=st(),s=t==null?void 0:t.workspace_id,[r,a]=h.useState([]),[i,o]=h.useState(!1),l=h.useCallback(async()=>{if(!e||!s)return;o(!0);const{data:f,error:g}=await I.from("live_clips").select("*").eq("live_session_id",e).order("block_index",{ascending:!0});g||a(f),o(!1)},[e,s]);h.useEffect(()=>{l()},[l]),h.useEffect(()=>{if(!(!e||!s))return Sp({table:"live_clips",filter:`live_session_id=eq.${e}`,channelKey:`live_clips:${e}`,onChange:()=>l()})},[e,s,l]);const c=h.useCallback(async f=>f.video_path?Bd(f.video_path,3600):null,[]),d=h.useCallback(async(f,g=["youtube"],x)=>{const b={live_clip_id:f,targets:g};x!=null&&x.scheduleHoursOffset&&x.scheduleHoursOffset>0&&(b.schedule_hours_offset=x.scheduleHoursOffset);const{data:v,error:y}=await I.functions.invoke("publish-live-clip",{body:b});if(y)throw y;return v},[]),u=h.useCallback(async(f,g)=>{const{data:x,error:b}=await I.functions.invoke("unpublish-live-clip",{body:{live_clip_id:f,platform:g}});if(b)throw b;if(x!=null&&x.error)throw new Error(x.error);return x},[]),m=h.useCallback(async f=>{const{data:g,error:x}=await I.functions.invoke("refresh-clip-analytics",{body:{live_clip_id:f}});if(x)throw x;if(g!=null&&g.error)throw new Error(g.error);return g},[]),p=h.useCallback(async(f=3)=>{if(!e)throw new Error("No session id");const{data:g,error:x}=await I.functions.invoke("analyze-top-clips",{body:{live_session_id:e,top_n:f}});if(x)throw x;if(g!=null&&g.error)throw new Error(g.error);return g},[e]);return{clips:r,loading:i,refresh:l,getSignedUrl:c,publish:d,unpublish:u,refreshAnalytics:m,analyzeTopClips:p}}var AU=e=>{switch(e){case"success":return LU;case"info":return OU;case"warning":return IU;case"error":return DU;default:return null}},RU=Array(12).fill(0),$U=({visible:e,className:t})=>Se.createElement("div",{className:["sonner-loading-wrapper",t].filter(Boolean).join(" "),"data-visible":e},Se.createElement("div",{className:"sonner-spinner"},RU.map((s,r)=>Se.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${r}`})))),LU=Se.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},Se.createElement("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z",clipRule:"evenodd"})),IU=Se.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},Se.createElement("path",{fillRule:"evenodd",d:"M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z",clipRule:"evenodd"})),OU=Se.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},Se.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z",clipRule:"evenodd"})),DU=Se.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},Se.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z",clipRule:"evenodd"})),MU=Se.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"},Se.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),Se.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),zU=()=>{let[e,t]=Se.useState(document.hidden);return Se.useEffect(()=>{let s=()=>{t(document.hidden)};
798return document.addEventListener("visibilitychange",s),()=>window.removeEventListener("visibilitychange",s)},[]),e},ev=1,FU=class{constructor(){this.subscribe=t=>(this.subscribers.push(t),()=>{let s=this.subscribers.indexOf(t);this.subscribers.splice(s,1)}),this.publish=t=>{this.subscribers.forEach(s=>s(t))},this.addToast=t=>{this.publish(t),this.toasts=[...this.toasts,t]},this.create=t=>{var s;let{message:r,...a}=t,i=typeof(t==null?void 0:t.id)=="number"||((s=t.id)==null?void 0:s.length)>0?t.id:ev++,o=this.toasts.find(c=>c.id===i),l=t.dismissible===void 0?!0:t.dismissible;return this.dismissedToasts.has(i)&&this.dismissedToasts.delete(i),o?this.toasts=this.toasts.map(c=>c.id===i?(this.publish({...c,...t,id:i,title:r}),{...c,...t,id:i,dismissible:l,title:r}):c):this.addToast({title:r,...a,dismissible:l,id:i}),i},this.dismiss=t=>(this.dismissedToasts.add(t),t||this.toasts.forEach(s=>{this.subscribers.forEach(r=>r({id:s.id,dismiss:!0}))}),this.subscribers.forEach(s=>s({id:t,dismiss:!0})),t),this.message=(t,s)=>this.create({...s,message:t}),this.error=(t,s)=>this.create({...s,message:t,type:"error"}),this.success=(t,s)=>this.create({...s,type:"success",message:t}),this.info=(t,s)=>this.create({...s,type:"info",message:t}),this.warning=(t,s)=>this.create({...s,type:"warning",message:t}),this.loading=(t,s)=>this.create({...s,type:"loading",message:t}),this.promise=(t,s)=>{if(!s)return;let r;s.loading!==void 0&&(r=this.create({...s,promise:t,type:"loading",message:s.loading,description:typeof s.description!="function"?s.description:void 0}));let a=t instanceof Promise?t:t(),i=r!==void 0,o,l=a.then(async d=>{if(o=["resolve",d],Se.isValidElement(d))i=!1,this.create({id:r,type:"default",message:d});else if(BU(d)&&!d.ok){i=!1;let u=typeof s.error=="function"?await s.error(`HTTP error! status: ${d.status}`):s.error,m=typeof s.description=="function"?await s.description(`HTTP error! status: ${d.status}`):s.description;this.create({id:r,type:"error",message:u,description:m})}else if(s.success!==void 0){i=!1;let u=typeof s.success=="function"?await s.success(d):s.success,m=typeof s.description=="function"?await s.description(d):s.description;this.create({id:r,type:"success",message:u,description:m})}}).catch(async d=>{if(o=["reject",d],s.error!==void 0){i=!1;let u=typeof s.error=="function"?await s.error(d):s.error,m=typeof s.description=="function"?await s.description(d):s.description;this.create({id:r,type:"error",message:u,description:m})}}).finally(()=>{var d;i&&(this.dismiss(r),r=void 0),(d=s.finally)==null||d.call(s)}),c=()=>new Promise((d,u)=>l.then(()=>o[0]==="reject"?u(o[1]):d(o[1])).catch(u));return typeof r!="string"&&typeof r!="number"?{unwrap:c}:Object.assign(r,{unwrap:c})},this.custom=(t,s)=>{let r=(s==null?void 0:s.id)||ev++;return this.create({jsx:t(r),id:r,...s}),r},this.getActiveToasts=()=>this.toasts.filter(t=>!this.dismissedToasts.has(t.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}},Hs=new FU,UU=(e,t)=>{let s=(t==null?void 0:t.id)||ev++;return Hs.addToast({title:e,...t,id:s}),s},BU=e=>e&&typeof e=="object"&&"ok"in e&&typeof e.ok=="boolean"&&"status"in e&&typeof e.status=="number",VU=UU,qU=()=>Hs.toasts,HU=()=>Hs.getActiveToasts(),Le=Object.assign(VU,{success:Hs.success,info:Hs.info,warning:Hs.warning,error:Hs.error,custom:Hs.custom,message:Hs.message,promise:Hs.promise,dismiss:Hs.dismiss,loading:Hs.loading},{getHistory:qU,getToasts:HU});function WU(e,{insertAt:t}={}){if(typeof document>"u")return;let s=document.head||document.getElementsByTagName("head")[0],r=document.createElement("style");r.type="text/css",t==="top"&&s.firstChild?s.insertBefore(r,s.firstChild):s.appendChild(r),r.styleSheet?r.styleSheet.cssText=e:r.appendChild(document.createTextNode(e))}WU(`:where(html[dir="ltr"]),:where([data-sonner-toaster][dir="ltr"]){--toast-icon-margin-start: -3px;--toast-icon-margin-end: 4px;--toast-svg-margin-start: -1px;--toast-svg-margin-end: 0px;--toast-button-margin-start: auto;--toast-button-margin-end: 0;--toast-close-button-start: 0;--toast-close-button-end: unset;--toast-close-button-transform: translate(-35%, -35%)}:where(html[dir="rtl"]),:where([data-sonner-toaster][dir="rtl"]){--toast-icon-margin-start: 4px;--toast-icon-margin-end: -3px;--toast-svg-margin-start: 0px;--toast-svg-margin-end: -1px;--toast-button-margin-start: 0;--toast-button-margin-end: auto;--toast-close-button-start: unset;--toast-close-button-end: 0;--toast-close-button-transform: translate(35%, -35%)}:where([data-sonner-toaster]){position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1: hsl(0, 0%, 99%);--gray2: hsl(0, 0%, 97.3%);--gray3: hsl(0, 0%, 95.1%);--gray4: hsl(0, 0%, 93%);--gray5: hsl(0, 0%, 90.9%);--gray6: hsl(0, 0%, 88.7%);--gray7: hsl(0, 0%, 85.8%);--gray8: hsl(0, 0%, 78%);--gray9: hsl(0, 0%, 56.1%);--gray10: hsl(0, 0%, 52.3%);--gray11: hsl(0, 0%, 43.5%);--gray12: hsl(0, 0%, 9%);--border-radius: 8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:none;z-index:999999999;transition:transform .4s ease}:where([data-sonner-toaster][data-lifted="true"]){transform:translateY(-10px)}@media (hover: none) and (pointer: coarse){:where([data-sonner-toaster][data-lifted="true"]){transform:none}}:where([data-sonner-toaster][data-x-position="right"]){right:var(--offset-right)}:where([data-sonner-toaster][data-x-position="left"]){left:var(--offset-left)}:where([data-sonner-toaster][data-x-position="center"]){left:50%;transform:translate(-50%)}:where([data-sonner-toaster][data-y-position="top"]){top:var(--offset-top)}:where([data-sonner-toaster][data-y-position="bottom"]){bottom:var(--offset-bottom)}:where([data-sonner-toast]){--y: translateY(100%);--lift-amount: calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);filter:blur(0);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:none;overflow-wrap:anywhere}:where([data-sonner-toast][data-styled="true"]){padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px #0000001a;width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}:where([data-sonner-toast]:focus-visible){box-shadow:0 4px 12px #0000001a,0 0 0 2px #0003}:where([data-sonner-toast][data-y-position="top"]){top:0;--y: translateY(-100%);--lift: 1;--lift-amount: calc(1 * var(--gap))}:where([data-sonner-toast][data-y-position="bottom"]){bottom:0;--y: translateY(100%);--lift: -1;--lift-amount: calc(var(--lift) * var(--gap))}:where([data-sonner-toast]) :where([data-description]){font-weight:400;line-height:1.4;color:inherit}:where([data-sonner-toast]) :where([data-title]){font-weight:500;line-height:1.5;color:inherit}:where([data-sonner-toast]) :where([data-icon]){display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}:where([data-sonner-toast][data-promise="true"]) :where([data-icon])>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}:where([data-sonner-toast]) :where([data-icon])>*{flex-shrink:0}:where([data-sonner-toast]) :where([data-icon]) svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}:where([data-sonner-toast]) :where([data-content]){display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;cursor:pointer;outline:none;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}:where([data-sonner-toast]) :where([data-button]):focus-visible{box-shadow:0 0 0 2px #0006}:where([data-sonner-toast]) :where([data-button]):first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}:where([data-sonner-toast]) :where([data-cancel]){color:var(--normal-text);background:rgba(0,0,0,.08)}:where([data-sonner-toast][data-theme="dark"]) :where([data-cancel]){background:rgba(255,255,255,.3)}:where([data-sonner-toast]) :where([data-close-button]){position:absolute;
798left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast] [data-close-button]{background:var(--gray1)}:where([data-sonner-toast]) :where([data-close-button]):focus-visible{box-shadow:0 4px 12px #0000001a,0 0 0 2px #0003}:where([data-sonner-toast]) :where([data-disabled="true"]){cursor:not-allowed}:where([data-sonner-toast]):hover :where([data-close-button]):hover{background:var(--gray2);border-color:var(--gray5)}:where([data-sonner-toast][data-swiping="true"]):before{content:"";position:absolute;left:-50%;right:-50%;height:100%;z-index:-1}:where([data-sonner-toast][data-y-position="top"][data-swiping="true"]):before{bottom:50%;transform:scaleY(3) translateY(50%)}:where([data-sonner-toast][data-y-position="bottom"][data-swiping="true"]):before{top:50%;transform:scaleY(3) translateY(-50%)}:where([data-sonner-toast][data-swiping="false"][data-removed="true"]):before{content:"";position:absolute;inset:0;transform:scaleY(2)}:where([data-sonner-toast]):after{content:"";position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}:where([data-sonner-toast][data-mounted="true"]){--y: translateY(0);opacity:1}:where([data-sonner-toast][data-expanded="false"][data-front="false"]){--scale: var(--toasts-before) * .05 + 1;--y: translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}:where([data-sonner-toast])>*{transition:opacity .4s}:where([data-sonner-toast][data-expanded="false"][data-front="false"][data-styled="true"])>*{opacity:0}
798:where([data-sonner-toast][data-visible="false"]){opacity:0;pointer-events:none}:where([data-sonner-toast][data-mounted="true"][data-expanded="true"]){--y: translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}:where([data-sonner-toast][data-removed="true"][data-front="true"][data-swipe-out="false"]){--y: translateY(calc(var(--lift) * -100%));opacity:0}:where([data-sonner-toast][data-removed="true"][data-front="false"][data-swipe-out="false"][data-expanded="true"]){--y: translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}:where([data-sonner-toast][data-removed="true"][data-front="false"][data-swipe-out="false"][data-expanded="false"]){--y: translateY(40%);opacity:0;transition:transform .5s,opacity .2s}:where([data-sonner-toast][data-removed="true"][data-front="false"]):before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y, 0px)) translate(var(--swipe-amount-x, 0px));transition:none}[data-sonner-toast][data-swiped=true]{user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{0%{transform:var(--y) translate(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translate(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{0%{transform:var(--y) translate(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translate(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{0%{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{0%{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width: 600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-theme=light]{--normal-bg: #fff;--normal-border: var(--gray4);--normal-text: var(--gray12);--success-bg: hsl(143, 85%, 96%);--success-border: hsl(145, 92%, 91%);--success-text: hsl(140, 100%, 27%);--info-bg: hsl(208, 100%, 97%);--info-border: hsl(221, 91%, 91%);--info-text: hsl(210, 92%, 45%);--warning-bg: hsl(49, 100%, 97%);--warning-border: hsl(49, 91%, 91%);--warning-text: hsl(31, 92%, 45%);--error-bg: hsl(359, 100%, 97%);--error-border: hsl(359, 100%, 94%);--error-text: hsl(360, 100%, 45%)}[data-sonner-toaster][data-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg: #000;--normal-border: hsl(0, 0%, 20%);--normal-text: var(--gray1)}[data-sonner-toaster][data-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg: #fff;--normal-border: var(--gray3);--normal-text: var(--gray12)}[data-sonner-toaster][data-theme=dark]{--normal-bg: #000;--normal-bg-hover: hsl(0, 0%, 12%);--normal-border: hsl(0, 0%, 20%);--normal-border-hover: hsl(0, 0%, 25%);--normal-text: var(--gray1);--success-bg: hsl(150, 100%, 6%);--success-border: hsl(147, 100%, 12%);--success-text: hsl(150, 86%, 65%);--info-bg: hsl(215, 100%, 6%);--info-border: hsl(223, 100%, 12%);--info-text: hsl(216, 87%, 65%);--warning-bg: hsl(64, 100%, 6%);--warning-border: hsl(60, 100%, 12%);--warning-text: hsl(46, 87%, 65%);--error-bg: hsl(358, 76%, 10%);--error-border: hsl(357, 89%, 16%);
798--error-text: hsl(358, 100%, 81%)}[data-sonner-toaster][data-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success],[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info],[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning],[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error],[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size: 16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:nth-child(1){animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}to{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}to{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}to{opacity:.15}}@media (prefers-reduced-motion){[data-sonner-toast],[data-sonner-toast]>*,.sonner-loading-bar{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}
799`);function oh(e){return e.label!==void 0}var GU=3,YU="32px",KU="16px",L1=4e3,QU=356,JU=14,ZU=20,XU=200;function zn(...e){return e.filter(Boolean).join(" ")}function e8(e){let[t,s]=e.split("-"),r=[];return t&&r.push(t),s&&r.push(s),r}var t8=e=>{var t,s,r,a,i,o,l,c,d,u,m;let{invert:p,toast:f,unstyled:g,interacting:x,setHeights:b,visibleToasts:v,heights:y,index:w,toasts:j,expanded:_,removeToast:N,defaultRichColors:k,closeButton:S,style:T,cancelButtonStyle:C,actionButtonStyle:B,className:E="",descriptionClassName:H="",duration:z,position:ne,gap:V,loadingIcon:te,expandByDefault:R,classNames:F,icons:$,closeButtonAriaLabel:J="Close toast",pauseWhenPageIsHidden:Y}=e,[re,G]=Se.useState(null),[O,Z]=Se.useState(null),[A,oe]=Se.useState(!1),[ue,je]=Se.useState(!1),[ae,ie]=Se.useState(!1),[we,Ae]=Se.useState(!1),[nt,Qe]=Se.useState(!1),[P,U]=Se.useState(0),[Q,ve]=Se.useState(0),We=Se.useRef(f.duration||z||L1),Ze=Se.useRef(null),Je=Se.useRef(null),xt=w===0,Pt=w+1<=v,K=f.type,ye=f.dismissible!==!1,De=f.className||"",pt=f.de
799scriptionClassName||"",kt=Se.useMemo(()=>y.findIndex(Re=>Re.toastId===f.id)||0,[y,f.id]),X=Se.useMemo(()=>{var Re;return(Re=f.closeButton)!=null?Re:S},[f.closeButton,S]),M=Se.useMemo(()=>f.duration||z||L1,[f.duration,z]),se=Se.useRef(0),he=Se.useRef(0),Ce=Se.useRef(0),Ve=Se.useRef(null),[me,Ge]=ne.split("-"),Ye=Se.useMemo(()=>y.reduce((Re,lt,at)=>at>=kt?Re:Re+lt.height,0),[y,kt]),ee=zU(),W=f.invert||p,ge=K==="loading";he.current=Se.useMemo(()=>kt*V+Ye,[kt,Ye]),Se.useEffect(()=>{We.current=M},[M]),Se.useEffect(()=>{oe(!0)},[]),Se.useEffect(()=>{let Re=Je.current;if(Re){let lt=Re.getBoundingClientRect().height;return ve(lt),b(at=>[{toastId:f.id,height:lt,position:f.position},...at]),()=>b(at=>at.filter(vs=>vs.toastId!==f.id))}},[b,f.id]),Se.useLayoutEffect(()=>{if(!A)return;let Re=Je.current,lt=Re.style.height;Re.style.height="auto";let at=Re.getBoundingClientRect().height;Re.style.height=lt,ve(at),b(vs=>vs.find(Ht=>Ht.toastId===f.id)?vs.map(Ht=>Ht.toastId===f.id?{...Ht,height:at}:Ht):[{toastId:f.id,height:at,position:f.position},...vs])},[A,f.title,f.description,b,f.id]);let Ne=Se.useCallback(()=>{je(!0),U(he.current),b(Re=>Re.filter(lt=>lt.toastId!==f.id)),setTimeout(()=>{N(f)},XU)},[f,N,b,he]);Se.useEffect(()=>{if(f.promise&&K==="loading"||f.duration===1/0||f.type==="loading")return;let Re;return _||x||Y&&ee?(()=>{if(Ce.current<se.current){let lt=new Date().getTime()-se.current;We.current=We.current-lt}Ce.current=new Date().getTime()})():We.current!==1/0&&(se.current=new Date().getTime(),Re=setTimeout(()=>{var lt;(lt=f.onAutoClose)==null||lt.call(f,f),Ne()},We.current)),()=>clearTimeout(Re)},[_,x,f,K,Y,ee,Ne]),Se.useEffect(()=>{f.delete&&Ne()},[Ne,f.delete]);function rt(){var Re,lt,at;return $!=null&&$.loading?Se.createElement("div",{className:zn(F==null?void 0:F.loader,(Re=f==null?void 0:f.classNames)==null?void 0:Re.loader,"sonner-loader"),"data-visible":K==="loading"},$.loading):te?Se.createElement("div",{className:zn(F==null?void 0:F.loader,(lt=f==null?void 0:f.classNames)==null?void 0:lt.loader,"sonner-loader"),"data-visible":K==="loading"},te):Se.createElement($U,{className:zn(F==null?void 0:F.loader,(at=f==null?void 0:f.classNames)==null?void 0:at.loader),visible:K==="loading"})}return Se.createElement("li",{tabIndex:0,ref:Je,className:zn(E,De,F==null?void 0:F.toast,(t=f==null?void 0:f.classNames)==null?void 0:t.toast,F==null?void 0:F.default,F==null?void 0:F[K],(s=f==null?void 0:f.classNames)==null?void 0:s[K]),"data-sonner-toast":"","data-rich-colors":(r=f.richColors)!=null?r:k,"data-styled":!(f.jsx||f.unstyled||g),"data-mounted":A,"data-promise":!!f.promise,"data-swiped":nt,"data-removed":ue,"data-visible":Pt,"data-y-position":me,"data-x-position":Ge,"data-index":w,"data-front":xt,"data-swiping":ae,"data-dismissible":ye,"data-type":K,"data-invert":W,"data-swipe-out":we,"data-swipe-direction":O,"data-expanded":!!(_||R&&A),style:{"--index":w,"--toasts-before":w,"--z-index":j.length-w,"--offset":`${ue?P:he.current}px`,"--initial-height":R?"auto":`${Q}px`,...T,...f.style},onDragEnd:()=>{ie(!1),G(null),Ve.current=null},onPointerDown:Re=>{ge||!ye||(Ze.current=new Date,U(he.current),Re.target.setPointerCapture(Re.pointerId),Re.target.tagName!=="BUTTON"&&(ie(!0),Ve.current={x:Re.clientX,y:Re.clientY}))},onPointerUp:()=>{var Re,lt,at,vs;if(we||!ye)return;Ve.current=null;let Ht=Number(((Re=Je.current)==null?void 0:Re.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),On=Number(((lt=Je.current)==null?void 0:lt.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),$r=new Date().getTime()-((at=Ze.current)==null?void 0:at.getTime()),nn=re==="x"?Ht:On,Dn=Math.abs(nn)/$r;if(Math.abs(nn)>=ZU||Dn>.11){U(he.current),(vs=f.onDismiss)==null||vs.call(f,f),Z(re==="x"?Ht>0?"right":"left":On>0?"down":"up"),Ne(),Ae(!0),Qe(!1);return}ie(!1),G(null)},onPointerMove:Re=>{var lt,at,vs,Ht;if(!Ve.current||!ye||((lt=window.getSelection())==null?void 0:lt.toString().length)>0)return;let On=Re.clientY-Ve.current.y,$r=Re.clientX-Ve.current.x,nn=(at=e.swipeDirections)!=null?at:e8(ne);!re&&(Math.abs($r)>1||Math.abs(On)>1)&&G(Math.abs($r)>Math.abs(On)?"x":"y");let Dn={x:0,y:0};re==="y"?(nn.includes("top")||nn.includes("bottom"))&&(nn.includes("top")&&On<0||nn.includes("bottom")&&On>0)&&(Dn.y=On):re==="x"&&(nn.includes("left")||nn.includes("right"))&&(nn.includes("left")&&$r<0||nn.includes("right")&&$r>0)&&(Dn.x=$r),(Math.abs(Dn.x)>0||Math.abs(Dn.y)>0)&&Qe(!0),(vs=Je.current)==null||vs.style.setProperty("--swipe-amount-x",`${Dn.x}px`),(Ht=Je.current)==null||Ht.style.setProperty("--swipe-amount-y",`${Dn.y}px`)}}
799,X&&!f.jsx?Se.createElement("button",{"aria-label":J,"data-disabled":ge,"data-close-button":!0,onClick:ge||!ye?()=>{}:()=>{var Re;Ne(),(Re=f.onDismiss)==null||Re.call(f,f)},className:zn(F==null?void 0:F.closeButton,(a=f==null?void 0:f.classNames)==null?void 0:a.closeButton)},(i=$==null?void 0:$.close)!=null?i:MU):null,f.jsx||h.isValidElement(f.title)?f.jsx?f.jsx:typeof f.title=="function"?f.title():f.title:Se.createElement(Se.Fragment,null,K||f.icon||f.promise?Se.createElement("div",{"data-icon":"",className:zn(F==null?void 0:F.icon,(o=f==null?void 0:f.classNames)==null?void 0:o.icon)},f.promise||f.type==="loading"&&!f.icon?f.icon||rt():null,f.type!=="loading"?f.icon||($==null?void 0:$[K])||AU(K):null):null,Se.createElement("div",{"data-content":"",className:zn(F==null?void 0:F.content,(l=f==null?void 0:f.classNames)==null?void 0:l.content)},Se.createElement("div",{"data-title":"",className:zn(F==null?void 0:F.title,(c=f==null?void 0:f.classNames)==null?void 0:c.title)},typeof f.title=="function"?f.title():f.title),f.description?Se.createElement("div",{"data-description":"",className:zn(H,pt,F==null?void 0:F.description,(d=f==null?void 0:f.classNames)==null?void 0:d.description)},typeof f.description=="function"?f.description():f.description):null),h.isValidElement(f.cancel)?f.cancel:f.cancel&&oh(f.cancel)?Se.createElement("button",{"data-button":!0,"data-cancel":!0,style:f.cancelButtonStyle||C,onClick:Re=>{var lt,at;oh(f.cancel)&&ye&&((at=(lt=f.cancel).onClick)==null||at.call(lt,Re),Ne())},className:zn(F==null?void 0:F.cancelButton,(u=f==null?void 0:f.classNames)==null?void 0:u.cancelButton)},f.cancel.label):null,h.isValidElement(f.action)?f.action:f.action&&oh(f.action)?Se.createElement("button",{"data-button":!0,"data-action":!0,style:f.actionButtonStyle||B,onClick:Re=>{var lt,at;oh(f.action)&&((at=(lt=f.action).onClick)==null||at.call(lt,Re),!Re.defaultPrevented&&Ne())},className:zn(F==null?void 0:F.actionButton,(m=f==null?void 0:f.classNames)==null?void 0:m.actionButton)},f.action.label):null))};function I1(){if(typeof window>"u"||typeof document>"u")return"ltr";let e=document.documentElement.getAttribute("dir");return e==="auto"||!e?window.getComputedStyle(document.documentElement).direction:e}function s8(e,t){let s={};return[e,t].forEach((r,a)=>{let i=a===1,o=i?"--mobile-offset":"--offset",l=i?KU:YU;function c(d){["top","right","bottom","left"].forEach(u=>{s[`${o}-${u}`]=typeof d=="number"?`${d}px`:d})}typeof r=="number"||typeof r=="string"?c(r):typeof r=="object"?["top","right","bottom","left"].forEach(d=>{r[d]===void 0?s[`${o}-${d}`]=l:s[`${o}-${d}`]=typeof r[d]=="number"?`${r[d]}px`:r[d]}):c(l)}),s}h.forwardRef(function(e,t){let{invert:s,position:r="bottom-right",hotkey:a=["altKey","KeyT"],expand:i,closeButton:o,className:l,offset:c,mobileOffset:d,theme:u="light",richColors:m,duration:p,style:f,visibleToasts:g=GU,toastOptions:x,dir:b=I1(),gap:v=JU,loadingIcon:y,icons:w,containerAriaLabel:j="Notifications",pauseWhenPageIsHidden:_}=e,[N,k]=Se.useState([]),S=Se.useMemo(()=>Array.from(new Set([r].concat(N.filter(Y=>Y.position).map(Y=>Y.position)))),[N,r]),[T,C]=Se.useState([]),[B,E]=Se.useState(!1),[H,z]=Se.useState(!1),[ne,V]=Se.useState(u!=="system"?u:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),te=Se.useRef(null),R=a.join("+").replace(/Key/g,"").replace(/Digit/g,""),F=Se.useRef(null),$=Se.useRef(!1),J=Se.useCallback(Y=>{k(re=>{var G;return(G=re.find(O=>O.id===Y.id))!=null&&G.delete||Hs.dismiss(Y.id),re.filter(({id:O})=>O!==Y.id)})},[]);return Se.useEffect(()=>Hs.subscribe(Y=>{if(Y.dismiss){k(re=>re.map(G=>G.id===Y.id?{...G,delete:!0}:G));return}setTimeout(()=>{wk.flushSync(()=>{k(re=>{let G=re.findIndex(O=>O.id===Y.id);return G!==-1?[...re.slice(0,G),{...re[G],...Y},...re.slice(G+1)]:[Y,...re]})})})}),[]),Se.useEffect(()=>{if(u!=="system"){V(u);return}if(u==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?V("dark"):V("light")),typeof window>"u")return;let Y=window.matchMedia("(prefers-color-scheme: dark)");try{Y.addEventListener("change",({matches:re})=>{V(re?"dark":"light")})}catch{Y.addListener(({matches:G})=>{try{V(G?"dark":"light")}catch(O){console.error(O)}})}},[u]),Se.useEffect(()=>{N.length<=1&&E(!1)},[N]),Se.useEffect(()=>{let Y=re=>{var G,O;a.every(Z=>re[Z]||re.code===Z)&&(E(!0),(G=te.current)==null||G.focus()),re.code==="Escape"&&(document.activeElement===te.current||(O=te.current)!=null&&O.contains(document.activeElement))&&E(!1)};return document.addEventListener("keydown",Y),()=>document.removeEventListener("keydown",Y)},[a]),Se.useEffect(()=>{if(te.current)return()=>{F.current&&(F.current.focus({preventScroll:!0}),F.current=null,$.current=!1)}},[te.current]),Se.createElement("section",{ref:t,"aria-label":`${j} ${R}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},S.map((Y,re)=>{var G;let[O,Z]=Y.split("-");return N.length?Se.createElement("ol",{key:Y,dir:b==="auto"?I1():b,tabIndex:-1,ref:te,className:l,"data-sonner-toaster":!0,"data-theme":ne,"data-y-position":O,"data-lifted":B&&N.length>1&&!i,"data-x-position":Z,style:{"--front-toast-height":`${((G=T[0])==null?void 0:G.height)||0}px`,"--width":`${QU}px`,"--gap":`${v}px`,...f,...s8(c,d)},onBlur:A=>{$.current&&!A.currentTarget.contains(A.relatedTarget)&&($.current=!1,F.current&&(F.current.focus({preventScroll:!0}),F.current=null))},onFocus:A=>{A.target instanceof HTMLElement&&A.target.dataset.dismissible==="false"||$.current||($.current=!0,F.current=A.relatedTarget)},onMouseEnter:()=>E(!0),onMouseMove:()=>E(!0),onMouseLeave:()=>{H||E(!1)},onDragEnd:()=>E(!1),onPointerDown:A=>{A.target instanceof HTMLElement&&A.target.dataset.dismissible==="false"||z(!0)},onPointerUp:()=>z(!1)},N.filter(A=>!A.position&&re===0||A.position===Y).map((A,oe)=>{var ue,je;return Se.createElement(t8,{key:A.id,icons:w,index:oe,toast:A,defaultRichColors:m,duration:(ue=x==null?void 0:x.duration)!=null?ue:p,className:x==null?void 0:x.className,descriptionClassName:x==null?void 0:x.descriptionClassName,invert:s,visibleToasts:g,closeButton:(je=x==null?void 0:x.closeButton)!=null?je:o,interacting:H,position:Y,style:x==null?void 0:x.style,unstyled:x==null?void 0:x.unstyled,classNames:x==null?void 0:x.classNames,cancelButtonStyle:x==null?void 0:x.cancelButtonStyle,actionButtonStyle:x==null?void 0:x.actionButtonStyle,removeToast:J,toasts:N.filter(ae=>ae.position==A.position),heights:T.filter(ae=>ae.position==A.position),setHeights:C,expandByDefault:i,gap:v,loadingIcon:y,expanded:B,pauseWhenPageIsHidden:_,swipeDirections:e.swipeDirections})})):null}))});async function Gy(e,t,s){var a;const r=Le.loading(`Загрузка ${t}… 0%`);try{const i=await fetch(e);if(!i.ok||!i.body)throw new Error(`HTTP ${i.status}`);const o=i.headers.get("content-length"),l=o?parseInt(o,10):0,c=i.body.getReader(),d=[];let u=0,m=-1,p=0;for(;;){const{done:y,value:w}=await c.read();if(y)break;if(w){d.push(w),u+=w.length;const j=Date.now();if(l>0){const _=Math.floor(u/l*100);_!==m&&j-p>150&&(m=_,p=j,Le.loading(`Загрузка ${t}… ${_}%`,{id:r}))}else if(j-p>300){p=j;const _=(u/1024/1024).toFixed(1);Le.loading(`Загрузка ${t}… ${_} MB`,{id:r})}}}const f=i.headers.get("content-type")||(s==null?void 0:s.mimeFallback)||"application/octet-stream",g=new Blob(d,{type:f}),x=navigator;try{const y=new File([g],t,{type:f});if((a=x==null?void 0:x.canShare)!=null&&a.call(x,{files:[y]})&&x.share){Le.dismiss(r);try{await x.share({files:[y],title:(s==null?void 0:s.title)||t});return}catch(w){if((w==null?void 0:w.name)==="AbortError")return}}}catch{}const b=URL.createObjectURL(g),v=document.createElement("a");v.href=b,v.download=t,document.body.appendChild(v),v.click(),v.remove(),setTimeout(()=>URL.revokeObjectURL(b),1e3),Le.success(`Скачано: ${t}`,{id:r})}catch(i){throw Le.error((i==null?void 0:i.message)||"Не удалось скачать",{id:r}),i}}const n8=()=>{const{t:e}=Oe("dashboard"),{t}=Oe("common"),{profile:s}=st(),{planKey:r,status:a,subscriptionEnd:i,startCheckout:o,openPortal:l}=ar(),{status:c,error:d,startConnect:u}=lo(),{status:m,error:p,startConnect:f}=Cp(),{sessions:g,upcoming:x,active:b}=uo(),{active:v,recent:y}=ho(),{personas:w}=wi(),j=Tp(),{enabled:_,hours:N}=Hy(),k=y.filter(G=>G.status==="failed"),S=g.filter(G=>G.status==="failed"),T=kp({t,ytStatus:c,ytError:d,patreonStatus:m,patreonError:p,subStatus:a,planKey:r,failedJobs:k,failedLiveSessions:S,onYtReconnect:u,onPatreonReconnect:f,onManageBilling:l,onUpgrade:()=>{var O;const G=(O=Md.pro.monthly)==null?void 0:O.priceId;G&&o(G)}}),C=b??x??null,[B,E]=h.useState([]),[H,z]=h.useState({total:0,ready:0,pending:0,uploading:0,failed:0}),[ne,V]=h.useState(null),[te,R]=h.useState({});h.useEffect(()=>{if(!(s!=null&&s.workspace_id))return;let G=!1;const O=async()=>{const{data:A}=await I.from("live_clips").select("id, live_session_id, block_index, duration_seconds, spoken_text, video_path, created_at, status, publish_started_at, published_at, published_url, published_targets").eq("workspace_id",s.workspace_id).order("created_at",{ascending:!1}).limit(50);if(!G&&A){const oe=A;E(oe.filter(ue=>ue.status==="ready").slice(0,6)),z({total:oe.length,ready:oe.filter(ue=>ue.status==="ready").length,pending:oe.filter(ue=>ue.status==="pending").length,uploading:oe.filter(ue=>ue.status==="uploading").length,failed:oe.filter(ue=>ue.status==="failed").length})}};O();const Z=Sp({table:"live_clips",filter:`workspace_id=eq.${s.workspace_id}
799`,channelKey:`dash-clips:${s.workspace_id}`,onChange:()=>O()});return()=>{G=!0,Z()}},[s==null?void 0:s.workspace_id]);const F=async G=>{if(!G.video_path)return;const O=await Bd(G.video_path,60*60);O?window.open(O,"_blank"):Le.error(e("clipPreviewFailed","Preview unavailable"))},$=async G=>{var A,oe;if(ne===G.id||Sm(G))return;let O=j.linkedPlatforms;if(j.status==="connected"&&O.length===0&&(O=await j.refreshStatus()),j.status!=="connected"||O.length===0){Le.error(e("noSocialLinked","Привяжите соцсети в разделе Интеграции"));return}const Z=$2(G,O);if(Z.length===0){Le.info(e("toastNothingToDo","Уже опубликовано во все подключённые сети"));return}V(G.id);try{const ue={live_clip_id:G.id,targets:Z};_&&(ue.schedule_hours_offset=N);const{data:je,error:ae}=await I.functions.invoke("publish-live-clip",{body:ue});if(ae)throw ae;const ie=je;if(ie!=null&&ie.in_progress)Le.info(e("toastPublishingBg","Публикация запущена в фоне — статус обновится автоматически"));else{const we=(ie==null?void 0:ie.results_now)||(ie==null?void 0:ie.results)||{},Ae=Object.entries(we).filter(([,U])=>U==null?void 0:U.ok),nt=Object.entries(we).filter(([,U])=>!(U!=null&&U.ok)),Qe=Ae.map(([U])=>Br[js(U)]||U),P=nt.map(([U])=>Br[js(U)]||U);if(ie!=null&&ie.nothing_to_do)Le.info(e("toastNothingToDo","Уже опубликовано во все подключённые сети"));else if(Ae.length>0&&nt.length===0)Le.success(e("toastPublishedTo",{list:Qe.join(", "),defaultValue:`Опубликовано: ${Qe.join(", ")}`}));else if(Ae.length>0&&nt.length>0){const U=((A=nt[0][1])==null?void 0:A.error)||"failed";Le.warning(e("toastPartial",{ok:Qe.join(", "),fail:P.join(", "),defaultValue:`Опубликовано: ${Qe.join(", ")}. Ошибки: ${P.join(", ")} — ${U}`}))}else if(nt.length>0){const U=((oe=nt[0][1])==null?void 0:oe.error)||"failed";Le.error(`${P.join(", ")}: ${U}`)}}}catch(ue){Le.error((ue==null?void 0:ue.message)||e("publishFailed","Publish failed"))}finally{V(null)}},J=async G=>{if(!G.video_path)return;const O=await Bd(G.video_path,60*60);if(!O){Le.error(e("clipPreviewFailed","Preview unavailable"));return}try{await Gy(O,`clip-${G.block_index+1}.mp4`,{mimeFallback:"video/mp4"})}catch{}},Y=w.length===0||c!=="connected",re=[{icon:Xs,label:e("qa.persona","Personas"),to:"/app/persona"},{icon:Sy,label:e("qa.content","Create short"),to:"/app/content"},{icon:St,label:e("qa.live","Schedule live"),to:"/app/live"},{icon:by,label:e("qa.analytics","Analytics"),to:"/app/analytics"}];return n.jsxs("div",{className:"max-w-6xl mx-auto space-y-6",children:[n.jsx(QC,{status:a,planKey:r,subscriptionEnd:i,onUpgrade:()=>{var O;const G=(O=Md.pro.monthly)==null?void 0:O.priceId;G&&o(G)},onManage:l}),n.jsx(_p,{alerts:T,title:e("needsAttention")}),n.jsx(lU,{}),Y&&n.jsxs(de.div,{...Te(0),className:"rounded-2xl bg-gradient-hero border border-border/50 shadow-premium-sm p-6 md:p-8 flex flex-col md:flex-row md:items-center gap-4 md:gap-6",children:[n.jsxs("div",{className:"flex-1",children:[n.jsx("h1",{className:"font-heading font-bold text-xl md:text-2xl text-foreground mb-1.5",children:w.length===0?e("onboard.noPersona","Создай первую персону"):e("onboard.connectYt","Подключи YouTube")}),n.jsx("p",{className:"text-sm text-muted-foreground",children:w.length===0?e("onboard.noPersonaSub","С неё начинается всё — голос, аватар, стиль для шортсов и эфиров."):e("onboard.connectYtSub","Без YouTube не получится публиковать клипы и видеть аналитику.")})]}),n.jsx(L,{variant:"hero",className:"gap-2 shrink-0",asChild:!0,children:n.jsxs(zt,{to:w.length===0?"/app/persona":"/app/integrations",children:[n.jsx(tt,{size:15})," ",w.length===0?e("createPersona"):e("onboard.connectBtn","Подключить")]})})]}),C&&n.jsx(de.div,{...Te(.05),children:n.jsx(E2,{session:C,onCreateClick:()=>{},acting:!1})}),v.length>0&&n.jsxs(de.section,{...Te(.08),className:"rounded-2xl bg-surface-elevated border border-primary/15 shadow-premium-sm p-5 md:p-6",children:[n.jsxs("div",{className:"flex items-center justify-between mb-4 gap-3",children:[n.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[n.jsx(Ed,{size:16,className:"text-primary shrink-0"}),n.jsx("h2",{className:"font-heading font-semibold text-sm md:text-base text-foreground",children:e("activeJobs.title","Active tasks")}),n.jsx("span",{className:"text-xs text-muted-foreground truncate",children:e("tasksRunning",{count:v.length})})]}),n.jsxs(zt,{to:"/app/content",className:"text-xs font-medium text-primary hover:text-primary/80 flex items-center gap-1 shrink-0",children:[e("activeJobs.viewAll","All tasks")," ",n.jsx(Tr,{size:13})]})]}),n.jsx("div",{className:"grid sm:grid-cols-2 gap-3",children:v.slice(0,4).map(G=>n.jsx(ZC,{job:G},G.id))})]}),n.jsxs(de.section,{...Te(.1),className:"rounded-2xl bg-surface-elevated border border-border/50 shadow-premium-sm p-5 md:p-6",children:[n.jsxs("div",{className:"flex items-center justify-between mb-4",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(pm,{size:16,className:"text-primary"}),n.jsx("h2",{className:"font-heading font-semibold text-sm md:text-base text-foreground",children:e("recentClips.title","Готовые клипы")}),n.jsx(fe,{variant:"outline",className:"text-[10px]",children:H.ready})]}),n.jsxs(zt,{to:"/app/live",className:"text-xs font-medium text-primary hover:text-primary/80 flex items-center gap-1",children:[e("recentClips.all","Все эфиры")," ",n.jsx(Tr,{size:13})]})]}),B.length===0?n.jsxs("div",{className:"rounded-xl border border-border/40 bg-muted/20 p-4 text-sm text-muted-foreground",children:[n.jsx("p",{children:e("recentClips.empty","Пока нет готовых клипов.")}),n.jsx("p",{className:"text-xs mt-1",children:H.total>0?e("recentClips.processing",{defaultValue:"Клипы есть, но ещё не готовы: {{pending}} в очереди, {{uploading}} загружается, {{failed}}
799 с ошибкой.",pending:H.pending,uploading:H.uploading,failed:H.failed}):e("recentClips.noRows","В базе пока нет нарезок из эфиров. Когда воркер создаст клипы, они появятся здесь.")})]}):n.jsx("div",{className:"space-y-1.5",children:B.map(G=>n.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-lg bg-muted/20 border border-border/30 text-xs",children:[n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsxs("div",{className:"flex items-center gap-2 text-foreground",children:[n.jsxs("span",{className:"font-medium",children:["#",G.block_index+1]}),n.jsx("span",{className:"text-muted-foreground",children:G.duration_seconds?`${Math.round(G.duration_seconds)}s`:"—"})]}),G.spoken_text&&n.jsxs(n.Fragment,{children:[n.jsx("p",{className:`text-[11px] text-muted-foreground mt-0.5 whitespace-pre-wrap break-words ${te[G.id]?"":"line-clamp-2"}`,children:G.spoken_text}),G.spoken_text.length>140&&n.jsx("button",{type:"button",onClick:O=>{O.stopPropagation(),R(Z=>({...Z,[G.id]:!Z[G.id]}))},className:"text-[10px] text-primary hover:underline mt-0.5",children:te[G.id]?e("collapse","Свернуть"):e("expand","Показать весь текст")})]})]}),n.jsx(L,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0",onClick:()=>F(G),title:e("preview","Preview"),children:n.jsx(Rs,{size:12})}),n.jsx(L,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0",onClick:()=>J(G),title:e("download","Download"),children:n.jsx(Ny,{size:12})}),(()=>{const O=ne===G.id||Sm(G),Z=Wy(G),A=j.linkedPlatforms.map(js),oe=A.filter(we=>!Z.has(we)),ue=j.status!=="connected"||A.length===0,je=!ue&&oe.length===0,ae=!ue&&Z.size>0&&oe.length>0;if(ue&&Z.size===0)return n.jsx(L,{asChild:!0,size:"sm",variant:"outline",className:"h-7 gap-1 text-[11px] px-2",children:n.jsxs(zt,{to:"/app/integrations",title:e("connectSocialsCta","Подключите соцсети"),children:[n.jsx(Pr,{size:11}),e("connectSocialsCta","Подключите соцсети")]})});const ie=O?e("publishingBtn","Публикуется…"):je?e("publishedEverywhere","Опубликовано везде"):ae?e("publishMoreBtn",{count:oe.length,defaultValue:`Опубликовать ещё в ${oe.length}`}):e("publishBtn","Опубликовать");return n.jsxs(L,{size:"sm",variant:je?"outline":"hero",className:"h-7 gap-1 text-[11px] px-2",onClick:()=>{je||$(G)},disabled:O||je,title:je?A.map(we=>Br[we]||we).join(", "):void 0,children:[O?n.jsx(xe,{size:11,className:"animate-spin"}):je?n.jsx(ms,{size:11}):n.jsx(Za,{size:11}),ie]})})()]},G.id))})]}),n.jsx(de.div,{...Te(.15),className:"grid grid-cols-2 sm:grid-cols-4 gap-3",children:re.map(G=>n.jsxs(zt,{to:G.to,className:"rounded-xl bg-surface-elevated border border-border/50 shadow-premium-sm p-4 hover:border-primary/30 hover:shadow-premium-md transition-all flex flex-col items-center gap-2 text-center",children:[n.jsx("div",{className:"w-10 h-10 rounded-lg bg-primary/8 flex items-center justify-center",children:n.jsx(G.icon,{size:18,className:"text-primary"})}),n.jsx("span",{className:"text-xs font-semibold text-foreground",children:G.label})]},G.to))})]})};function Cm({imageUrl:e,targetWidth:t,targetHeight:s,onCrop:r,onCancel:a}){const{t:i}=Oe("common"),o=h.useRef(null),[l,c]=h.useState(null),[d,u]=h.useState(1),[m,p]=h.useState({x:0,y:0}),[f,g]=h.useState(!1),x=h.useRef({x:0,y:0,ox:0,oy:0}),b=400,y=t/s>=1?b/t:b/s,w=t*y,j=s*y,_=(l==null?void 0:l.naturalWidth)||(l==null?void 0:l.width)||0,N=(l==null?void 0:l.naturalHeight)||(l==null?void 0:l.height)||0;h.useEffect(()=>{const $=new Image;$.crossOrigin="anonymous",$.onload=()=>{c($),u(1),p({x:0,y:0})},$.src=e},[e]);const k=l&&_&&N?Math.max(w/_,j/N):1,S=h.useCallback(($,J,Y)=>{if(!l||!_||!N)return{x:0,y:0};const re=k*Y,G=_*re,O=N*re,Z=Math.max(0,(G-w)/2),A=Math.max(0,(O-j)/2);return{x:Math.min(Math.max($,-Z),Z),y:Math.min(Math.max(J,-A),A)}},[l,_,N,k,w,j]),T=h.useCallback($=>{if($.preventDefault(),!l)return;const J=$.deltaY>0?-.05:.05;u(Y=>{const re=Math.max(1,Math.min(Y+J,5));return p(G=>S(G.x,G.y,re)),re})},[l,S]),C=h.useCallback($=>{$.preventDefault(),g(!0),x.current={x:$.clientX,y:$.clientY,ox:m.x,oy:m.y},$.target.setPointerCapture($.pointerId)},[m]),B=h.useCallback($=>{if(!f)return;const J=$.clientX-x.current.x,Y=$.clientY-x.current.y;p(S(x.current.ox+J,x.current.oy+Y,d))},[f,d,S]),E=h.useCallback(()=>g(!1),[]),H=h.useCallback($=>{const J=parseFloat($.target.value);u(J),p(Y=>S(Y.x,Y.y,J))},[S]),z=h.useCallback(()=>
799{if(!l||!_||!N)return;const $=document.createElement("canvas");$.width=t,$.height=s;const J=$.getContext("2d"),Y=k*d,re=_*Y,G=N*Y,O=w/2-re/2+m.x,Z=j/2-G/2+m.y,A=w/Y,oe=j/Y,ue=Math.min(Math.max(-O/Y,0),Math.max(0,_-A)),je=Math.min(Math.max(-Z/Y,0),Math.max(0,N-oe));J.imageSmoothingEnabled=!0,J.imageSmoothingQuality="high",J.drawImage(l,ue,je,A,oe,0,0,t,s),$.toBlob(ae=>{ae&&r(ae)},"image/jpeg",.92)},[l,_,N,d,m,t,s,k,w,j,r]),ne=l?k*d:1,V=l?_*ne:0,te=l?N*ne:0,R=w/2-V/2+m.x,F=j/2-te/2+m.y;return n.jsxs("div",{className:"flex flex-col items-center gap-4",children:[n.jsxs("div",{ref:o,className:"relative overflow-hidden rounded-xl border-2 border-primary/30 bg-muted/50 cursor-grab active:cursor-grabbing",style:{width:w,height:j},onWheel:T,onPointerDown:C,onPointerMove:B,onPointerUp:E,onPointerLeave:E,children:[l&&n.jsx("img",{src:e,alt:"",draggable:!1,className:"select-none pointer-events-none",style:{position:"absolute",width:V,height:te,maxWidth:"none",maxHeight:"none",left:R,top:F,objectFit:"contain"}}),n.jsx("div",{className:"absolute inset-0 pointer-events-none",style:{backgroundImage:"linear-gradient(rgba(255,255,255,.08) 1px, transparent 1px), linear-gradient(90deg, rgba(255,255,255,.08) 1px, transparent 1px)",backgroundSize:`${w/3}px ${j/3}px`}})]}),n.jsxs("div",{className:"flex items-center gap-3 w-full max-w-[320px]",children:[n.jsx("span",{className:"text-xs text-muted-foreground",children:"−"}),n.jsx("input",{type:"range",min:1,max:5,step:.01,value:d,onChange:H,className:"flex-1 accent-primary h-1.5"}),n.jsx("span",{className:"text-xs text-muted-foreground",children:"+"})]}),n.jsx("p",{className:"text-[11px] text-muted-foreground",children:i("avatarCropper.hint")}),n.jsxs("div",{className:"flex gap-3 w-full",children:[n.jsx("button",{onClick:a,className:"flex-1 rounded-xl border border-border/50 py-2.5 text-sm font-medium text-muted-foreground hover:bg-muted/30 transition-colors",children:i("avatarCropper.back")}),n.jsx("button",{onClick:z,className:"flex-1 rounded-xl bg-primary py-2.5 text-sm font-semibold text-primary-foreground hover:bg-primary/90 transition-colors",children:i("avatarCropper.crop")})]})]})}const ns=Dy,r8=My,L2=h.forwardRef(({className:e,...t},s)=>n.jsx(fu,{ref:s,className:_e("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t}));L2.displayName=fu.displayName;const Zt=h.forwardRef(({className:e,children:t,...s},r)=>n.jsxs(r8,{children:[n.jsx(L2,{}),n.jsxs(gu,{ref:r,className:_e("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",e),...s,children:[t,n.jsxs(vp,{className:"absolute right-4 top-4 roun
799ded-sm opacity-70 ring-offset-background transition-opacity data-[state=open]:bg-accent data-[state=open]:text-muted-foreground hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none",children:[n.jsx(Qn,{className:"h-4 w-4"}),n.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Zt.displayName=gu.displayName;const Xt=({className:e,...t})=>n.jsx("div",{className:_e("flex flex-col space-y-1.5 text-center sm:text-left",e),...t});Xt.displayName="DialogHeader";const Hl=({className:e,...t})=>n.jsx("div",{className:_e("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",e),...t});Hl.displayName="DialogFooter";const es=h.forwardRef(({className:e,...t},s)=>n.jsx(xu,{ref:s,className:_e("text-lg font-semibold leading-none tracking-tight",e),...t}));es.displayName=xu.displayName;const us=h.forwardRef(({className:e,...t},s)=>n.jsx(vu,{ref:s,className:_e("text-sm text-muted-foreground",e),...t}));us.displayName=vu.displayName;const a8=({t:e,persona:t,selectedRole:s,selectedStyle:r,orientation:a,update:i,save:o,onReplaceAvatar:l})=>{var k,S,T;const c=a!=="landscape",[d,u]=h.useState(!1),m=h.useRef(null),p=((k=t.prompt_config)==null?void 0:k.background_restore)??.5,f=((S=t.prompt_config)==null?void 0:S.face_restore)??.5,g=h.useRef(t.prompt_config||{});g.current=t.prompt_config||{};const[x,b]=h.useState(!1),v=h.useCallback((C,B)=>{const E={...g.current,[C]:B};g.current=E,i({prompt_config:E}),m.current&&clearTimeout(m.current),m.current=setTimeout(()=>{o()},2e3)},[i,o]),y=h.useCallback(async()=>{if(!(t!=null&&t.id)||!(t!=null&&t.avatar_url)){Le.error(e("filters.autoNeedsAvatar")||"Загрузи фото персоны");return}b(!0);try{const{data:C,error:B}=await I.functions.invoke("analyze-avatar-restore",{body:{persona_id:t.id}});if(B)throw B;if(C!=null&&C.error)throw new Error(C.error);const E={...g.current,face_restore:Number(C.face_restore),background_restore:Number(C.background_restore)};g.current=E,i({prompt_config:E}),await o(),Le.success((e("filters.autoApplied")||"Применено")+` · face ${Number(C.face_restore).toFixed(1)} / bg ${Number(C.background_restore).toFixed(1)}`,{description:C.reason||void 0})}catch(C){Le.error(e("filters.autoFailed")||"Не получилось проанализировать",{description:C==null?void 0:C.message})}finally{b(!1)}},[t==null?void 0:t.id,t==null?void 0:t.avatar_url,i,o,e]),w=cc(t.avatar_url),[j,_]=h.useState(!1),N=h.useRef(null);return h.useEffect(()=>{w!==N.current&&(_(!1),N.current=w??null)},[w]),n.jsxs(de.div,{...br,transition:{delay:.1},className:"rounded-2xl border border-border/50 shadow-premium-md overflow-hidden bg-surface-elevated",children:[n.jsxs("div",{className:"bg-gradient-primary p-4 sm:p-5 relative",children:[n.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(circle_at_70%_30%,hsl(195_85%_48%/0.3),transparent_60%)]"}),n.jsxs("p",{className:"text-primary-foreground/70 text-xs font-medium relative z-10 flex items-center gap-1.5",children:[n.jsx(oi,{size:12})," ",e("preview")]})]}),n.jsxs("div",{className:"flex flex-col items-center px-5 sm:px-6 pb-5 sm:pb-6 pt-4",children:[w?n.jsxs(de.div,{onClick:()=>u(C=>!C),animate:{width:d?c?270:480:c?162:288,height:d?c?480:270:c?288:162},transition:{type:"spring",stiffness:300,damping:28},className:"relative rounded-2xl overflow-hidden shadow-premium-md border-2 border-border/30 cursor-pointer group",children:[n.jsx("img",{src:w,alt:t.name,onLoad:()=>_(!0),className:"w-full h-full object-cover",style:{filter:j?"blur(0)":"blur(16px)",opacity:j?1:.5,transform:j?"scale(1)":"scale(1.08)",transition:"filter 0.6s ease-out, opacity 0.6s ease-out, transform 0.6s ease-out"}}),l&&n.jsx("button",{onClick:C=>{C.stopPropagation(),l()},className:"absolute inset-0 flex items-center justify-center bg-black/0 group-hover:bg-black/40 transition-all opacity-0 group-hover:opacity-100 z-10",children:n.jsxs("div",{className:"flex flex-col items-center gap-1",children:[n.jsx(Rw,{size:24,className:"text-white drop-shadow-lg"}),n.jsx("span",{className:"text-[10px] text-white font-medium drop-shadow-lg",children:e("replaceAvatar")})]})})]}):n.jsxs("div",{className:`relative rounded-2xl bg-gradient-primary shadow-premium-md flex items-center justify-center text-primary-foreground font-bold border-2 border-border/30 group text-3xl ${c?"w-[162px] h-[288px]":"w-[288px] h-[162px]"}`,children:[t.name.charAt(0).toUpperCase(),l&&n.jsx("button",{onClick:C=>{C.stopPropagation(),l()},className:"absolute inset-0 flex items-center justify-center bg-black/0 group-hover:bg-black/40 transition-all opacity-0 group-hover:opacity-100 rounded-2xl",children:n.jsxs("div",{className:"flex flex-col items-center gap-1",children:[n.jsx(Rw,{size:24,className:"text-white drop-shadow-lg"}),n.jsx("span",{className:"text-[10px] text-white font-medium drop-shadow-lg",children:e("replaceAvatar")})]})})]}),n.jsxs("div",{className:"mt-4 space-y-3 text-center w-full",children:[n.jsxs("div",{children:[n.jsx("h3",{className:"font-heading font-bold text-base sm:text-lg text-foreground",children:t.name}),n.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1.5",children:[s&&n.jsx(s.icon,{size:12}),s==null?void 0:s.label,c?` · ${e("portrait")}`:` · ${e("landscape")}`]})]}),n.jsx("p",{className:"text-xs sm:text-sm text-muted-foreground leading-relaxed",children:t.description}),r&&n.jsxs("div",{className:"flex items-center justify-center gap-2 rounded-lg bg-muted/30 px-3 py-2",children:[n.jsx("span",{className:"text-base",children:r.emoji}),n.jsx("span",{className:"text-xs text-muted-foreground font-medium",children:r.label})]}
799),(((T=t.prompt_config)==null?void 0:T.continue_cooldown_sec)??0)>0&&n.jsxs("div",{className:"flex items-center justify-center gap-1.5 rounded-lg bg-muted/30 px-3 py-1.5",children:[n.jsx(O4,{size:12,className:"text-muted-foreground"}),n.jsxs("span",{className:"text-xs text-muted-foreground font-medium",children:[e("voice.continueCooldown"),": ",t.prompt_config.continue_cooldown_sec,e("voice.continueCooldownUnit")]})]}),n.jsxs("div",{className:"space-y-3 pt-2 border-t border-border/30",children:[n.jsxs("div",{className:"flex items-center justify-between mb-1 gap-2",children:[n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx(C4,{size:12,className:"text-primary"}),n.jsx("span",{className:"text-xs font-semibold text-foreground",children:e("filters.title")})]}),n.jsxs("button",{type:"button",onClick:y,disabled:x||!(t!=null&&t.avatar_url),className:"flex items-center gap-1 text-[10px] font-medium px-2 py-1 rounded-md bg-primary/10 text-primary hover:bg-primary/20 disabled:opacity-50 disabled:cursor-not-allowed transition",title:e("filters.autoTitle")||"Gemini посмотрит фото и подберёт значения",children:[x?n.jsx(xe,{size:10,className:"animate-spin"}):n.jsx(tt,{size:10}),x?e("filters.autoLoading")||"Анализ…":e("filters.auto")||"Авто"]})]}),n.jsxs("div",{className:"space-y-1",children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsx("label",{className:"text-[11px] text-muted-foreground",children:e("filters.face")}),n.jsx("span",{className:"text-[11px] font-mono text-foreground/70",children:f.toFixed(1)})]}),n.jsx("input",{type:"range",min:"0",max:"1",step:"0.1",value:f,onChange:C=>v("face_restore",parseFloat(C.target.value)),className:"w-full accent-primary h-1.5"}),n.jsxs("div",{className:"flex justify-between text-[9px] text-muted-foreground",children:[n.jsx("span",{children:e("filters.faceMin")}),n.jsx("span",{children:e("filters.faceMax")})]})]}),n.jsxs("div",{className:"space-y-1",children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsx("label",{className:"text-[11px] text-muted-foreground",children:e("filters.background")}),n.jsx("span",{className:"text-[11px] font-mono text-foreground/70",children:p.toFixed(1)})]}),n.jsx("input",{type:"range",min:"0",max:"1",step:"0.1",value:p,onChange:C=>v("background_restore",parseFloat(C.target.value)),className:"w-full accent-primary h-1.5"}),n.jsxs("div",{className:"flex justify-between text-[9px] text-muted-foreground",children:[n.jsx("span",{children:e("filters.bgMin")}),n.jsx("span",{children:e("filters.bgMax")})]})]})]})]})]})]})},os=h.forwardRef(({className:e,aiLoading:t,onAiFill:s,hideAi:r,value:a,...i},o)=>{const l=!a||String(a).trim()==="";return n.jsxs("div",{className:"relative group",children:[n.jsx("textarea",{className:_e("flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm r
799ing-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 pr-10",e),ref:o,value:a,...i}),!r&&s&&n.jsx(L,{type:"button",variant:"ghost",size:"icon",className:_e("absolute top-1.5 right-1.5 h-7 w-7 transition-colors",l&&!t?"text-primary animate-pulse-soft hover:text-primary hover:bg-primary/10":"text-primary/50 hover:text-primary hover:bg-primary/10"),onClick:s,disabled:t,tabIndex:-1,children:t?n.jsx(xe,{size:14,className:"animate-spin"}):n.jsx(xi,{size:14})})]})});os.displayName="AiTextarea";const Ot=h.forwardRef(({className:e,aiLoading:t,onAiFill:s,hideAi:r,value:a,...i},o)=>{const l=!a||String(a).trim()==="";return n.jsxs("div",{className:"relative group",children:[n.jsx("input",{className:_e("flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 pr-10",e),ref:o,value:a,...i}),!r&&s&&n.jsx(L,{type:"button",variant:"ghost",size:"icon",className:_e("absolute top-1/2 -translate-y-1/2 right-1.5 h-7 w-7 transition-colors",l&&!t?"text-primary animate-pulse-soft hover:text-primary hover:bg-primary/10":"text-primary/50 hover:text-primary hover:bg-primary/10"),onClick:s,disabled:t,tabIndex:-1,children:t?n.jsx(xe,{size:14,className:"animate-spin"}):n.jsx(xi,{size:14})})]})});Ot.displayName="AiInput";const i8="/assets/preset-male-1-C-HTFL-S.jpg",o8="/assets/preset-female-1-CFVhfDHM.jpg",l8="/assets/preset-male-2-04-qnY14.jpg",c8=["male1","female1","male2"],O1={male1:i8,female1:o8,male2:l8},D1=({t:e,step:t,data:s,setData:r,setStep:a,onFinish:i,uploading:o,onAvatarUpload:l,onPresetSelect:c,onCroppedBlob:d,avatarRef:u,avatarDimensions:m,roles:p,styles:f})=>n.jsxs(n.Fragment,{children:[n.jsx(ns,{open:t==="name",onOpenChange:g=>!g&&a(null),children:n.jsxs(Zt,{className:"sm:max-w-md",children:[n.jsxs(Xt,{children:[n.jsx(es,{children:e("wizard.nameTitle")}),n.jsx(us,{children:e("wizard.nameDesc")})]}),n.jsx(Ot,{value:s.name,onChange:g=>r(x=>({...x,name:g.target.value})),placeholder:e("wizard.namePlaceholder"),className:"bg-muted/30 text-lg",hideAi:!0,autoFocus:!0,onKeyDown:g=>{g.key==="Enter"&&s.name.trim()&&a("orientation")}}),n.jsxs(L,{variant:"hero",className:"w-full gap-2",disabled:!s.name.trim(),onClick:()=>a("orientation"),children:[e("wizard.next")," ",n.jsx(Tr,{size:16})]})]})}),n.jsx(ns,{open:t==="orientation",onOpenChange:g=>!g&&a(null),children:n.jsxs(Zt,{className:"sm:max-w-lg",children:[n.jsxs(Xt,{children:[n.jsx(es,{children:e("wizard.orientationTitle")}),n.jsx(us,{children:e("wizard.orientationDesc")})]}),n.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[n.jsxs("button",{onClick:()=>{r(g=>({...g,orientation:"portrait"})),a("avatar")},className:`rounded-xl border-2 p-6 flex flex-col items-center gap-3 transition-all hover:border-primary/40 hover:bg-primary/5 ${s.orientation==="portrait"?"border-primary bg-primary/5":"border-border/50"}`,children:[n.jsx("div",{className:"w-12 h-20 rounded-lg bg-gradient-primary flex items-center justify-center",children:n.jsx(L4,{size:24,className:"text-primary-foreground"})}),n.jsxs("div",{className:"text-center",children:[n.jsx("p",{className:"text-sm font-semibold text-foreground",children:e("wizard.portraitLabel")}),n.jsx("p",{className:"text-[11px] text-muted-foreground mt-0.5",children:e("wizard.portraitSize")})]})]}),n.jsxs("button",{onClick:()=>{r(g=>({...g,orientation:"landscape"})),a("avatar")},className:`rounded-xl border-2 p-6 flex flex-col items-center gap-3 transition-all hover:border-primary/40 hover:bg-primary/5 ${s.orientation==="landscape"?"border-primary bg-primary/5":"border-border/50"}`,children:[n.jsx("div",{className:"w-20 h-12 rounded-lg bg-gradient-primary flex items-center justify-center",children:n.jsx(dS,{size:24,className:"text-primary-foreground"})}),n.jsxs("div",{className:"text-center",children:[n.jsx("p",{className:"text-sm font-semibold text-foreground",children:e("wizard.landscapeLabel")}),n.jsx("p",{className:"text-[11px] text-muted-foreground mt-0.5",children:e("wizard.landscape
799Size")})]})]})]})]})}),n.jsx(ns,{open:t==="avatar",onOpenChange:g=>!g&&a(null),children:n.jsxs(Zt,{className:"sm:max-w-lg",children:[n.jsxs(Xt,{children:[n.jsx(es,{children:e("wizard.avatarTitle")}),n.jsx(us,{children:e("wizard.avatarDesc")})]}),n.jsxs("div",{className:"grid grid-cols-4 gap-3",children:[n.jsxs("button",{onClick:()=>{var g;return(g=u.current)==null?void 0:g.click()},className:"rounded-xl border-2 border-dashed border-border/50 hover:border-primary/40 hover:bg-primary/5 p-3 flex flex-col items-center justify-center gap-1.5 transition-all aspect-[9/16]",children:[n.jsx(Ay,{size:22,className:"text-muted-foreground"}),n.jsx("span",{className:"text-[10px] text-muted-foreground font-medium leading-tight text-center",children:e("wizard.uploadOwn")})]}),n.jsx("input",{ref:u,type:"file",accept:"image/*",className:"hidden",onChange:l}),c8.map(g=>n.jsxs("button",{onClick:()=>c(O1[g]),className:"rounded-xl border-2 border-border/50 hover:border-primary/40 transition-all overflow-hidden aspect-[9/16] relative group",children:[n.jsx("img",{src:O1[g],alt:e(`avatarPresets.${g}`),className:"w-full h-full object-cover",loading:"lazy"}),n.jsx("div",{className:"absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/60 to-transparent p-2 pt-6",children:n.jsx("p",{className:"text-[10px] text-white font-medium text-center",children:e(`avatarPresets.${g}`)})})]},g))]})]})}),n.jsx(ns,{open:t==="crop",onOpenChange:g=>!g&&a(null),children:n.jsxs(Zt,{className:"sm:max-w-md",children:[n.jsxs(Xt,{children:[n.jsx(es,{children:e("wizard.cropTitle")}),n.jsx(us,{children:e("wizard.cropDesc")})]}),s.raw_avatar_url&&n.jsx(Cm,{imageUrl:s.raw_avatar_url,targetWidth:m.w,targetHeight:m.h,onCrop:d,onCancel:()=>a("avatar")}),o&&n.jsxs("div",{className:"flex items-center justify-center gap-2 py-2",children:[n.jsx(xe,{size:16,className:"animate-spin text-primary"}),n.jsx("span",{className:"text-sm text-muted-foreground",children:e("wizard.saving")})]})]})}),n.jsx(ns,{open:t==="role",onOpenChange:g=>!g&&a(null),children:n.jsxs(Zt,{className:"sm:max-w-lg",children:[n.jsxs(Xt,{children:[n.jsx(es,{children:e("wizard.roleTitle")}),n.jsx(us,{children:e("wizard.roleDesc")})]}),n.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3",children:p.map(g=>{const x=s.role===g.id;return n.jsxs("button",{onClick:()=>r(b=>({...b,role:g.id})),className:`rounded-xl border-2 p-3 text-center transition-all duration-200 ${x?"border-primary bg-primary/5 shadow-premium-sm":"border-border/50 hover:border-primary/30"}`,children:[n.jsx(g.icon,{size:20,className:`mx-auto ${x?"text-primary":"text-muted-foreground"}`}),n.jsx("p",{className:`mt-1.5 text-xs font-semibold ${x?"text-foreground":"text-muted-foreground"}`,children:g.label}),n.jsx("p",{className:"text-[10px] text-muted-foreground mt-0.5 leading-tight",children:g.desc})]},g.id)})}),n.jsxs(L,{variant:"hero",className:"w-full gap-2",onClick:()=>a("style"),children:[e("wizard.next")," ",n.jsx(Tr,{size:16})]})]})}),n.jsx(ns,{open:t==="style",onOpenChange:g=>!g&&a(null),children:n.jsxs(Zt,{className:"sm:max-w-lg",children:[n.jsxs(Xt,{children:[n.jsx(es,{children:e("wizard.styleTitle")}),n.jsx(us,{children:e("wizard.styleDesc")})]}),n.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3",children:f.map(g=>{const x=s.style_key===g.id;return n.jsxs("button",{onClick:()=>r(b=>({...b,style_key:g.id})),className:`rounded-xl border-2 p-3 text-center transition-all duration-200 ${x?"border-primary bg-primary/5 shadow-premium-sm":"border-border/50 hover:border-primary/30"}`,children:[n.jsx("span",{className:"text-2xl",children:g.emoji}),n.jsx("p",{className:`mt-1 text-xs font-semibold leading-tight ${x?"text-foreground":"text-muted-foreground"}`,children:g.label})]},g.id)})}),n.jsxs(L,{variant:"hero",className:"w-full gap-2",onClick:i,children:[n.jsx(tt,{size:16})," ",e("wizard.finish")]})]})})]});var qf="rovingFocusGroup.onEntryFocus",d8={bubbles:!1,cancelable:!0},wu="RovingFocusGroup",[tv,I2,u8]=zy(wu),[h8,Ep]=Is(wu,[u8]),[m8,p8]=h8(wu),O2=h.forwardRef((e,t)=>n.jsx(tv.Provider,{scope:e.__scopeRovingFocusGroup,children:n.jsx(tv.Slot,{scope:e.__scopeRovingFocusGroup,children:n.jsx(f8,{...e,ref:t})})}));O2.displayName=wu;var f8=h.forwardRef((e,t)=>
vendor: 4,486 bytes, line 799
799{const{__scopeRovingFocusGroup:s,orientation:r,loop:a=!1,dir:i,currentTabStopId:o,defaultCurrentTabStopId:l,onCurrentTabStopIdChange:c,onEntryFocus:d,preventScrollOnEntryFocus:u=!1,...m}=e,p=h.useRef(null),f=bt(t,p),g=yp(i),[x,b]=tr({prop:o,defaultProp:l??null,onChange:c,caller:wu}),[v,y]=h.useState(!1),w=Zn(d),j=I2(s),_=h.useRef(!1),[N,k]=h.useState(0);return h.useEffect(()=>{const S=p.current;if(S)return S.addEventListener(qf,w),()=>S.removeEventListener(qf,w)},[w]),n.jsx(m8,{scope:s,orientation:r,dir:g,loop:a,currentTabStopId:x,onItemFocus:h.useCallback(S=>b(S),[b]),onItemShiftTab:h.useCallback(()=>y(!0),[]),onFocusableItemAdd:h.useCallback(()=>k(S=>S+1),[]),onFocusableItemRemove:h.useCallback(()=>k(S=>S-1),[]),children:n.jsx(qe.div,{tabIndex:v||N===0?-1:0,"data-orientation":r,...m,ref:f,style:{outline:"none",...e.style},onMouseDown:Ee(e.onMouseDown,()=>{_.current=!0}),onFocus:Ee(e.onFocus,S=>{const T=!_.current;if(S.target===S.currentTarget&&T&&!v){const C=new CustomEvent(qf,d8);if(S.currentTarget.dispatchEvent(C),!C.defaultPrevented){const B=j().filter(V=>V.focusable),E=B.find(V=>V.active),H=B.find(V=>V.id===x),ne=[E,H,...B].filter(Boolean).map(V=>V.ref.current);z2(ne,u)}}_.current=!1}),onBlur:Ee(e.onBlur,()=>y(!1))})})}),D2="RovingFocusGroupItem",M2=h.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:s,focusable:r=!0,active:a=!1,tabStopId:i,children:o,...l}=e,c=pn(),d=i||c,u=p8(D2,s),m=u.currentTabStopId===d,p=I2(s),{onFocusableItemAdd:f,onFocusableItemRemove:g,currentTabStopId:x}=u;return h.useEffect(()=>{if(r)return f(),()=>g()},[r,f,g]),n.jsx(tv.ItemSlot,{scope:s,id:d,focusable:r,active:a,children:n.jsx(qe.span,{tabIndex:m?0:-1,"data-orientation":u.orientation,...l,ref:t,onMouseDown:Ee(e.onMouseDown,b=>{r?u.onItemFocus(d):b.preventDefault()}),onFocus:Ee(e.onFocus,()=>u.onItemFocus(d)),onKeyDown:Ee(e.onKeyDown,b=>{if(b.key==="Tab"&&b.shiftKey){u.onItemShiftTab();return}if(b.target!==b.currentTarget)return;const v=v8(b,u.orientation,u.dir);if(v!==void 0){if(b.metaKey||b.ctrlKey||b.altKey||b.shiftKey)return;b.preventDefault();let w=p().filter(j=>j.focusable).map(j=>j.ref.current);if(v==="last")w.reverse();else if(v==="prev"||v==="next"){v==="prev"&&w.reverse();const j=w.indexOf(b.currentTarget);w=u.loop?y8(w,j+1):w.slice(j+1)}setTimeout(()=>z2(w))}}),children:typeof o=="function"?o({isCurrentTabStop:m,hasTabStop:x!=null}):o})})});M2.displayName=D2;var g8={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function x8(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function v8(e,t,s){const r=x8(e.key,s);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return g8[r]}function z2(e,t=!1){const s=document.activeElement;for(const r of e)if(r===s||(r.focus({preventScroll:t}),document.activeElement!==s))return}function y8(e,t){return e.map((s,r)=>e[(t+r)%e.length])}var F2=O2,U2=M2,Ap="Tabs",[b8,Z1e]=Is(Ap,[Ep]),B2=Ep(),[w8,Yy]=b8(Ap),V2=h.forwardRef((e,t)=>{const{__scopeTabs:s,value:r,onValueChange:a,defaultValue:i,orientation:o="horizontal",dir:l,activationMode:c="automatic",...d}=e,u=yp(l),[m,p]=tr({prop:r,onChange:a,defaultProp:i??"",caller:Ap});return n.jsx(w8,{scope:s,baseId:pn(),value:m,onValueChange:p,orientation:o,dir:u,activationMode:c,children:n.jsx(qe.div,{dir:u,"data-orientation":o,...d,ref:t})})});V2.displayName=Ap;var q2="TabsList",H2=h.forwardRef((e,t)=>{const{__scopeTabs:s,loop:r=!0,...a}=e,i=Yy(q2,s),o=B2(s);return n.jsx(F2,{asChild:!0,...o,orientation:i.orientation,dir:i.dir,loop:r,children:n.jsx(qe.div,{role:"tablist","aria-orientation":i.orientation,...a,ref:t})})});H2.displayName=q2;var W2="TabsTrigger",G2=h.forwardRef((e,t)=>{const{__scopeTabs:s,value:r,disabled:a=!1,...i}=e,o=Yy(W2,s),l=B2(s),c=Q2(o.baseId,r),d=J2(o.baseId,r),u=r===o.value;return n.jsx(U2,{asChild:!0,...l,focusable:!a,active:u,children:n.jsx(qe.button,{type:"button",role:"tab","aria-selected":u,"aria-controls":d,"data-state":u?"active":"inactive","data-disabled":a?"":void 0,disabled:a,id:c,...i,ref:t,onMouseDown:Ee(e.onMouseDown,m=>{!a&&m.button===0&&m.ctrlKey===!1?o.onValueChange(r):m.preventDefault()}),onKeyDown:Ee(e.onKeyDown,m=>{[" ","Enter"].includes(m.key)&&o.onValueChange(r)}),onFocus:Ee(e.onFocus,()=>{const m=o.activationMode!=="manual";!u&&!a&&m&&o.onValueChange(r)})})})});G2.displayName=W2;var Y2="TabsContent",K2=h.forwardRef((e,t)=>
799{const{__scopeTabs:s,value:r,forceMount:a,children:i,...o}=e,l=Yy(Y2,s),c=Q2(l.baseId,r),d=J2(l.baseId,r),u=r===l.value,m=h.useRef(u);return h.useEffect(()=>{const p=requestAnimationFrame(()=>m.current=!1);return()=>cancelAnimationFrame(p)},[]),n.jsx(sn,{present:a||u,children:({present:p})=>n.jsx(qe.div,{"data-state":u?"active":"inactive","data-orientation":l.orientation,role:"tabpanel","aria-labelledby":c,hidden:!p,id:d,tabIndex:0,...o,ref:t,style:{...e.style,animationDuration:m.current?"0s":void 0},children:p&&i})})});K2.displayName=Y2;function Q2(e,t){return`${e}-trigger-${t}`}function J2(e,t){return`${e}-content-${t}`}var j8=V2,Z2=H2,X2=G2,eT=K2;const Rp=j8,ju=h.forwardRef(({className:e,...t},s)=>n.jsx(Z2,{ref:s,className:_e("inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",e),...t}));ju.displayName=Z2.displayName;const un=h.forwardRef(({className:e,...t},s)=>n.jsx(X2,{ref:s,className:_e("inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",e),...t}));un.displayName=X2.displayName;const hn=h.forwardRef(({className:e,...t},s)=>n.jsx(eT,{ref:s,className:_e("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",e),...t}));hn.displayName=eT.displayName;const _8=[{voice_id:"onwK4e9ZLuTAKqWW03F9",name:"Daniel",description:"Calm British male",preview_url:""},{voice_id:"JBFqnCBsd6RMkjVDRZzb",name:"George",description:"Deep British male",preview_url:""},{voice_id:"N2lVS1w4EtoT3dr4eOWO",name:"Callum",description:"Young British male",preview_url:""},{voice_id:"TX3LPaxmHKxFdv7VOQHJ",name:"Liam",description:"Energetic US male",preview_url:""},{voice_id:"cjVigY5qzO86Huf0OWal",name:"Eric",description:"Confident US male",preview_url:""},{voice_id:"nPczCjzI2devNBz1zQrb",name:"Brian",description:"Narrative US male",preview_url:""},{voice_id:"EXAVITQu4vr4xnSDxMaL",name:"Sarah",description:"Warm US female",preview_url:""},{voice_id:"FGY2WhTYpPnrIDTdsKH5",name:"Laura",description:"Friendly US female",preview_url:""},{voice_id:"XrExE9yKIg1WjnnlVkGX",name:"Matilda",description:"Confident British female",preview_url:""},{voice_id:"Xb7hH8MSUJpSbSDYk0k2",name:"Alice",description:"Calm British female",preview_url:""},{voice_id:"pFZP5JQG7iQjIQuC4Bku",name:"Lily",description:"Soft British female",preview_url:""},{voice_id:"cgSgspJ2msm6clMCkdW9",name:"Jessica",description:"Energetic US female",preview_url:""}];function k8({open:e,onOpenChange:t,t:s,persona:r,update:a}){var U;const[i,o]=h.useState("browse"),[l,c]=h.useState(""),[d,u]=h.useState("any"),[m,p]=h.useState("any"),[f,g]=h.useState("any"),[x,b]=h.useState("any"),[v,y]=h.useState([]),[w,j]=h.useState(!1),[_,N]=h.useState(0),[k,S]=h.useState(!1),[T,C]=h.useState(""),B=h.useRef(null),[E,H]=h.useState(null),[z,ne]=h.useState(""),[V,te]=h.useState(!1),[R,F]=h.useState(""),[$,J]=h.useState(""),[Y,re]=h.useState(null),[G,O]=h.useState(!1),[Z,A]=h.useState(""),oe=h.useRef(null),[ue,je]=h.useState(null),ae=((U=r.prompt_config)==null?void 0:U.custom_voices)||[],ie=h.useCallback(async(Q=!1)=>{S(!0),C("");try{const ve=new URLSearchParams;l.trim()&&ve.set("search",l.trim()),d!=="any"&&ve.set("gender",d),m!=="any"&&ve.set("age",m),f!=="any"&&ve.set("language",f),x!=="any"&&ve.set("use_cases",x);const We=Q?0:_;ve.set("page",String(We)),ve.set("page_size","30");const{data:{session:Ze}}=await I.auth.getSession();if(!(Ze!=null&&Ze.access_token))throw new Error("Not authenticated");const Je=`https://nfqxajdgklseicehjolk.supabase.co/functions/v1/elevenlabs-voices-search?${ve.toString()}`,xt=await fetch(Je,{headers:{apikey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Im5mcXhhamRna2xzZWljZWhqb2xrIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzQ4OTE1MzksImV4cCI6MjA5MDQ2NzUzOX0.6_j0QrbnSX8MwR-HqRHEG6jOotimefvkE_S9mchl3TE",Authorization:`Bearer ${Ze.access_token}`}});if(!xt.ok){const K=await xt.json().catch(()=>({error:`HTTP ${xt.status}`}));throw new Error(K.error||`HTTP ${xt.status}`)}const Pt=await xt.json();y(K=>Q?Pt.voices:[...K,...Pt.voices]),j(!!Pt.has_more),N(Q?1:K=>K+1)}catch(ve){C(ve.message||"Search failed")}finally{S(!1)}},[l,d,m,f,x,_]);h.useEffect(()=>{if(!e||i!=="browse")return;const Q=setTimeout(()=>ie(!0),400);return()=>clearTimeout(Q)},[e,i,l,d,m,f,x]),h.useEffect(()=>{!e&&B.current&&(B.current.pause(),B.current=null,H(null))},[e]);const we=Q=>{var We;
799if(E===Q.voice_id){(We=B.current)==null||We.pause(),H(null);return}if(B.current&&B.current.pause(),!Q.preview_url)return;const ve=new Audio(Q.preview_url);B.current=ve,ve.onended=()=>H(null),ve.onerror=()=>H(null),ve.play().then(()=>H(Q.voice_id)).catch(()=>H(null))},Ae=async(Q,ve)=>{var We,Ze;je(Q);try{let Je=ve;try{const De=await I.functions.invoke("elevenlabs-voice-info",{body:{voice_id:Q}});!De.error&&((We=De.data)!=null&&We.name)&&(Je=De.data.name)}catch{}const Pt=[{id:Q,name:Je,desc:""},...ae.filter(De=>De.id!==Q)],K={...r.prompt_config,custom_voices:Pt},ye={...r.voice_config,voice_id:Q,voice_name:Je};a({prompt_config:K,voice_config:ye}),r.id&&await I.from("personas").update({prompt_config:{...K,voice_config:ye}}).eq("id",r.id),(Ze=B.current)==null||Ze.pause(),t(!1)}finally{je(null)}},nt=async()=>{if(z.trim()){te(!0),F("");try{const Q=await I.functions.invoke("elevenlabs-voice-info",{body:{voice_id:z.trim()}});if(Q.error)throw new Error(Q.error.message);const ve=Q.data,We={id:z.trim(),name:ve.name||z.trim(),desc:ve.description||""},Ze=[We,...ae.filter(Pt=>Pt.id!==We.id)],Je={...r.prompt_config,custom_voices:Ze},xt={...r.voice_config,voice_id:We.id,voice_name:We.name};a({prompt_config:Je,voice_config:xt}),r.id&&await I.from("personas").update({prompt_config:{...Je,voice_config:xt}}).eq("id",r.id),t(!1),ne("")}catch(Q){F(Q.message||s("common:defaultPersona.voiceError"))}finally{te(!1)}}},Qe=async()=>{if(!(!$.trim()||!Y)){O(!0),A("");try{const Q=new FormData;Q.append("name",$.trim()),Q.append("audio",Y);const ve="https://nfqxajdgklseicehjolk.supabase.co/functions/v1/elevenlabs-clone-voice",{data:{session:We}}=await I.auth.getSession();if(!(We!=null&&We.access_token))throw new Error("Not authenticated");const Ze=await fetch(ve,{method:"POST",headers:{apikey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Im5mcXhhamRna2xzZWljZWhqb2xrIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzQ4OTE1MzksImV4cCI6MjA5MDQ2NzUzOX0.6_j0QrbnSX8MwR-HqRHEG6jOotimefvkE_S9mchl3TE",Authorization:`Bearer ${We.access_token}`},body:Q});if(!Ze.ok){const De=await Ze.json().catch(()=>({error:`HTTP ${Ze.status}`}));throw new Error(De.error||`Clone failed: ${Ze.status}`)}const Je=await Ze.json(),xt={id:Je.voice_id,name:Je.name,desc:s("customVoice.cloneSuccess")},Pt=[xt,...ae.filter(De=>De.id!==xt.id)],K={...r.prompt_config,custom_voices:Pt},ye={...r.voice_config,voice_id:xt.id,voice_name:xt.name};a({prompt_config:K,voice_config:ye}),r.id&&await I.from("personas").update({prompt_config:{...K,voice_config:ye}}).eq("id",r.id),t(!1),J(""),re(null)}catch(Q){A(Q.message||"Clone failed")}finally{O(!1)}}},P=({voice:Q})=>{const ve=E===Q.voice_id,We=r.voice_config.voice_id===Q.voice_id,Ze=ue===Q.voice_id,Je=Q;return n.jsx("div",{className:`group rounded-lg border p-3 transition-all ${We?"border-primary bg-primary/5":"border-border hover:border-primary/40 bg-background"}`,children:n.jsxs("div",{className:"flex items-start gap-3",children:[n.jsx("button",{type:"button",onClick:()=>we(Q),disabled:!Q.preview_url,className:`shrink-0 w-10 h-10 rounded-full flex items-center justify-center transition-colors ${Q.preview_url?"bg-primary/10 hover:bg-primary/20 text-primary":"bg-muted text-muted-foreground cursor-not-allowed"}`,title:Q.preview_url?s("voiceBrowser.play"):s("voiceBrowser.noPreview"),children:ve?n.jsx($x,{size:16}):n.jsx(en,{size:16,className:"ml-0.5"})}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsxs("div",{className:"flex items-baseline gap-2 flex-wrap",children:[n.jsx("span",{className:"font-medium text-sm truncate",children:Q.name}),Je.gender&&n.jsx("span",{className:"text-[10px] text-muted-foreground",children:Je.gender}),Je.age&&n.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["· ",Je.age]}),Je.accent&&n.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["· ",Je.accent]})]}),Q.description&&n.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-0.5",children:Q.description}),Je.use_case&&n.jsx("div",{className:"flex gap-1 mt-1.5 flex-wrap",children:n.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-muted text-muted-foreground",children:Je.use_case})})]}),n.jsx(L,{type:"button",size:"sm",variant:We?"secondary":"default",disabled:Ze||We,onClick:()=>Ae(Q.voice_id,Q.name),className:"shrink-0 h-8",children:Ze?n.jsx(xe,{size:12,className:"animate-spin"}):We?n.jsx(ms,{size:12}):s("voiceBrowser.select")})]})})};return n.jsx(ns,{open:e,onOpenChange:t,children:n.jsxs(Zt,{className:"max-w-3xl max-h-[85vh] flex flex-col p-0 gap-0",children:[n.jsx(Xt,{className:"px-6 pt-6 pb-3 border-b",children:n.jsx(es,{children:s("voiceBrowser.title")})}),n.jsxs(Rp,{value:i,onValueChange:Q=>o(Q),className:"flex-1 flex flex-col min-h-0",children:[n.jsx("div",{className:"px-6 pt-3",children:n.jsxs(ju,{className:"w-full",children:[n.jsx(un,{value:"browse",className:"flex-1",children:s("voiceBrowser.tabBrowse")}),n.jsx(un,{value:"top",className:"flex-1",children:s("voiceBrowser.tabTop")}),n.jsx(un,{value:"id",className:"flex-1",children:s("voiceBrowser.tabId")}),n.jsx(un,{value:"clone",className:"flex-1",children:s("voiceBrowser.tabClone")})]})}),n.jsxs(hn,{value:"browse",className:"flex-1 flex flex-col min-h-0 mt-0",children:[n.jsxs("div",{className:"px-6 py-3 border-b space-y-2",children:[n.jsxs("div",{className:"relative",children:[n.jsx(bn,{size:14,className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"}),n.jsx(gt,{placeholder:s("voiceBrowser.searchPlaceholder"),value:l,onCh
799ange:Q=>c(Q.target.value),className:"pl-9 h-9"}),l&&n.jsx("button",{onClick:()=>c(""),className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",children:n.jsx(Qn,{size:14})})]}),n.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2",children:[n.jsxs(ut,{value:d,onValueChange:u,children:[n.jsx(ct,{className:"h-8 text-xs",children:n.jsx(ht,{placeholder:s("voiceBrowser.filterGender")})}),n.jsxs(dt,{children:[n.jsx(ce,{value:"any",children:s("voiceBrowser.any")}),n.jsx(ce,{value:"male",children:s("voiceBrowser.male")}),n.jsx(ce,{value:"female",children:s("voiceBrowser.female")}),n.jsx(ce,{value:"neutral",children:s("voiceBrowser.neutral")})]})]}),n.jsxs(ut,{value:m,onValueChange:p,children:[n.jsx(ct,{className:"h-8 text-xs",children:n.jsx(ht,{placeholder:s("voiceBrowser.filterAge")})}),n.jsxs(dt,{children:[n.jsx(ce,{value:"any",children:s("voiceBrowser.any")}),n.jsx(ce,{value:"young",children:s("voiceBrowser.young")}),n.jsx(ce,{value:"middle_aged",children:s("voiceBrowser.middle")}),n.jsx(ce,{value:"old",children:s("voiceBrowser.old")})]})]}),n.jsxs(ut,{value:f,onValueChange:g,children:[n.jsx(ct,{className:"h-8 text-xs",children:n.jsx(ht,{placeholder:s("voiceBrowser.filterLang")})}),n.jsxs(dt,{children:[n.jsx(ce,{value:"any",children:s("voiceBrowser.any")}),n.jsx(ce,{value:"en",children:"English"}),n.jsx(ce,{value:"ru",children:"Русский"}),n.jsx(ce,{value:"es",children:"Español"}),n.jsx(ce,{value:"de",children:"Deutsch"}),n.jsx(ce,{value:"fr",children:"Français"}),n.jsx(ce,{value:"it",children:"Italiano"}),n.jsx(ce,{value:"pt",children:"Português"}),n.jsx(ce,{value:"ja",children:"日本語"}),n.jsx(ce,{value:"zh",children:"中文"})]})]}),n.jsxs(ut,{value:x,onValueChange:b,children:[n.jsx(ct,{className:"h-8 text-xs",children:n.jsx(ht,{placeholder:s("voiceBrowser.filterUseCase")})}),n.jsxs(dt,{children:[n.jsx(ce,{value:"any",children:s("voiceBrowser.any")}),n.jsx(ce,{value:"narrative_story",children:s("voiceBrowser.uc_narrative")}),n.jsx(ce,{value:"conversational",children:s("voiceBrowser.uc_conversational")}),n.jsx(ce,{value:"characters_animation",children:s("voiceBrowser.uc_characters")}),n.jsx(ce,{value:"social_media",children:s("voiceBrowser.uc_social")}),n.jsx(ce,{value:"entertainment_tv",children:s("voiceBrowser.uc_entertainment")}),n.jsx(ce,{value:"advertisement",children:s("voiceBrowser.uc_ads")}),n.jsx(ce,{value:"informative_educational",children:s("voiceBrowser.uc_educational")})]})]})]})]}),n.jsxs("div",{className:"flex-1 overflow-y-auto px-6 py-3 space-y-2",children:[T&&n.jsx("p",{className:"text-xs text-destructive",children:T}),v.length===0&&!k&&!T&&n.jsx("p",{className:"text-center text-sm text-muted-foreground py-8",children:s("voiceBrowser.noResults")}),v.map(Q=>n.jsx(P,{voice:Q},Q.voice_id)),k&&n.jsx("div",{className:"flex justify-center py-4",children:n.jsx(xe,{size:18,className:"animate-spin text-muted-foreground"})}),w&&!k&&n.jsx(L,{variant:"outline",className:"w-full",onClick:()=>ie(!1),children:s("voiceBrowser.loadMore")})]})]}),n.jsxs(hn,{value:"top",className:"flex-1 overflow-y-auto px-6 py-3 space-y-2 mt-0",children:[_8.map(Q=>n.jsx(P,{voice:Q},Q.voice_id)),n.jsx("p",{className:"text-[11px] text-muted-foreground text-center pt-2",children:s("voiceBrowser.topNote")})]}),n.jsxs(hn,{value:"id",className:"px-6 py-4 space-y-3 mt-0",children:[n.jsxs("p",{className:"text-xs text-muted-foreground",children:[s("customVoice.desc")," ",n.jsx("a",{href:"https://elevenlabs.io/voice-library",target:"_blank",rel:"noopener noreferrer",className:"text-primary underline",children:"elevenlabs.io"}),"."]}),n.jsx(Ot,{placeholder:s("customVoice.placeholder"),value:z,onChange:Q=>ne(Q.target.value),className:"font-mono text-sm",hideAi:!0}),R&&n.jsx("p",{className:"text-xs text-destructive",children:R}),R&&n.jsxs("p",{className:"text-[11px] text-muted-foreground leading-relaxed bg-muted/30 rounded-lg p-3",children:["💡 ",s("customVoice.notFoundHint")]}),n.jsxs(L,{className:"w-full gap-2",onClick:nt,disabled:V||!z.trim(),children:[V?n.jsx(xe,{size:14,className:"animate-spin"}):n.jsx(sr,{size:14}),s(V?"customVoice.loading":"customVoice.add")]})]}),n.jsxs(hn,{value:"clone",className:"px-6 py-4 space-y-3 mt-0",children:[n.jsx("p",{className:"text-xs text-muted-foreground leading-relaxed",children:s("customVoice.cloneDesc")}),n.jsxs("div",{className:"space-y-1.5",children:[n.jsx("label",{className:"text-xs font-medium text-muted-foreground",children:s("customVoice.cloneName")}),n.jsx(Ot,{placeholder:s("customVoice.cloneNamePlaceholder"),value:$,onChange:Q=>J(Q.target.value),hideAi:!0})]}),n.jsxs("div",{className:"space-y-1.5",children:[n.jsx("label",{className:"text-xs font-medium text-muted-foreground",children:s("customVoice.cloneFile")}),n.jsx("input",{ref:oe,type:"file",accept:"audio/*",onChange:Q=>{var ve;return re(((ve=Q.target.files)==null?void 0:ve[0])||null)},className:"hidden"}),n.jsxs(L,{variant:"outline",className:"w-full gap-2 text-sm",onClick:()=>{var Q;return(Q=oe.current)==null?void 0:Q.click()},children:[n.jsx(Ay,{size:14}
799),Y?Y.name:s("customVoice.cloneFile")]}),n.jsx("p",{className:"text-[10px] text-muted-foreground",children:s("customVoice.cloneFormats")})]}),Z&&n.jsx("p",{className:"text-xs text-destructive",children:Z}),n.jsxs(L,{className:"w-full gap-2",onClick:Qe,disabled:G||!$.trim()||!Y,children:[G?n.jsx(xe,{size:14,className:"animate-spin"}):n.jsx(cu,{size:14}),s(G?"customVoice.cloning":"customVoice.cloneBtn")]})]})]})]})})}const N8=[{id:"onwK4e9ZLuTAKqWW03F9",name:"Daniel",flag:"🇬🇧"},{id:"JBFqnCBsd6RMkjVDRZzb",name:"George",flag:"🇬🇧"},{id:"N2lVS1w4EtoT3dr4eOWO",name:"Callum",flag:"🇬🇧"},{id:"TX3LPaxmHKxFdv7VOQHJ",name:"Liam",flag:"🇺🇸"},{id:"cjVigY5qzO86Huf0OWal",name:"Eric",flag:"🇺🇸"},{id:"nPczCjzI2devNBz1zQrb",name:"Brian",flag:"🇺🇸"},{id:"EXAVITQu4vr4xnSDxMaL",name:"Sarah",flag:"🇺🇸"},{id:"FGY2WhTYpPnrIDTdsKH5",name:"Laura",flag:"🇺🇸"},{id:"XrExE9yKIg1WjnnlVkGX",name:"Matilda",flag:"🇬🇧"},{id:"Xb7hH8MSUJpSbSDYk0k2",name:"Alice",flag:"🇬🇧"},{id:"pFZP5JQG7iQjIQuC4Bku",name:"Lily",flag:"🇬🇧"},{id:"cgSgspJ2msm6clMCkdW9",name:"Jessica",flag:"🇺🇸"}];function S8(e){const t=e.split(/\s+/).slice(0,8);let s="";for(const r of t){const a=r.search(/[.,;:!?—–]/);if(a>0){s+=(s?" ":"")+r.slice(0,a);break}if(a===0)break;s+=(s?" ":"")+r}return s||e.slice(0,30)}function C8({t:e,persona:t,update:s,aiLoading:r,fill:a}){var g,x,b;const[i,o]=h.useState(!1),[l,c]=h.useState(!1),d=h.useRef(null),u=((g=t.prompt_config)==null?void 0:g.custom_voices)||[],m=N8.map(v=>({...v,desc:e(`voices.${v.id}`,v.name)})),p=[...u.map(v=>({id:v.id,name:v.name,flag:"🎤",desc:v.desc||e("common:defaultPersona.customVoice")})),...m],f=async()=>{var w;if(l){(w=d.current)==null||w.pause(),c(!1);return}const y=(t.description||t.name).split(/\s+/).slice(0,30).join(" ");if(y.trim()){c(!0);try{const _=await fetch("https://nfqxajdgklseicehjolk.supabase.co/functions/v1/elevenlabs-tts-preview",{method:"POST",headers:{"Content-Type":"application/json",apikey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Im5mcXhhamRna2xzZWljZWhqb2xrIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzQ4OTE1MzksImV4cCI6MjA5MDQ2NzUzOX0.6_j0QrbnSX8MwR-HqRHEG6jOotimefvkE_S9mchl3TE",Authorization:"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Im5mcXhhamRna2xzZWljZWhqb2xrIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzQ4OTE1MzksImV4cCI6MjA5MDQ2NzUzOX0.6_j0QrbnSX8MwR-HqRHEG6jOotimefvkE_S9mchl3TE"},body:JSON.stringify({text:y,voice_id:t.voice_config.voice_id,stability_mode:t.voice_config.stability_mode,use_speaker_boost:t.voice_config.use_speaker_boost})});if(!_.ok)throw new Error("TTS error");const N=await _.blob(),k=URL.createObjectURL(N),S=new Audio(k);d.current=S,S.onended=()=>c(!1),S.onerror=()=>c(!1),await S.play()}catch(j){console.error("TTS preview error:",j),c(!1)}}};return n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"space-y-4",children:[n.jsxs("div",{className:"space-y-1.5",children:[n.jsx("label",{className:"text-xs font-medium text-muted-foreground",children:e("voice.voiceLabel")}),n.jsxs(ut,{value:t.voice_config.voice_id,onValueChange:v=>{var w;const y=((w=p.find(j=>j.id===v))==null?void 0:w.name)||v;s({voice_config:{...t.voice_config,voice_id:v,voice_name:y}})},children:[n.jsx(ct,{className:"bg-muted/30",children:n.jsx(ht,{})}),n.jsx(dt,{children:p.map(v=>n.jsx(ce,{value:v.id,children:n.jsxs("span",{className:"flex items-center gap-2",children:[n.jsx("span",{children:v.flag}),n.jsx("span",{className:"font-medium",children:v.name}),n.jsxs("span",{className:"text-muted-foreground text-[10px]",children:["— ",S8(v.desc)]})]})},v.id))})]}),n.jsxs("button",{type:"button",onClick:()=>o(!0),className:"text-[11px] text-primary hover:text-primary/80 font-medium transition-colors mt-1 inline-flex items-center gap-1",children:[n.jsx(bn,{size:11}),e("voiceBrowser.openBtn")]})]}),n.jsxs("div",{className:"space-y-1.5",children:[n.jsx("label",{className:"text-xs font-medium text-muted-foreground",children:e("voice.stability")}),n.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:["creative","natural","robust"].map(v
799=>{const y=t.voice_config.stability_mode===v;return n.jsx("button",{type:"button",onClick:()=>s({voice_config:{...t.voice_config,stability_mode:v}}),className:`text-xs font-medium py-2 px-2 rounded-md border transition-colors ${y?"bg-primary text-primary-foreground border-primary":"bg-muted/30 text-foreground/70 border-border hover:bg-muted/60"}`,children:e(`voice.stabilityMode.${v}`)},v)})}),n.jsx("p",{className:"text-[10px] text-muted-foreground",children:e(`voice.stabilityHint.${t.voice_config.stability_mode}`)})]}),n.jsxs("div",{className:"flex items-start justify-between gap-3 pt-1",children:[n.jsxs("div",{className:"space-y-0.5",children:[n.jsx("label",{className:"text-xs font-medium text-muted-foreground",children:e("voice.speakerBoost")}),n.jsx("p",{className:"text-[10px] text-muted-foreground",children:e("voice.speakerBoostDesc")})]}),n.jsx("button",{type:"button",role:"switch","aria-checked":t.voice_config.use_speaker_boost,onClick:()=>s({voice_config:{...t.voice_config,use_speaker_boost:!t.voice_config.use_speaker_boost}}),className:`relative inline-flex h-5 w-9 shrink-0 items-center rounded-full transition-colors ${t.voice_config.use_speaker_boost?"bg-primary":"bg-muted"}`,children:n.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-background shadow transition-transform ${t.voice_config.use_speaker_boost?"translate-x-4":"translate-x-0.5"}`})})]}),n.jsx(L,{variant:"outline",size:"sm",className:"gap-2 w-full",onClick:f,disabled:l&&!d.current,children:l?n.jsxs(n.Fragment,{children:[n.jsx(xe,{size:14,className:"animate-spin"})," ",e("voice.playing")]}):n.jsxs(n.Fragment,{children:[n.jsx(cu,{size:14})," ",e("voice.listen")]})}),n.jsx("p",{className:"text-[10px] text-muted-foreground text-center -mt-2",children:e("voice.listenNote")}),n.jsxs("div",{className:"space-y-1.5 pt-2 border-t border-border/30",children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsx("label",{className:"text-xs font-medium text-muted-foreground",children:e("voice.continueCooldown")}),n.jsxs("span",{className:"text-xs font-mono text-foreground/70",children:[((x=t.prompt_config)==null?void 0:x.continue_cooldown_sec)??1,e("voice.continueCooldownUnit")]})]}),n.jsx("input",{type:"range",min:"1",max:"20",step:"1",value:((b=t.prompt_config)==null?void 0:b.continue_cooldown_sec)??1,onChange:v=>s({prompt_config:{...t.prompt_config,continue_cooldown_sec:parseInt(v.target.value)}}),className:"w-full accent-primary"}),n.jsxs("div",{className:"flex justify-between text-[10px] text-muted-foreground",children:[n.jsx("span",{children:"1"}),n.jsx("span",{children:"10"}),n.jsx("span",{children:"20"})]}),n.jsx("p",{className:"text-[10px] text-muted-foreground",children:e("voice.continueCooldownDesc")})]})]}),n.jsx(k8,{open:i,onOpenChange:o,t:e,persona:t,update:s})]})}const T8=[{key:"shorts",icon:Ns,path:"/app/content",color:"from-primary to-primary/70",emoji:"🎬",pattern:"radial-gradient(circle at 80% 20%, hsl(var(--primary) / 0.15), transparent 50%)"},{key:"streams",icon:St,path:"/app/live",color:"from-red-500 to-red-400",emoji:"🔴",pattern:"radial-gradient(circle at 80% 20%, hsl(0 80% 60% / 0.12), transparent 50%)"},{key:"webinars",icon:Ja,path:"/app/webinars",color:"from-amber-500 to-amber-400",emoji:"🎓",pattern:"radial-gradient(circle at 80% 20%, hsl(38 90% 55% / 0.12), transparent 50%)"},{key:"consultations",icon:Zs,path:"/app/consultations",color:"from-emerald-500 to-emerald-400",emoji:"🎙️",pattern:"radial-gradient(circle at 80% 20%, hsl(152 60% 45% / 0.12), transparent 50%)"}];function P8({open:e,onOpenChange:t,t:s}){return n.jsx(ns,{open:e,onOpenChange:t,children:n.jsxs(Zt,{className:"sm:max-w-lg",children:[n.jsxs(Xt,{children:[n.jsxs(es,{className:"flex items-center gap-2",children:[n.jsx(tt,{size:20,className:"text-primary"}),s("contentPlan.title")]}),n.jsx(us,{children:s("contentPlan.desc")})]}),n.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3 pt-2",children:T8.map(r=>n.jsxs(zt,{to:r.path,onClick:()=>t(!1),className:"group relative rounded-xl border-2 border-border/50 hover:border-primary/30 p-4 transition-all hover:shadow-
799premium-sm overflow-hidden",style:{backgroundImage:r.pattern},children:[n.jsx("div",{className:"absolute top-3 right-3 text-2xl opacity-30 group-hover:opacity-60 transition-opacity select-none",children:r.emoji}),n.jsx("div",{className:`w-10 h-10 rounded-xl bg-gradient-to-br ${r.color} flex items-center justify-center mb-3 shadow-md group-hover:scale-110 transition-transform`,children:n.jsx(r.icon,{size:20,className:"text-white"})}),n.jsx("h4",{className:"text-sm font-semibold text-foreground group-hover:text-primary transition-colors",children:s(`contentPlan.${r.key}`)}),n.jsx("p",{className:"text-[11px] text-muted-foreground mt-1 leading-relaxed",children:s(`contentPlan.${r.key}Desc`)})]},r.key))})]})})}function pa(){const{profile:e}=st(),[t,s]=h.useState({}),[r,a]=h.useState({open:!1,pending:null,resolve:null}),i=h.useCallback(async u=>{if(!(e!=null&&e.workspace_id))return null;s(m=>({...m,[u.fieldName]:!0}));try{const{data:m,error:p}=await I.functions.invoke("ai-fill-field",{body:{field_name:u.fieldName,field_label:u.fieldLabel,current_value:u.currentValue||"",page_context:u.pageContext,persona_id:u.personaId||null,workspace_id:e.workspace_id,language:u.language||"ru"}});return p?(console.error("AI fill error:",p),null):(m==null?void 0:m.text)||null}catch(m){return console.error("AI fill error:",m),null}finally{s(m=>({...m,[u.fieldName]:!1}))}},[e==null?void 0:e.workspace_id]),o=h.useCallback(async u=>{var p;return((p=u.topicValue)==null?void 0:p.trim())?i(u):new Promise(f=>{a({open:!0,pending:u,resolve:g=>{var b;if(!g){f(null);return}(b=u.onTopicSet)==null||b.call(u,g);const x={...u,pageContext:{...u.pageContext,topic:g}};i(x).then(f)}})})},[i]),l=h.useCallback(u=>{var m;(m=r.resolve)==null||m.call(r,u),a({open:!1,pending:null,resolve:null})},[r.resolve]),c=h.useCallback(()=>{var u;(u=r.resolve)==null||u.call(r,null),a({open:!1,pending:null,resolve:null})},[r.resolve]),d=h.useCallback(u=>!!t[u],[t]);return{fill:i,fillWithTopicCheck:o,isLoading:d,topicModal:{open:r.open,onConfirm:l,onCancel:c}}}const Ph={voice_id:"onwK4e9ZLuTAKqWW03F9",voice_name:"Daniel",stability_mode:"natural",use_speaker_boost:!0};function E8(e){const t=typeof e=="number"?e:NaN;return isFinite(t)?t<=.33?"creative":t>=.67?"robust":"natural":"natural"}function A8(e){if(!e||typeof e!="object")return{...Ph};const t=e.stability_mode==="creative"||e.stability_mode==="natural"||e.stability_mode==="robust"?e.stability_mode:E8(e.stability);return{voice_id:e.voice_id||Ph.voice_id,voice_name:e.voice_name||Ph.voice_name,stability_mode:t,use_speaker_boost:typeof e.use_speaker_boost=="boolean"?e.use_speaker_boost:!0}}const lh={name:"",role:"blogger",description:"",primary_topic:"",language:"ru",tone:"friendly",style_key:"calm",audience_type:"",avatar_url:"",can_create_shorts:!0,can_go_live:!0,can_reply_live_chat:!1,can_consult:!1,can_teach:!1,can_generate_clips:!0,prompt_config:{},voice_config:{...Ph},status:"draft"};function ch(e){var t;return((t=e==null?void 0:e.prompt_config)==null?void 0:t.orientation)==="landscape"?"landscape":"portrait"}function Hf(e){var r;const t=(r=e.prompt_config)==null?void 0:r.voice_config,s=A8(t);return{id:e.id,name:e.name,role:e.role,description:e.description||"",primary_topic:e.primary_topic||"",language:e.language||"ru",tone:e.tone||"neutral",style_key:e.style_key||"calm",audience_type:e.audience_type||"",avatar_url:e.avatar_url||"",can_create_shorts:e.can_create_shorts??!0,can_go_live:e.can_go_live??!1,can_reply_live_chat:e.can_reply_live_chat??!1,can_consult:e.can_consult??!1,can_teach:e.can_teach??!1,can_generate_clips:e.can_generate_clips??!1,prompt_config:e.prompt_config||{},voice_config:s,status:e.status}}const dh="selected_persona_id";function tT(){const{profile:e}=st(),t=e==null?void 0:e.workspace_id,[s,r]=h.useState(lh),[a,i]=h.useState(lh),[o,l]=h.useState([]),[c,d]=h.useState(!0),[u,m]=h.useState(!1),[p,f]=h.useState(!1),g=h.useCallback(async()=>{if(!t){d(!1);return}const{data:N,error:k}=await I.from("personas").select("*").eq("workspace_id",t).order("created_at",{ascending:!0});if(k){console.error("Failed to load personas:",k),d(!1);return}if(N&&N.length>0){l(N.map(E=>({id:E.id,name:E.name,role:E.role,status:E.status,avatar_url:E.avatar_url||"",orientation:ch(E)})));const S=localStorage.getItem(dh),C=(S?N.find(E=>E.id===S):null)||N.find(E=>E.is_default)||N[0],B=Hf(C);r(B),i(B),f(!1),C.id&&localStorage.setItem(dh,C.id)}d(!1)},[t]);h.useEffect(()=>{g()},[g]);const x=h.useCallback(async N=>{if(!t)return;const{data:k,error:S}=await I.from("personas").select("*").eq("id",N).single();if(k){const T=Hf(k);r(T),i(T),f(!1),localStorage.setItem(dh,N)}S&&console.error("Failed to select persona:",S)},[t]),b=h.useCallback(()=>{r({...lh}
799),f(!0)},[]),v=h.useCallback(async N=>{if(!t)return;const{error:k}=await I.from("personas").delete().eq("id",N);if(k){console.error(k);return}if(l(S=>S.filter(T=>T.id!==N)),s.id===N){const S=o.filter(T=>T.id!==N);S.length>0?x(S[0].id):r({...lh})}},[t,s.id,o,x]),y=h.useCallback(N=>{r(k=>({...k,...N})),f(!0)},[]),w=h.useCallback(async()=>{if(!t)return;m(!0);const N={workspace_id:t,name:s.name,role:s.role,description:s.description,primary_topic:s.primary_topic,language:s.language,tone:s.tone,style_key:s.style_key,audience_type:s.audience_type,avatar_url:s.avatar_url||null,can_create_shorts:s.can_create_shorts,can_go_live:s.can_go_live,can_reply_live_chat:s.can_reply_live_chat,can_consult:s.can_consult,can_teach:s.can_teach,can_generate_clips:s.can_generate_clips,prompt_config:{...s.prompt_config,voice_config:s.voice_config},is_default:o.length===0||!s.id,status:s.status==="draft"?"active":s.status};try{if(s.id){const{error:k}=await I.from("personas").update(N).eq("id",s.id);if(k)throw k;l(S=>S.map(T=>T.id===s.id?{id:s.id,name:s.name,role:s.role,status:N.status,avatar_url:s.avatar_url,orientation:ch(s)}:T))}else{const{data:k,error:S}=await I.from("personas").insert(N).select("id").single();if(S)throw S;r(T=>({...T,id:k.id,status:"active"})),l(T=>[...T,{id:k.id,name:s.name,role:s.role,status:"active",avatar_url:s.avatar_url,orientation:ch(s)}])}i(s),f(!1)}catch(k){console.error("Save persona error:",k)}finally{m(!1)}},[s,t,o.length]),j=h.useCallback(()=>{r(a),f(!1)},[a]),_=h.useCallback(async(N,k)=>{if(!t)return null;const{data:S,error:T}=await I.from("personas").select("*").eq("id",N).single();if(T||!S)return console.error("Clone fetch failed:",T),null;const{id:C,created_at:B,updated_at:E,is_default:H,slug:z,...ne}=S,V={...ne,workspace_id:t,avatar_url:k,name:`${S.name} (copy)`,is_default:!1,status:"active"},{data:te,error:R}=await I.from("personas").insert(V).select("*").single();if(R||!te)return console.error("Clone insert failed:",R),null;const{data:F}=await I.from("persona_prompt_templates").select("prompt_type, content, version, is_active").eq("persona_id",N);F&&F.length&&await I.from("persona_prompt_templates").insert(F.map(J=>({...J,persona_id:te.id})));const $=Hf(te);return r($),i($),f(!1),l(J=>[...J,{id:te.id,name:te.name,role:te.role,status:te.status,avatar_url:te.avatar_url||"",orientation:ch(te)}]),localStorage.setItem(dh,te.id),te.id},[t]);return{persona:s,personas:o,update:y,save:w,saving:u,loading:c,dirty:p,selectPersona:x,createNew:b,deletePersona:v,clonePersona:_,revert:j}}const M1={friendly:"дружелюбный и тёплый",professional:"профессиональный и уверенный",casual:"неформальный и лёгкий",academic:"академический и точный",neutral:"нейтральный и сбалансированный"},z1={blogger:"ИИ-блогер, создающий короткий видеоконтент",host:"ИИ-ведущий прямых эфиров",consultant:"ИИ-консультант для персональных сессий",teacher:"ИИ-преподаватель и наставник",mixed:"универсальный ИИ-персонаж"},F1={calm:"Говори спокойно и экспертно, без суеты.",energetic:"Будь энергичным, держи темп, зажигай аудиторию.",friendly:"Общайся как хороший знакомый — тепло и открыто.",premium:"Держи премиальный тон — уверенно, без лишних слов.",mentor:"Объясняй как наставник — терпеливо, с примерами, по шагам."};function R8(e,t){return t?t(`roles_map.${e}`,{defaultValue:z1[e]||e}):z1[e]||e}function $8(e,t){return t?t(`tone_map.${e}`,{defaultValue:M1[e]||e}):M1[e]||e}function L8(e,t){return t?t(`style_map.${e}`,{defaultValue:F1[e]||""}):F1[e]||""}function on(e,t){if(t){const r=t(`defaultPrompts.${e}`,{defaultValue:""});if(r)return r}return{shorts_mode:`Режим коротких видео (Shorts).
800- Начинай с мощного hook
801- Держи 30-60 секунд
802- Одна идея = одно видео
803- Финал: чёткий вывод или CTA`,live_mode:`Режим прямого эфира.
804- Говори плавно и естественно
805- Приглашай задавать вопросы
806- Удерживай тему, но реагируй на чат
807- Подводи итоги каждые 5-7 минут`,chat_reply_mode:`Режим ответов на live-чат.
808- 1-3 предложения
809- Не ломай flow эфира
810- Будь доброжелательным`,consultation_mode:`Режим персональной консультации.
811- Задавай уточняющие вопросы
812- Давай структурные советы
813- Фокус на пользе`,webinar_mode:`Режим обучающего вебинара.
814- Структура: введение → блоки → итоги
815- Объясняй сложное просто
816- Повторяй ключевые мысли`,repurposing_mode:`Режим нарезки контента.
817- Находи яркие моменты
818- Формат: 15-60 секунд на клип
819- Создавай hook для каждого`,speaking_animation_mode:`Анимация аватара во время речи.
820- Естественные жесты руками
821- Мимика соответствует тону
822- Взгляд в камеру
823- Плавные движения`,idle_animation_mode:`Анимация аватара в ожидании.
824- Лёгкое дыхание, покачивания
825- Моргание, смена выражения
826- Ощущение присутствия`,video_prompt:`Реалистичное видео говорящего человека крупным планом.
827- Естественное мягкое освещение, тёплый телесный тон
828- Резкий фокус на лице, чёткие глаза и губы
829- Плавная синхронизация губ с речью
830- Лёгкие естественные движения головы и плеч
831- Стабильная камера, без рывков
832- Спокойный неотвлекающий фон, мягкое боке
833- Высокое качество, кинематографичная подача`,video_negative_prompt:`low quality, blurry, out of focus, low resolution, pixelated, jpeg artifacts, compression artifacts, noise, grain,
834deformed face, distorted face, asymmetric eyes, cross-eyed, extra eyes, missing eyes, melting face, plastic skin, waxy skin,
835bad mouth, deformed lips, extra teeth, missing teeth, mouth out of sync,
836extra fingers, missing fingers, deformed hands, mutated hands, fused fingers, extra limbs, missing limbs,
837duplicate person, double face, cloned face, two heads,
838flickering, frame jumps, motion blur, camera shake, jitter, warping,
839watermark, text, captions, subtitles, logo, signature,
840oversaturated, oversharpened, cartoon, anime, painting, 3d render, cgi`}[e]||""}function I8(e,t){const s=R8(e.role,t),r=$8(e.tone,t);return t?t("defaultPrompts.core_identity",{name:e.name,role:s,topic:e.primaryTopic||"",audience:"",language:e.language,tone:r,description:e.description}):`Ты — ${e.name}, ${s}.
841
842Тема: ${e.primaryTopic}
843Аудитория: широкая аудитория
844Язык: ${e.language==="ru"?"русский":e.language}
845Тон: ${r}
846
847${e.description}
848
849Ты — цифровой эксперт, а не безличный чатбот. У тебя есть характер, позиция и стиль.`}function O8(e,t){const s=L8(e.styleKey||"calm",t);return t?t("defaultPrompts.behavior_rules",{styleInstruction:s}):`Правила поведения:
850- Говори ясно и уверенно
851- Не звучи как безличный AI-ассистент
852- Не уходи в воду и пустые рассуждения
853- Не обещай лёгких денег и быстрых результатов
854- Признавай неопределённость, когда она есть
855- Используй естественные формулировки
856- Не спорь агрессивно
857- Сохраняй единый стиль во всех форматах
858
859${s}
860
861Бизнес-ограничения:
862- Не вводи в заблуждение
863- Не путай подписку на платформу с монетизацией аудитории
864- Не выдавай себя за человека, если это не задумано`}on("shorts_mode"),on("live_mode"),on("chat_reply_mode"),on("consultation_mode"),on("webinar_mode"),on("repurposing_mode"),on("speaking_animation_mode"),on("idle_animation_mode");const Fs=h.forwardRef(({className:e,...t},s)=>n.jsx("textarea",{className:_e("flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm r
864ing-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",e),ref:s,...t}));Fs.displayName="Textarea";const D8={short:"🎬",live:"📡",chat:"💬",consultation:"🎧",webinar:"🎓",manual:"✏️"};function M8({personaId:e,workspaceId:t}){const{t:s}=Oe("persona"),[r,a]=h.useState(!1),[i,o]=h.useState([]),[l,c]=h.useState(!1),[d,u]=h.useState(""),[m,p]=h.useState(null),[f,g]=h.useState(!1),[x,b]=h.useState(!1),[v,y]=h.useState(""),[w,j]=h.useState(!1),[_,N]=h.useState(null),[k,S]=h.useState(!1),[T,C]=h.useState(null),B=h.useCallback(async()=>{if(e){S(!0),C(null);try{const{data:V,error:te}=await I.functions.invoke("persona-memory-summary",{body:{persona_id:e}});if(te)throw te;N((V==null?void 0:V.summary)||null)}catch(V){C((V==null?void 0:V.message)||"error")}finally{S(!1)}}},[e]);h.useEffect(()=>{N(null),C(null)},[e]);const E=h.useCallback(async()=>{if(!e||!t)return;c(!0);const{data:V,error:te}=await I.from("persona_memory").select("id, summary, source_type, source_id, created_at").eq("persona_id",e).order("created_at",{ascending:!1}).limit(200);!te&&V&&o(V),c(!1)},[e,t]);h.useEffect(()=>{r&&i.length===0&&E()},[r,E]),h.useEffect(()=>{r&&E()},[e]);const H=async()=>{if(!m)return;g(!0);const{error:V}=await I.from("persona_memory").delete().eq("id",m);V||o(te=>te.filter(R=>R.id!==m)),g(!1),p(null)},z=async()=>{if(!v.trim()||!e||!t)return;j(!0);const{data:V,error:te}=await I.from("persona_memory").insert({persona_id:e,workspace_id:t,summary:v.trim(),source_type:"manual"}).select("id, summary, source_type, source_id, created_at").single();!te&&V&&(o(R=>[V,...R]),y(""),b(!1)),j(!1)},ne=d.trim()?i.filter(V=>V.summary.toLowerCase().includes(d.toLowerCase())):i;return e?n.jsxs(n.Fragment,{children:[n.jsxs(de.div,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{delay:.2},className:"rounded-2xl bg-surface-elevated border border-border/50 shadow-premium-sm overflow-hidden",children:[n.jsxs("button",{onClick:()=>a(!r),className:"w-full flex items-center justify-between p-5 sm:p-6 hover:bg-muted/10 transition-colors",children:[n.jsxs("h2",{className:"font-heading font-semibold text-base sm:text-lg text-foreground flex items-center gap-2",children:[n.jsx(vy,{size:18,className:"text-primary"})," ",s("memory.title"),i.length>0&&n.jsx(fe,{variant:"secondary",className:"text-[10px] ml-1",children:i.length})]}),n.jsx(ps,{size:18,className:`text-muted-foreground transition-transform shrink-0 ${r?"rotate-180":""}`})]}),n.jsx(xn,{children:r&&n.jsx(de.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.3},className:"overflow-hidden",children:n.jsxs("div",{className:"px-5 sm:px-6 pb-5 sm:pb-6 space-y-3",children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsx("p",{className:"text-xs text-muted-foreground",children:s("memory.desc")}),n.jsxs(L,{size:"sm",variant:"outline",className:"h-7 text-xs gap-1",onClick:()=>b(!x),children:[n.jsx(sr,{size:12})," ",s("memory.addManual")]})]}),i.length>0&&n.jsxs("div",{className:"rounded-lg border border-primary/20 bg-primary/5 p-3 space-y-2",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsxs("div",{className:"flex items-center gap-1.5 text-xs font-medium text-foreground",children:[n.jsx(tt,{size:13,className:"text-primary"}),s("memory.digest.title")]}),n.jsxs(L,{size:"sm",variant:"ghost",className:"h-6 text-[11px] gap-1 px-2",onClick:B,disabled:k,children:[k?n.jsx(xe,{size:11,className:"animate-spin"}):_?n.jsx(ss,{size:11}):n.jsx(tt,{size:11}),s(k?"memory.digest.generating":_?"memory.digest.regenerate":"memory.digest.generate")]})]}),!_&&!k&&!T&&n.jsx("p",{className:"text-[11px] text-muted-foreground",children:s("memory.digest.subtitle")}),T&&n.jsx("p",{className:"text-[11px] text-destructive",children:s("memory.digest.error")}),_&&n.jsx("p",{className:"text-xs text-foreground/90 leading-relaxed whitespace-pre-wrap",children:_})]}),n.jsx(xn,{children:x&&n.jsx(de.div,{initial:{height:0,opacity:0}
864,animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},className:"overflow-hidden",children:n.jsxs("div",{className:"flex flex-col gap-2 p-3 rounded-lg border border-primary/20 bg-primary/5",children:[n.jsx(Fs,{value:v,onChange:V=>y(V.target.value),placeholder:s("memory.addPlaceholder"),className:"min-h-[60px] text-xs bg-background/50 resize-none",maxLength:2e3}),n.jsxs("div",{className:"flex justify-end gap-2",children:[n.jsx(L,{size:"sm",variant:"ghost",className:"h-7 text-xs",onClick:()=>{b(!1),y("")},children:s("cancel")}),n.jsxs(L,{size:"sm",className:"h-7 text-xs gap-1",onClick:z,disabled:w||!v.trim(),children:[w?n.jsx(xe,{size:12,className:"animate-spin"}):n.jsx(Za,{size:12}),s("memory.addBtn")]})]})]})})}),l?n.jsx("div",{className:"flex justify-center py-8",children:n.jsx(xe,{className:"w-5 h-5 animate-spin text-primary"})}):i.length===0?n.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:s("memory.empty")}):n.jsxs(n.Fragment,{children:[i.length>5&&n.jsxs("div",{className:"relative",children:[n.jsx(bn,{size:14,className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"}),n.jsx(gt,{value:d,onChange:V=>u(V.target.value),placeholder:s("memory.search"),className:"pl-9 bg-muted/30 text-sm h-8"})]}),n.jsxs("div",{className:"space-y-2 max-h-[400px] overflow-y-auto pr-1",children:[ne.map(V=>n.jsxs("div",{className:"group flex items-start gap-2 rounded-lg border border-border/40 p-3 hover:bg-muted/10 transition-colors",children:[n.jsx("span",{className:"text-sm shrink-0 mt-0.5",children:D8[V.source_type]||"📝"}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("p",{className:"text-xs text-foreground leading-relaxed line-clamp-3",children:V.summary}),n.jsxs("div",{className:"flex items-center gap-2 mt-1.5",children:[n.jsx(fe,{variant:"outline",className:"text-[9px] px-1.5 py-0",children:s(`memory.source.${V.source_type}`,V.source_type)}),n.jsx("span",{className:"text-[10px] text-muted-foreground",children:new Date(V.created_at).toLocaleDateString()})]})]}),n.jsx("button",{onClick:()=>p(V.id),className:"opacity-0 group-hover:opacity-100 p-1 rounded-md hover:bg-destructive/10 text-muted-foreground hover:text-destructive transition-all shrink-0",children:n.jsx(ci,{size:13})})]},V.id)),ne.length===0&&d&&n.jsx("p",{className:"text-xs text-muted-foreground text-center py-4",children:s("memory.noResults")})]})]})]})})})]}),n.jsx(bi,{open:!!m,onOpenChange:V=>
864!V&&p(null),children:n.jsxs(oa,{children:[n.jsxs(la,{children:[n.jsx(da,{children:s("memory.deleteTitle")}),n.jsx(ua,{children:s("memory.deleteDesc")})]}),n.jsxs(ca,{children:[n.jsx(ma,{children:s("cancel")}),n.jsxs(ha,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",onClick:H,disabled:f,children:[f?n.jsx(xe,{size:14,className:"animate-spin mr-1"}):null,s("delete")]})]})]})})]}):null}function z8({path:e,isPortrait:t,onDelete:s}){const r=cc(e);return n.jsxs("div",{className:`relative rounded-xl overflow-hidden border border-border/40 bg-muted/30 group ${t?"aspect-[9/16]":"aspect-[16/9]"}`,children:[r?n.jsx("img",{src:r,alt:"",className:"w-full h-full object-cover"}):n.jsx("div",{className:"w-full h-full bg-muted animate-pulse"}),n.jsx("button",{onClick:s,className:"absolute top-1.5 right-1.5 p-1.5 rounded-md bg-black/50 hover:bg-destructive/80 text-white opacity-0 group-hover:opacity-100 transition-all",title:"Remove",children:n.jsx(ci,{size:12})})]})}function F8({t:e,personaId:t,workspaceId:s,orientation:r,extras:a,onChange:i}){const o=r!=="landscape",l=h.useRef(null),[c,d]=h.useState(""),[u,m]=h.useState(!1),[p,f]=h.useState(!1),g=!!t&&!!s,x=h.useCallback(()=>{var j;return(j=l.current)==null?void 0:j.click()},[]),b=h.useCallback(j=>{var N;const _=(N=j.target.files)==null?void 0:N[0];l.current&&(l.current.value=""),_&&(d(URL.createObjectURL(_)),m(!0))},[]),v=h.useCallback(async j=>{if(!t)return;const{data:_}=await I.from("personas").select("prompt_config").eq("id",t).single(),N=(_==null?void 0:_.prompt_config)||{};N.extra_avatars=j;const{error:k}=await I.from("personas").update({prompt_config:N}).eq("id",t);k&&console.error("Save extra_avatars error:",k)},[t]),y=h.useCallback(async j=>{if(!(!s||!t)){f(!0);try{const _=`${s}/avatars/${t}-extra-${Date.now()}.jpg`,{error:N}=await I.storage.from("generated-assets").upload(_,j,{contentType:"image/jpeg",upsert:!0});if(N)throw N;const k=[...a,_];i(k),await v(k),m(!1),d("")}catch(_){console.error("Upload extra photo error:",_)}finally{f(!1)}}},[s,t,a,i,v]),w=h.useCallback(async j=>{const _=a.filter(N=>N!==j);i(_),await v(_);try{await I.storage.from("generated-assets").remove([j])}catch{}},[a,i,v]);return n.jsxs(de.div,{...br,transition:{delay:.07},className:"rounded-2xl bg-surface-elevated border border-border/50 shadow-premium-sm p-5 sm:p-6 space-y-4",children:[n.jsxs("div",{className:"flex items-center justify-between gap-3",children:[n.jsxs("div",{children:[n.jsxs("h2",{className:"font-heading font-semibold text-base sm:text-lg text-foreground flex items-center gap-2",children:[n.jsx(x4,{size:18,className:"text-primary shrink-0"}),e("extraPhotos.title")]}),n.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:e("extraPhotos.subtitle")})]}),n.jsx("span",{className:"text-[11px] font-mono text-muted-foreground shrink-0",children:a.length+1})]}),!t&&n.jsx("p",{className:"text-xs text-muted-foreground italic",children:e("extraPhotos.saveFirst")}),n.jsxs("div",{className:`grid gap-3 ${o?"grid-cols-3 sm:grid-cols-4 md:grid-cols-5":"grid-cols-2 sm:grid-cols-3"}`,children:[a.map(j=>n.jsx(z8,{path:j,isPortrait:o,onDelete:()=>w(j)},j)),g&&n.jsxs("button",{onClick:x,className:`rounded-xl border-2 border-dashed border-border/50 hover:border-primary/40 hover:bg-primary/[0.03] transition-all flex flex-col items-center justify-center gap-1.5 text-muted-foreground hover:text-foreground ${o?"aspect-[9/16]":"aspect-[16/9]"}`,children:[n.jsx(sr,{size:20}),n.jsx("span",{className:"text-[11px] font-medium",children:e("extraPhotos.add")})]})]}),n.jsx("input",{ref:l,type:"file",accept:"image/*",className:"hidden",onChange:b}),n.jsx(ns,{open:u&&!!c,onOpenChange:j=>{j||(m(!1),d(""))},children:n.jsxs(Zt,{className:"sm:max-w-md",children:[n.jsxs(Xt,{children:[n.jsx(es,{children:e("extraPhotos.cropTitle")}),n.jsx(us,{children:e("extraPhotos.cropDesc")})]}),c&&n.jsx(Cm,{imageUrl:c,targetWidth:o?720:1280,targetHeight:o?1280:720,onCrop:y,onCancel:()=>{m(!1),d("")}}),p&&n.jsxs("div",{className:"flex items-center justify-center gap-2 py-2",children:[n.jsx(xe,{size:16,className:"animate-spin text-primary"}),n.jsx("span",{className:"text-sm text-muted-foreground",children:e("extraPhotos.uploading")})]})]})})]})}const U8=["webinar_plan_block","topic_synthesis","trending_cluster","trending_juice","speaking_format","continue_text","summary_text"];function $p({personaPromptConfig:e,update:t,keys:s,title:r,subtitle:a,defaultOpen:i=!1}){const{t:o}
864=Oe("persona"),[l,c]=h.useState(i),[d,u]=h.useState(null),[m,p]=h.useState(null),[f,g]=h.useState(!1),x=s&&s.length?s:U8,b=(e==null?void 0:e.generation_prompts)||{};h.useEffect(()=>{!l||m||(g(!0),I.functions.invoke("gen-prompt-defaults",{body:{}}).then(({data:y,error:w})=>{!w&&(y!=null&&y.defaults)&&p(y.defaults)}).finally(()=>g(!1)))},[l,m]);const v=(y,w)=>{var _;const j={...b};!w||!w.trim()?delete j[y]:j[y]={value:w,version:(((_=b[y])==null?void 0:_.version)??0)+1,updated_at:new Date().toISOString()},t({prompt_config:{...e,generation_prompts:j}})};return n.jsxs(de.div,{...br,transition:{delay:.18},className:"rounded-2xl bg-surface-elevated border border-border/50 shadow-premium-sm overflow-hidden",children:[n.jsxs("button",{onClick:()=>c(!l),className:"w-full flex items-center justify-between p-5 sm:p-6 hover:bg-muted/10 transition-colors",children:[n.jsxs("div",{className:"text-left",children:[n.jsxs("h2",{className:"font-heading font-semibold text-base sm:text-lg text-foreground flex items-center gap-2",children:[n.jsx(xi,{size:18,className:"text-primary"})," ",r??o("generationPrompts.title")]}),n.jsx("p",{className:"text-[11px] text-muted-foreground mt-1",children:a??o("generationPrompts.subtitle")})]}),n.jsx(ps,{size:18,className:`text-muted-foreground transition-transform shrink-0 ${l?"rotate-180":""}`})]}),n.jsx(xn,{children:l&&n.jsx(de.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.3},className:"overflow-hidden",children:n.jsxs("div",{className:"px-5 sm:px-6 pb-5 sm:pb-6 space-y-3",children:[f&&!m&&n.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground py-2",children:[n.jsx(xe,{size:14,className:"animate-spin"}),o("generationPrompts.loadingDefaults")]}),x.map(y=>{const w=d===y,j=b[y],_=(j==null?void 0:j.value)||"",N=(m==null?void 0:m[y])||"",k=!!_.trim();return n.jsxs("div",{className:"rounded-xl border border-border/40 overflow-hidden",children:[n.jsxs("button",{onClick:()=>u(w?null:y),className:"w-full flex items-center justify-between px-3 sm:px-4 py-3 hover:bg-muted/10 transition-colors gap-2",children:[n.jsxs("div",{className:"text-left min-w-0",children:[n.jsx("p",{className:"text-xs sm:text-sm font-semibold text-foreground",children:o(`generationPrompts.keys.${y}.label`)}),n.jsx("p",{className:"text-[10px] sm:text-[11px] text-muted-foreground truncate",children:o(`generationPrompts.keys.${y}.desc`)})]}),n.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[k&&n.jsx(fe,{variant:"secondary",className:"text-[9px]",children:o("generationPrompts.custom")}),n.jsx(ps,{size:14,className:`text-muted-foreground transition-transform ${w?"rotate-180":""}`})]})]}),n.jsx(xn,{children:w&&n.jsx(de.div,{initial:{height:0},animate:{height:"auto"},exit:{height:0},className:"overflow-hidden",children:n.jsxs("div",{className:"px-3 sm:px-4 pb-4 space-y-2",children:[n.jsx(Fs,{value:_||N,onChange:S=>v(y,S.target.value),placeholder:N||o("generationPrompts.emptyPlaceholder"),className:"bg-muted/20 min-h-[220px] text-xs font-mono resize-y"}),n.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[n.jsx("p",{className:"text-[10px] text-muted-foreground",children:o("generationPrompts.placeholdersHint")}),n.jsx("div",{className:"flex items-center gap-2",children:k&&n.jsxs(L,{size:"sm",variant:"ghost",className:"h-7 text-[11px] gap-1",onClick:()=>v(y,""),children:[n.jsx(hp,{size:12})," ",o("generationPrompts.resetDefault")]})})]})]})})})]},y)})]})})})]})}const B8={live:"Live / Эфиры",content:"Контент-студия",discovery:"Discovery / Темы",helper:"Вспомогательные"},V8=["live","content","discovery","helper"];function sT({personaPromptConfig:e,update:t,overrides:s,onOverridesChange:r,slotFilter:a,title:i="Промпты движка (системные)",subtitle:o="Точечные системные тексты, которые модель получает в момент генерации. Переопредели любой из них только для этой персоны — остальные продолжат использовать заводской/глобаÐ
864»ÑŒÐ½Ñ‹Ð¹.",defaultOpen:l=!1}){const[c,d]=h.useState(l),[u,m]=h.useState(null),[p,f]=h.useState(null),[g,x]=h.useState(!1),b=!!r,v=b?s||{}:(e==null?void 0:e.overrides)||{};h.useEffect(()=>{!c||p||(x(!0),I.from("prompt_templates").select("slot_key,title,description,category,body,variables,where_used,is_workspace_scope").order("category").order("slot_key").then(({data:j})=>{const _=(j||[]).filter(N=>!N.is_workspace_scope);f(_),x(!1)}))},[c,p]);const y=h.useMemo(()=>{var N;const j=(p||[]).filter(k=>!a||a(k.slot_key)),_={};for(const k of j)(_[N=k.category]??(_[N]=[])).push(k);return _},[p,a]),w=(j,_)=>{const N={...v};!_||!_.trim()?delete N[j]:N[j]=_,b?r(N):t==null||t({prompt_config:{...e,overrides:N}})};return n.jsxs(de.div,{...br,transition:{delay:.22},className:"rounded-2xl bg-surface-elevated border border-border/50 shadow-premium-sm overflow-hidden",children:[n.jsxs("button",{onClick:()=>d(!c),className:"w-full flex items-center justify-between p-5 sm:p-6 hover:bg-muted/10 transition-colors",children:[n.jsxs("div",{className:"text-left",children:[n.jsxs("h2",{className:"font-heading font-semibold text-base sm:text-lg text-foreground flex items-center gap-2",children:[n.jsx($4,{size:18,className:"text-primary"})," ",i]}),n.jsx("p",{className:"text-[11px] text-muted-foreground mt-1",children:o})]}),n.jsx(ps,{size:18,className:`text-muted-foreground transition-transform shrink-0 ${c?"rotate-180":""}`})]}),n.jsx(xn,{children:c&&n.jsx(de.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.3},className:"overflow-hidden",children:n.jsxs("div",{className:"px-5 sm:px-6 pb-5 sm:pb-6 space-y-4",children:[g&&n.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground py-2",children:[n.jsx(xe,{size:14,className:"animate-spin"})," Загружаю слоты…"]}),V8.filter(j=>{var _;return(_=y[j])==null?void 0:_.length}).map(j=>n.jsxs("div",{className:"space-y-2",children:[n.jsx("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground/70 font-medium",children:B8[j]??j}),y[j].map(_=>{var C;const N=u===_.slot_key,k=v[_.slot_key]||"",S=_.body||"",T=!!k.trim();return n.jsxs("div",{className:"rounded-xl border border-border/40 overflow-hidden",children:[n.jsxs("button",{onClick:()=>m(N?null:_.slot_key),className:"w-full flex items-center justify-between px-3 sm:px-4 py-3 hover:bg-muted/10 transition-colors gap-2",children:[n.jsxs("div",{className:"text-left min-w-0",children:[n.jsx("p",{className:"text-xs sm:text-sm font-semibold text-foreground",children:_.title}),n.jsx("p",{className:"text-[10px] sm:text-[11px] text-muted-foreground truncate font-mono",children:_.slot_key})]}),n.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[T&&n.jsx(fe,{variant:"secondary",className:"text-[9px]",children:"override"}),n.jsx(ps,{size:14,className:`text-muted-foreground transition-transform ${N?"rotate-180":""}`})]})]}),n.jsx(xn,{children:N&&n.jsx(de.div,{initial:{height:0},animate:{height:"auto"},exit:{height:0},className:"overflow-hidden",children:n.jsxs("div",{className:"px-3 sm:px-4 pb-4 space-y-2",children:[_.description&&n.jsx("p",{className:"text-[11px] text-muted-foreground",children:_.description}),_.where_used&&n.jsxs("div",{className:"text-[11px] bg-muted/40 rounded-md px-2 py-1.5 text-muted-foreground",children:[n.jsx("span",{className:"font-medium text-foreground",children:"Куда уходит:"})," ",_.where_used]}),n.jsx(Fs,{value:k||S,onChange:B=>w(_.slot_key,B.target.value),placeholder:S,className:"bg-muted/20 min-h-[200px] text-xs font-mono resize-y"}),n.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[(C=_.variables)!=null&&C.length?n.jsx("div",{className:"flex flex-wrap gap-1",children:_.variables.map(B=>n.jsx("code",{className:"text-[10px] bg-muted px-1.5 py-0.5 rounded font-mono",children:`{{${B}}}`},B))}):n.jsx("span",{}),T&&n.jsxs(L,{size:"sm",variant:"ghost",className:"h-7 text-[11px] gap-1",onClick:()=>w(_.slot_key,""),children:[n.jsx(hp,{size:12}
864)," Вернуть глобальный"]})]})]})})})]},_.slot_key)})]},j)),!g&&p&&Object.keys(y).length===0&&n.jsx("p",{className:"text-xs text-muted-foreground py-2",children:"Нет доступных слотов."})]})})})]})}function q8({path:e,name:t}){const s=cc(e);return s?n.jsx("img",{src:s,alt:t,className:"w-full h-full object-cover"}):n.jsx("div",{className:"w-full h-full bg-muted animate-pulse"})}const H8=[{id:"blogger",icon:Ns},{id:"host",icon:St},{id:"consultant",icon:Zs},{id:"teacher",icon:Cy},{id:"lawyer",icon:mS},{id:"mixed",icon:Ey}],W8=["calm","energetic","friendly","premium","mentor","sad"],G8={calm:"🧘",energetic:"⚡",friendly:"🤝",premium:"🎩",mentor:"📚",sad:"😔"},Y8=["behavior_rules","shorts_mode","live_mode","chat_reply_mode","consultation_mode","webinar_mode","repurposing_mode","speaking_animation_mode","idle_animation_mode","video_prompt","video_negative_prompt"],Wf=({children:e,className:t="",delay:s=0})=>n.jsx(de.div,{...br,transition:{delay:s},className:`rounded-2xl bg-surface-elevated border border-border/50 shadow-premium-sm p-5 sm:p-6 space-y-4 ${t}`,children:e}),Gf=({icon:e,children:t})=>n.jsxs("h2",{className:"font-heading font-semibold text-base sm:text-lg text-foreground flex items-center gap-2",children:[n.jsx(e,{size:18,className:"text-primary shrink-0"})," ",t]}),K8=()=>{var kt,X;const{t:e}=Oe("persona"),{persona:t,personas:s,update:r,save:a,saving:i,loading:o,dirty:l,selectPersona:c,createNew:d,deletePersona:u,clonePersona:m,revert:p}=tT(),{profile:f}=st(),{fill:g,isLoading:x}=pa(),[b,v]=h.useState(!1),[y,w]=h.useState(null),[j,_]=h.useState(null),[N,k]=h.useState(!1),[S,T]=h.useState(!1),[C,B]=h.useState(null),[E,H]=h.useState(""),[z,ne]=h.useState(!1),V=h.useRef(null),te=h.useRef(null),R=h.useRef(null),[F,$]=h.useState(""),[J,Y]=h.useState(!1),[re,G]=h.useState(!1),O=h.useRef(null),Z=H8.map(M=>({...M,label:e(`roles.${M.id}`),desc:e(`roles.${M.id}Desc`)})),A=W8.map(M=>({id:M,label:e(`styles.${M}`),emoji:G8[M]})),oe=Y8.map(M=>({key:M,label:e(`promptLayers.${M}`),desc:e(`promptLayers.${M}Desc`)})),[ue,je]=h.useState(null),[ae,ie]=h.useState({name:"",orientation:"",avatar_url:"",raw_avatar_url:"",role:"blogger",style_key:"calm"}),we=()=>{ie({name:"",orientation:"",avatar_url:"",raw_avatar_url:"",role:"blogger",style_key:"calm"}),je("name")},Ae=ae.orientation==="landscape"?{w:1280,h:720}:{w:720,h:1280},nt=h.useCallback(async M=>{var Ce;const se=(Ce=M.target.files)==null?void 0:Ce[0];if(!se)return;const he=URL.createObjectURL(se);ie(Ve=>({...Ve,raw_avatar_url:he,avatar_url:""})),je("crop"),R.current&&(R.current.value="")},[]),Qe=h.useCallback(M=>{ie(se=>({...se,raw_avatar_url:M,avatar_url:""})),je("crop")},[]),P=h.useCallback(async M=>{if(f!=null&&f.workspace_id){k(!0);try{const se=`${f.workspace_id}/avatars/new-${Date.now()}.jpg`,{error:he}=await I.storage.from("generated-assets").upload(se,M,{contentType:"image/jpeg",upsert:!0});if(he)throw he;ie(Ce=>({...Ce,avatar_url:se})),je("role")}catch(se){console.error("Avatar upload error:",se)}finally{k(!1)}}},[f==null?void 0:f.workspace_id]),U=h.useCallback(()=>{var Ve;const M=Z.find(me=>me.id===ae.role),se=A.find(me=>me.id===ae.style_key),he=e("wizardAutoDesc",{style:(se==null?void 0:se.label)||"",role:((Ve=M==null?void 0:M.label)==null?void 0:Ve.toLowerCase())||e("wizardFallbackRole")}),Ce=(me,Ge)=>String(e(me,Ge));d(),setTimeout(()=>{r({name:ae.name,role:ae.role,style_key:ae.style_key,avatar_url:ae.avatar_url,description:he,prompt_config:{orientation:ae.orientation,speaking_animation_mode:on("speaking_animation_mode",Ce),idle_animation_mode:on("idle_animation_mode",Ce),video_prompt:on("video_prompt",Ce),video_negative_prompt:on("video_negative_prompt",Ce)}})},0),je(null)},[ae,d,r,Z,A,e]),Q=h.useCallback(M=>{var se;B({id:M,orientation:"portrait"}),H(""),(se=V.current)==null||se.click()},[]),ve=h.useCallback(async M=>{var Ve,me;const se=(Ve=M.target.files)==null?void 0:Ve[0];if(V.current&&(V.current.value=""),!se||!C)return;const{data:he}=await I.from("personas").select("prompt_config").eq("id",C.id).single(),Ce=((me=he==null?void 0:he.prompt_config)==null?void 0:me.orientation)==="landscape"?"landscape":"portrait";B({id:C.id,orientation:Ce}),H(URL.createObjectURL(se))},[C]),We=h.useCallback(async M=>
864{if(!(!(f!=null&&f.workspace_id)||!C)){ne(!0);try{const se=`${f.workspace_id}/avatars/clone-${Date.now()}.jpg`,{error:he}=await I.storage.from("generated-assets").upload(se,M,{contentType:"image/jpeg",upsert:!0});if(he)throw he;await m(C.id,se),B(null),H("")}catch(se){console.error("Clone error:",se)}finally{ne(!1)}}},[f==null?void 0:f.workspace_id,C,m]),Ze=h.useCallback(()=>{var M;$(""),(M=O.current)==null||M.click()},[]),Je=h.useCallback(M=>{var he;const se=(he=M.target.files)==null?void 0:he[0];O.current&&(O.current.value=""),se&&($(URL.createObjectURL(se)),Y(!0))},[]),xt=h.useCallback(async M=>{if(!(!(f!=null&&f.workspace_id)||!t.id)){G(!0);try{const se=`${f.workspace_id}/avatars/${t.id}-${Date.now()}.jpg`,{error:he}=await I.storage.from("generated-assets").upload(se,M,{contentType:"image/jpeg",upsert:!0});if(he)throw he;const{error:Ce}=await I.from("personas").update({avatar_url:se}).eq("id",t.id);if(Ce)throw Ce;r({avatar_url:se}),Y(!1),$("")}catch(se){console.error("Replace avatar error:",se)}finally{G(!1)}}},[f==null?void 0:f.workspace_id,t.id,r]),Pt=Z.find(M=>M.id===t.role),K=A.find(M=>M.id===t.style_key),ye=((kt=t.prompt_config)==null?void 0:kt.orientation)||"portrait",De={name:t.name,role:t.role,description:t.description,primaryTopic:"",language:t.language,tone:"friendly",audienceType:"",styleKey:t.style_key},pt=(M,se)=>{r({prompt_config:{...t.prompt_config,[M]:se}})};return o?n.jsx("div",{className:"flex items-center justify-center min-h-[400px]",children:n.jsx(xe,{className:"w-6 h-6 animate-spin text-primary"})}):s.length===0&&!t.id&&!t.name?n.jsxs("div",{className:"max-w-6xl mx-auto",children:[n.jsx(de.div,{...br,children:n.jsxs("h1",{className:"font-heading font-bold text-xl sm:text-2xl md:text-3xl text-foreground flex items-center gap-2",children:[n.jsx(Xs,{className:"text-primary",size:24}),e("pageTitle")]})}),n.jsxs(de.div,{...br,transition:{delay:.15},className:"mt-16 flex flex-col items-center justify-center text-center",children:[n.jsx("div",{className:"w-20 h-20 rounded-3xl bg-gradient-primary flex items-center justify-center text-primary-foreground shadow-glow mb-6",children:n.jsx(r4,{size:36})}),n.jsx("h2",{className:"font-heading font-bold text-lg sm:text-xl text-foreground mb-2",children:e("noPersonas")}),n.jsx("p",{className:"text-sm text-muted-foreground max-w-md mb-8",children:e("noPersonasDesc")}),n.jsxs(L,{variant:"hero",size:"lg",className:"gap-2 text-base px-8",onClick:we,children:[n.jsx(sr,{size:20})," ",e("createPersona")]})]}),n.jsx(D1,{t:e,step:ue,data:ae,setData:ie,setStep:je,onFinish:U,uploading:N,onAvatarUpload:nt,onPresetSelect:Qe,onCroppedBlob:P,avatarRef:R,avatarDimensions:Ae,roles:Z,styles:A})]}):n.jsxs("div",{className:"max-w-6xl mx-auto space-y-6 sm:space-y-8",children:[n.jsx(de.div,{...br,children:n.jsxs("h1",{className:"font-heading font-bold text-xl sm:text-2xl md:text-3xl text-foreground flex items-center gap-2",children:[n.jsx(Xs,{className:"text-primary",size:24}),e("pageTitle")]})}),n.jsx(de.div,{...br,className:"space-y-3",children:n.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-3",children:[s.map(M=>{const se=t.id===M.id,he=n.jsxs("button",{onClick:()=>{var Ce;se?(Ce=te.current)==null||Ce.scrollIntoView({behavior:"smooth",block:"start"}):c(M.id)},className:`relative group rounded-xl border-2 overflow-hidden transition-all duration-200 ${se?"border-primary shadow-[0_0_12px_hsl(var(--primary)/0.35)] ring-1 ring-primary/20":"border-border/50 hover:border-primary/30"}`,children:[se&&n.jsx("div",{className:"absolute inset-0 z-[1] pointer-events-none rounded-xl animate-pulse-soft ring-2 ring-primary/30"}),n.jsxs("div",{className:"absolute top-2 right-2 z-10 flex gap-1 opacity-0 group-hover:opacity-100 transition-all",children:[n.jsx("button",{onClick:Ce=>{Ce.stopPropagation(),Q(M.id)},className:"p-1 rounded-md bg-black/40 hover:bg-primary/80 text-white transition-all",title:e("clone"),children:n.jsx(Ma,{size:13})}),n.jsx("button",{onClick:Ce=>{Ce.stopPropagation(),_(M.id)},className:"p-1 rounded-md bg-black/40 hover:bg-destructive/80 text-white transition-all",title:e("delete"),children:n.jsx(ci,{size:13})})]}),M.avatar_url?n.jsx("div",{className:"aspect-[9/16] w-full",children:n.jsx(q8,{path:M.avatar_url,name:M.name})}):n.jsx("div",{className:"aspect-[9/16] w-full bg-gradient-primary flex items-center justify-center text-primary-foreground font-bold text-2xl",children:M.name.charAt(0).toUpperCase()}),n.jsx("div",{className:"absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/70 to-transparent p-2 pt-6",children:n.jsx("p",{className:"text-xs font-semibold text-white text-center truncate",children:M.name})})]},M.id);return se?n.jsxs(LN,{delayDuration:600,children:[n.jsx(IN,{asChild:!0,children:he}),n.jsx(fy,{side:"bottom",children:e("scrollToSettings")})]},M.id):he}),n.jsxs("button",{onClick:we,className:"rounded-xl border-2 border-dashed border-border/50 p-3 sm:p-4 text-center hover:border-primary/30 hover:bg-primary/[0.02] transition-all duration-200 flex flex-col items-center justify-center min-h-[120px]",children:[n.jsx(sr,{size:20,className:"text-muted-foreground mb-1"}),n.jsx("p",{className:"text-xs text-muted-foreground font-medium",children:e("createNew")})]})]})}),n.jsx(bi,{open:!!j,onOpenChange:M=>
864!M&&_(null),children:n.jsxs(oa,{children:[n.jsxs(la,{children:[n.jsx(da,{children:e("deleteTitle")}),n.jsx(ua,{children:e("deleteDesc")})]}),n.jsxs(ca,{children:[n.jsx(ma,{children:e("cancel")}),n.jsx(ha,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",onClick:()=>{j&&u(j),_(null)},children:e("delete")})]})]})}),n.jsx("input",{ref:V,type:"file",accept:"image/*",className:"hidden",onChange:ve}),n.jsx(ns,{open:!!C&&!!E,onOpenChange:M=>{M||(B(null),H(""))},children:n.jsxs(Zt,{className:"sm:max-w-md",children:[n.jsxs(Xt,{children:[n.jsx(es,{children:e("cloneTitle")}),n.jsx(us,{children:e("cloneDesc")})]}),E&&C&&n.jsx(Cm,{imageUrl:E,targetWidth:C.orientation==="landscape"?1280:720,targetHeight:C.orientation==="landscape"?720:1280,onCrop:We,onCancel:()=>{B(null),H("")}}),z&&n.jsxs("div",{className:"flex items-center justify-center gap-2 py-2",children:[n.jsx(xe,{size:16,className:"animate-spin text-primary"}),n.jsx("span",{className:"text-sm text-muted-foreground",children:e("cloning")})]})]})}),n.jsx("input",{ref:O,type:"file",accept:"image/*",className:"hidden",onChange:Je}),n.jsx(ns,{open:J&&!!F,onOpenChange:M=>{M||(Y(!1),$(""))},children:n.jsxs(Zt,{className:"sm:max-w-md",children:[n.jsxs(Xt,{children:[n.jsx(es,{children:e("replaceAvatarTitle")}),n.jsx(us,{children:e("replaceAvatarDesc")})]}),F&&n.jsx(Cm,{imageUrl:F,targetWidth:ye==="landscape"?1280:720,targetHeight:ye==="landscape"?720:1280,onCrop:xt,onCancel:()=>{Y(!1),$("")}}),re&&n.jsxs("div",{className:"flex items-center justify-center gap-2 py-2",children:[n.jsx(xe,{size:16,className:"animate-spin text-primary"}),n.jsx("span",{className:"text-sm text-muted-foreground",children:e("saving")})]})]})}),n.jsx("div",{ref:te,children:n.jsx(a8,{t:e,persona:t,selectedRole:Pt,selectedStyle:K,orientation:ye,update:r,save:a,onReplaceAvatar:Ze})}),n.jsx(F8,{t:e,personaId:t.id,workspaceId:f==null?void 0:f.workspace_id,orientation:ye,extras:Array.isArray((X=t.prompt_config)==null?void 0:X.extra_avatars)?t.prompt_config.extra_avatars:[],onChange:M=>r({prompt_config:{...t.prompt_config,extra_avatars:M}})}),n.jsxs("div",{className:"space-y-5 sm:space-y-6",children:[n.jsxs(Wf,{delay:.05,children:[n.jsx(Gf,{icon:Xs,children:e("profile.title")}),n.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[n.jsxs("div",{className:"space-y-1.5",children:[n.jsx("label",{className:"text-xs font-medium text-muted-foreground",children:e("profile.name")}),n.jsx(Ot,{value:t.name,onChange:M=>r({name:M.target.value}),className:"bg-muted/30",aiLoading:x("persona_name"),onAiFill:async()=>{const M=await g({fieldName:"persona_name",fieldLabel:e("profile.name"),currentValue:t.name,pageContext:{role:t.role,description:t.description,language:t.language,style:t.style_key||""},personaId:t.id,language:t.language});M&&r({name:M})}})]}),n.jsxs("div",{className:"space-y-1.5",children:[n.jsxs("label",{className:"text-xs font-semibold text-foreground flex items-center gap-1.5",children:[n.jsx("span",{className:"text-lg",children:"🌐"})," ",e("profile.language")]}),n.jsxs(ut,{value:t.language,onValueChange:M=>r({language:M}),children:[n.jsx(ct,{className:"bg-primary/5 border-primary/30 ring-primary/20 font-medium text-foreground",children:n.jsx(ht,{})}),n.jsx(dt,{children:["ru","en","es","de","fil","ja"].map(M=>{const se={ru:"🇷🇺",en:"🇬🇧",es:"🇪🇸",de:"🇩🇪",fil:"🇵🇭",ja:"🇯🇵"};return n.jsx(ce,{value:M,children:n.jsxs("span",{className:"flex items-center gap-2",children:[n.jsx("span",{children:se[M]})," ",e(`languages.${M}`)]})},M)})})]})]})]}),n.jsxs("div",{className:"space-y-1.5",children:[n.jsx("label",{className:"text-xs font-medium text-muted-foreground",children:e("profile.description")}),n.jsx(os,{value:t.description,onChange:M=>r({description:M.target.value}),className:"bg-muted/30 min-h-[72px] resize-none",aiLoading:x("description"),onAiFill:async()=>{const M=await g({fieldName:"description",fieldLabel:e("profile.description"),currentValue:t.description,pageContext:{name:t.name,role:t.role,language:t.language,style:t.style_key||"",topic:t.primary_topic||""},personaId:t.id,language:t.language});M&&r({description:M})}})]})]}),n.jsxs(Wf,{delay:.1,children:[n.jsx(Gf,{icon:M4,children:e("voice.title")}),n.jsx("p",{className:"text-[11px] text-muted-foreground -mt-2",children:e("voice.modelNote").split("<mono>").map((M,se)=>{if(se===0)return M;const[he,Ce]=M.split("</mono>");return n.jsxs("span",{children:[n.jsx("span",{className:"font-mono text-foreground
864/70",children:he}),Ce]},se)})}),n.jsx(C8,{t:e,persona:t,update:r,aiLoading:x,fill:g})]}),n.jsxs(Wf,{delay:.12,children:[n.jsx(Gf,{icon:Xi,children:e("systemPrompt.title")}),(()=>{const se=I8(De,(Ce,Ve)=>String(e(Ce,Ve))),he=t.prompt_config.core_identity||"";return n.jsxs(n.Fragment,{children:[n.jsx(os,{value:he,onChange:Ce=>pt("core_identity",Ce.target.value),placeholder:se,className:"bg-muted/20 min-h-[260px] text-xs font-mono resize-y",aiLoading:x("prompt_core_identity"),onAiFill:async()=>{const Ce=await g({fieldName:"prompt_core_identity",fieldLabel:e("systemPrompt.title"),currentValue:he,pageContext:{name:t.name,role:t.role,description:t.description,language:t.language,style:t.style_key||""},personaId:t.id,language:t.language});Ce&&pt("core_identity",Ce)}}),he&&n.jsx("button",{onClick:()=>pt("core_identity",""),className:"text-[11px] text-muted-foreground hover:text-foreground transition-colors",children:e("advanced.resetDefault")})]})})()]}),n.jsxs(de.div,{...br,transition:{delay:.15},className:"rounded-2xl bg-surface-elevated border border-border/50 shadow-premium-sm overflow-hidden",children:[n.jsxs("button",{onClick:()=>v(!b),className:"w-full flex items-center justify-between p-5 sm:p-6 hover:bg-muted/10 transition-colors",children:[n.jsxs("h2",{className:"font-heading font-semibold text-base sm:text-lg text-foreground flex items-center gap-2",children:[n.jsx(R4,{size:18,className:"text-primary"})," ",e("advanced.title")]}),n.jsx(ps,{size:18,className:`text-muted-foreground transition-transform shrink-0 ${b?"rotate-180":""}`})]}),n.jsx(xn,{children:b&&n.jsx(de.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.3},className:"overflow-hidden",children:n.jsx("div",{className:"px-5 sm:px-6 pb-5 sm:pb-6 space-y-3",children:oe.map(M=>{const se=y===M.key,he=t.prompt_config[M.key]||"",Ce=(me,Ge)=>String(e(me,Ge)),Ve=M.key==="behavior_rules"?O8(De,Ce):on(M.key,Ce);return n.jsxs("div",{className:"rounded-xl border border-border/40 overflow-hidden",children:[n.jsxs("button",{onClick:()=>w(se?null:M.key),className:"w-full flex items-center justify-between px-3 sm:px-4 py-3 hover:bg-muted/10 transition-colors gap-2",children:[n.jsxs("div",{className:"text-left min-w-0",children:[n.jsx("p",{className:"text-xs sm:text-sm font-semibold text-foreground",children:M.label}),n.jsx("p",{className:"text-[10px] sm:text-[11px] text-muted-foreground truncate",children:M.desc})]}),n.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[he&&n.jsx(fe,{variant:"secondary",className:"text-[9px]",children:e("advanced.custom")}),n.jsx(ps,{size:14,className:`text-muted-foreground transition-transform ${se?"rotate-180":""}`})]})]}),n.jsx(xn,{children:se&&n.jsx(de.div,{initial:{height:0},animate:{height:"auto"},exit:{height:0},className:"overflow-hidden",children:n.jsxs("div",{className:"px-3 sm:px-4 pb-4",children:[n.jsx(os,{value:he,onChange:me=>pt(M.key,me.target.value),placeholder:Ve||e("advanced.emptyPlaceholder",{layer:M.label}),className:"bg-muted/20 min-h-[120px] text-xs font-mono resize-y",aiLoading:x(`prompt_${M.key}`),onAiFill:async()=>{const me=await g({fieldName:`prompt_${M.key}`,fieldLabel:M.label,currentValue:he,pageContext:{name:t.name,role:t.role,description:t.description,language:t.language,style:t.style_key||""},personaId:t.id,language:t.language});me&&pt(M.key,me)}}),he&&n.jsx("button",{onClick:()=>pt(M.key,""),className:"text-[11px] text-muted-foreground hover:text-foreground mt-2 transition-colors",children:e("advanced.resetDefault")})]})})})]},M.key)})})})})]})]}),n.jsx($p,{personaPromptConfig:t.prompt_config,update:r}),n.jsx(sT,{personaPromptConfig:t.prompt_config,update:r}),n.jsx(M8,{personaId:t.id,workspaceId:f==null?void 0:f.workspace_id}),n.jsx("div",{className:"sticky bottom-0 z-20 -mx-4 px-4 py-3 bg-background/95 backdrop-blur-sm border-t border-border/50",children:n.jsxs("div",{className:"flex gap-3",children:[l&&n.jsxs(L,{variant:"outline",className:"gap-2",onClick:p,children:[n.jsx(hp,{size:16})," ",e("cancel")]}),n.jsxs(L,{variant:"hero",className:"flex-1 gap-2",onClick:a,disabled:i||!l,children:[i?n.jsx(xe,{size:16,className:"animate-spin"}):l?n.jsx(Id,{size:16}):n.jsx(ms,{size:16}),e(i?"saving":l?"save":"saved")]}),t.id&&!l&&n.jsxs(L,{variant:"hero-outline",className:"gap-2",onClick:()=>T(!0),children:[n.jsx(Xi,{size:16})," ",e("createContentPlan")]})]})}),n.jsx(P8,{open:S,onOpenChange:T,t:e}),n.jsx(D1,{t:e,step:ue,data:ae,setData:ie,setStep:je,onFinish:U,uploading:N,onAvatarUpload:nt,onPresetSelect:Qe,onCroppedBlob:P,avatarRef:R,avatarDimensions:Ae,roles:Z,styles:A})]})};function Lp({open:e,onConfirm:t,onCancel:s}){const{t:r}=Oe("common"),[a,i]=h.useState("");return h.useEffect(()=>{e&&i("")},[e]),n.jsx(ns,{open:e,onOpenChange:o=>{o||s()},children:n.jsxs(Zt,{className:"sm:max-w-md",children:[n.jsxs(Xt,{children:[n.jsx(es,{children:r("aiFill.topicRequiredTitle")}),n.jsx(us,{children:r("aiFill.topicRequiredDesc")})]}),n.jsx(gt,{autoFocus:!0,value:a,onChange:o=>i(o.target.value),placeholder:r("aiFill.topicPlaceholder"),onKeyDown:o=>{o.key==="Enter"&&a.trim()&&t(a.trim())}}),n.jsxs("div",{className:"flex justify-end gap-2 mt-2",children:[n.jsx(L,{variant:"outline",onClick:s,children:r("aiFill.cancel")}),n.jsx(L,{onClick:()=>a.trim()&&t(a.trim()),disabled:!a.trim(),children:r("aiFill.continue")})]})]})})}async function Q8(e){const{data:t,error:s}=await I.from("content_items").select("*").eq("workspace_id",e).order("created_at",{ascending:!1});if(s)throw s;return t??[]}function nT(){const{profile:e}=st(),t=e==null?void 0:e.workspace_id,s=na(),r=["content_items",t],{data:a=[],isLoading:i}=Zr({queryKey:r,queryFn:()=>Q8(t),enabled:!!t}),o=h.useCallback(()=>{s.invalidateQueries({queryKey:r})},[s,r]);lc({table:"content_items",filter:t?`workspace_id=eq.${t}`:void 0,queryKey:r,enabled:!!t});const l=h.useCallback(async p=>{if(!t)return null;const{data:f,error:g}=await I.from("content_items").insert({...p,workspace_id:t}).select().single();return g?(console.error("Create content error:",g),null):(s.setQueryData(r,x=>[f,...x??[]]),f)},[t,s,r]),c=h.useCallback(async(p,f)=>{const{error:g}=await I.from("content_items").update({status:f}).eq("id",p);if(g){console.error("Update status error:",g);return}s.setQueryData(r,x=>(x??[]).map(b=>b.id===p?{...b,status:f}:b))},[s,r]),d=h.useCallback(async(p,f)=>{const{error:g}=await I.from("content_items").update(f).eq("id",p);if(g){console.error("Update fields error:",g);return}s.setQueryData(r,x=>(x??[]).map(b=>b.id===p?{...b,...f}:b))},[s,r]),u=h.useCallback(async p=>{const{error:f}=await I.from("content_items").delete().eq("id",p);if(f){console.error("Delete content error:",f);return}s.setQueryData(r,g=>(g??[]).filter(x=>x.id!==p))},[s,r]),m={ideas:a.filter(p=>p.status==="idea"),production:a.filter(p=>["draft","generating","failed"].includes(p.status)),review:a.filter(p=>["ready","review"].includes(p.status)),approved:a.filter(p=>["approved","scheduled"].includes(p.status)),published:a.filter(p=>p.status==="published")};return{items:a,grouped:m,loading:i,refresh:o,create:l,updateStatus:c,updateFields:d,remove:u}}
vendor: 4,486 bytes, line 864
864function Pe({label:e,children:t}){return n.jsxs("div",{className:"space-y-1.5",children:[n.jsx("label",{className:"text-xs font-medium text-muted-foreground",children:e}),t]})}var Ip="Switch",[J8,X1e]=Is(Ip),[Z8,X8]=J8(Ip),rT=h.forwardRef((e,t)=>{const{__scopeSwitch:s,name:r,checked:a,defaultChecked:i,required:o,disabled:l,value:c="on",onCheckedChange:d,form:u,...m}=e,[p,f]=h.useState(null),g=bt(t,w=>f(w)),x=h.useRef(!1),b=p?u||!!p.closest("form"):!0,[v,y]=tr({prop:a,defaultProp:i??!1,onChange:d,caller:Ip});return n.jsxs(Z8,{scope:s,checked:v,disabled:l,children:[n.jsx(qe.button,{type:"button",role:"switch","aria-checked":v,"aria-required":o,"data-state":lT(v),"data-disabled":l?"":void 0,disabled:l,value:c,...m,ref:g,onClick:Ee(e.onClick,w=>{y(j=>!j),b&&(x.current=w.isPropagationStopped(),x.current||w.stopPropagation())})}),b&&n.jsx(oT,{control:p,bubbles:!x.current,name:r,value:c,checked:v,required:o,disabled:l,form:u,style:{transform:"translateX(-100%)"}})]})});rT.displayName=Ip;var aT="SwitchThumb",iT=h.forwardRef((e,t)=>{const{__scopeSwitch:s,...r}=e,a=X8(aT,s);return n.jsx(qe.span,{"data-state":lT(a.checked),"data-disabled":a.disabled?"":void 0,...r,ref:t})});iT.displayName=aT;var eB="SwitchBubbleInput",oT=h.forwardRef(({__scopeSwitch:e,control:t,checked:s,bubbles:r=!0,...a},i)=>{const o=h.useRef(null),l=bt(o,i),c=Fy(s),d=dy(t);return h.useEffect(()=>{const u=o.current;if(!u)return;const m=window.HTMLInputElement.prototype,f=Object.getOwnPropertyDescriptor(m,"checked").set;if(c!==s&&f){const g=new Event("click",{bubbles:r});f.call(u,s),u.dispatchEvent(g)}},[c,s,r]),n.jsx("input",{type:"checkbox","aria-hidden":!0,defaultChecked:s,...a,tabIndex:-1,ref:l,style:{...a.style,...d,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});oT.displayName=eB;function lT(e){return e?"checked":"unchecked"}var cT=rT,tB=iT;const Ut=h.forwardRef(({className:e,...t},s)=>n.jsx(cT,{className:_e("peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors data-[state=checked]:bg-primary data-[state=unchecked]:bg-input focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50",e),...t,ref:s,children:n.jsx(tB,{className:_e("pointer-events-none block h-5 w-5 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0")})}));Ut.displayName=cT.displayName;var Op="Checkbox",[sB,eje]=Is(Op),[nB,Ky]=sB(Op);function rB(e){const{__scopeCheckbox:t,checked:s,children:r,defaultChecked:a,disabled:i,form:o,name:l,onCheckedChange:c,required:d,value:u="on",internal_do_not_use_render:m}=e,[p,f]=tr({prop:s,defaultProp:a??!1,onChange:c,caller:Op}),[g,x]=h.useState(null),[b,v]=h.useState(null),y=h.useRef(!1),w=g?!!o||!!g.closest("form"):!0,j={checked:p,disabled:i,setChecked:f,control:g,setControl:x,name:l,form:o,value:u,hasConsumerStoppedPropagationRef:y,required:d,defaultChecked:ei(a)?!1:a,isFormControl:w,bubbleInput:b,setBubbleInput:v};return n.jsx(nB,{scope:t,...j,children:aB(m)?m(j):r})}var dT="CheckboxTrigger",uT=h.forwardRef(({__scopeCheckbox:e,onKeyDown:t,onClick:s,...r},a)=>{const{control:i,value:o,disabled:l,checked:c,required:d,setControl:u,setChecked:m,hasConsumerStoppedPropagationRef:p,isFormControl:f,bubbleInput:g}=Ky(dT,e),x=bt(a,u),b=h.useRef(c);return h.useEffect(()=>{const v=i==null?void 0:i.form;if(v){const y=()=>m(b.current);return v.addEventListener("reset",y),()=>v.removeEventListener("reset",y)}},[i,m]),n.jsx(qe.button,{type:"button",role:"checkbox","aria-checked":ei(c)?"mixed":c,"aria-required":d,"data-state":gT(c),"data-disabled":l?"":void 0,disabled:l,value:o,...r,ref:x,onKeyDown:Ee(t,v=>{v.key==="Enter"&&v.preventDefault()}),onClick:Ee(s,v=>{m(y=>ei(y)?!0:!y),g&&f&&(p.current=v.isPropagationStopped(),p.current||v.stopPropagation())})})});uT.displayName=dT;var Qy=h.forwardRef((e,t)=>{const{__scopeCheckbox:s,name:r,checked:a,defaultChecked:i,required:o,disabled:l,value:c,onCheckedChange:d,form:u,...m}=e;return n.jsx(rB,{__scopeCheckbox:s,checked:a,defaultChecked:i,disabled:l,required:o,onCheckedChange:d,name:r,form:u,value:c,internal_do_not_use_render:({isFormControl:p})=>n.jsxs(n.Fragment,{children:[n.jsx(uT,{...m,ref:t,__scopeCheckbox:s}),p&&n.jsx(fT,{__scopeCheckbox:s})]})})});Qy.displayName=Op;var hT="CheckboxIndicator",mT=h.forwardRef((e,t)=>
864{const{__scopeCheckbox:s,forceMount:r,...a}=e,i=Ky(hT,s);return n.jsx(sn,{present:r||ei(i.checked)||i.checked===!0,children:n.jsx(qe.span,{"data-state":gT(i.checked),"data-disabled":i.disabled?"":void 0,...a,ref:t,style:{pointerEvents:"none",...e.style}})})});mT.displayName=hT;var pT="CheckboxBubbleInput",fT=h.forwardRef(({__scopeCheckbox:e,...t},s)=>{const{control:r,hasConsumerStoppedPropagationRef:a,checked:i,defaultChecked:o,required:l,disabled:c,name:d,value:u,form:m,bubbleInput:p,setBubbleInput:f}=Ky(pT,e),g=bt(s,f),x=Fy(i),b=dy(r);h.useEffect(()=>{const y=p;if(!y)return;const w=window.HTMLInputElement.prototype,_=Object.getOwnPropertyDescriptor(w,"checked").set,N=!a.current;if(x!==i&&_){const k=new Event("click",{bubbles:N});y.indeterminate=ei(i),_.call(y,ei(i)?!1:i),y.dispatchEvent(k)}},[p,x,i,a]);const v=h.useRef(ei(i)?!1:i);return n.jsx(qe.input,{type:"checkbox","aria-hidden":!0,defaultChecked:o??v.current,required:l,disabled:c,name:d,value:u,form:m,...t,tabIndex:-1,ref:g,style:{...t.style,...b,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})});fT.displayName=pT;function aB(e){return typeof e=="function"}function ei(e){return e==="indeterminate"}function gT(e){return ei(e)?"indeterminate":e?"checked":"unchecked"}const Wl=h.forwardRef(({className:e,...t},s)=>n.jsx(Qy,{ref:s,className:_e("peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",e),...t,children:n.jsx(mT,{className:_e("flex items-center justify-center text-current"),children:n.jsx(ms,{className:"h-4 w-4"})})}));Wl.displayName=Qy.displayName;function Jy({entityType:e,entityId:t,initialUrl:s,autoGenerate:r,aspect:a="16:9",compact:i,onGenerated:o}){const{t:l}=Oe("common"),[c,d]=h.useState(s??null),[u,m]=h.useState(!1),[p,f]=h.useState(!1),[g,x]=h.useState("");h.useEffect(()=>{d(s??null)},[s]);const b=async(y,w)=>{if(!u){m(!0);try{const{data:j,error:_}=await I.functions.invoke("generate-thumbnail",{body:{entity_type:e,entity_id:t,custom_prompt:y||null,force:!!w}});if(_)throw new Error(_.message);if(j!=null&&j.error)throw new Error(j.error);const N=j==null?void 0:j.thumbnail_url;N&&(d(N),o==null||o(N))}catch(j){Le.error((j==null?void 0:j.message)||l("thumbnail.generateFailed"))}finally{m(!1)}}},v=a==="9:16"?i?"w-12 h-[5.4rem]":"w-24 h-[10.8rem]":i?"w-20 h-11":"w-40 h-[5.625rem]";return n.jsxs("div",{className:"flex items-start gap-2",children:[n.jsxs("div",{className:`relative ${v} rounded-md overflow-hidden border border-border/50 bg-muted/30 flex items-center justify-center shrink-0`,children:[c?n.jsx("img",{src:c,alt:"thumbnail",className:"w-full h-full object-cover"}):n.jsx(g4,{size:i?14:22,className:"text-muted-foreground"}),u&&n.jsx("div",{className:"absolute inset-0 bg-background/70 flex items-center justify-center",children:n.jsx(xe,{size:i?12:18,className:"animate-spin text-primary"})})]}),n.jsxs("div",{className:"flex flex-col gap-1",children:[n.jsxs(L,{type:"button",size:"sm",variant:"outline",className:"h-6 px-2 text-[10px] gap-1",onClick:()=>b(void 0,!0),disabled:u,title:l("thumbnail.regenerate"),children:[n.jsx(tt,{size:10}),l(c?"thumbnail.generateAgain":"thumbnail.generate")]}),n.jsxs(L,{type:"button",size:"sm",variant:"ghost",className:"h-6 px-2 text-[10px] gap-1",onClick:()=>f(!0),disabled:u,title:l("thumbnail.customPrompt"),children:[n.jsx(xi,{size:10}),l("thumbnail.promptBtn")]})]}),n.jsx(ns,{open:p,onOpenChange:f,children:n.jsxs(Zt,{children:[n.jsxs(Xt,{children:[n.jsx(es,{children:l("thumbnail.dialogTitle")}),n.jsx(us,{children:l("thumbnail.dialogDesc")})]}),n.jsx(Fs,{rows:5,placeholder:l("thumbnail.promptPlaceholder"),value:g,onChange:y=>x(y.target.value)}),n.jsxs(Hl,{children:[n.jsx(L,{variant:"outline",onClick:()=>f(!1),disabled:u,children:l("thumbnail.cancel")}),n.jsxs(L,{onClick:async()=>{f(!1),await b(g,!0)},disabled:u||!g.trim(),children:[u?n.jsx(xe,{size:14,className:"animate-spin mr-1"}):n.jsx(tt,{size:14,className:"mr-1"}),l("thumbnail.generateBtn")]})]})]})})]})}function iB({chunk:e,n:t}){const s=cc(e.audio_url);return n.jsxs("div",{className:"rounded-lg border border-border/40 bg-surface-elevated/40 p-2 space-y-1.5",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:"inline-flex items-center justify-center min-w-[1.25rem] h-5 px-1.5 text-[10px] font-semibold rounded-md bg-primary/10 text-primary",children:t}
864),e.text&&n.jsx("p",{className:"text-[11px] text-foreground/70 line-clamp-2 leading-snug flex-1",children:e.text})]}),n.jsx("audio",{controls:!0,className:"w-full h-9",src:s??void 0})]})}function oB({audioChunks:e,fallbackAudioUrl:t,className:s}){var i;const r=Array.isArray(e)&&e.length>0?e:null;if(r&&r.length>1)return n.jsx("div",{className:`space-y-1.5 ${s??""}`,children:r.map((o,l)=>n.jsx(iB,{chunk:o,n:(o.index??l)+1},l))});const a=((i=r==null?void 0:r[0])==null?void 0:i.audio_url)||t;return n.jsx(lB,{audioUrl:a,className:s})}function lB({audioUrl:e,className:t}){const s=cc(e);return n.jsx("audio",{controls:!0,className:`w-full h-10 ${t??""}`,src:s??void 0})}const Zy="watermark:text",sv="watermark:changed";function U1(){try{return(localStorage.getItem(Zy)||"").slice(0,120)}catch{return""}}function cB(e){const t=(e||"").slice(0,120);try{localStorage.setItem(Zy,t)}catch{}try{window.dispatchEvent(new CustomEvent(sv,{detail:t}))}catch{}}function _u(){const[e,t]=h.useState(()=>U1());h.useEffect(()=>{const r=i=>{const o=i.detail??U1();t(l=>l===o?l:o)},a=i=>{i.key===Zy&&t((i.newValue||"").slice(0,120))};return window.addEventListener(sv,r),window.addEventListener("storage",a),()=>{window.removeEventListener(sv,r),window.removeEventListener("storage",a)}},[]);const s=h.useCallback(r=>{const a=(r||"").slice(0,120);t(a),cB(a)},[]);return[e,s]}function xT(e,t){if(!(t!=null&&t.ok))return!1;const s=String(t.id||"").toLowerCase();return!(e==="tiktok"&&s==="pending"&&!t.url)}function Yf(e,t){if(!t)return"idle";if(xT(e,t))return"published";const s=String(t.status||"").toLowerCase();return t.ok||s==="pending"||s==="queued"||s==="scheduled"||s==="processing"?"queued":t.error?"failed":"idle"}function dB(e,t){const s=e.metadata_json;if(e.status==="published")return"published";if(e.status==="failed")return"failed";const r=t.filter(u=>{const m=u.payload_json;return(m==null?void 0:m.content_item_id)===e.id}),a=r.some(u=>u.status==="failed"),i=u=>["queued","running"].includes(u.status),o=r.some(u=>u.job_type==="generate_short_script"&&i(u)),l=r.some(u=>(u.job_type==="render_video"||u.job_type==="video_test"||u.job_type==="render_short_video"||u.job_type==="generate_voice")&&i(u)),c=r.some(u=>u.job_type==="upload_video_to_youtube"&&i(u)),d=["generating","voicing","rendering","publishing"].includes(e.status);return a&&d&&!o&&!l&&!c?"failed":e.status==="generating"||o?"generating":e.status==="voicing"||e.status==="rendering"||l?"rendering":c?"publishing":s!=null&&s.video_url?"video":e.script_text?"script":a&&d?"failed":"generating"}function uB(e,t){const s=t.filter(r=>{const a=r.payload_json;return(a==null?void 0:a.content_item_id)===e.id&&r.status==="failed"});return s.length===0?null:s[s.length-1].error_text||null}function Kf({videoUrl:e,orientation:t}){const s=cc(e),[r,a]=h.useState(null),i=(r??(t==="landscape"?"landscape":"portrait"))==="portrait";return n.jsx("div",{className:i?"mx-auto w-full max-w-[280px]":"w-full max-w-[560px] mx-auto",children:n.jsx("div",{className:"relative w-full overflow-hidden rounded-lg bg-black",style:{aspectRatio:i?"9 / 16":"16 / 9"},children:n.jsx("video",{controls:!0,playsInline:!0,className:"absolute inset-0 w-full h-full object-contain",src:s??void 0,onLoadedMetadata:o=>{const l=o.currentTarget;l.videoWidth&&l.videoHeight&&a(l.videoHeight>=l.videoWidth?"portrait":"landscape")}})})})}function hB({item:e,personaName:t,activeJobs:s,onUpdateScript:r,onRegenerate:a,onVoice:i,onRenderVideo:o,onPublish:l,onPublishSocial:c,onDelete:d,onRetry:u,onCancelActiveJob:m,onClose:p,testWorkerAvailable:f,collapsed:g,onExpand:x}){const{t:b}=Oe("content-studio"),v=Tp(),y=dB(e,s),w=uB(e,s),j=e.metadata_json,_=(j==null?void 0:j.published_targets)||{},N=Object.entries(_).filter(([ee,W])=>xT(ee,W)),k=s.find(ee=>{const W=ee.payload_json;return(W==null?void 0:W.content_item_id)===e.id&&(ee.job_type==="render_video"||ee.job_type==="video_test")&&["queued","running"].includes(ee.status)}),S=(k==null?void 0:k.progress)??0,T=k,C=(T==null?void 0:T.stage_label)||(S===0?b("workflow.renderPreparing"):S<=40?b("workflow.renderGenerating"):S<=80?b("workflow.renderProcessing"):b("workflow.renderEnhancing")),B=(T==null?void 0:T.stage_index)!=null&&(T!=null&&T.stage_total)?`${T.stage_index}/${T.stage_total}`:null,E=s.find(ee=>{const W=ee.payload_json;return(W==null?void 0:W.content_item_id)===e.id&&ee.job_type==="generate_voice"&&["queued","running"].includes(ee.status)}),H=E;E==null||E.progress,H!=null&&H.stage_label||b("workflow.voicingProgress"),(H==null?void 0:H.stage_index)!=null&&(H!=null&&H.stage_total)&&`${H.stage_index}${H.stage_total}`;const z={generating:b("workflow.statusGenerating"),script:b("workflow.statusScript"),voicing:b("workflow.statusVoicing"),audio:b("workflow.statusAudio"),rendering:b("workflow.statusRendering"),video:b("workflow.statusVideo"),publishing:b("workflow.statusPublishing"),published:b("workflow.statusPublished"),failed:b("workflow.statusFailed")},ne=[b("workflow.stepScript"),b("workflow.stepVideo"),b("workflow.stepPublish")],[V,te]=h.useState(e.script_text||""),[R,F]=h.useState(""),[$,J]=h.useState(()=>(j==null?void 0:j.subtitles)!==!1),[Y,re]=h.useState(()=>{const ee=typeof(j==null?void 0:j.sample_steps)=="number"?j.sample_steps:10;return Math.max(4,Math.min(12,Math.round(ee)))}),[G,O]=_u();h.useEffect(()=>
864{const ee=typeof(j==null?void 0:j.watermark_text)=="string"?j.watermark_text.slice(0,120):"";!G&&ee&&O(ee)},[e.id]);const[Z,A]=h.useState(!0),[oe,ue]=h.useState(null),[je,ae]=h.useState(null),[ie,we]=h.useState("unlisted"),[Ae,nt]=h.useState(new Set),[Qe,P]=h.useState(!1),[U,Q]=h.useState(!1),{enabled:ve,hours:We,setEnabled:Ze,setHours:Je}=Hy(),xt={youtube:"YouTube",tiktok:"TikTok",instagram:"Instagram",facebook:"Facebook",twitter:"X",linkedin:"LinkedIn"},Pt=(v.linkedPlatforms||[]).map(ee=>ee==="twitter"?"twitter":ee);h.useEffect(()=>{const ee=new Set;for(const W of Pt){const ge=Yf(W,_[W]);ge!=="published"&&ge!=="queued"&&ee.add(W)}nt(ee)},[v.linkedPlatforms.join(","),e.id]),h.useEffect(()=>{if(!Qe)return;if(j!=null&&j.publish_started_at){Q(!0);return}if(U){P(!1),Q(!1);return}const ee=setTimeout(()=>P(!1),5*60*1e3);return()=>clearTimeout(ee)},[j==null?void 0:j.publish_started_at,Qe,U]),h.useEffect(()=>{e.script_text&&e.script_text!==V&&te(e.script_text)},[e.script_text]);const K=y==="failed"?-1:y==="generating"||y==="script"?0:y==="voicing"||y==="audio"||y==="rendering"||y==="video"?1:2,ye=oe!==null,De=Qe||!!(j!=null&&j.publish_started_at),pt=h.useCallback(async(ee,W)=>{if(!oe){ue(ee),ae(null);try{await W()}catch(ge){ae((ge==null?void 0:ge.message)||b("workflow.unknownError"))}finally{ue(null)}}},[oe,b]),kt=h.useCallback(async()=>{var Ne;const ee=(Ne=e.metadata_json)==null?void 0:Ne.video_url;if(!ee)return;const W=await Bd(ee);if(!W)throw new Error(b("workflow.saveLinkFailed"));const ge=(e.title||"video").replace(/[^\p{L}\p{N}_-]+/gu,"_").slice(0,60)||"video";await Gy(W,`${ge}.mp4`,{title:e.title||void 0,mimeFallback:"video/mp4"})},[e,b]),X=s.filter(ee=>{const W=ee.payload_json;return(W==null?void 0:W.content_item_id)===e.id&&["queued","running"].includes(ee.status)}),M=X.length>0,[se,he]=h.useState(()=>Date.now());h.useEffect(()=>{if(!M)return;const ee=setInterval(()=>he(Date.now()),15e3);return()=>clearInterval(ee)},[M]);const Ce=2*60*1e3,Ve=M&&X.every(ee=>{const W=ee.progress_at||ee.started_at||ee.created_at;return W?se-new Date(W).getTime()>Ce:!1}),me=y==="generating"||y==="voicing"||y==="rendering"||y==="publishing",Ge=({variant:ee="ghost"})=>n.jsxs(L,{variant:ee,size:"sm",onClick:()=>pt("cancel",()=>m(e)),disabled:oe==="cancel",className:"gap-1.5 text-xs",children:[oe==="cancel"?n.jsx(xe,{size:12,className:"animate-spin"}):n.jsx(gn,{size:12}),b(oe==="cancel"?"workflow.cancelling":"workflow.cancelJob")]}),Ye=()=>n.jsxs("div",{className:"rounded-xl bg-amber-50/60 dark:bg-amber-950/20 border border-amber-300/40 p-3 flex items-start gap-2",children:[n.jsx(ft,{size:14,className:"text-amber-600 shrink-0 mt-0.5"}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("p",{className:"text-xs font-semibold text-foreground",children:b("workflow.stuckTitle")}),n.jsx("p",{className:"text-[11px] text-muted-foreground mt-0.5",children:b("workflow.stuckDesc")})]}),n.jsx(Ge,{variant:"outline"})]});if(g){const ee={generating:"workflow.statusGenerating",script:"workflow.statusScript",voicing:"workflow.statusVoicing",audio:"workflow.statusAudio",rendering:"workflow.statusRendering",video:"workflow.statusVideo",publishing:"workflow.statusPublishing",published:"workflow.statusPublished",failed:"workflow.statusFailed"};return n.jsxs(de.button,{type:"button",initial:{opacity:0,y:8},animate:{opacity:1,y:0},exit:{opacity:0,y:-8},onClick:x,className:"w-full flex items-center justify-between gap-3 rounded-xl border border-border/40 bg-surface-elevated px-4 py-3 text-left hover:border-primary/40 hover:bg-muted/20 transition-colors",children:[n.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[M&&n.jsx(xe,{size:14,className:"text-primary animate-spin shrink-0"}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("p",{className:"text-sm font-semibold text-foreground truncate",children:e.title||b("workflow.noTitle")}),n.jsxs("div",{className:"flex items-center gap-2 mt-0.5 text-[11px] text-muted-foreground flex-wrap",children:[t&&n.jsxs("span",{children:["🎭 ",t]}),(j==null?void 0:j.format)&&n.jsxs("span",{children:["· ",j.format]}),(j==null?void 0:j.duration)&&n.jsxs("span",{children:["· ",j.duration,"s"]})]})]})]}),n.jsx(fe,{variant:"outline",className:"text-[10px] shrink-0",children:b(ee[y])})]})}return n.jsxs(de.div,{initial:{opacity:0,y:12}
864,animate:{opacity:1,y:0},exit:{opacity:0,y:-12},className:"rounded-2xl border border-primary/20 bg-surface-elevated shadow-premium-sm overflow-hidden",children:[n.jsxs("div",{className:"p-5 pb-3 flex items-start justify-between gap-3",children:[n.jsxs("div",{className:"flex items-start gap-3 flex-1 min-w-0",children:[n.jsx(Jy,{entityType:"content_item",entityId:e.id,initialUrl:(j==null?void 0:j.thumbnail_url)??null,autoGenerate:!!e.script_text,aspect:"16:9",compact:!0}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("h3",{className:"font-heading font-semibold text-base text-foreground leading-tight",children:e.title||b("workflow.noTitle")}),n.jsxs("div",{className:"flex items-center gap-2 mt-1.5 text-[11px] text-muted-foreground flex-wrap",children:[t&&n.jsxs("span",{children:["🎭 ",t]}),(j==null?void 0:j.format)&&n.jsx(fe,{variant:"secondary",className:"text-[9px]",children:j.format}),(j==null?void 0:j.duration)&&n.jsxs("span",{children:[j.duration,"s"]})]})]})]}),n.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[p&&n.jsxs(L,{variant:"ghost",size:"sm",className:"h-8 gap-1 text-xs text-muted-foreground",onClick:p,children:[n.jsx(Hi,{size:12})," ",b("workflow.backToLibrary","К библиотеке")]}),n.jsxs(bi,{children:[n.jsx(T2,{asChild:!0,children:n.jsx(L,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground hover:text-destructive",children:n.jsx(ci,{size:14})})}),n.jsxs(oa,{children:[n.jsxs(la,{children:[n.jsx(da,{children:b("workflow.deleteTitle")}),n.jsx(ua,{children:b("workflow.deleteDesc")})]}),n.jsxs(ca,{children:[n.jsx(ma,{children:b("workflow.cancel")}),n.jsx(ha,{onClick:()=>d(e.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:b("workflow.delete")})]})]})]})]})]}),n.jsx("div",{className:"px-5 pb-4",children:n.jsx("div",{className:"flex items-center",children:ne.map((ee,W)=>{const ge=W<K,Ne=W===K,rt=Ne&&(y==="generating"||y==="voicing"||y==="rendering"||y==="publishing");return n.jsxs("div",{className:"flex items-center flex-1 last:flex-initial",children:[n.jsxs("div",{className:"flex flex-col items-center",children:[n.jsxs("div",{className:`relative w-8 h-8 rounded-full flex items-center justify-center text-[11px] font-semibold transition-all duration-300 ${ge?"bg-primary text-primary-foreground shadow-sm":Ne?"bg-primary/15 text-primary border-2 border-primary":"bg-muted/30 text-muted-foreground/60 border border-border/50"}`,children:[ge?n.jsx(wt,{size:16}):W+1,rt&&n.jsx("span",{className:"absolute -top-0.5 -right-0.5 w-2.5 h-2.5 rounded-full bg-primary animate-pulse"})]}),n.jsx("span",{className:`text-[10px] mt-1.5 font-medium leading-tight text-center ${ge?"text-primary":Ne?"text-foreground":"text-muted-foreground/50"}`,children:ee})]}),W<ne.length-1&&n.jsx("div",{className:`h-[2px] flex-1 rounded-full mx-1 mb-5 transition-colors duration-300 ${ge?"bg-primary":Ne?"bg-primary/25":"bg-border/40"}`})]},ee)})})}),(y==="script"||y==="audio"||y==="video"||y==="published"||y==="failed")&&n.jsx("div",{className:"px-5 pb-3",children:n.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:z[y]})}),n.jsxs("div",{className:"px-5 pb-5 space-y-3",children:[me&&Ve&&n.jsx(Ye,{}),y==="generating"&&n.jsxs("div",{className:"space-y-2",children:[n.jsxs("div",{className:"rounded-xl bg-muted/20 p-6 flex flex-col items-center gap-2",children:[n.jsx(xe,{size:24,className:"animate-spin text-primary"}),n.jsx("p",{className:"text-xs text-muted-foreground",children:b("workflow.aiGenerating")})]}),n.jsx("div",{className:"flex justify-end",children:n.jsx(Ge,{})})]}),y==="script"&&n.jsxs("div",{className:"space-y-3",children:[n.jsx(Fs,{value:V,onChange:ee=>te(ee.target.value),className:"min-h-[120px] text-sm",placeholder:b("workflow.scriptPlaceholder")}),((j==null?void 0:j.audio_chunks)||(j==null?void 0:j.audio_url))&&n.jsx(oB,{audioChunks:j==null?void 0:j.audio_chunks,fallbackAudioUrl:j==null?void 0:j.audio_url,className:"w-full"}),n.jsxs("div",{className:"flex items-center justify-between rounded-xl border border-border/50 bg-muted/20 px-3 py-2.5",children:[n.jsxs("div",{className:"min-w-0 pr-3",children:[n.jsx("div",{className:"text-xs font-medium text-foreground",children:b("workflow.subtitlesLabel")}),n.jsx("div",{className:"text-[10px] text-muted-foreground truncate",children:b("workflow.subtitlesDesc")})]}),n.jsx(Ut,{checked:$,onCheckedChange:J})]}),n.jsxs("div",{className:"rounded-xl border border-border/50 bg-muted/20 px-3 py-2.5 space-y-2",children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{className:"min-w-0 pr-3",children:[n.jsx("div",{className:"text-xs font-medium text-foreground",children:b("workflow.sampleStepsLabel")}),n.jsx("div",{className:"text-[10px] text-muted-foreground truncate",children:b("workflow.sampleStepsDesc")})]}),n.jsx("div",{className:"text-xs font-semibold tabular-nums text-foreground w-6 text-right",children:Y})]}),n.jsx("input",{type:"range",min:4,max:12,step:1,value:Y,onChange:ee=>re(Math.max(4,Math.min(12,parseInt(ee.target.value,10)||10))),className:"w-full accent-primary"}),n.jsxs("div",{className:"flex justify-between text-[10px] text-muted-foreground tabular-nums",children:[n.jsx("span",{children:"4"}),n.jsx("span",{children:"8"}),n.jsx("span",{children:"12"})]})]}),n.jsxs("div",{className:"space-y-1.5",children:[n.jsx("label",{className:"text-[11px] font-medium text-muted-foreground",children:b("workflow.watermarkLabel")}),n.jsx(gt,{value:G,onChange:ee=>O(ee.target.value.slice(0,120)),maxLength:120,className:"h-9 text-xs",placeholder:b("workflow.watermarkPlaceholder")}),n.jsx("p",{className:"text-[10px] text-muted-foreground",children:b("workflow.watermarkDesc")})]}),n.jsxs("div",{className:"space-y-1.5",children:[n.jsx("label",{className:"text-[11px] font-medium text-muted-foreground",children:b("workflow.promptOverrideLabel")}),n.jsx(Fs,{value:R,onChange:ee=>F(ee.target.value),className:"min-h-[80px] text-xs",placeholder:b("workflow.promptOverridePlaceholder")})]}),f&&n.jsxs("div",{className:"flex items-center justify-between rounded-xl border border-border/50 bg-muted/20 px-3 py-2.5",children:[n.jsxs("div",{className:"min-w-0 pr-3",children:[n.jsx("div",{className:"text-xs font-medium text-foreground",children:"Test worker"}),n.jsx("div",{className:"text-[10px] text-muted-foreground truncate",children:Z?"video_test job → test server (also handles live)":"render_video job → production server"})]}),n.jsx(Ut,{checked:Z,onCheckedChange:A})]}),n.jsxs("div",{className:"flex gap-2",children:[n.jsxs(L,{variant:"hero",className:"flex-1 gap-2",onClick:()=>pt("render",async()=>{V!==e.script_text&&await r(e.id,V),await o({...e,script_text:V},R,$,Y,G,Z)}),disabled:ye||!V.trim(),children:[oe==="render"?n.jsx(xe,{size:14,className:"animate-spin"}):n.jsx(Ns,{size:14}),b("workflow.createVideo")]}),n.jsxs(L,{variant:"outline",className:"gap-1.5",onClick:()=>pt("regen",()=>a(e)),disabled:ye,children:[oe==="regen"?n.jsx(xe,{size:14,className:"animate-spin"}):n.jsx(tt,{size:12}),b("workflow.rewriteBtn")]})]})]}),y==="rendering"&&n.jsxs("div",{className:"space-y-3",children:[j!=null&&j.video_url?n.jsxs("div",{className:"rounded-xl bg-muted/20 overflow-hidden",children:[n.jsx(Kf,{videoUrl:j.video_url,orientation:j==null?void 0:j.orientation}),n.jsxs("div",{className:"px-3 py-2 flex items-center gap-2",children:[n.jsx(xe,{size:12,className:"animate-spin text-primary"}),n.jsx("p",{className:"text-[10px] text-muted-foreground",children:b("workflow.renderFinis
864hing")})]})]}):S>=100?n.jsxs("div",{className:"rounded-xl bg-primary/5 p-4 flex items-center gap-3",children:[n.jsx(xe,{size:18,className:"animate-spin text-primary"}),n.jsxs("div",{className:"flex-1",children:[n.jsxs("p",{className:"text-sm font-medium text-foreground",children:[b("workflow.renderUploading")," ",n.jsx("span",{className:"text-primary",children:"100%"})]}),n.jsx("p",{className:"text-[10px] text-muted-foreground mt-0.5",children:b("workflow.renderUploadingServer")})]})]}):n.jsxs("div",{className:"rounded-xl bg-primary/5 p-4 space-y-3",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx(xe,{size:18,className:"animate-spin text-primary"}),n.jsxs("div",{className:"flex-1",children:[n.jsxs("p",{className:"text-sm font-medium text-foreground",children:[C," ",S>0&&n.jsxs("span",{className:"text-primary",children:[S,"%"]}),B&&n.jsxs("span",{className:"text-muted-foreground ml-1",children:["· ",B]})]}),n.jsx("p",{className:"text-[10px] text-muted-foreground mt-0.5",children:b("workflow.renderSafe")})]})]}),S>0&&n.jsx("div",{className:"w-full h-1.5 bg-muted/30 rounded-full overflow-hidden",children:n.jsx("div",{className:"h-full bg-primary rounded-full transition-all duration-500",style:{width:`${S}%`}})})]}),n.jsx("div",{className:"flex justify-end",children:n.jsx(Ge,{})})]}),y==="video"&&n.jsxs("div",{className:"space-y-3",children:[n.jsx("div",{className:"rounded-xl bg-muted/20 overflow-hidden",children:n.jsx(Kf,{videoUrl:j==null?void 0:j.video_url,orientation:j==null?void 0:j.orientation})}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:"text-xs text-muted-foreground whitespace-nowrap",children:b("workflow.privacyLabel")}),n.jsx("div",{className:"flex gap-1",children:[{value:"unlisted",label:b("workflow.privacyUnlisted"),icon:m4},{value:"public",label:b("workflow.privacyPublic"),icon:Rd},{value:"private",label:b("workflow.privacyPrivate"),icon:lS}].map(ee=>n.jsxs("button",{onClick:()=>we(ee.value),className:`flex items-center gap-1 px-2.5 py-1 rounded-md text-xs border transition-colors ${ie===ee.value?"border-primary bg-primary/10 text-primary font-medium":"border-border text-muted-foreground hover:border-primary/40"}`,children:[n.jsx(ee.icon,{size:12}),ee.label]},ee.value))})]}),n.jsxs("div",{className:"flex gap-2",children:[n.jsxs(L,{variant:"hero",className:"flex-1 gap-2",onClick:()=>pt("publish",()=>l(e.id,ie)),disabled:ye,children:[oe==="publish"?n.jsx(xe,{size:14,className:"animate-spin"}):n.jsx(Za,{size:14}),b("workflow.publishBtn")]}),n.jsxs(L,{variant:"outline",className:"gap-1.5",onClick:()=>pt("save",kt),disabled:ye,children:[oe==="save"?n.jsx(xe,{size:14,className:"animate-spin"}):n.jsx(Ny,{size:14}),b("workflow.saveBtn","Сохранить")]}),n.jsxs(L,{variant:"outline",className:"gap-1.5",onClick:()=>pt("back",()=>u(e)),disabled:ye,children:[n.jsx(Hi,{size:12})," ",b("workflow.back")]})]}),c&&n.jsxs("div",{className:"rounded-xl border border-border/50 bg-muted/10 p-3 space-y-2",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(fm,{size:14,className:"text-primary"}),n.jsx("p",{className:"text-xs font-semibold text-foreground",children:b("workflow.socialPublishTitle","Опубликовать в соцсети")})]}),v.status!=="connected"||Pt.length===0?n.jsx("p",{className:"text-[11px] text-muted-foreground",children:b("workflow.socialNotLinked","Привяжите соцсети в разделе Интеграции → Социальный хаб.")}):n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"flex flex-wrap gap-1.5",children:Pt.map(ee=>{const W=Yf(ee,_[ee]),ge=Ae.has(ee),Ne=W==="published"||W==="queued";return n.jsxs("button",{type:"button",disabled:Ne,title:W==="queued"?b("workflow.socialQueued","В очереди публикации"):void 0,onClick:()=>{Ne||nt(rt=>{const Re=new Set(rt);return Re.has(ee)?Re.delete(ee):Re.add(ee),Re})},className:`flex items-center gap-1 px-2 py-1 rounded-md text-[11px] border transition-colors ${Ne?"border-border bg-muted/30 text-muted-foreground cursor-not-allowed":ge?"border-primary bg-primary/10 text-primary font-medium":"border-border text-muted-foreground hover:border-primary/40"}
864`,children:[W==="published"&&n.jsx(wt,{size:10,className:"text-emerald-600"}),W==="queued"&&n.jsx(ls,{size:10,className:"text-amber-600 animate-pulse"}),W==="failed"&&n.jsx(gn,{size:10,className:"text-destructive"}),xt[ee]||ee]},ee)})}),n.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[n.jsx(Wl,{id:`sched-a-${e.id}`,checked:ve,onCheckedChange:ee=>Ze(!!ee)}),n.jsx("label",{htmlFor:`sched-a-${e.id}`,className:"text-[11px] text-foreground cursor-pointer",children:b("workflow.scheduleLabel","Отложенная публикация")}),ve&&n.jsxs("div",{className:"flex items-center gap-1 ml-1",children:[n.jsx("span",{className:"text-[11px] text-muted-foreground",children:"+"}),n.jsx(gt,{type:"number",min:1,max:720,value:We,onChange:ee=>Je(Math.max(1,Math.min(720,parseInt(ee.target.value||"1",10)||1))),className:"h-7 w-16 text-[11px]"}),n.jsx("span",{className:"text-[11px] text-muted-foreground",children:b("workflow.scheduleHours","ч после последнего отложенного")})]})]}),n.jsxs(L,{variant:"outline",size:"sm",className:"w-full gap-1.5",disabled:ye||Ae.size===0||De,onClick:async()=>{if(!(!c||De)){P(!0),ae(null);try{await c(e.id,Array.from(Ae),ve?{scheduleHoursOffset:We}:void 0)}catch(ee){ae((ee==null?void 0:ee.message)||b("workflow.unknownError")),P(!1)}}},children:[De?n.jsx(xe,{size:12,className:"animate-spin"}):n.jsx(Za,{size:12}),De?b("workflow.publishingSocial","Публикуется…"):b("workflow.publishSocialBtn","Опубликовать в выбранные")]}),N.length>0&&n.jsx("div",{className:"flex flex-wrap gap-1 pt-1 border-t border-border/40",children:N.map(([ee,W])=>n.jsxs("a",{href:W.url||"#",target:"_blank",rel:"noreferrer",className:"text-[10px] text-primary hover:underline",children:[xt[ee]||ee," ↗"]},ee))})]})]})]}),y==="published"&&n.jsxs("div",{className:"space-y-3",children:[n.jsxs("div",{className:"rounded-xl bg-emerald-50/50 dark:bg-emerald-950/20 border border-emerald-200/50 p-4 flex items-center gap-3",children:[n.jsx(wt,{size:20,className:"text-emerald-600 shrink-0"}),n.jsxs("div",{children:[n.jsx("p",{className:"text-sm font-medium text-foreground",children:b("workflow.publishedLabel")}),e.published_url&&n.jsx("a",{href:e.published_url,target:"_blank",rel:"noreferrer",className:"text-xs text-primary hover:underline",children:b("workflow.openYouTube")})]})]}),(j==null?void 0:j.video_url)&&n.jsx("div",{className:"rounded-xl bg-muted/20 overflow-hidden",children:n.jsx(Kf,{videoUrl:j.video_url,orientation:j==null?void 0:j.orientation})}),c&&(j==null?void 0:j.video_url)&&n.jsxs("div",{className:"rounded-xl border border-border/50 bg-muted/10 p-3 space-y-2",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(fm,{size:14,className:"text-primary"}),n.jsx("p",{className:"text-xs font-semibold text-foreground",children:b("workflow.socialPublishTitle","Опубликовать в соцсети")})]}),v.status!=="connected"||Pt.length===0?n.jsx("p",{className:"text-[11px] text-muted-foreground",children:b("workflow.socialNotLinked","Привяжите соцсети в разделе Интеграции → Социальный хаб.")}):n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"flex flex-wrap gap-1.5",children:Pt.map(ee=>{const W=Yf(ee,_[ee]),ge=Ae.has(ee),Ne=W==="published"||W==="queued";return n.jsxs("button",{type:"button",disabled:Ne,title:W==="queued"?b("workflow.socialQueued","В очереди публикации"):void 0,onClick:()=>{Ne||nt(rt=>{const Re=new Set(rt);return Re.has(ee)?Re.delete(ee):Re.add(ee),Re})},className:`flex items-center gap-1 px-2 py-1 rounded-md text-[11px] border transition-colors ${Ne?"border-border bg-muted/30 text-muted-foreground cursor-not-allowed":ge?"border-primary bg-primary/10 text-primary font-medium":"border-border text-muted-foreground hover:border-primary/40"}`,children:[W==="published"&&n.jsx(wt,{size:10,className:"text-emerald-600"}),W==="queued"&&n.jsx(ls,{size:10,className:"text-amber-600 animate-pulse"}),W==="failed"&&n.jsx(gn,{size:10,className:"text-destructive"}),xt[ee]||ee]},ee)})}),n.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[n.jsx(Wl,{id:`sched-b-${e.id}`,checked:ve,onCheckedChange:ee=>Ze(!!ee)}),n.jsx("label",{htmlFor:`sched-b-${e.id}`,className:"text-[11px] text-foreground cursor-pointer",children:b("workflow.scheduleLabel","Отложенная публикация")}),ve&&n.jsxs("div",{className:"flex items-center gap-1 ml-1",children:[n.jsx("span",{className:"text-[11px] text-muted-foreground",children:"+"}),n.jsx(gt,{type:"number",min:1,max:720,value:We,onChange:ee=>Je(Math.max(1,Math.min(720,parseInt(ee.target.value||"1",10)||1))),className:"h-7 w-16 text-[11px]"}),n.jsx("span",{className:"text-[11px] text-muted-foreground",children:b("workflow.scheduleHours","ч после последнего отложенного")}
864)]})]}),n.jsxs(L,{variant:"outline",size:"sm",className:"w-full gap-1.5",disabled:ye||Ae.size===0||De,onClick:async()=>{if(!(!c||De)){P(!0),ae(null);try{await c(e.id,Array.from(Ae),ve?{scheduleHoursOffset:We}:void 0)}catch(ee){ae((ee==null?void 0:ee.message)||b("workflow.unknownError")),P(!1)}}},children:[De?n.jsx(xe,{size:12,className:"animate-spin"}):n.jsx(Za,{size:12}),De?b("workflow.publishingSocial","Публикуется…"):b("workflow.publishSocialBtn","Опубликовать в выбранные")]}),N.length>0&&n.jsx("div",{className:"flex flex-wrap gap-1 pt-1 border-t border-border/40",children:N.map(([ee,W])=>n.jsxs("a",{href:W.url||"#",target:"_blank",rel:"noreferrer",className:"text-[10px] text-primary hover:underline",children:[xt[ee]||ee," ↗"]},ee))})]})]})]}),je&&y!=="failed"&&n.jsxs("div",{className:"rounded-xl bg-destructive/5 border border-destructive/20 p-3 flex items-start gap-2",children:[n.jsx(ft,{size:14,className:"text-destructive shrink-0 mt-0.5"}),n.jsx("p",{className:"text-xs text-destructive",children:je})]}),y==="failed"&&n.jsxs("div",{className:"space-y-3",children:[n.jsxs("div",{className:"rounded-xl bg-destructive/5 border border-destructive/20 p-4",children:[n.jsxs("p",{className:"text-sm text-destructive font-medium flex items-center gap-1.5",children:[n.jsx(ft,{size:14})," ",b("workflow.errorOccurred")]}),w&&n.jsx("p",{className:"text-xs text-destructive/80 mt-1",children:w})]}),n.jsxs(L,{variant:"outline",className:"gap-1.5",onClick:()=>pt("retry",()=>u(e,{keepReadyAsset:!0})),disabled:ye,children:[n.jsx(Hi,{size:12})," ",b("workflow.retryBtn")]})]})]})]})}function Gr(e,t){const[s,r]=tu(),a=s.get(e)??t,i=h.useCallback(o=>{r(l=>{const c=new URLSearchParams(l);return!o||o===t?c.delete(e):c.set(e,o),c},{replace:!0})},[e,t,r]);return[a,i]}function Tm(e,t){const[s,r]=tu(),a=s.get(e),i=a!=null?Number.parseInt(a,10):NaN,o=Number.isFinite(i)&&i>0?i:t,l=h.useCallback(c=>{r(d=>{const u=new URLSearchParams(d);return!Number.isFinite(c)||c===t?u.delete(e):u.set(e,String(c)),u},{replace:!0})},[e,t,r]);return[o,l]}function mB({status:e}){const{t}=Oe("content-studio"),s={queued:{label:t("jobs.statusQueued"),icon:ls,className:"text-muted-foreground",badgeClass:"bg-muted/50 text-muted-foreground border-border/40"},running:{label:t("jobs.statusRunning"),icon:xe,className:"text-primary animate-spin",badgeClass:"bg-primary/10 text-primary border-primary/20"},completed:{label:t("jobs.statusCompleted"),icon:wt,className:"text-emerald-500",badgeClass:"bg-emerald-50 text-emerald-600 border-emerald-200"},failed:{label:t("jobs.statusFailed"),icon:gn,className:"text-red-500",badgeClass:"bg-red-50 text-red-600 border-red-200"},canceled:{label:t("jobs.statusCanceled"),icon:gn,className:"text-muted-foreground",badgeClass:"bg-muted/50 text-muted-foreground border-border/40"}},r=s[e]??s.queued,a=r.icon;return n.jsxs(fe,{variant:"outline",className:`${r.badgeClass} text-[10px] font-semibold gap-1`,children:[n.jsx(a,{size:10,className:r.className}),r.label]})}function pB({job:e,onDismiss:t}){const{t:s}=Oe("content-studio"),r={generate_short_script:s("jobs.typeGenerateScript"),generate_voice:s("jobs.typeGenerateVoice"),render_video:s("jobs.typeRenderVideo"),render_short_video:s("jobs.typeRenderShortLegacy"),upload_video_to_youtube:s("jobs.typeUploadYouTube"),create_youtube_live_objects:s("jobs.typeCreateLive"),prepare_live_assets:s("jobs.typePrepareAssets"),ingest_live_chat:s("jobs.typeIngestChat"),generate_chat_reply_suggestions:s("jobs.typeGenerateReplies"),extract_live_highlights:s("jobs.typeExtractHighlights"),repurpose_live_to_shorts:s("jobs.typeRepurposeLive"),generate_consultation_summary:s("jobs.typeConsultationSummary")},a={queued:{className:"text-muted-foreground"},running:{className:"text-primary animate-spin"},completed:{className:"text-emerald-500"},failed:{className:"text-red-500"},canceled:{className:"text-muted-foreground"}},i={queued:ls,running:xe,completed:wt,failed:gn,canceled:gn},o=a[e.status]??a.queued,l=i[e.status]??ls,c=r[e.job_type]??e.job_type;return n.jsxs("div",{className:"flex items-center gap-3 rounded-xl border border-border/40 bg-muted/10 px-4 py-3",children:[n.jsx("div",{className:`w-8 h-8 rounded-lg bg-muted/30 flex items-center justify-center ${o.className}`,children:n.jsx(l,{size:16})}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("p",{className:"text-xs font-semibold text-foreground truncate",children:c}),e.error_text&&e.status==="failed"&&n.jsx("p",{className:"text-[10px] text-red-500 truncate mt-0.5",children:e.error_text})]}),n.jsx(mB,{status:e.status}),t&&n.jsx(L,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0 text-muted-foreground",onClick:()=>t(e),title:s("allJobs.dismiss"),"aria-label":s("allJobs.dismiss"),children:n.jsx(Qn,{size:13})})]})}const Zo=10,fB=["generate_short_script","generate_voice","render_short_video","render_video","upload_video_to_youtube"];async function gB(e,t,s){const r=(s-1)*Zo,a=r+Zo-1,{data:i,error:o}=await I.from("content_items").select("id").eq("workspace_id",e).eq("content_type","short").is("source_live_session_id",null).is("metadata_json->>live_clip_id",null);if(o)throw o;const l=(i??[]).map(p=>p.id);if(l.length===0)return{rows:[],total:0};let c=I.from("jobs").select("*",{count:"exact"}).eq("workspace_id",e).in("job_type",fB).is("dismissed_at",null).in("payload_json->>content_item_id",l).order("created_at",{ascending:!1}).range(r,a);t!=="all"&&(c=c.eq("status",t));const{data:d,error:u,count:m}=await c;if(u)throw u;return{rows:d??[],total:m??0}}function xB(){const{t:e}=Oe("content-studio"),{profile:t}=st(),s=t==null?void 0:t.workspace_id,r=na(),[a,i]=Gr("jobs_status","all"),o=a,[l,c]=Tm("jobs_page",1),d=j=>i(j),u=h.useMemo(()=>["all-jobs",s,o,l],[s,o,l]),{data:m,isLoading:p,isFetching:f}=Zr({queryKey:u,queryFn:()=>gB(s,o,l),enabled:!!s}),g=h.useCallback(async j=>{var T;if(!s)return;const _=new Date().toISOString(),N={dismissed_at:_};["queued","running"].includes(j.status)&&(N.status="canceled",N.completed_at=_,N.error_text="Dismissed by user");const{error:k}=await I.from("jobs").update(N).eq("id",j.id);
864k&&console.error("Dismiss job error:",k);const S=(T=j.payload_json)==null?void 0:T.content_item_id;if(typeof S=="string"&&["queued","running","failed"].includes(j.status)){const{error:C}=await I.from("content_items").delete().eq("id",S).eq("workspace_id",s).neq("status","published");C&&console.error("Dismiss content item error:",C)}r.invalidateQueries({queryKey:["all-jobs",s]}),r.invalidateQueries({queryKey:["jobs",s]}),r.invalidateQueries({queryKey:["content_items",s]})},[r,s]);h.useEffect(()=>{l!==1&&c(1)},[l,c,o]),lc({table:"jobs",filter:s?`workspace_id=eq.${s}`:void 0,queryKey:["all-jobs",s],channelKey:`all-jobs-${s}`,enabled:!!s});const x=(m==null?void 0:m.rows)??[],b=(m==null?void 0:m.total)??0,v=Math.max(1,Math.ceil(b/Zo)),y=l>1,w=l<v;return n.jsxs("div",{className:"rounded-2xl bg-surface-elevated border border-border/50 shadow-premium-sm p-6 space-y-4",children:[n.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[n.jsxs("h2",{className:"font-heading font-semibold text-lg text-foreground flex items-center gap-2",children:[n.jsx(oS,{size:18,className:"text-primary"})," ",e("allJobs.title"),b>0&&n.jsx(fe,{variant:"outline",className:"text-[10px] ml-1",children:b})]}),n.jsx("div",{className:"flex items-center gap-2",children:n.jsxs(ut,{value:o,onValueChange:j=>d(j),children:[n.jsx(ct,{className:"bg-muted/30 h-9 w-[160px] text-xs",children:n.jsx(ht,{})}),n.jsxs(dt,{children:[n.jsx(ce,{value:"all",children:e("allJobs.filterAll")}),n.jsx(ce,{value:"running",children:e("jobs.statusRunning")}),n.jsx(ce,{value:"queued",children:e("jobs.statusQueued")}),n.jsx(ce,{value:"completed",children:e("jobs.statusCompleted")}),n.jsx(ce,{value:"failed",children:e("jobs.statusFailed")}),n.jsx(ce,{value:"canceled",children:e("jobs.statusCanceled")})]})]})})]}),p?n.jsx("div",{className:"flex items-center justify-center py-10",children:n.jsx(xe,{className:"w-5 h-5 animate-spin text-primary"})}):x.length===0?n.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:e("allJobs.empty")}):n.jsx("div",{className:"space-y-2",children:x.map(j=>n.jsx(pB,{job:j,onDismiss:g},j.id))}),b>Zo&&n.jsxs("div",{className:"flex items-center justify-between gap-2 pt-2",children:[n.jsx("p",{className:"text-[11px] text-muted-foreground",children:e("allJobs.pageInfo",{from:(l-1)*Zo+1,to:Math.min(l*Zo,b),total:b})}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsxs(L,{variant:"outline",size:"sm",disabled:!y||f,onClick:()=>c(Math.max(1,l-1)),className:"h-8 gap-1",children:[n.jsx(ou,{size:14})," ",e("allJobs.prev")]}),n.jsxs("span",{className:"text-[11px] text-muted-foreground tabular-nums",children:[l," / ",v]}),n.jsxs(L,{variant:"outline",size:"sm",disabled:!w||f,onClick:()=>c(l+1),className:"h-8 gap-1",children:[e("allJobs.next")," ",n.jsx(yn,{size:14})]})]})]})]})}const Pm="draft:";function vB(e,t,s){try{const r=localStorage.getItem(Pm+e);
864if(!r)return null;const a=JSON.parse(r);return a.v!==t?null:Date.now()-a.t>s?(localStorage.removeItem(Pm+e),null):a.data}catch{return null}}function dc(e,t,s={}){const{ttlDays:r=7,debounceMs:a=400,version:i=1}=s,o=r*24*60*60*1e3,[l,c]=h.useState(()=>{const p=vB(e,i,o);return p?{...t,...p}:t}),d=h.useRef(null),u=h.useRef(l);u.current=l,h.useEffect(()=>(d.current&&clearTimeout(d.current),d.current=setTimeout(()=>{try{const p={v:i,t:Date.now(),data:u.current};localStorage.setItem(Pm+e,JSON.stringify(p))}catch{}},a),()=>{d.current&&clearTimeout(d.current)}),[l,e,i,a]);const m=h.useCallback(()=>{try{localStorage.removeItem(Pm+e)}catch{}c(t)},[e]);return[l,c,m]}const yB=new Set(["generate_short_script","generate_voice","render_short_video","render_video","video_test","upload_video_to_youtube"]),bB=e=>{const t=e.metadata_json;return e.content_type==="short"&&!e.source_live_session_id&&!(t!=null&&t.live_clip_id)},wB=e=>{const t=e.payload_json;return yB.has(e.job_type)&&!!(t!=null&&t.content_item_id)&&!(t!=null&&t.live_session_id)&&!(t!=null&&t.live_clip_id)},jB=()=>{var kt;const{t:e}=Oe("content-studio"),{t}=Oe("common"),{profile:s,user:r}=st(),{status:a}=lo();fi();const{items:i,loading:o,create:l,updateStatus:c,updateFields:d,remove:u,refresh:m}=nT(),{jobs:p,dispatch:f,refresh:g}=ho(),{personas:x}=wi(),{fill:b,fillWithTopicCheck:v,isLoading:y,topicModal:w}=pa();e("repurpose.shorts"),e("repurpose.teasers"),e("repurpose.promo"),e("repurpose.archive");const[j,_,N]=dc("content-studio:shorts",{persona:"",topic:"",format:"hook",duration:"60",cta:"",lang:"ru",tone:""}),{persona:k,topic:S,format:T,duration:C,cta:B,lang:E,tone:H}=j,z=X=>_(M=>({...M,persona:X})),ne=X=>_(M=>({...M,topic:X})),V=X=>_(M=>({...M,format:X})),te=X=>_(M=>({...M,duration:X})),R=X=>_(M=>({...M,cta:X})),F=X=>_(M=>({...M,lang:X})),$=X=>_(M=>({...M,tone:X})),[J,Y]=h.useState(!1);h.useEffect(()=>{_(X=>X.cta?X:{...X,cta:e("generator.ctaDefault")})},[e]),h.useEffect(()=>{x.length&&(!k||!x.some(X=>X.id===k))&&_(X=>({...X,persona:x[0].id,lang:x[0].language||X.lang}))},[x]);const re=i.filter(bB),G=re.filter(X=>X.status!=="published"),O=re.filter(X=>X.status==="published"),[Z,A]=h.useState(null),oe=Z?O.find(X=>X.id===Z)??null:null,ue=oe?[oe,...G]:G,je=Z&&ue.some(X=>X.id===Z)?Z:((kt=G[0])==null?void 0:kt.id)??null,ae=ue.find(X=>X.id===je),ie=p.filter(wB),we=X=>{var se;const M=p.find(he=>{var Ve;const Ce=he.payload_json;return(Ce==null?void 0:Ce.content_item_id)===X&&(he.job_type==="generate_voice"||he.job_type==="render_short_video")&&he.status==="completed"&&((Ve=he.result_json)==null?void 0:Ve.audio_url)});return(se=M==null?void 0:M.result_json)==null?void 0:se.audio_url};h.useEffect(()=>{if(!ae)return;const X=ae.metadata_json;if(X!=null&&X.audio_url||!["rendering","publishing"].includes(ae.status))return;const M=we(ae.id);M&&d(ae.id,{metadata_json:{...X||{},audio_url:M}}).then(m)},[ae==null?void 0:ae.id,ae==null?void 0:ae.metadata_json,ae==null?void 0:ae.status,p]);const Ae=async()=>{if(!S.trim())return;const X=String(Math.min(Number(C)||60,90));Y(!0);const M=await l({persona_id:k||null,content_type:"short",title:S,topic:S,status:"generating",language:E,metadata_json:{format:T,duration:X,cta:B,tone:H}});M&&(await f({job_type:"generate_short_script",persona_id:k||null,payload_json:{content_item_id:M.id,persona_id:k||null,topic:S,format:T,duration:X,cta:B,tone:H,language:E}}),_(se=>({...se,topic:"",tone:""}))),Y(!1)},nt=async(X,M)=>{await d(X,{script_text:M})},Qe=async X=>{const M=X.metadata_json;await d(X.id,{status:"generating",script_text:null}),await f({job_type:"generate_short_script",persona_id:X.persona_id,payload_json:{content_item_id:X.id,persona_id:X.persona_id,topic:X.topic||X.title,format:(M==null?void 0:M.format)||"hook",duration:(M==null?void 0:M.duration)||"60",cta:(M==null?void 0:M.cta)||"",tone:(M==null?void 0:M.tone)||"",language:X.language||"ru"}}),m()},P=async X=>{if(await d(X.id,{status:"voicing"}),!await f({job_type:"generate_voice",persona_id:X.persona_id,payload_json:{content_item_id:X.id,persona_id:X.persona_id,script_text:X.script_text}}))throw new Error(t("errors.voiceFailed"))},U=new Set(["[email protected]","[email protected]","[email protected]"]),Q=((r==null?void 0:r.email)||"").toLowerCase(),ve=U.has(Q),We=async(X,M,se,he,Ce,Ve)=>{var Ht;const me=X.metadata_json;if(!((Ht=X.script_text)!=null&&Ht.trim()))throw new Error(t("errors.noScriptForVideo","Нет текста для озвучки"));const Ge=(me==null?void 0:me.audio_url)||we(X.id);Ge&&!(me!=null&&me.audio_url)&&await d(X.id,{metadata_json:{...me||{},audio_url:Ge}}),await d(X.id,{status:"rendering"});
864const Ye=M==null?void 0:M.trim(),W=ve?Ve??(ve&&Q!=="[email protected]"):!1,ge=se??(me==null?void 0:me.subtitles)!==!1,Ne=he??(typeof(me==null?void 0:me.sample_steps)=="number"?me.sample_steps:10),rt=Math.max(4,Math.min(12,Math.round(Ne))),lt=((Ce??(typeof(me==null?void 0:me.watermark_text)=="string"?me.watermark_text:""))||"").trim().slice(0,120);if(((me==null?void 0:me.subtitles)!==ge||(me==null?void 0:me.sample_steps)!==rt||((me==null?void 0:me.watermark_text)||"")!==lt)&&await d(X.id,{metadata_json:{...me||{},...Ge?{audio_url:Ge}:{},subtitles:ge,sample_steps:rt,watermark_text:lt}}),!await f({job_type:W?"video_test":"render_video",persona_id:X.persona_id||null,payload_json:{content_item_id:X.id,subtitles:ge,sample_steps:rt,...lt?{watermark_text:lt}:{},...Ye?{effective_prompt_override:Ye}:{}}}))throw new Error(t("errors.renderFailed"))},Ze=async(X,M)=>{const se=X.metadata_json;if(M!=null&&M.keepReadyAsset){const he=(se==null?void 0:se.audio_url)||we(X.id);if(he){const{video_url:Ce,...Ve}=se||{};await d(X.id,{metadata_json:{...Ve,audio_url:he},status:"draft"})}else await c(X.id,"draft");m();return}if(se!=null&&se.video_url){const{video_url:he,...Ce}=se;await d(X.id,{metadata_json:Ce,status:"draft"})}else if(se!=null&&se.audio_url){const{audio_url:he,...Ce}=se;await d(X.id,{metadata_json:Ce,status:"draft"})}else await c(X.id,"draft");m()},Je=async X=>{const M=ie.filter(Ve=>{const me=Ve.payload_json;return(me==null?void 0:me.content_item_id)===X});if(M.length===0)return;const se=new Date().toISOString(),he=M.filter(Ve=>["queued","running"].includes(Ve.status)).map(Ve=>Ve.id);if(he.length>0){const{error:Ve}=await I.from("jobs").update({status:"canceled",completed_at:se,dismissed_at:se,error_text:"Canceled by user"}).in("id",he);Ve&&console.error("[ContentStudio] cancel jobs error:",Ve)}const{error:Ce}=await I.from("jobs").update({dismissed_at:se}).in("id",M.map(Ve=>Ve.id));Ce&&console.error("[ContentStudio] dismiss jobs error:",Ce)},xt=async X=>{var he;await Je(X.id);const M=X.metadata_json||{};!!((he=X.script_text)!=null&&he.trim()||M.audio_url||M.video_url)?await c(X.id,"draft"):await u(X.id),g(),m()},Pt=async()=>{const X=String(Math.min(Number(C)||60,90)),M=S.trim()||e("generator.untitled","Без названия"),se=await l({persona_id:k||null,content_type:"short",title:M,topic:S.trim()||null,status:"draft",language:E,script_text:" ",metadata_json:{format:T,duration:X,cta:B,tone:H}});se&&(A(se.id),m())},K=async(X,M="unlisted")=>{if(a!=="connected")throw new Error(t("errors.youtubeNotConnected"));if(!await f({job_type:"upload_video_to_youtube",payload_json:{content_item_id:X,privacy_status:M}}))throw new Error(t("errors.publishFailed"))},ye=async(X,M,se)=>{const{data:he,error:Ce}=await I.functions.invoke("publish-content-item",{body:{content_item_id:X,targets:M,schedule_hours_offset:(se
864==null?void 0:se.scheduleHoursOffset)||0}});if(Ce)throw Ce;if(he!=null&&he.error)throw new Error(he.error);return setTimeout(()=>m(),1200),he},De=async X=>{await Je(X),await u(X),g(),Z===X&&A(null)},pt=X=>{var M;return(M=x.find(se=>se.id===X))==null?void 0:M.name};return o?n.jsx("div",{className:"flex items-center justify-center min-h-[400px]",children:n.jsx(xe,{className:"w-6 h-6 animate-spin text-primary"})}):n.jsxs("div",{className:"max-w-4xl mx-auto space-y-8",children:[n.jsx(de.div,{...Te(),children:n.jsxs("h1",{className:"font-heading font-bold text-2xl md:text-3xl text-foreground flex items-center gap-2",children:[n.jsx(Sy,{className:"text-primary",size:24}),e("pageTitle")]})}),ue.length>0&&n.jsx("div",{className:"space-y-2",children:n.jsx(xn,{initial:!1,children:ue.map(X=>n.jsx(hB,{item:X,personaName:pt(X.persona_id),activeJobs:ie,onUpdateScript:nt,onRegenerate:Qe,onVoice:P,onRenderVideo:We,testWorkerAvailable:ve,onPublish:K,onPublishSocial:ye,onDelete:De,onRetry:Ze,onCancelActiveJob:xt,collapsed:X.id!==je,onExpand:()=>A(X.id),onClose:X.id===je&&ue.length>1?()=>A(null):void 0},X.id))})}),n.jsxs(de.div,{...Te(.08),className:"rounded-2xl bg-surface-elevated border border-border/50 shadow-premium-sm overflow-hidden",children:[n.jsx("div",{className:"p-6 border-b border-border/40",children:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Ns,{size:18,className:"text-primary"}),n.jsx("h2",{className:"font-heading font-semibold text-lg text-foreground",children:e("generator.title")})]})}),n.jsxs("div",{className:"p-6 space-y-4",children:[n.jsxs("div",{className:"grid sm:grid-cols-2 lg:grid-cols-3 gap-4",children:[x.length>0&&n.jsx(Pe,{label:e("generator.persona"),children:n.jsxs(ut,{value:k,onValueChange:X=>{z(X);const M=x.find(se=>se.id===X);M!=null&&M.language&&F(M.language)},children:[n.jsx(ct,{className:"bg-muted/30",children:n.jsx(ht,{})}),n.jsx(dt,{children:x.map(X=>n.jsx(ce,{value:X.id,children:X.name},X.id))})]})}),n.jsx(Pe,{label:e("generator.topic"),children:n.jsx(Ot,{value:S,onChange:X=>ne(X.target.value),placeholder:e("generator.topicPlaceholder"),className:"bg-muted/30",aiLoading:y("topic"),onAiFill:async()=>{const X=await b({fieldName:"topic",fieldLabel:e("generator.topic"),currentValue:S,pageContext:{format:T,duration:C,cta:B,language:E,tone:H},personaId:k,language:E});X&&ne(X)}})}),n.jsx(Pe,{label:e("generator.format"),children:n.jsxs(ut,{value:T,onValueChange:V,children:[n.jsx(ct,{className:"bg-muted/30",children:n.jsx(ht,{})}),n.jsxs(dt,{children:[n.jsx(ce,{value:"hook",children:e("formats.hook")}),n.jsx(ce,{value:"educational",children:e("formats.educational")}),n.jsx(ce,{value:"story",children:e("formats.story")}),n.jsx(ce,{value:"list",children:e("formats.list")}),n.jsx(ce,{value:"commentary",children:e("formats.commentary")}),n.jsx(ce,{value:"myth",children:e("formats.myth")}),n.jsx(ce,{value:"qa",children:e("formats.qa")})]})]})}),n.jsx(Pe,{label:e("generator.duration"),children:n.jsxs(ut,{value:C,onValueChange:X=>{const M=Math.min(Number(X),90);te(String(M))},children:[n.jsx(ct,{className:"bg-muted/30",children:n.jsx(ht,{})}),n.jsxs(dt,{children:[n.jsx(ce,{value:"15",children:e("durations.15")}),n.jsx(ce,{value:"30",children:e("durations.30")}),n.jsx(ce,{value:"60",children:e("durations.60")}),n.jsx(ce,{value:"90",children:e("durations.90")})]})]})}),n.jsx(Pe,{label:e("generator.cta"),children:n.jsx(Ot,{value:B,onChange:X=>R(X.target.value),className:"bg-muted/30",aiLoading:y("cta"),onAiFill:async()=>{const X=await v({fieldName:"cta",fieldLabel:e("generator.cta"),currentValue:B,pageContext:{topic:S,format:T,language:E},personaId:k,language:E,topicValue:S,onTopicSet:ne});X&&R(X)}})})]}),n.jsx(Pe,{label:e("generator.tone"),children:n.jsx(Ot,{value:H,onChange:X=>$(X.target.value),placeholder:e("generator.tonePlaceholder"),className:"bg-muted/30",aiLoading:y("tone"),onAiFill:async()=>{const X=await v({fieldName:"tone",fieldLabel:e("generator.tone"),currentValue:H,pageContext:{topic:S,format:T,language:E},personaId:k,language:E,topicValue:S,onTopicSet:ne});X&&$(X)}})}),n.jsxs("div",{className:"flex flex-wrap gap-2",children:[n.jsxs(L,{variant:"hero",className:"gap-2",onClick:Ae,disabled:J,children:[J?n.jsx(xe,{size:15,className:"animate-spin"}):n.jsx(tt,{size:15}),e(J?"generator.generating":"generator.generate")]}),n.jsxs(L,{variant:"outline",className:"gap-2",onClick:Pt,disabled:J,title:e("generator.skipHint","Перейти сразу к вводу своего текста"),children:[n.jsx(Tr,{size:15}),e("generator.skip","Пропустить — у меня уже есть текст")]})]})]})]}),O.length>0&&n.jsxs(de.div,{...Te(.12),className:"rounded-2xl bg-surface-elevated border border-border/50 shadow-premium-sm p-6 space-y-3",children:[n.jsxs("h2",{className:"font-heading font-semibold text-lg text-foreground flex items-center gap-2",children:[n.jsx(Ns,{size:18,className:"text-primary"})," ",e("library.title","Библиотека"),n.jsx(fe,{variant:"outline",className:"text-[10px] ml-1",children:O.length})]}),n.jsx("div",{className:"space-y-2",children:O.map(X=>{const M=X.metadata_json||{},se=X.status==="published"?e("library.statusPublished","Опубликовано"):M.video_url?e("library.statusVideo","Видео готово"):M.audio_url?e("library.statusAudio","Аудио готово"):X.script_text?e("library.statusScript","Сценарий"):e("library.statusDraft","Черновик");return n.jsxs("button",{type:"button",onClick:()=>A(X.id),className:"w-full flex items-center justify-between gap-3 rounded-lg border border-border/40 bg-muted/10 px-4 py-2.5 text-left hover:border-primary/40 hover:bg-muted/20 transition-colors",children:[n.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[n.jsx(fe,{variant:"secondary",className:"text-[9px] shrink-0",children:"Shorts"}),n.jsx("p",{className:"text-xs font-semibold text-foreground truncate",children:X.title||e("published.noTitle")})]}),n.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[n.jsx(fe,{variant:"outline",className:"text-[9px]",children:se}),X.published_url&&n.jsx("a",{href:X.published_url,target:"_blank",rel:"noreferrer",onClick:he=>he.stopPropagation(),className:"text-[10px] text-primary hover:underline",children:e("published.open")})]})]},X.id)})})]}),n.jsx(de.div,{...Te(.16),children:n.jsx(xB,{})}),n.jsx(Lp,{open:w.open,onConfirm:w.onConfirm,onCancel:w.onCancel})]})};function _B({onCreate:e,saving:t}){const{t:s}=Oe("live-center");st();const{fill:r,fillWithTopicCheck:a,isLoading:i,topicModal:o}=pa(),{personas:l}=wi(),{status:c,account:d,startConnect:u}=nS(),[m,p,f]=dc("live:create",{title:"",description:"",liveMode:"free_live",chatReply:!0,chatReplyMode:"suggest_only",duration:"45",personaId:"",greeting:"",continueText:"",summaryText:"",language:"ru",streamSource:"youtube",rtmpUrl:"",rtmpKey:"",liveSubtitles:!0,webinarPlan:"",topicQuery:""}),{title:g,description:x,liveMode:b,chatReply:v,chatReplyMode:y,duration:w,personaId:j,greeting:_,continueText:N,summaryText:k,language:S,streamSource:T,rtmpUrl:C,rtmpKey:B,liveSubtitles:E,webinarPlan:H,topicQuery:z}=m,ne=P=>p(U=>({...U,title:P})),V=P=>p(U=>({...U,description:P})),te=P=>p(U=>({...U,liveMode:P})),R=P=>p(U=>({...U,chatReply:P})),F=P=>p(U=>({...U,chatReplyMode:P})),$=P=>p(U=>({...U,duration:P})),J=P=>p(U=>({...U,greeting:P})),Y=P=>p(U=>({...U,continueText:P})),re=P=>p(U=>({...U,summaryText:P})),G=P=>p(U=>({...U,streamSource:P})),O=P=>p(U=>({...U,rtmpUrl:P})),Z=P=>p(U=>({...U,rtmpKey:P})),A=P=>p(U=>({...U,liveSubtitles:P})),oe=P=>p(U=>({...U,webinarPlan:P})),ue=P=>p(U=>({...U,topicQuery:P})),[je,ae]=_u(),[ie,we]=h.useState(!1);h.useEffect(()=>{l.length&&!j&&p(P=>({...P,personaId:l[0].id,language:l[0].language||P.language}))},[l,j,p]);const Ae=h.useCallback(async()=>
864{if(!g.trim())return;const P=l.find(U=>U.id===j);we(!0);try{const{data:U,error:Q}=await I.functions.invoke("generate-auto-messages",{body:{persona_name:(P==null?void 0:P.name)||"Host",persona_id:j||null,language:S,title:g.trim(),description:"",session_type:b==="webinar"?"webinar":"stream"}});!Q&&(U!=null&&U.greeting)&&(J(U.greeting),Y(U.continue_talking),U.summary&&re(U.summary))}catch{}we(!1)},[g,j,l,b,S]),nt=P=>{const U=l.find(Q=>Q.id===P);p(Q=>({...Q,personaId:P,language:(U==null?void 0:U.language)||Q.language}))},Qe=async()=>{if(!g.trim()||T==="custom_rtmp"&&(!C.trim()||!B.trim())||T==="restream"&&c!=="connected")return;const P=T==="custom_rtmp",U=T==="restream";let Q=x.trim();if(!Q)try{const{data:Ze}=await I.functions.invoke("expand-live-description",{body:{title:g.trim(),language:S,persona_id:j||null}});Q=((Ze==null?void 0:Ze.description)||"").toString().trim()||g.trim()}catch{Q=g.trim()}const ve={...w!=="unlimited"?{planned_duration_min:parseInt(w)}:{},stream_source:T,live_subtitles:E,watermark_text:(je||"").trim().slice(0,120)};P&&(ve.stream_target={type:"rtmp",url:C.trim(),key:B.trim()},ve.chat_enabled=!1),b==="nonstop_trends"&&z.trim()&&(ve.topic_query=z.trim()),await e({title:g.trim(),description:Q,live_mode:b,chat_reply_mode:P?"off":v?y:"off",persona_id:j||null,status:"scheduled",platform:U?"restream":P?"custom_rtmp":"youtube",metadata_json:ve,greeting_text:_||null,continue_text:N||null,summary_text:k.trim(),...b==="webinar"&&H.trim()?{webinar_plan:H.trim()}:{}})&&p(Ze=>({...Ze,title:"",description:"",greeting:"",continueText:"",summaryText:"",rtmpKey:""}))};return n.jsxs(n.Fragment,{children:[n.jsxs(de.div,{...Te(.1),className:"rounded-2xl bg-surface-elevated border border-border/50 shadow-premium-sm p-6 space-y-4",children:[n.jsxs("h2",{className:"font-heading font-semibold text-lg text-foreground flex items-center gap-2",children:[n.jsx(St,{size:18,className:"text-accent"})," ",s("form.newStream")]}),n.jsxs("div",{className:"space-y-3.5",children:[n.jsx(Pe,{label:s("form.topicLabel"),children:n.jsx(Ot,{value:g,onChange:P=>ne(P.target.value),placeholder:s("form.topicPlaceholder"),className:"bg-muted/30",aiLoading:i("topic"),onAiFill:async()=>{var U;const P=await r({fieldName:"topic",fieldLabel:s("form.topicLabel"),currentValue:g,pageContext:{persona:((U=l.find(Q=>Q.id===j))==null?void 0:U.name)||"",format:b,language:S},personaId:j,language:S});P&&ne(P)}})}),n.jsx(Pe,{label:s("form.descriptionLabel"),children:n.jsx(os,{value:x,onChange:P=>V(P.target.value),placeholder:s("form.descriptionPlaceholder"),className:"bg-muted/30 min-h-[64px] text-sm",rows:2,aiLoading:i("description"),onAiFill:async()=>{const P=await a({fieldName:"description",fieldLabel:s("form.descriptionLabel"),currentValue:x,pageContext:{topic:g,format:b,language:S},personaId:j,language:S,topicValue:g,onTopicSet:ne});P&&V(P)}})}),l.length>0&&n.jsx(Pe,{label:s("form.personaLabel"),children:n.jsxs(ut,{value:j,onValueChange:nt,children:[n.jsx(ct,{className:"bg-muted/30",children:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Xs,{size:14,className:"text-muted-foreground"}),n.jsx(ht,{})]})}),n.jsx(dt,{children:l.map(P=>n.jsx(ce,{value:P.id,children:P.name},P.id))})]})}),n.jsx(Pe,{label:s("form.formatLabel"),children:n.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-2",children:[{id:"free_live",icon:St,title:"Free live",desc:"Болтает со зрителями"},{id:"nonstop_trends",icon:Ol,title:"Trends",desc:"Сама берёт горячие темы"},{id:"webinar",icon:dp,title:"Webinar",desc:"Идёт по твоему плану"}].map(({id:P,icon:U,title:Q,desc:ve})=>{const We=b===P;return n.jsxs("button",{type:"button",onClick:()=>te(P),className:`text-left rounded-xl border p-3 transition-all ${We?"border-primary bg-primary/5 shadow-premium-sm":"border-border/50 bg-muted/20 hover:border-border"}`,children:[n.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[n.jsx(U,{size:15,className:We?"text-primary":"text-muted-foreground"}),n.jsx("div",{className:"text-sm font-medium text-foreground",children:Q})]}),n.jsx("div",{className:"text-[11px] text-muted-foreground leading-snug",children:ve})]},P)})})}),b==="webinar"&&n.jsx(Pe,{label:"План вебинара (свободный текст, разобьётся на блоки автоматически)",children:n.jsx(os,{value:H,onChange:P=>oe(P.target.value),placeholder:`Например:
8651. Введение — кто я и о чём поговорим.
8662. Главный кейс — пошагово.
8673. Q&A.`,className:"bg-muted/30 min-h-[110px] text-sm",rows:5,aiLoading:i("webinar_plan"),onA
867iFill:async()=>{const P=await a({fieldName:"webinar_plan",fieldLabel:"Webinar plan",currentValue:H,pageContext:{topic:g,format:"webinar",language:S},personaId:j,language:S,topicValue:g,onTopicSet:ne});P&&oe(P)}})}),b==="nonstop_trends"&&n.jsx(Pe,{label:"Тематика трендов (опционально)",children:n.jsx(gt,{value:z,onChange:P=>ue(P.target.value),placeholder:"например: AI, fitness, crypto",className:"bg-muted/30"})}),n.jsx(Pe,{label:s("form.durationLabel"),children:n.jsxs(ut,{value:w,onValueChange:$,children:[n.jsx(ct,{className:"bg-muted/30",children:n.jsx(ht,{})}),n.jsxs(dt,{children:[n.jsx(ce,{value:"30",children:s("form.duration30")}),n.jsx(ce,{value:"45",children:s("form.duration45")}),n.jsx(ce,{value:"60",children:s("form.duration60")}),n.jsx(ce,{value:"90",children:s("form.duration90")}),n.jsx(ce,{value:"unlimited",children:s("form.durationUnlimited")})]})]})}),n.jsx(Pe,{label:s("form.streamSourceLabel"),children:n.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[n.jsxs("button",{type:"button",onClick:()=>G("youtube"),className:`flex items-center gap-2 rounded-xl border p-3 text-left transition-all ${T==="youtube"?"border-primary bg-primary/5 shadow-premium-sm":"border-border/50 bg-muted/20 hover:border-border"}`,children:[n.jsx(Ls,{size:16,className:T==="youtube"?"text-primary":"text-muted-foreground"}),n.jsxs("div",{className:"min-w-0",children:[n.jsx("div",{className:"text-sm font-medium text-foreground",children:s("form.sourceYoutube")}),n.jsx("div",{className:"text-[10px] text-muted-foreground truncate",children:s("form.sourceYoutubeDesc")})]})]}),n.jsxs("button",{type:"button",onClick:()=>G("restream"),className:`flex items-center gap-2 rounded-xl border p-3 text-left transition-all ${T==="restream"?"border-primary bg-primary/5 shadow-premium-sm":"border-border/50 bg-muted/20 hover:border-border"}`,children:[n.jsx(fm,{size:16,className:T==="restream"?"text-primary":"text-muted-foreground"}),n.jsxs("div",{className:"min-w-0",children:[n.jsx("div",{className:"text-sm font-medium text-foreground",children:"Restream"}),n.jsx("div",{className:"text-[10px] text-muted-foreground truncate",children:"Все площадки сразу"})]})]}),n.jsxs("button",{type:"button",onClick:()=>G("custom_rtmp"),className:`flex items-center gap-2 rounded-xl border p-3 text-left transition-all ${T==="custom_rtmp"?"border-primary bg-primary/5 shadow-premium-sm":"border-border/50 bg-muted/20 hover:border-border"}`,children:[n.jsx(St,{size:16,className:T==="custom_rtmp"?"text-primary":"text-muted-foreground"}),n.jsxs("div",{className:"min-w-0",children:[n.jsx("div",{className:"text-sm font-medium text-foreground",children:s("form.sourceRtmp")}),n.jsx("div",{className:"text-[10px] text-muted-foreground truncate",children:s("form.sourceRtmpDesc")})]})]})]})}),T==="restream"&&n.jsx("div",{className:"rounded-xl border border-border/40 bg-muted/10 p-4 space-y-2",children:c==="connected"?n.jsxs("div",{className:"flex items-center gap-2 text-sm text-foreground",children:[n.jsx(wt,{size:15,className:"text-emerald-500"}),n.jsxs("span",{children:["Restream подключён",d!=null&&d.username?`: ${d.username}`:"",". Стрим уйдёт на все привязанные площадки."]})]}):n.jsxs("div",{className:"space-y-2",children:[n.jsx("p",{className:"text-xs text-muted-foreground",children:"Подключите Restream, чтобы транслировать сразу на YouTube, Twitch, Facebook и др."}),n.jsxs("div",{className:"flex gap-2",children:[n.jsx(L,{type:"button",size:"sm",variant:"outline",onClick:u,children:"Подключить Restream"}),n.jsx(L,{type:"button",size:"sm",variant:"ghost",asChild:!0,children:n.jsx(zt,{to:"/app/integrations",children:"Настройки"})})]})]})}),T==="custom_rtmp"&&n.jsxs("div",{className:"rounded-xl border border-border/40 bg-muted/10 p-4 space-y-3",children:[n.jsx(Pe,{label:s("form.rtmpUrlLabel"),children:n.jsxs("div",{className:"relative",children:[n.jsx(Pr,{size:14,className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"}),n.jsx(gt,{value:C,onChange:P=>O(P.target.value),placeholder:"rtmp://a.rtmp.youtube.com/live2",className:"bg-muted/30 pl-9 font-mono text-xs"})]})}),n.jsx(Pe,{label:s("form.rtmpKeyLabel"),children:n.jsxs("div",{className:"relative",children:[n.jsx(Py,{size:14,className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"}),n.jsx(gt,{value:B,onChange:P=>Z(P.target.value),type:"password",placeholder:s("form.rtmpKeyPlaceholder"),className:"bg-muted/30 pl-9 font-mono text-xs"})]})}),n.jsx("p",{className:"text-[11px] text-muted-foreground leading-relaxed",children:s("form.rtmpHint")})]}),(T==="youtube"||T==="restream")&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[n.jsx(Pe,{label:s("form.qaMode"),children:n.jsxs(ut,{value:y,onValueChange:F,children:[n.jsx(ct,{className:"bg-muted/30",children:n.jsx(ht,{})}),n.jsxs(dt,{children:[n.jsx(ce,{value:"suggest_only",children:s("form.qaSuggest")}),n.jsx(ce,{value:"hybrid",children:s("form.qaHybrid")}),n.jsx(ce,{value:"auto_reply",children:s("form.qaAuto")})]})]})}),n.jsx("div",{})]}),n.jsxs("div",{className:"flex items-center justify-between rounded-xl border border-border/50 bg-muted/20 px-4 py-3",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("div",{className:"w-8 h-8 rounded-lg bg-accent/10 flex items-center justify-center text-accent",children:n.jsx(lu,{size:16})}),n.jsx("span",{className:"text-sm font-medium text-foreground",children:s("form.chatReply")})]}),n.jsx(Ut,{checked:v,onCheckedChange:R})]})]}),n.jsxs("div",{className:"flex items-center justify-between rounded-xl border border-border/50 bg-muted/20 px-4 py-3",children:[n.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[n.jsx("div",{className:"w-8 h-8 rounded-lg bg-primary/10 flex items-center justify-center text-primary shrink-0",children:n.jsx(tt,{size:16})}),n.jsxs("div",{className:"min-w-0",children:[n.jsx("div",{className:"text-sm font-medium text-foreground",children:s("form.liveSubtitles")}),n.jsx("div",{className:"text-[11px] text-muted-foreground truncate",children:s("form.liveSubtitlesDesc")})]})]}),n.jsx(Ut,{checked:E,onCheckedChange:A})]}),n.jsxs("div",{className:"rounded-xl border border-border/50 bg-muted/20 px-4 py-3 space-y-2",children:[n.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[n.jsx("div",{className:"w-8 h-8 rounded-lg bg-primary/10 flex items-center justify-center text-primary shrink-0",children:n.jsx(tt,{size:16})}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("div",{className:"text-sm font-medium text-foreground",children:s("form.watermark")}),n.jsx("div",{className:"text-[11px] text-muted-foreground truncate",children:s("form.watermarkDesc")})]})]}),n.jsx(gt,{value:je,onChange:P=>ae(P.target.value),maxLength:120,placeholder:s("form.watermarkPlaceholder"),className:"h-9 text-sm bg-background"})]}),n.jsxs("div",{className:"rounded-xl border border-border/50 bg-muted/10 p-4 space-y-3",children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsx("span",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wider",children:s("autoMessages.sectionTitle")}),n.jsxs(L,{type:"button",variant:"ghost",size:"sm",className:"gap-1.5 text-xs h-7",onClick:Ae,disabled:ie||!g.trim(),children:[n.jsx(xi,{size:13,className:ie?"animate-spin":""}),s(ie?"autoMessages.generating":"autoMessages.generate")]})]}),n.jsx(Pe,{label:s("autoMessages.greetingLabel"),children:n.jsx(os,{value:_,onCh
867ange:P=>J(P.target.value),placeholder:s("autoMessages.greetingPlaceholder"),className:"bg-muted/30 min-h-[60px] text-sm",rows:2,aiLoading:i("greeting"),onAiFill:async()=>{const P=await a({fieldName:"greeting",fieldLabel:s("autoMessages.greetingLabel"),currentValue:_,pageContext:{topic:g,format:b,language:S},personaId:j,language:S,topicValue:g,onTopicSet:ne});P&&J(P)}})}),n.jsx(Pe,{label:s("autoMessages.continueLabel"),children:n.jsx(os,{value:N,onChange:P=>Y(P.target.value),placeholder:s("autoMessages.continuePlaceholder"),className:"bg-muted/30 min-h-[60px] text-sm",rows:2,aiLoading:i("continue"),onAiFill:async()=>{const P=await a({fieldName:"continue_text",fieldLabel:s("autoMessages.continueLabel"),currentValue:N,pageContext:{topic:g,greeting:_,format:b,language:S},personaId:j,language:S,topicValue:g,onTopicSet:ne});P&&Y(P)}})}),n.jsx(Pe,{label:s("autoMessages.summaryLabel"),children:n.jsx(os,{value:k,onChange:P=>re(P.target.value),placeholder:s("autoMessages.summaryPlaceholder"),className:"bg-muted/30 min-h-[60px] text-sm",rows:2,aiLoading:i("summary_text"),onAiFill:async()=>{const P=await a({fieldName:"summary_text",fieldLabel:s("autoMessages.summaryLabel"),currentValue:k,pageContext:{topic:g,greeting:_,continueText:N,format:b,language:S},personaId:j,language:S,topicValue:g,onTopicSet:ne});P&&re(P)}})})]}),n.jsxs(L,{variant:"hero",className:"w-full gap-2 mt-1",onClick:Qe,disabled:t||!j||!k.trim()||T==="custom_rtmp"&&(!C.trim()||!B.trim())||T==="restream"&&c!=="connected",children:[n.jsx(tt,{size:15})," ",s("form.scheduleStream")]})]})]}),n.jsx(Lp,{open:o.open,onConfirm:o.onConfirm,onCancel:o.onCancel})]})}function kB(){const{t:e}=Oe("live-center"),t=[{icon:pm,label:e("postLive.makeClips"),desc:e("postLive.clipsDesc")},{icon:ii,label:e("postLive.archiveVersion"),desc:e("postLive.archiveDesc")},{icon:gS,label:e("postLive.bestQuestions"),desc:e("postLive.bestQuestionsDesc")},{icon:Ns,label:e("postLive.teaser"),desc:e("postLive.teaserDesc")}];return n.jsxs(de.div,{...Te(.2),className:"rounded-2xl bg-surface-elevated border border-border/50 shadow-premium-sm p-6 space-y-4",children:[n.jsxs("h2",{className:"font-heading font-semibold text-lg text-foreground flex items-center gap-2",children:[n.jsx(tt,{size:18,className:"text-primary"})," ",e("postLive.title")]}),n.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-4 gap-3",children:t.map(s=>n.jsxs("button",{className:"group rounded-xl border border-border/50 bg-muted/20 p-4 text-left hover:shadow-premium-sm hover:border-primary/20 transition-all",children:[n.jsx("div",{className:"w-10 h-10 rounded-xl bg-primary/10 flex items-center justify-center text-primary mb-3 group-hover:bg-primary/15 transition-colors",children:n.jsx(s.icon,{size:20})}),n.jsx("p",{className:"font-heading font-semibold text-sm text-foreground",children:s.label}),n.jsx("p",{className:"text-[11px] text-muted-foreground mt-0.5",children:s.desc})]},s.label))})]})}var Dp="Popover",[vT,tje]=Is(Dp,[gi]),ku=gi(),[NB,ji]=vT(Dp),yT=e=>{const{__scopePopover:t,children:s,open:r,defaultOpen:a,onOpenChange:i,modal:o=!1}=e,l=ku(t),c=h.useRef(null),[d,u]=h.useState(!1),[m,p]=tr({prop:r,defaultProp:a??!1,onChange:i,caller:Dp});return n.jsx(tp,{...l,children:n.jsx(NB,{scope:t,contentId:pn(),triggerRef:c,open:m,onOpenChange:p,onOpenToggle:h.useCallback(()=>p(f=>!f),[p]),hasCustomAnchor:d,onCustomAnchorAdd:h.useCallback(()=>u(!0),[]),onCustomAnchorRemove:h.useCallback(()=>u(!1),[]),modal:o,children:s})})};yT.displayName=Dp;var bT="PopoverAnchor",SB=h.forwardRef((e,t)=>{const{__scopePopover:s,...r}=e,a=ji(bT,s),i=ku(s),{onCustomAnchorAdd:o,onCustomAnchorRemove:l}=a;return h.useEffect(()=>(o(),()=>l()),[o,l]),n.jsx(nu,{...i,...r,ref:t})});SB.displayName=bT;var wT="PopoverTrigger",jT=h.forwardRef((e,t)=>{const{__scopePopover:s,...r}=e,a=ji(wT,s),i=ku(s),o=bt(t,a.triggerRef),l=n.jsx(qe.button,{type:"button","aria-haspopup":"dialog","aria-expanded":a.open,"aria-controls":a.contentId,"data-state":CT(a.open),...r,ref:o,onClick:Ee(e.onClick,a.onOpenToggle)});return a.hasCustomAnchor?l:n.jsx(nu,{asChild:!0,...i,children:l})});jT.displayName=wT;var Xy="PopoverPortal",[CB,TB]=vT(Xy,{forceMount:void 0}),_T=e=>{const{__scopePopover:t,forceMount:s,children:r,container:a}=e,i=ji(Xy,t);return n.jsx(CB,{scope:t,forceMount:s,children:n.jsx(sn,{present:s||i.open,children:n.jsx(ru,{asChild:!0,container:a,children:r})})})};_T.displayName=Xy;var Gl="PopoverContent",kT=h.forwardRef((e,t)=>
867{const s=TB(Gl,e.__scopePopover),{forceMount:r=s.forceMount,...a}=e,i=ji(Gl,e.__scopePopover);return n.jsx(sn,{present:r||i.open,children:i.modal?n.jsx(EB,{...a,ref:t}):n.jsx(AB,{...a,ref:t})})});kT.displayName=Gl;var PB=ni("PopoverContent.RemoveScroll"),EB=h.forwardRef((e,t)=>{const s=ji(Gl,e.__scopePopover),r=h.useRef(null),a=bt(t,r),i=h.useRef(!1);return h.useEffect(()=>{const o=r.current;if(o)return gp(o)},[]),n.jsx(pu,{as:PB,allowPinchZoom:!0,children:n.jsx(NT,{...e,ref:a,trapFocus:s.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Ee(e.onCloseAutoFocus,o=>{var l;o.preventDefault(),i.current||(l=s.triggerRef.current)==null||l.focus()}),onPointerDownOutside:Ee(e.onPointerDownOutside,o=>{const l=o.detail.originalEvent,c=l.button===0&&l.ctrlKey===!0,d=l.button===2||c;i.current=d},{checkForDefaultPrevented:!1}),onFocusOutside:Ee(e.onFocusOutside,o=>o.preventDefault(),{checkForDefaultPrevented:!1})})})}),AB=h.forwardRef((e,t)=>{const s=ji(Gl,e.__scopePopover),r=h.useRef(!1),a=h.useRef(!1);return n.jsx(NT,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var o,l;(o=e.onCloseAutoFocus)==null||o.call(e,i),i.defaultPrevented||(r.current||(l=s.triggerRef.current)==null||l.focus(),i.preventDefault()),r.current=!1,a.current=!1},onInteractOutside:i=>{var c,d;(c=e.onInteractOutside)==null||c.call(e,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(a.current=!0));const o=i.target;((d=s.triggerRef.current)==null?void 0:d.contains(o))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&a.current&&i.preventDefault()}})}),NT=h.forwardRef((e,t)=>{const{__scopePopover:s,trapFocus:r,onOpenAutoFocus:a,onCloseAutoFocus:i,disableOutsidePointerEvents:o,onEscapeKeyDown:l,onPointerDownOutside:c,onFocusOutside:d,onInteractOutside:u,...m}=e,p=ji(Gl,s),f=ku(s);return pp(),n.jsx(mu,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:a,onUnmountAutoFocus:i,children:n.jsx(tc,{asChild:!0,disableOutsidePointerEvents:o,onInteractOutside:u,onEscapeKeyDown:l,onPointerDownOutside:c,onFocusOutside:d,onDismiss:()=>p.onOpenChange(!1),children:n.jsx(sp,{"data-state":CT(p.open),role:"dialog",id:p.contentId,...f,...m,ref:t,style:{...m.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})}),ST="PopoverClose",RB=h.forwardRef((e,t)=>{const{__scopePopover:s,...r}=e,a=ji(ST,s);return n.jsx(qe.button,{type:"button",...r,ref:t,onClick:Ee(e.onClick,()=>a.onOpenChange(!1))})});RB.displayName=ST;var $B="PopoverArrow",LB=h.forwardRef((e,t)=>{const{__scopePopover:s,...r}=e,a=ku(s);return n.jsx(np,{...a,...r,ref:t})});LB.displayName=$B;function CT(e){return e?"open":"closed"}var IB=yT,OB=jT,DB=_T,TT=kT;const MB=IB,zB=OB,PT=h.forwardRef(({className:e,align:t="center",sideOffset:s=4,...r},a)=>n.jsx(DB,{children:n.jsx(TT,{ref:a,align:t,sideOffset:s,className:_e("z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...r})}));PT.displayName=TT.displayName;function eb(){const{session:e,profile:t}=st(),s=t==null?void 0:t.workspace_id,[r,a]=h.useState("not_connected"),[i,o]=h.useState(null),[l,c]=h.useState([]),[d,u]=h.useState([]),[m,p]=h.useState(!0),[f,g]=h.useState(null),x=h.useCallback(async()=>{if(!s){p(!1);return}try{const{data:w}=await I.from("meta_ads_accounts").select("*").eq("workspace_id",s).maybeSingle();if(!w)a("not_connected"),o(null),c([]),u([]);else{o({fbUserId:w.fb_user_id,adAccountId:w.ad_account_id,adAccountName:w.ad_account_name,pageId:w.page_id,pageName:w.page_name,instagramAccountId:w.instagram_account_id,instagramUsername:w.instagram_username,tokenExpiresAt:w.token_expires_at}),c(w.available_ad_accounts||[]),u(w.available_pages||[]);const j=w.token_expires_at&&new Date(w.token_expires_at).getTime()-Date.now()<24*3600*1e3;a(j?"expired":w.status)}}catch(w){console.error("Meta Ads fetch failed",w)}finally{p(!1)}},[s]);h.useEffect(()=>{x()},[x]),h.useEffect(()=>{const w=new URL(window.location.href),j=w.searchParams.get("meta");if(!j)return;const _=w.searchParams.get("msg");w.searchParams.delete("meta"),w.searchParams.delete("msg"),window.history.replaceState({},"",w.pathname+(w.search?`?${w.searchParams}`:"")),j==="connected"?(a("connected"),g(null),x()):(a("error"),g(_||"Connection failed"))},[x]);const b=h.useCallback(async()=>
867{if(!(e!=null&&e.access_token))return;a("connecting"),g(null);const{data:w,error:j}=await I.functions.invoke("meta-auth-url",{headers:{Authorization:`Bearer ${e.access_token}`}});if(j||w!=null&&w.error){a("error"),g((w==null?void 0:w.error)||(j==null?void 0:j.message)||"Failed to get auth URL");return}w!=null&&w.url&&(window.location.href=w.url)},[e==null?void 0:e.access_token]),v=h.useCallback(async()=>{s&&(await I.from("meta_ads_accounts").delete().eq("workspace_id",s),a("not_connected"),o(null),c([]),u([]))},[s]),y=h.useCallback(async w=>{if(!s||!(e!=null&&e.access_token))throw new Error("Not ready");const{data:j,error:_}=await I.functions.invoke("meta-update-selection",{body:{workspaceId:s,...w},headers:{Authorization:`Bearer ${e.access_token}`}});if(_||j!=null&&j.error){const N=(j==null?void 0:j.error)||(_==null?void 0:_.message)||"Failed";throw new Error(N)}await x()},[s,e==null?void 0:e.access_token,x]);return{status:r,account:i,loading:m,error:f,availableAdAccounts:l,availablePages:d,startConnect:b,disconnect:v,refresh:x,updateSelection:y}}function ET(){const{session:e,profile:t}=st(),s=t==null?void 0:t.workspace_id,[r,a]=h.useState([]),[i,o]=h.useState(!0),[l,c]=h.useState(null),d=h.useCallback(async()=>{if(!s){o(!1);return}const{data:f,error:g}=await I.from("meta_ad_campaigns").select("*").eq("workspace_id",s).order("created_at",{ascending:!1});g?c(g.message):a(f||[]),o(!1)},[s]);h.useEffect(()=>{d()},[d]),h.useEffect(()=>{if(!s)return;const f=I.channel(`meta_ad_campaigns:${s}:${Math.random().toString(36).slice(2,8)}`).on("postgres_changes",{event:"*",schema:"public",table:"meta_ad_campaigns",filter:`workspace_id=eq.${s}`},()=>d()).subscribe();return()=>{I.removeChannel(f)}},[s,d]);const u=h.useCallback(async f=>{if(!s||!(e!=null&&e.access_token))throw new Error("Not ready");c(null);const{data:g,error:x}=await I.functions.invoke("meta-create-campaign",{body:{workspaceId:s,...f},headers:{Authorization:`Bearer ${e.access_token}`}});if(x||g!=null&&g.error){const b=(g==null?void 0:g.error)||(x==null?void 0:x.message)||"Failed";throw c(b),new Error(b)}return await d(),g},[s,e==null?void 0:e.access_token,d]),m=h.useCallback(async(f,g)=>{if(!(e!=null&&e.access_token))return;c(null);const{data:x,error:b}=await I.functions.invoke("meta-update-campaign-status",{body:{campaignId:f,action:g},headers:{Authorization:`Bearer ${e.access_token}`}});if(b||x!=null&&x.error){const v=(x==null?void 0:x.error)||(b==null?void 0:b.message)||"Failed";throw c(v),new Error(v)}await d()},[e==null?void 0:e.access_token,d]),p=h.useCallback(async(f,g)=>{if(!(e!=null&&e.access_token))throw new Error("Not ready");c(null);const{data:x,error:b}=await I.functions.invoke("meta-update-campaign",{body:{campaignId:f,...g},headers:{Authorization:`Bearer ${e.access_token}`}});if(b||x!=null&&x.error){const v=(x==null?void 0:x.error)||(b==null?void 0:b.message)||"Failed";throw c(v),new Error(v)}await d()},[e==null?void 0:e.access_token,d]);return{campaigns:r,loading:i,error:l,refresh:d,create:u,updateStatus:m,update:p}}function FB(e){const{profile:t}=st(),s=t==null?void 0:t.workspace_id,[r,a]=h.useState({}),i=e.slice().sort().join(","),o=h.useCallback(async()=>{if(!s||e.length===0){a({});return}const{data:l}=await I.from("meta_ad_campaigns").select("*").eq("workspace_id",s).in("live_clip_id",e).order("created_at",{ascending:!1}),c={};for(const d of l||[])d.live_clip_id&&!c[d.live_clip_id]&&(c[d.live_clip_id]=d);a(c)},[s,i]);return h.useEffect(()=>{o()},[o]),h.useEffect(()=>{if(!s)return;const l=I.channel(`meta_ad_campaigns_byclip:${s}:${Math.random().toString(36).slice(2,8)}`).on("postgres_changes",{event:"*",schema:"public",table:"meta_ad_campaigns",filter:`workspace_id=eq.${s}`},()=>o()).subscribe();return()=>{I.removeChannel(l)}},[s,o]),{byClip:r,refresh:o}}var UB="Label",AT=h.forwardRef((e,t)=>n.jsx(qe.label,{...e,ref:t,onMouseDown:s=>{var a;s.target.closest("button, input, select, textarea")||((a=e.onMouseDown)==null||a.call(e,s),!s.defaultPrevented&&s.detail>1&&s.preventDefault())}}));AT.displayName=UB;var RT=AT;const BB=hu("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Jt=h.forwardRef(({className:e,...t},s)=>n.jsx(RT,{ref:s,className:_e(BB(),e),...t}));Jt.displayName=RT.displayName;
vendor: 1,074 bytes, line 867
867const{slice:VB,forEach:qB}=[];function HB(e){return qB.call(VB.call(arguments,1),t=>{if(t)for(const s in t)e[s]===void 0&&(e[s]=t[s])}),e}function WB(e){return typeof e!="string"?!1:[/<\s*script.*?>/i,/<\s*\/\s*script\s*>/i,/<\s*img.*?on\w+\s*=/i,/<\s*\w+\s*on\w+\s*=.*?>/i,/javascript\s*:/i,/vbscript\s*:/i,/expression\s*\(/i,/eval\s*\(/i,/alert\s*\(/i,/document\.cookie/i,/document\.write\s*\(/i,/window\.location/i,/innerHTML/i].some(s=>s.test(e))}const B1=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/,GB=function(e,t){const r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{path:"/"},a=encodeURIComponent(t);let i=`${e}=${a}`;if(r.maxAge>0){const o=r.maxAge-0;if(Number.isNaN(o))throw new Error("maxAge should be a Number");i+=`; Max-Age=${Math.floor(o)}`}if(r.domain){if(!B1.test(r.domain))throw new TypeError("option domain is invalid");i+=`; Domain=${r.domain}`}if(r.path){if(!B1.test(r.path))throw new TypeError("option path is invalid");i+=`; Path=${r.path}`}if(r.expires){if(typeof r.expires.toUTCString!="function")throw new TypeError("option expires is invali
867d");i+=`; Expires=${r.expires.toUTCString()}`}if(r.httpOnly&&(i+="; HttpOnly"),r.secure&&(i+="; Secure"),r.sameSite)switch(typeof r.sameSite=="string"?r.sameSite.toLowerCase():r.sameSite){case!0:i+="; SameSite=Strict";break;case"lax":i+="; SameSite=Lax";break;case"strict":i+="; SameSite=Strict";break;case"none":i+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}return r.partitioned&&(i+="; Partitioned"),i},V1={create(e,t,s,r){let a=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{path:"/",sameSite:"strict"};s&&(a.expires=new Date,a.expires.setTime(a.expires.getTime()+s*60*1e3)),r&&(a.domain=r),document.cookie=GB(e,t,a)},read(e){const t=`${e}=`,s=document.cookie.split(";");for(let r=0;r<s.length;r++){let a=s[r];for(;a.charAt(0)===" ";)a=a.substring(1,a.length);if(a.indexOf(t)===0)return a.substring(t.length,a.length)}return null},remove(e,t){this.create(e,"",-1,t)}};var YB={name:"cookie",lookup(e){let{lookupCookie:t}=e;if(t&&typeof document<"u")return V1.read(t)||void 0},cacheUserLanguage(e,t){let{lookupCookie:s,cookieMinutes:r,cookieDomain:a,cookieOptions:i}=t;s&&typeof document<"u"&&V1.create(s,e,r,a,i)}},KB={name:"querystring",lookup(e){var r;let{lookupQuerystring:t}=e,s;if(typeof window<"u"){let{search:a}=window.location;!window.location.search&&((r=window.location.hash)==null?void 0:r.indexOf("?"))>-1&&(a=window.location.hash.substring(window.location.hash.indexOf("?")));const o=a.substring(1).split("&");for(let l=0;l<o.length;l++){const c=o[l].indexOf("=");c>0&&o[l].substring(0,c)===t&&(s=o[l].substring(c+1))}}return s}},QB={name:"hash",lookup(e){var a;let{lookupHash:t,lookupFromHashIndex:s}=e,r;if(typeof window<"u"){const{hash:i}=window.location;if(i&&i.length>2){const o=i.substring(1);if(t){const l=o.split("&");for(let c=0;c<l.length;c++){const d=l[c].indexOf("=");d>0&&l[c].substring(0,d)===t&&(r=l[c].substring(d+1))}}if(r)return r;if(!r&&s>-1){const l=i.match(/\/([a-zA-Z-]*)/g);return Array.isArray(l)?(a=l[typeof s=="number"?s:0])==null?void 0:a.replace("/",""):void 0}}}return r}};let So=null;const q1=()=>{if(So!==null)return So;try{if(So=typeof window<"u"&&window.localStorage!==null,!So)return!1;const e="i18next.translate.boo";window.localStorage.setItem(e,"foo"),window.localStorage.removeItem(e)}catch{So=!1}return So};var JB={name:"localStorage",lookup(e){let{lookupLocalStorage:t}=e;if(t&&q1())return window.localStorage.getItem(t)||void 0},cacheUserLanguage(e,t){let{lookupLocalStorage:s}=t;s&&q1()&&window.localStorage.setItem(s,e)}};let Co=null;const H1=()=>{if(Co!==null)return Co;try{if(Co=typeof window<"u"&&window.sessionStorage!==null,!Co)return!1;const e="i18next.translate.boo";window.sessionStorage.setItem(e,"foo"),window.sessionStorage.removeItem(e)}catch{Co=!1}return Co};var ZB={name:"sessionStorage",lookup(e){let{lookupSessionStorage:t}=e;if(t&&H1())return window.sessionStorage.getItem(t)||void 0},cacheUserLanguage(e,t){let{lookupSessionStorage:s}=t;s&&H1()&&window.sessionStorage.setItem(s,e)}},XB={name:"navigator",lookup(e){const t=[];if(typeof navigator<"u"){const{languages:s,userLanguage:r,language:a}=navigator;if(s)for(let i=0;i<s.length;i++)t.push(s[i]);r&&t.push(r),a&&t.push(a)}return t.length>0?t:void 0}},eV={name:"htmlTag",lookup(e){let{htmlTag:t}=e,s;const r=t||(typeof document<"u"?document.documentElement:null);return r&&typeof r.getAttribute=="function"&&(s=r.getAttribute("lang")),s}},tV={name:"path",lookup(e){var a;let{lookupFromPathIndex:t}=e;if(typeof window>"u")return;const s=window.location.pathname.match(/\/([a-zA-Z-]*)/g);return Array.isArray(s)?(a=s[typeof t=="number"?t:0])==null?void 0:a.replace("/",""):void 0}},sV={name:"subdomain",lookup(e){var a,i;let{lookupFromSubdomainIndex:t}=e;const s=typeof t=="number"?t+1:1,r=typeof window<"u"&&((i=(a=window.location)==null?void 0:a.hostname)==null?void 0:i.match(/^(\w{2,5})\.(([a-z0-9-]{1,63}\.[a-z]{2,6})|localhost)/i));if(r)return r[s]}};let $T=!1;try{document.cookie,$T=!0}catch{}const LT=["querystring","cookie","localStorage","sessionStorage","navigator","htmlTag"];$T||LT.splice(1,1);const nV=()=>({order:LT,lookupQuerystring:"lng",lookupCookie:"i18next",lookupLocalStorage:"i18nextLng",lookupSessionStorage:"i18nextLng",caches:["localStorage"],excludeCacheFor:["cimode"],convertDetectedLanguage:e=>e});class IT{constructor(t){let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.type="languageDetector",this.detectors={},this.init(t,s)}init(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{languageUtils:{}},s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};this.services=t,this.options=HB(s,this.options||{},nV()),typeof this.options.convertDetectedLanguage=="string"&&this.options.convertDetectedLanguage.indexOf("15897")>-1&&(this.options.convertDetectedLanguage=a=>a.replace("-","_")),this.options.lookupFromUrlIndex&&(this.options.lookupFromPathIndex=this.options.lookupFromUrlIndex),this.i18nOptions=r,this.addDetector(YB),this.addDetector(KB),this.addDetector(JB),this.addDetector(ZB),this.addDetector(XB),this.addDetector(eV),this.addDetector(tV),this.addDetector(sV),this.addDetector(QB)}addDetector(t){return this.detectors[t.name]=t,this}detect(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.options.order,s=[];return t.forEach(r=>{if(this.detectors[r]){let a=this.detectors[r].lookup(this.options);
vendor: 11,019 bytes, line 867
867a&&typeof a=="string"&&(a=[a]),a&&(s=s.concat(a))}}),s=s.filter(r=>r!=null&&!WB(r)).map(r=>this.options.convertDetectedLanguage(r)),this.services&&this.services.languageUtils&&this.services.languageUtils.getBestMatchFromCodes?s:s.length>0?s[0]:null}cacheUserLanguage(t){let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.options.caches;s&&(this.options.excludeCacheFor&&this.options.excludeCacheFor.indexOf(t)>-1||s.forEach(r=>{this.detectors[r]&&this.detectors[r].cacheUserLanguage(t,this.options)}))}}IT.type="languageDetector";const rV={howItWorks:"Как это работает",useCases:"Кейсы",pricing:"Тарифы",faq:"FAQ",login:"Войти",startFree:"Начать бесплатно",dashboard:"Дашборд"},aV={desc:"Платформа для запуска ИИ-блогеров, ИИ-ведущих и ИИ-консультантов.",product:"Продукт",resources:"Ресурсы",legal:"Правовая информация",cookiePolicy:"Кук-политика",privacy:"Конфиденциальность",terms:"Условия",offer:"Оферта",copyright:"© {{year}} SmartBlogAI. Все права защищены.",tagline:"Сделано для создателей нового поколения"},iV={myProject:"Мой проект",searchPlaceholder:"Поиск по платформе...",upgrade:"Улучшить"},oV={free:"Free",pro:"Pro",business:"Business"},lV={ru:"RU",en:"EN"},cV={main:"Основное",dashboard:"Дашборд",persona:"Персонаж",contentStudio:"Контент-студия",live:"Эфиры",simulator:"Симулятор",webinars:"Вебинары",trends:"Тренды",news:"Новости",topicDiscovery:"Поиск тем",consultations:"Консультации",integrations:"Интеграции",ads:"Реклама",monetization:"Монетизация",analytics:"Аналитика",operations:"Операции",prompts:"Промпты движка",billing:"Оплата",settings:"Настройки",signOut:"Выйти",admin:"Админ-панель"},dV={seconds:"{{count}} сек назад",minutes:"{{count}} мин назад",hours:"{{count}} ч назад",days:"{{count}} д назад"},uV={title:"Мы используем cookies",desc:"Для корректной работы платформы и улучшения вашего опыта.",more:"Подробнее",accept:"Принять",decline:"Только необходимые"},hV={loading:"Загружаем…",errorTitle:"Произошла ошибка",retryButton:"Попробовать снова",dismiss:"Убрать",reason:"Причина: {{reason}}",status:{idea:"Идея",draft:"Черновик",generating:"Генерация",queued:"В очереди",running:"Выполняется",ready:"Готово",scheduled:"Запланировано",published:"Опубликовано",live:"В эфире",ended:"Завершён",canceled:"Отменён",failed:"Ошибка",timed_out:"Таймаут",completed:"Готово",review:"На проверке",approved:"Одобрен",active:"Активна",inactive:"Неактивна",past_due:"Просрочена",trialing:"Пробный",connected:"Подключено",not_connected:"Не подключено",connecting:"Подключение",expired:"Истёк",error:"Ошибка"},subscription:{pastDueTitle:"Оплата не прошла",pastDueDesc:"Обновите способ оплаты, чтобы сохранить доступ к функциям тарифа.",pastDueAction:"Обновить оплату",canceledTitle:"Подписка отменена",canceledDesc:"Доступ к тарифу сохранится до {{date}}. После этого аккаунт перейдёт на Free.",canceledAction:"Возобновить",freeTitle:"Вы на бесплатном тарифе",freeDesc:"Перейдите на Pro, чтобы разблокировать Live Center, расширенную аналитику и больше Shorts.",freeAction:"Перейти на Pro"},recovery:{ytExpiredTitle:"YouTube: токен истёк",ytExpiredDesc:"Доступ к YouTube API истёк. Переподключите YouTube, чтобы продолжить публикацию и live-эфиры.",ytExpiredAction:"Переподключить YouTube",ytErrorTitle:"YouTube: ошибка подключения",ytErrorDesc:"Не удалось подключиться к YouTube API.",ytErrorAction:"Переподключить",ytErrorSecondary:"Подробнее",unknownError:"Неизвестная ошибка",patreonExpiredTitle:"Patreon: токен истёк",patreonExpiredDesc:"Доступ к Patreon API истёк. Переподключите для продолжения работы платного слоя.",patreonExpiredAction:"Переподключить Patreon",patreonErrorTitle:"Patreon: ошибка подключения",patreonErrorDesc:"Не удалось подключиться к Patreon API.",patreonErrorAction:"Переподключить",patreonErrorSecondary:"Подробнее",billingPastDueTitle:"Оплата не прошла",billingPastDueDesc:"Последний платёж не удался. Обновите способ оплаты, чтобы сохранить доступ к функциям тарифа.",billingPastDueAction:"Обновить оплату",billingCanceledTitle:"Подписка отменена",billingCanceledDesc:"Ваша подписка отменена. Аккаунт перейдёт на бесплатный тариф.",billingCanceledAction:"Возобновить подписку",jobErrorSuffix:"ошибка",jobErrorFallback:"Фоновая задача завершилась с ошибкой.",jobTypes:{generate_short_script:"Генерация сценария",render_short_video:"Рендер видео",tts_generate:"TTS озвучка",upload_video_to_youtube:"Загрузка на YouTube"},liveFailedTitle:"Live «{{title}}»: не удалось запустить",liveFailedDesc:"Эфир не смог запуститься. Проверьте настройки и попробуйте снова.",liveFailedAction:"Открыть Live Center"},patreonConnectError:"Ошибка подключения Patreon",patreonStartError:"Не удалось начать подключение"},mV={title:"Сначала создайте персонажа",description:"Персонаж определяет голос, стиль и поведение вашего ИИ-ведущего. Создайте хотя бы одного, чтобы начать работу с контентом и эфирами.",createButton:"Создать персонажа"},pV={hint:"Перетащите для позиционирования · Колёсико или слайдер для масштаба",back:"Назад",crop:"Обрезать"},fV={statusLive:"Работает",statusPreview:"Превью",statusComing:"Скоро",previewBadge:"Превью-режим",allPipelinesActive:"Все pipeline платформы активны",productionUpgrade:"Обновление до Production:",productionUpgradeDesc:"те же workflows будут подключены к рендерингу аватара в реальном времени без изменения архитектуры.",test:{label:"Превью-режим",shortLabel:"Превью",badge:"Тестовые воркеры",description:"Платформа работает в превью-режиме. Голосовой pipeline, контентный pipeline и job-система полностью рабочие. Видео-рендер использует placeholder-визуализацию вместо Smart Avatar анимации.",renderLabel:"Превью-рендер",renderDescription:"Видео собирается с генеративной визуализацией и реальной озвучкой. Smart Avatar анимация будет подключена в production-режиме.",liveLabel:"Тестовый Live",liveDescription:"Live-эфиры используют placeholder-визуализацию с реальной озвучкой и чат-интеграцией."},production:{label:"Production-режим",shortLabel:"Production",badge:"Production",description:"Все pipeline работают в production-режиме с полной аватар-анимацией.",renderLabel:"Полный рендер",renderDescription:"Видео собирается с полной Smart Avatar анимацией.",liveLabel:"Production Live",liveDescription:"Live-эфиры с полной аватар-анимацией в реальном времени."},capabilities:{scriptGen:"Генерация сценариев",tts:"TTS озвучка",jobPipeline:"Job pipeline",chatIntegration:"Интеграция чата",repurposing:"Переработка контента",previewRender:"Превью-рендер видео",fullRender:"Полный рендер видео",avatarAnimation:"Аватар-анимация"}},gV={name:"AI Эксперт",description:"Помогает разбираться в AI, бизнесе и создании контента.",customVoice:"Кастомный голос",voiceError:"Не удалось получить информацию о голосе"},xV={topicRequiredTitle:"Сначала укажите тему",topicRequiredDesc:"AI нужна тема, чтобы сгенерировать релевантный контент. Введите тему ниже.",topicPlaceholder:"Например, монетизация AI-контента…",continue:"Продолжить",cancel:"Отмена"},vV={voiceFailed:"Не удалось запустить озвучку",noAudioForVideo:"Нет аудио для создания видео",renderFailed:"Не удалось создать задачу рендера видео",youtubeNotConnected:"YouTube не подключён — перейдите в Интеграции",publishFailed:"Не удалось запустить публикацию"},yV={generateFailed:"Не удалось сгенерировать тумбнейл",regenerate:"Перегенерировать",generateAgain:"Заново",generate:"Сгенерировать",customPrompt:"Свой промпт",promptBtn:"Промпт",dialogTitle:"Свой промпт для тумбнейла",dialogDesc:"Опиши сцену, эмоцию и текст на картинке. Стиль (медийный/провокационный) добавится автоматически.",promptPlaceholder:"Например: крупное лицо в шоке, руки у головы, на фоне горящие цифры $10K, надпись «ПРОВАЛ»",cancel:"Отмена",generateBtn:"Сгенерировать"}
867,bV={title:"Что-то пошло не так",fallback:"Произошла непредвиденная ошибка",retry:"Попробовать снова",home:"На главную"},wV={ru:"Русский",en:"English"},jV={nav:rV,footer:aV,topBar:iV,plans:oV,lang:lV,sidebar:cV,timeAgo:dV,cookie:uV,system:hV,personaGate:mV,avatarCropper:pV,workerMode:fV,defaultPersona:gV,aiFill:xV,errors:vV,thumbnail:yV,errorBoundary:bV,languages:wV},_V={howItWorks:"How It Works",useCases:"Use Cases",pricing:"Pricing",faq:"FAQ",login:"Sign In",startFree:"Start for Free",dashboard:"Dashboard"},kV={desc:"Platform for launching AI bloggers, AI hosts, and AI consultants.",product:"Product",resources:"Resources",legal:"Legal",cookiePolicy:"Cookie Policy",privacy:"Privacy",terms:"Terms",offer:"Offer",copyright:"© {{year}} SmartBlogAI. All rights reserved.",tagline:"Made for next-generation creators"},NV={myProject:"My Project",searchPlaceholder:"Search the platform...",upgrade:"Upgrade"},SV={free:"Free",pro:"Pro",business:"Business"},CV={ru:"RU",en:"EN"},TV={main:"Main",dashboard:"Dashboard",persona:"Persona",contentStudio:"Content Studio",live:"Streams",simulator:"Simulator",webinars:"Webinars",trends:"Trends",news:"News",topicDiscovery:"Topic Discovery",consultations:"Consultations",integrations:"Integrations",ads:"Ads",monetization:"Monetization",analytics:"Analytics",operations:"Operations",prompts:"Engine Prompts",billing:"Billing",settings:"Settings",signOut:"Sign out",admin:"Admin Panel"},PV={seconds:"{{count}}s ago",minutes:"{{count}}m ago",hours:"{{count}}h ago",days:"{{count}}d ago"},EV={title:"We use cookies",desc:"For proper platform operation and to improve your experience.",more:"Learn more",accept:"Accept",decline:"Only necessary"},AV={loading:"Loading…",errorTitle:"An error occurred",retryButton:"Try again",dismiss:"Dismiss",reason:"Reason: {{reason}}",status:{idea:"Idea",draft:"Draft",generating:"Generating",queued:"Queued",running:"Running",ready:"Ready",scheduled:"Scheduled",published:"Published",live:"Live",ended:"Ended",canceled:"Canceled",failed:"Failed",timed_out:"Timed out",completed:"Completed",review:"In review",approved:"Approved",active:"Active",inactive:"Inactive",past_due:"Past due",trialing:"Trial",connected:"Connected",not_connected:"Not connected",connecting:"Connecting",expired:"Expired",error:"Error"},subscription:{pastDueTitle:"Payment failed",pastDueDesc:"Update your payment method to keep access to plan features.",pastDueAction:"Update payment",canceledTitle:"Subscription canceled",canceledDesc:"Access to your plan will continue until {{date}}. After that, the account will switch to Free.",canceledAction:"Resume",freeTitle:"You're on the Free plan",freeDesc:"Upgrade to Pro to unlock Live Center, advanced analytics, and more Shorts.",freeAction:"Upgrade to Pro"},recovery:{ytExpiredTitle:"YouTube: token expired",ytExpiredDesc:"YouTube API access has expired. Reconnect YouTube to continue publishing and live streams.",ytExpiredAction:"Reconnect YouTube",ytErrorTitle:"YouTube: connection error",ytErrorDesc:"Failed to connect to YouTube API.",ytErrorAction:"Reconnect",ytErrorSecondary:"Details",unknownError:"Unknown error",patreonExpiredTitle:"Patreon: token expired",patreonExpiredDesc:"Patreon API access has expired. Reconnect to continue using the paid tier.",patreonExpiredAction:"Reconnect Patreon",patreonErrorTitle:"Patreon: connection error",patreonErrorDesc:"Failed to connect to Patreon API.",patreonErrorAction:"Reconnect",patreonErrorSecondary:"Details",billingPastDueTitle:"Payment failed",billingPastDueDesc:"The last payment failed. Update your payment method to keep access to plan features.",billingPastDueAction:"Update payment",billingCanceledTitle:"Subscription canceled",billingCanceledDesc:"Your subscription has been canceled. The account will switch to the free plan.",billingCanceledAction:"Resume subscription",jobErrorSuffix:"error",jobErrorFallback:"A background job failed.",jobTypes:{generate_short_script:"Script generation",render_short_video:"Video render",tts_generate:"TTS voiceover",upload_video_to_youtube:"YouTube upload"},liveFailedTitle:'Live "{{title}}": failed to start',liveFailedDesc:"The stream could not start. Check settings and try again.",liveFailedAction:"Open Live Center"},patreonConnectError:"Patreon connection error",patreonStartError:"Failed to start connection"},RV={title:"Create a persona first",description:"A persona defines the voice, style, and behavior of your AI host. Create at least one to start working with content and streams.",createButton:"Create persona"},$V={hint:"Drag to position · Scroll or slider to zoom",back:"Back",crop:"Crop"},LV={statusLive:"Live",statusPreview:"Preview",statusComing:"Coming soon",previewBadge:"Preview mode",allPipelinesActive:"All platform pipelines active",productionUpgrade:"Upgrade to Production:",productionUpgradeDesc:"the same workflows will connect to real-time avatar rendering without changing architecture.",test:{label:"Preview mode",shortLabel:"Preview",badge:"Test workers",description:"The platform is running in preview mode. Voice pipeline, content pipeline, and j
867ob system are fully operational. Video rendering uses placeholder visuals instead of Smart Avatar animation.",renderLabel:"Preview render",renderDescription:"Video is assembled with generative visuals and real voiceover. Smart Avatar animation will be enabled in production mode.",liveLabel:"Test Live",liveDescription:"Live streams use placeholder visuals with real voiceover and chat integration."},production:{label:"Production mode",shortLabel:"Production",badge:"Production",description:"All pipelines are running in production mode with full avatar animation.",renderLabel:"Full render",renderDescription:"Video is assembled with full Smart Avatar animation.",liveLabel:"Production Live",liveDescription:"Live streams with full real-time avatar animation."},capabilities:{scriptGen:"Script generation",tts:"TTS voiceover",jobPipeline:"Job pipeline",chatIntegration:"Chat integration",repurposing:"Content repurposing",previewRender:"Preview video render",fullRender:"Full video render",avatarAnimation:"Avatar animation"}},IV={name:"AI Expert",description:"Helps understand AI, business, and content creation.",customVoice:"Custom voice",voiceError:"Failed to get voice information"},OV={topicRequiredTitle:"Enter a topic first",topicRequiredDesc:"AI needs a topic to generate relevant content. Please enter the topic below.",topicPlaceholder:"E.g. AI content monetization…",continue:"Continue",cancel:"Cancel"},DV={voiceFailed:"Failed to start voiceover",noAudioForVideo:"No audio for video creation",renderFailed:"Failed to create video render job",youtubeNotConnected:"YouTube not connected — go to Integrations",publishFailed:"Failed to start publishing"},MV={generateFailed:"Failed to generate thumbnail",regenerate:"Regenerate",generateAgain:"Regenerate",generate:"Generate",customPrompt:"Custom prompt",promptBtn:"Prompt",dialogTitle:"Custom thumbnail prompt",dialogDesc:"Describe the scene, emotion, and text on the image. The style (editorial / provocative) is added automatically.",promptPlaceholder:'E.g.: shocked close-up face, hands at the temples, burning $10K numbers in the background, caption "FAIL"',cancel:"Cancel",generateBtn:"Generate"},zV={title:"Something went wrong",fallback:"An unexpected error occurred",retry:"Try again",home:"Go home"},FV={ru:"Русский",en:"English"},UV={nav:_V,footer:kV,topBar:NV,plans:SV,lang:CV,sidebar:TV,timeAgo:PV,cookie:EV,system:AV,personaGate:RV,avatarCropper:$V,workerMode:LV,defaultPersona:IV,aiFill:OV,errors:DV,thumbnail:MV,errorBoundary:zV,languages:FV},BV="ИИ-блогер",VV="ИИ-ведущий",qV="ИИ-консультант",HV="Цифровые персонажи, ",WV="которые говорят, выступают и консультируют",GV="Платформа для запуска ИИ-блогеров, ИИ-ведущих и ИИ-консультантов. Создавайте контент, ведите эфиры, отвечайте аудитории и монетизируйте экспертность.",YV="Начать бесплатно",KV="Как это работает",QV="Бесплатный старт · Не нужно быть на камере · Системный путь к монетизации",JV="ИИ-ведущие — девушка и парень в студии",ZV="🎙️ Live-эфир запущен",XV="✂️ 12 Shorts готовы",eq={badge_blogger:BV,badge_host:VV,badge_consultant:qV,title:HV,titleGradient:WV,subtitle:GV,ctaPrimary:YV,ctaSecondary:KV,note:QV,imgAlt:JV,floatLive:ZV,floatShorts:XV},tq="AI Blogger",sq="AI Host",nq="AI Consultant",rq="Digital characters that ",aq="speak, perform, and consult",iq="A platform for launching AI bloggers, AI hosts, and AI consultants. Create content, go live, engage your audience, and monetize expertise.",oq="Start for Free",lq="How It Works",cq="Free start · No camera needed · Systematic path to monetization",dq="AI hosts — a woman and a man in a studio",uq="🎙️ Live stream started",hq="✂️ 12 Shorts ready",mq={badge_blogger:tq,badge_host:sq,badge_consultant:nq,title:rq,titleGradient:aq,subtitle:iq,ctaPrimary:oq,ctaSecondary:lq,note:cq,imgAlt:dq,floatLive:uq,floatShorts:hq},pq="Платформа",fq="Не генератор контента. ",gq="Система запуска ИИ-персонажей.",xq="Вы создаёте цифрового блогера, ведущего или консультанта, который регулярно выступает, отвечает аудитории и приносит доход.",vq=[{title:"ИИ-блогер",text:"Создаёт короткие видео, говорит от лица вашего бренда, регулярно выпускает контент и помогает тестировать темы в Shorts-формате."},{title:"ИИ-ведущий",text:"Выходит в live-эфиры, ведёт темы, отвечает на вопросы аудитории в реальном времени и делает прямые эфиры живыми."},{title:"ИИ-консультант",text:"Проводит голосовые консультации 1-на-1, объясняет, разбирает ситуации и превращает экспертность в оплачиваемый сервис."}
867],yq={label:pq,title:fq,titleGradient:gq,subtitle:xq,cards:vq},bq="Platform",wq="Not a content generator. ",jq="An AI character launch system.",_q="Create a digital blogger, host, or consultant that regularly performs, engages audiences, and generates revenue.",kq=[{title:"AI Blogger",text:"Creates short videos, speaks on behalf of your brand, regularly publishes content, and helps test topics in Shorts format."},{title:"AI Host",text:"Goes live, leads discussions, answers audience questions in real time, and makes live streams engaging."},{title:"AI Consultant",text:"Conducts 1-on-1 voice consultations, explains, analyzes situations, and turns expertise into a paid service."}],Nq={label:bq,title:wq,titleGradient:jq,subtitle:_q,cards:kq},Sq="Для тех, кто хочет зарабатывать ",Cq="своим цифровым персонажем",Tq=[{title:"Эксперты",text:"Превращайте знания в работающего ИИ-спикера и контент-актив."},{title:"Консультанты",text:"Используйте ИИ-консультанта как дополнительный формат общения и монетизации."},{title:"Преподаватели",text:"Масштабируйте объяснения, эфиры и образовательный контент."},{title:"Блогеры и медиа-проекты",text:"Запускайте ИИ-ведущих и цифровых хостов для регулярного контента."},{title:"AI-first создатели",text:"Стройте новый тип медиа, где ИИ-персонаж — основа бренда и контентной системы."},{title:"Компании и бренды",text:"Создавайте брендированных цифровых представителей для контента, live и консультаций."}],Pq={title:Sq,titleGradient:Cq,items:Tq},Eq="For those who want to earn with ",Aq="their digital character",Rq=[{title:"Experts",text:"Turn your knowledge into a working AI speaker and content asset."},{title:"Consultants",text:"Use an AI consultant as an additional format for communication and monetization."},{title:"Educators",text:"Scale explanations, live sessions, and educational content."},{title:"Bloggers & media projects",text:"Launch AI hosts and digital characters for regular content."},{title:"AI-first creators",text:"Build a new type of media where the AI character is the foundation of the brand."},{title:"Companies & brands",text:"Create branded digital representatives for content, live, and consultations."}],$q={title:Eq,titleGradient:Aq,items:Rq},Lq="Возможности",Iq="Что может ",Oq="ваш ИИ-персонаж",Dq="Один персонаж — контент-машина, live-хост, консультант и основа вашей медиа-воронки.",Mq="Возможности ИИ-платформы",zq=[{title:"Записывать короткие видео",text:"Shorts для тестирования тем и набора охвата."},{title:"Вести регулярные рубрики",text:"Повторяемый формат для узнаваемого канала."},{title:"Выступать в прямом эфире",text:"Live-сессии с удержанием внимания."},{title:"Отвечать в live-чате",text:"Реакция на сообщения зрителей."},{title:"Проводить консультации",text:"Индивидуальные созвоны и сессии."},{title:"Записывать разборы",text:"Экспертный контент для монетизации."},{title:"Давать материал для нарезок",text:"Эфиры → Shorts, клипы и промо."},{title:"Работать 24/7 как актив",text:"ИИ-персонаж ценнее со временем."}],Fq={label:Lq,title:Iq,titleHighlight:Oq,subtitle:Dq,imgAlt:Mq,items:zq},Uq="Capabilities",Bq="What your ",Vq="AI character can do",qq="One character — a content machine, live host, consultant, and the foundation of your media funnel.",Hq="AI platform capabilities",Wq=[{title:"Record short videos",text:"Shorts for testing topics and gaining reach."},{title:"Run regular segments",text:"A repeatable format for a recognizable channel."},{title:"Go live",text:"Live sessions that hold attention."},{title:"Reply in live chat",text:"Respond to viewer messages."},{title:"Conduct consultations",text:"Individual calls and sessions."},{title:"Record deep dives",text:"Expert content for monetization."},{title:"Provide material for clips",text:"Streams → Shorts, clips, and promos."},{title:"Work 24/7 as an asset",text:"An AI character grows in value over time."}
867],Gq={label:Uq,title:Bq,titleHighlight:Vq,subtitle:qq,imgAlt:Hq,items:Wq},Yq="Простой онбординг, который ",Kq="реально ведёт к запуску",Qq="Вместо хаоса и пустой админки пользователь сразу получает понятный маршрут.",Jq=[{title:"Выберите тип ИИ-персонажа",options:["Блогер","Ведущий","Консультант","Преподаватель","Смешанный формат"]},{title:"Выберите тему",options:["AI","Обучение","Бизнес","Языки","Экспертные разборы","Личный бренд","Медиа"]},{title:"Подключите YouTube",text:"Сделайте YouTube основной публичной площадкой."},{title:"Получите стартовый план",text:"Сервис строит пошаговый маршрут: Shorts, live, нарезки, монетизация."},{title:"Запустите первые выступления",text:"Создайте первые ролики и первые live-сессии с вашим ИИ-персонажем."},{title:"Подключите платный слой",text:"Добавьте Patreon, платные эфиры и консультации."}],Zq={title:Yq,titleGradient:Kq,subtitle:Qq,steps:Jq},Xq="Simple onboarding that ",e9="actually leads to launch",t9="Instead of chaos and an empty dashboard, users get a clear roadmap from day one.",s9=[{title:"Choose your AI character type",options:["Blogger","Host","Consultant","Educator","Mixed format"]},{title:"Choose a topic",options:["AI","Education","Business","Languages","Expert analysis","Personal brand","Media"]},{title:"Connect YouTube",text:"Make YouTube your primary public platform."},{title:"Get a launch plan",text:"The service builds a step-by-step roadmap: Shorts, live, clips, monetization."},{title:"Launch your first sessions",text:"Create your first videos and live sessions with your AI character."},{title:"Enable the paid layer",text:"Add Patreon, paid live sessions, and consultations."}],n9={title:Xq,titleGradient:e9,subtitle:t9,steps:s9},r9="Один эфир может ",a9="кормить ваш контент неделями",i9="Каждое выступление ИИ-персонажа становится источником новых материалов.",o9=["Live-эфир / консультация / вебинар","Ключевые фрагменты","Короткие нарезки","Новые Shorts","Тизеры будущих эфиров","Контент для соцсетей","Платный архив / бонусные материалы","Новые точки входа в воронку"],l9=["Один live превращается в 5–20 единиц контента","Один Q&A становится серией Shorts","Одна консультация может стать образовательным разбором","Один вебинар может стать платным архивом и серией промо-клипов"],c9={title:r9,titleGradient:a9,subtitle:i9,flowSteps:o9,notes:l9},d9="One live session can ",u9="feed your content for weeks",h9="Every AI character performance becomes a source of new materials.",m9=["Live stream / consultation / webinar","Key highlights","Short clips","New Shorts","Teasers for upcoming streams","Social media content","Paid archive / bonus materials","New funnel entry points"],p9=["One live turns into 5–20 pieces of content","One Q&A becomes a series of Shorts","One consultation can become an educational deep dive","One webinar can become a paid archive and a series of promo clips"],f9={title:d9,titleGradient:u9,subtitle:h9,flowSteps:m9,notes:p9},g9="Понятное ",x9="распределение ролей",v9="Мы даём ИИ-персонажа и систему запуска. Вы управляете стратегией. Платформы обеспечивают размещение и монетизацию.",y9=[{title:"Что даём мы",items:["ИИ-блогеров для короткого контента","ИИ-ведущих для live-эфиров","ИИ-консультантов для голосовых консультаций","Систему запуска и роста","Контентный цикл: Shorts → Live → Нарезки → Продукты","Помощь в подключении YouTube и Patreon","Понятную дорожную карту роста"]}
867,{title:"Что делает пользователь",items:["Выбирает тему и роль ИИ-персонажа","Утверждает стиль и позиционирование","Подключает свои площадки","Следит за стратегией и развитием бренда","Решает, какие продукты продавать","Управляет ростом медиа-бизнеса"]},{title:"Что делают платформы",items:["YouTube размещает Shorts, live и видео","YouTube даёт нативную монетизацию","Patreon даёт платные tiers и подписки","Платёжные правила зависят от платформ"]}],b9={title:g9,titleGradient:x9,subtitle:v9,columns:y9},w9="Clear ",j9="role distribution",_9="We provide the AI character and launch system. You manage the strategy. Platforms handle distribution and monetization.",k9=[{title:"What we provide",items:["AI bloggers for short-form content","AI hosts for live streams","AI consultants for voice consultations","A launch and growth system","Content cycle: Shorts → Live → Clips → Products","Help connecting YouTube and Patreon","A clear growth roadmap"]},{title:"What you do",items:["Choose the topic and AI character role","Approve the style and positioning","Connect your platforms","Oversee strategy and brand development","Decide which products to sell","Manage media business growth"]},{title:"What platforms do",items:["YouTube hosts Shorts, live, and videos","YouTube provides native monetization","Patreon offers paid tiers and subscriptions","Payment rules depend on the platforms"]}],N9={title:w9,titleGradient:j9,subtitle:_9,columns:k9},S9="Ваш ИИ не просто говорит. Он может ",C9="вести, отвечать и консультировать",T9="Один ИИ-персонаж работает в нескольких форматах — от публичного live до приватной консультации.",P9="Live-эфиры и консультации",E9=[{title:"Бесплатные live-эфиры",text:"Открытые сессии для роста аудитории и знакомства с персонажем."},{title:"Q&A в реальном времени",text:"ИИ-ведущий отвечает на вопросы зрителей прямо во время эфира."},{title:"Тематические live-лекции",text:"ИИ выступает как эксперт по выбранной теме."},{title:"Закрытые платные live",text:"Глубокие эфиры для подписчиков и закрытых сообществ."},{title:"Голосовые консультации",text:"Индивидуальные сессии как отдельная платная услуга."}],A9={title:S9,titleGradient:C9,subtitle:T9,imgAlt:P9,items:E9},R9="Your AI doesn't just talk. It can ",$9="host, respond, and consult",L9="One AI character works across multiple formats — from public live streams to private consultations.",I9="Live streams and consultations",O9=[{title:"Free live streams",text:"Open sessions to grow your audience and introduce the character."},{title:"Real-time Q&A",text:"The AI host answers viewer questions during the stream."},{title:"Themed live lectures",text:"The AI performs as an expert on a chosen topic."},{title:"Paid private lives",text:"In-depth streams for subscribers and closed communities."},{title:"Voice consultations",text:"Individual sessions as a standalone paid service."}],D9={title:R9,titleGradient:$9,subtitle:L9,imgAlt:I9,items:O9},M9="Форматы дохода",z9="Один ИИ-персонаж — ",F9="несколько путей к доходу",U9="Ваш блогер, ведущий или консультант работает сразу в нескольких моделях монетизации.",B9="Монетизация",V9=[{title:"YouTube-монетизация",text:"Нативная монетизация по мере роста канала."},{title:"Платные подписки",text:"Клуб с эксклюзивным доступом и закрытыми эфирами."},{title:"Платные live-эфиры",text:"Обучающие и премиальные сессии для аудитории."},{title:"Вебинары",text:"Структурированные платные выступления по темам."},{title:"Голосовые консультации",text:"Платный формат прямой помощи и разборов."},{title:"Архив и бонусный контент",text:"Записи эфиров и дополнительные материалы."},{title:"Премиальные продукты",text:"Образовательные пакеты и интенсивы."}],q9={label:M9,title:z9,titleGradient:F9,subtitle:U9,imgAlt:B9,items:V9},H9="Revenue Formats",W9="One AI character — ",G9="multiple paths to revenue",Y9="Your blogger, host, or consultant works across several monetization models at once.",K9="Monetization",Q9=[{title:"YouTube monetization",text:"Native monetization as your channel grows."},{title:"Paid subscriptions",text:"A club with exclusive access and private streams."},{title:"Paid live streams",text:"Educational and premium sessions for your audience."},{title:"Webinars",text:"Structured paid talks on specific topics."},{title:"Voice consultations",text:"A paid format for direct help and analysis."},{title:"Archive & bonus content",text:"Stream recordings and additional materials."},{title:"Premium products",text:"Educational packages and intensives."}],J9={label:H9,title:W9,titleGradient:G9,subtitle:Y9,imgAlt:K9,items:Q9},Z9="Преимущества",X9="Почему это лучше, чем ",e7="делать всё вручную",t7="Запустите ИИ-персонажа, который возьмёт на себя контент, эфиры и консультации.",s7="Преимущества ИИ-платформы",n7=[{title:"Экономия времени",text:"ИИ-персонаж создаёт контент, ведёт эфиры и консультирует — вы тратите часы вместо недель.",metric:"10×",metricLabel:"быстрее"},{title:"Бесконечный контент-цикл",text:"Один эфир → 5–20 единиц контента: Shorts, клипы, тизеры, архив.",metric:"1→20",metricLabel:"единиц"},{title:"ИИ говорит сам",text:"Не нужно записывать себя, монтировать или быть на камере.",metric:"24/7",metricLabel:"готов"},{title:"Системность",text:"Пошаговый путь от первого ролика до платных подписок.",metric:"100%",metricLabel:"понятный путь"},{title:"Масштаб без команды",text:"Один человек управляет несколькими ИИ-персонажами.",metric:"1→∞",metricLabel:"персонажей"},{title:"Рост как актив",text:"ИИ-персонаж со временем приносит больше дохода.",metric:"↑",metricLabel:"ценность"}],r7={label:Z9,title:X9,titleGradient:e7,subtitle:t7,imgAlt:s7,items:n7},a7="Advantages",i7="Why this is better than ",o7="doing everything manually",l7="Launch an AI character that handles content, live streams, and consultations for you.",c7="AI platform advantages",d7=[{title:"Time savings",text:"Your AI character creates content, hosts streams, and consults — you spend hours, not weeks.",metric:"10×",metricLabel:"faster"},{title:"Infinite content cycle",text:"One stream → 5–20 pieces of content: Shorts, clips, teasers, archive.",metric:"1→20",metricLabel:"pieces"},{title:"AI speaks for itself",text:"No need to record yourself, edit, or be on camera.",metric:"24/7",metricLabel:"ready"},{title:"Systematic approach",text:"A step-by-step path from your first video to paid subscriptions.",metric:"100%",metricLabel:"clear path"},{title:"Scale without a team",text:"One person manages multiple AI characters.",metric:"1→∞",metricLabel:"characters"},{title:"Growth as an asset",text:"An AI character generates more revenue over time.",metric:"↑",metricLabel:"value"}],u7={label:a7,title:i7,titleGradient:o7,subtitle:l7,imgAlt:c7,items:d7},h7="Монетизация",m7="Как это ",p7="превращается в доход",f7="Путь от первого ролика до платных подписчиков и консультаций.",g7="Монетизация ИИ-персонажа",x7=[{num:"01",title:"ИИ-персонаж выпускает Shorts",text:"Короткие видео привлекают внимание и помогают тестировать темы."},{num:"02",title:"Бесплатные live-эфиры",text:"Эфиры выращивают доверие быстрее, чем обычные публикации."},{num:"03",title:"ИИ вовлекает аудиторию",text:"Ответы в реальном времени создают ощущение настоящего эксперта."},{num:"04",title:"Канал собирает ядро",text:"Shorts + эфиры + регулярность = лояльная аудитория."},{num:"05",title:"Подключаются платные слои",text:"Подписки, Patreon, платные эфиры, вебинары и архивы."}
867,{num:"06",title:"Появляются дорогие продукты",text:"Консультации 1-на-1, закрытые сессии и премиальные продукты."}],v7=["Внимание","Доверие","Платная глубина","Масштаб"],y7={label:h7,title:m7,titleGradient:p7,subtitle:f7,imgAlt:g7,steps:x7,funnel:v7},b7="Monetization",w7="How this ",j7="turns into revenue",_7="The path from your first video to paid subscribers and consultations.",k7="AI character monetization",N7=[{num:"01",title:"AI character releases Shorts",text:"Short videos attract attention and help test topics."},{num:"02",title:"Free live streams",text:"Streams build trust faster than regular posts."},{num:"03",title:"AI engages the audience",text:"Real-time responses create the feel of a real expert."},{num:"04",title:"Channel builds a core",text:"Shorts + streams + consistency = loyal audience."},{num:"05",title:"Paid layers connect",text:"Subscriptions, Patreon, paid streams, webinars, and archives."},{num:"06",title:"Premium products appear",text:"1-on-1 consultations, private sessions, and premium products."}],S7=["Attention","Trust","Paid depth","Scale"],C7={label:b7,title:w7,titleGradient:j7,subtitle:_7,imgAlt:k7,steps:N7,funnel:S7},T7="Экосистема",P7="YouTube для роста. Patreon для дохода. ",E7="Консультации для премиума.",A7="Публичная аудитория растёт на YouTube. Вовлечённые зрители переходят в платный слой.",R7="YouTube и Patreon экосистема",$7={title:"YouTube",desc:"Публичная площадка для Shorts, видео и live-эфиров.",items:["Shorts для охвата","Бесплатные эфиры","Рост бренда","Нативная монетизация","Подписки"]},L7={title:"Patreon",desc:"Платный слой с закрытым доступом и контентом.",items:["Платные уровни","Закрытые эфиры","Бонусный контент","Архив выступлений","Близкий формат"]},I7={title:"Консультации",desc:"Индивидуальные сессии и экспертные встречи.",items:["Голосовые 1-на-1","Экспертные разборы","Платные вебинары","Групповые сессии","Премиум-продукты"]},O7=["Shorts и live","Внимание и доверие","Платный клуб","Консультации","Премиальные продукты"],D7={label:T7,title:P7,titleGradient:E7,subtitle:A7,imgAlt:R7,youtube:$7,patreon:L7,consultations:I7,funnel:O7},M7="Ecosystem",z7="YouTube for growth. Patreon for revenue. ",F7="Consultations for premium.",U7="Your public audie
867nce grows on YouTube. Engaged viewers move to the paid layer.",B7="YouTube and Patreon ecosystem",V7={title:"YouTube",desc:"A public platform for Shorts, videos, and live streams.",items:["Shorts for reach","Free streams","Brand growth","Native monetization","Subscriptions"]},q7={title:"Patreon",desc:"A paid layer with exclusive access and content.",items:["Paid tiers","Private streams","Bonus content","Session archive","Close format"]},H7={title:"Consultations",desc:"Individual sessions and expert meetings.",items:["Voice 1-on-1","Expert analysis","Paid webinars","Group sessions","Premium products"]},W7=["Shorts & live","Attention & trust","Paid club","Consultations","Premium products"],G7={label:M7,title:z7,titleGradient:F7,subtitle:U7,imgAlt:B7,youtube:V7,patreon:q7,consultations:H7,funnel:W7},Y7="Маршрут",K7="Путь от нуля до ",Q7="системного дохода",J7="9 шагов от первого ролика до премиальных продуктов.",Z7="Путь новичка",X7=[{title:"Выберите роль ИИ-персонажа",text:"Блогер, ведущий или консультант — начните с одного формата."},{title:"Определите тему и нишу",text:"AI, обучение, бизнес, языки, личный бренд или экспертные разборы."},{title:"Подключите YouTube",text:"Сделайте YouTube основной площадкой для публичного контента."},{title:"Создайте первые Shorts",text:"Короткие видео для тестирования тем и набора охвата."},{title:"Запустите первые live-эфиры",text:"Бесплатные прямые эфиры для роста доверия аудитории."},{title:"Соберите лояльное ядро",text:"Регулярный контент + эфиры = ваша постоянная аудитория."},{title:"Подключите Patreon",text:"Добавьте платный слой с закрытым контентом и подписками."},{title:"Запустите консультации",text:"Голосовые 1-на-1 как отдельный платный продукт."},{title:"Масштабируйте доход",text:"Вебинары, интенсивы и премиальные продукты."}],eH={label:Y7,title:K7,titleHighlight:Q7,subtitle:J7,imgAlt:Z7,steps:X7},tH="Roadmap",sH="From zero to ",nH="systematic revenue",rH="9 steps from your first video to premium products.",aH="Beginner's path",iH=[{title:"Choose your AI character role",text:"Blogger, host, or consultant — start with one format."},{title:"Define your topic and niche",text:"AI, education, business, languages, personal brand, or expert analysis."},{title:"Connect YouTube",text:"Make YouTube your primary platform for public content."},{title:"Create your first Shorts",text:"Short videos for testing topics and gaining reach."},{title:"Launch your first live streams",text:"Free live streams to build audience trust."},{title:"Build a loyal core",text:"Regular content + streams = your consistent audience."},{title:"Connect Patreon",text:"Add a paid layer with exclusive content and subscriptions."},{title:"Launch consultations",text:"Voice 1-on-1 as a standalone paid product."},{title:"Scale your revenue",text:"Webinars, intensives, and premium products."}],oH={label:tH,title:sH,titleHighlight:nH,subtitle:rH,imgAlt:aH,steps:iH},lH="Админка, построенная вокруг ",cH="роста и монетизации",dH="Не набор инструментов, а понятная система управления ИИ-медиа-бизнесом.",uH=[{title:"Следующий лучший шаг",text:"Система всегда показывает, что важнее сделать прямо сейчас."},{title:"Контентный pipeline",text:"Идеи, Shorts, live-сессии, нарезки, повторное использование — всё в одном потоке."},{title:"Управление ИИ-персонажем",text:"Роль, стиль, темы, тип выступлений и монетизационная модель."},{title:"Дашборд роста",text:"Путь от первого контента до Ñ
867Ð´Ñ€Ð° аудитории и первой выручки."},{title:"Центр монетизации",text:"Подписки, Patreon, платные эфиры, вебинары и консультации."},{title:"Управление продуктами",text:"Управление консультациями, закрытыми эфирами, архивами и премиальными продуктами."}],hH={title:lH,titleGradient:cH,subtitle:dH,items:uH},mH="A dashboard built around ",pH="growth and monetization",fH="Not a set of tools, but a clear system for managing an AI media business.",gH=[{title:"Next best step",text:"The system always shows what's most important to do right now."},{title:"Content pipeline",text:"Ideas, Shorts, live sessions, clips, repurposing — all in one flow."},{title:"AI character management",text:"Role, style, topics, performance type, and monetization model."},{title:"Growth dashboard",text:"The path from first content to audience core and first revenue."},{title:"Monetization center",text:"Subscriptions, Patreon, paid streams, webinars, and consultations."},{title:"Product management",text:"Manage consultations, private streams, archives, and premium products."}],xH={title:mH,titleGradient:pH,subtitle:fH,items:gH},vH="FAQ",yH="Частые вопросы",bH=[{q:"Это просто генератор роликов?",a:"Нет. Это платформа для запуска ИИ-блогеров, ИИ-ведущих и ИИ-консультантов, которые говорят, выступают и участвуют в монетизации."},{q:"Что может делать ИИ-персонаж?",a:"Создавать видео, выступать в live, отвечать на вопросы, вести разборы, проводить консультации и давать материал для нарезок."},{q:"С чего лучше начинать?",a:"YouTube-канал, первые Shorts и несколько бесплатных live-эфиров, затем Patreon и более дорогие продукты."},{q:"Patreon обязателен?",a:"Нет. YouTube может быть основной площадкой. Patreon — следующий платный слой."},{q:"Можно ли использовать для консультаций?",a:"Да. ИИ-консультант работает для голосовых консультаций, разборов и экспертных сессий."},{q:"Можно ли делать контент из эфиров?",a:"Да. Эфиры и консультации превращаются в Shorts, клипы, тизеры и архивный контент."},{q:"Это для быстрого заработка?",a:"Нет. Это система для создания цифрового актива через внимание, доверие и платные предложения."}],wH={label:vH,title:yH,faqs:bH},jH="FAQ",_H="Frequently Asked Questions",kH=[{q:"Is this just a video generator?",a:"No. It's a platform for launching AI bloggers, AI hosts, and AI consultants that speak, perform, and participate in monetization."},{q:"What can an AI character do?",a:"Create videos, go live, answer questions, lead discussions, conduct consultations, and provide material for clips."},{q:"Where should I start?",a:"A YouTube channel, first Shorts, and a few free live streams, then Patreon and more premium products."},{q:"Is Patreon required?",a:"No. YouTube can be the main platform. Patreon is the next paid layer."},{q:"Can it be used for consultations?",a:"Yes. The AI consultant works for voice consultations, analysis, and expert sessions."},{q:"Can I create content from streams?",a:"Yes. Streams and consultations turn into Shorts, clips, teasers, and archive content."},{q:"Is this a get-rich-quick scheme?",a:"No. It's a system for building a digital asset through attention, trust, and paid offerings."}],NH={label:jH,title:_H,faqs:kH},SH="Тарифы",CH="Выберите план для ваших целей",TH="Начните бесплатно и масштабируйтесь по мере роста.",PH="Ежемесячно",EH="Ежегодно",AH="−20%",RH="/ мес",$H="/ мес/год",LH="Рекомендуем",IH="$",OH="Все цены в USD. Оплата картой или по счёту. Отмена в любой момент.",DH="Вопросы о тарифах",MH=[{name:"Free",tagline:"Попробовать и запустить основу",desc:"Создайте первого ИИ-персонажа и изучите платформу.",cta:"Начать бесплатно",features:["1 ИИ-персонаж","Базовый контент-план","Ограниченная генерация Shorts","Базовый путь запуска","Demo dashboard","Базовый live planning"]},{name:"Pro",tagline:"Строить и монетизировать",desc:"Активное развитие канала, live-форматов и стека монетизации.",cta:"Выбрать Pro",features:["Несколько ИИ-персонажей","Расширенная генерация Shorts","Центр эфиров","Переработка контента","Центр монетизации","Интеграция YouTube","Готовность к Patreon","Премиум-шаблоны","Расширенная админка"]},{name:"Бизнес",tagline:"Масштабировать как систему",desc:"Для брендов, команд и крупных запусков.",cta:"Выбрать Бизнес",features:["Мульти-персонажи","Командная работа","Контроль бренда","Расширенная аналитика","Премиум-поддержка","Консультации и вебинары","Расширенные инструменты"]}],zH=[{q:"Можно ли начать бесплатно?",a:"Да. Тариф Free позволяет создать первого ИИ-персонажа и попробовать генерацию Shorts без оплаты."},{q:"Можно ли сменить тариф позже?",a:"Да, переход на другой тариф возможен в любой момент."},{q:"Что произойдёт при исчерпании лимита?",a:"Генерация нового контента приостановится до перехода на платный тариф."},{q:"Входит ли Patreon в тариф?",a:"Интеграция Patreon доступна начиная с Pro. Сам Patreon бесплатен."},{q:"Нужен ли YouTube для старта?",a:"YouTube рекомендуется, но не обязателен. Можно начать с генерации контента."}],FH={label:SH,title:CH,subtitle:TH,monthly:PH,yearly:EH,discount:AH,perMonth:RH,perMonthYear:$H,recommended:LH,currency:IH,allPricesNote:OH,faqTitle:DH,plans:MH,faqs:zH},UH="Pricing",BH="Choose a plan for your goals",VH="Start for free and scale as you grow.",qH="Monthly",HH="Yearly",WH="−20%",GH="/ mo",YH="/ mo/yr",KH="Recommended",QH="$",JH="All prices in USD. Pay by card or invoice. Cancel anytime.",ZH="Pricing FAQ",XH=[{name:"Free",tagline:"Try it and build the foundation",desc:"Create your first AI character and explore the platform.",cta:"Start for Free",features:["1 AI character","Basic content plan","Limited Shorts generation","Basic launch path","Demo dashboard","Basic live planning"]},{name:"Pro",tagline:"Build and monetize",desc:"Active channel development, live formats, and monetization stack.",cta:"Choose Pro",features:["Multiple AI characters","Extended Shorts generation","Live center","Content repurposing","Monetization center","YouTube integration","Patreon readiness","Premium templates","Extended dashboard"]},{name:"Business",tagline:"Scale as a system",desc:"For brands, teams, and large launches.",cta:"Choose Business",features:["Multi-characters","Team collaboration","Brand control","Advanced analytics","Premium support","Consultations & webinars","Advanced tools"]}],eW=[{q:"Can I start for free?",a:"Yes. The Free plan lets you create your first AI character and try Shorts generation without payment."},{q:"Can I change plans later?",a:"Yes, switching plans is possible at any time."},{q:"What happens when limits are reached?",a:"New content generation pauses until you upgrade to a paid plan."},{q:"Is Patreon included?",a:"Patreon integration is available starting from Pro. Patreon itself is free."},{q:"Is YouTube required to start?",a:"YouTube is recommended but not required. You can start with content generation."}],tW={label:UH,title:BH,subtitle:VH,monthly:qH,yearly:HH,discount:WH,perMonth:GH,perMonthYear:YH,recommended:KH,currency:QH,allPricesNote:JH,faqTitle:ZH,plans:XH,faqs:eW},sW="Запустите ИИ-персонажа, который ",nW="работает как ваш цифровой актив",rW="Shorts, live-эфиры, ответы аудитории, платные подписки и консультации — с ИИ-блогером, ИИ-ведущим или ИИ-консультантом.",aW="Начать бесплатно",iW="Как это работает",oW="Полноценный ИИ-персонаж для медиа, общения и монетизации.",lW="Начните сейчас",cW={title:sW,titleGradient:nW,subtitle:rW,ctaPrimary:aW,ctaSecondary:iW,note:oW,imgAlt:lW},dW="Launch an AI character that ",uW="works as your digital asset",hW="Shorts, live streams, audience responses, paid subscriptions, and consultations — with an AI blogger, AI host, or AI consultant.",mW="Start for Free",pW="How It Works",fW="A full-featured AI character for media, engagement, and monetization.",gW="Start now",xW={title:dW,titleGradient:uW,subtitle:hW,ctaPrimary:mW,ctaSecondary:pW,note:fW,imgAlt:gW},vW={howItWorks:"Как это работает",cases:"Кейсы",pricing:"Тарифы",faq:"FAQ"},yW="Войти",bW="Начать бесплатно",wW={ru:"рус",en:"en",ge:"ge",fr:"fr"},jW={menu:vW,login:yW,startFree:bW,lang:wW},_W={howItWorks:"How it works",cases:"Cases",pricing:"Pricing",faq:"FAQ"},kW="Log in",NW="Start free",SW={ru:"ru",en:"en",ge:"ge",fr:"fr"}
867,CW={menu:_W,login:kW,startFree:NW,lang:SW},TW="Цифровые персонажи,<br/>которые говорят,<br/>выступают и консультируют",PW="Платформа для запуска ИИ-блогеров, ИИ-ведущих и ИИ-консультантов. Создавайте контент, ведите эфиры, отвечайте аудитории и монетизируйте экспертность.",EW="Начать бесплатно",AW="Как это работает",RW={title:TW,subtitle:PW,ctaPrimary:EW,ctaSecondary:AW},$W="Digital characters that<br/>speak, perform and consult",LW="A platform to launch AI bloggers, AI hosts and AI consultants. Create content, run live streams, engage your audience and monetize your expertise.",IW="Start free",OW="How it works",DW={title:$W,subtitle:LW,ctaPrimary:IW,ctaSecondary:OW},MW="ПЛАТФОРМА",zW="Не генератор контента.<br/>Система запуска ИИ-персонажей.",FW="Вы создаёте цифрового блогера, ведущего или консультанта,<br/>который регулярно выступает, отвечает аудитории и приносит доход.",UW=[{name:"ИИ-блогер",text:"<strong>ИИ-блоггер</strong> создаёт короткие видео, говорит от лица вашего бренда, регулярно выпускает контент и помогает тестировать темы в Shorts-формате."},{name:"ИИ-ведущий",text:"<strong>ИИ-ведущий</strong> выходит в live-эфиры, ведёт темы, отвечает на вопросы аудитории в реальном времени и делает ваши прямые эфиры более живыми."},{name:"ИИ-консультант",text:"<strong>ИИ-консультант</strong> проводит голосовые консультации 1-на-1, объясняет, разбирает ситуации и превращает экспертность в оплачиваемый сервис."}],BW={label:MW,title:zW,subtitle:FW,items:UW},VW="PLATFORM",qW="Not a content generator.<br/>A launch system for AI characters.",HW="You create a digital blogger, host, or consultant<br/>who performs regularly, engages your audience, and generates revenue.",WW=[{name:"AI Blogger",text:"<strong>An AI blogger</strong> records short videos, speaks for your brand, ships content consistently, and helps you test topics in Shorts format."},{name:"AI Host",text:"<strong>An AI host</strong> goes live, runs topics, answers audience questions in real time, and makes your live streams feel alive."},{name:"AI Consultant",text:"<strong>An AI consultant</strong> runs 1-on-1 voice sessions, explains, walks through situations, and turns your expertise into a paid service."}],GW={label:VW,title:qW,subtitle:HW,items:WW},YW="ВОЗМОЖНОСТИ",KW="Что может ваш ИИ-персонаж?",QW="Один персонаж — контент-машина, live-хост, консультант<br/>и основа вашей медиа-воронки.",JW="Начать бесплатно",ZW=[{icon:"feature_1",title:"Записывать короткие видео",text:"Shorts для тестирования тем и набора охвата."},{icon:"feature_5",title:"Проводить консультации",text:"Индивидуальные созвоны и сессии."},{icon:"feature_2",title:"Вести регулярные рубрики",text:"Повторяемый формат для узнаваемого канала."},{icon:"feature_6",title:"Записывать разборы",text:"Экспертный контент для монетизации."},{icon:"feature_3",title:"Выступать в прямом эфире",text:"Live-сессии с удержанием внимания."},{icon:"feature_7",title:"Давать материал для нарезок",text:"Эфиры → Shorts, клипы и промо."},{icon:"feature_4",title:"Отвечать в live-чате",text:"Реакция на сообщения зрителей."},{icon:"feature_8",title:"Работать 24/7 как актив",text:"ИИ-персонаж ценнее со временем."}
867],XW={label:YW,title:KW,subtitle:QW,cta:JW,items:ZW},eG="CAPABILITIES",tG="What can your AI character do?",sG="One character — a content engine, a live host, a consultant,<br/>and the backbone of your media funnel.",nG="Start free",rG=[{icon:"feature_1",title:"Record short videos",text:"Shorts to test topics and grow reach."},{icon:"feature_5",title:"Run consultations",text:"1-on-1 calls and personal sessions."},{icon:"feature_2",title:"Run regular formats",text:"A repeatable format for a recognizable channel."},{icon:"feature_6",title:"Record deep dives",text:"Expert content built for monetization."},{icon:"feature_3",title:"Go live",text:"Live sessions that hold attention."},{icon:"feature_7",title:"Feed your clip pipeline",text:"Streams → Shorts, clips, and promos."},{icon:"feature_4",title:"Answer the live chat",text:"Real reactions to viewer messages."},{icon:"feature_8",title:"Work 24/7 as an asset",text:"An AI character grows more valuable over time."}],aG={label:eG,title:tG,subtitle:sG,cta:nG,items:rG},iG="Ваш ИИ не просто говорит.<br/>Он может",oG=["вести","отвечать","консультировать"],lG="и",cG="Один ИИ-персонаж работает в нескольких форматах — от публичного live до приватной консультации.",dG=[{title:"Бесплатные live-эфиры",text:"Открытые сессии для роста аудитории и знакомства с персонажем."},{title:"Q&A в реальном времени",text:"ИИ-ведущий отвечает на вопросы зрителей прямо во время эфира."},{title:"Голосовые консультации",text:"Индивидуальные сессии как отдельная платная услуга."},{title:"Тематические<br/>live-лекции",text:"ИИ выступает как эксперт по выбранной теме."},{title:"Закрытые<br/>платные live",text:"Глубокие эфиры для подписчиков и закрытых сообществ."}],uG={title:iG,titleAccents:oG,and:lG,subtitle:cG,items:dG},hG="Your AI doesn't just talk.<br/>It can",mG=["host","respond","consult"],pG="and",fG="One AI character works across formats — from public live streams to private consultations.",gG=[{title:"Free live streams",text:"Open sessions to grow your audience and introduce your character."},{title:"Real-time Q&A",text:"The AI host answers viewer questions live, on the spot."},{title:"Voice consultations",text:"Personal 1-on-1 sessions sold as a paid service."},{title:"Topical<br/>live lectures",text:"Your AI performs as an expert on a chosen topic."},{title:"Paid private<br/>live",text:"Deep streams for subscribers and closed communities."}],xG={title:hG,titleAccents:mG,and:pG,subtitle:fG,items:gG},vG="МОНЕТИЗАЦИЯ",yG="Как это превращается в доход",bG="Путь от первого ролика до платных подписчиков и консультаций.",wG=[{title:"Записывать короткие видео",text:"Короткие видео привлекают внимание и помогают тестировать темы."},{title:"Бесплатные live-эфиры",text:"Эфиры выращивают доверие быстрее, чем обычные публикации."},{title:"ИИ вовлекает аудиторию",text:"Ответы в реальном времени создают ощущение настоящего эксперта."},{title:"Канал собирает ядро",text:"Shorts + эфиры + регулярность = лояльная аудитория."},{title:"Подключаются платные слои",text:"Подписки, Patreon, платные эфиры, вебинары и архивы."},{title:"Появляются дорогие продукты",text:"Консультации 1-на-1, закрытые сессии и премиальные продукты."}],jG={label:vG,title:yG,subtitle:bG,items:wG},_G="MONETIZATION",kG="How this turns into revenue",NG="The path from your first clip to paying subscribers and consultations.",SG=[{title:"Record short videos",text:"Shorts capture attention and let you test topics fast."},{title:"Run free live streams",text:"Live builds trust faster than regular posts."},{title:"AI engages the audience",text:"Real-time responses make it feel like a real expert."},{title:"The channel forms a core",text:"Shorts + live + consistency = a loyal audience."},{title:"Paid layers come online",text:"Subscriptions, Patreon, paid streams, webinars, archives."},{title:"High-ticket products appear",text:"1-on-1 consultations, closed sessions, premium offers."}],CG={label:_G,title:kG,subtitle:NG,items:SG}
867,TG="ТАРИФЫ",PG="Выберите план для ваших целей",EG="Начните бесплатно и масштабируйтесь по мере роста.",AG="/мес/год",RG="Ежемесячно",$G="Ежегодно",LG="Все цены в USD. Оплата картой или по счёту. Отмена в любой момент.",IG=[{name:"Free",shortDesc:"Попробовать и запустить основу",price:"$0",desc:"Создайте первого ИИ-персонажа и изучите платформу.",features:["1 ИИ-персонаж","Базовый контент-план","Ограниченная генерация Shorts","Базовый путь запуска","Demo dashboard","Базовый live planning"],cta:"Начать бесплатно"},{name:"Pro",shortDesc:"Строить и монетизировать",price:"$79",desc:"Активное развитие канала, live-форматов и стека монетизации.",features:["Несколько ИИ-персонажей","Расширенная генерация Shorts","Центр эфиров","Переработка контента","Центр монетизации","Интеграция YouTube","Готовность к Patreon","Премиум-шаблоны","Расширенная админка"],cta:"Выбрать Pro",highlight:!0},{name:"Business",shortDesc:"Масштабировать как систему",price:"$349",desc:"Для брендов, команд и крупных запусков.",features:["Мульти-персонажи","Командная работа","Контроль бренда","Расширенная аналитика","Премиум-поддержка","Консультации и вебинары","Расширенные инструменты"],cta:"Выбрать Business"}],OG={label:TG,title:PG,subtitle:EG,perMonth:AG,monthly:RG,yearly:$G,footnote:LG,items:IG},DG="PRICING",MG="Pick the plan for your goals",zG="Start free and scale as you grow.",FG="/mo/yr",UG="Monthly",BG="Yearly",VG="All prices in USD. Pay by card or invoice. Cancel anytime.",qG=[{name:"Free",shortDesc:"Try and launch the basics",price:"$0",desc:"Create your first AI persona and explore the platform.",features:["1 AI persona","Basic content plan","Limited Shorts generation","Basic launch path","Demo dashboard","Basic live planning"],cta:"Start free"},{name:"Pro",shortDesc:"Build and monetize",price:"$79",desc:"Active channel development, live formats and monetization stack.",features:["Multiple AI personas","Extended Shorts generation","Live center","Content repurposing","Monetization center","YouTube integration","Patreon-ready","Premium templates","Extended admin"],cta:"Choose Pro",highlight:!0},{name:"Business",shortDesc:"Scale as a system",price:"$349",desc:"For brands, teams and large launches.",features:["Multi-personas","Team collaboration","Brand control","Advanced analytics","Premium support","Consultations & webinars","Extended toolset"],cta:"Choose Business"}],HG={label:DG,title:MG,subtitle:zG,perMonth:FG,monthly:UG,yearly:BG,footnote:VG,items:qG},WG="ЭКОСИСТЕМА",GG="YouTube для роста. Patreon для дохода.<br/>Консультации для премиума.",YG="Публичная аудитория растёт на YouTube.<br/>Вовлечённые зрители переходят в платный слой.",KG=[{name:"YouTube",text:"Публичная площадка для Shorts, видео и live-эфиров.",list:["Shorts для охвата","Бесплатные эфиры","Рост бренда","Нативная монетизация","Подписки"]},{name:"Patreon",text:"Платный слой с закрытым доступом и контентом.",list:["Платные уровни","Закрытые эфиры","Бонусный контент","Архив выступлений","Близкий формат"]},{name:"Консультации",text:"Индивидуальные сессии и экспертные встречи.",list:["Голосовые 1-на-1","Экспертные разборы","Платные вебинары","Групповые сессии","Премиум-продукты"]}
867],QG={label:WG,title:GG,subtitle:YG,items:KG},JG="ECOSYSTEM",ZG="YouTube for growth. Patreon for revenue.<br/>Consultations for premium.",XG="Public audience grows on YouTube.<br/>Engaged viewers move to the paid layer.",eY=[{name:"YouTube",text:"Public stage for Shorts, videos and live streams.",list:["Shorts for reach","Free streams","Brand growth","Native monetization","Memberships"]},{name:"Patreon",text:"Paid layer with private access and content.",list:["Paid tiers","Private streams","Bonus content","Talk archive","Close format"]},{name:"Consultations",text:"1-on-1 sessions and expert meetups.",list:["Voice 1-on-1","Expert reviews","Paid webinars","Group sessions","Premium products"]}],tY={label:JG,title:ZG,subtitle:XG,items:eY},sY="МАРШРУТ",nY="Путь от нуля до системного дохода",rY="9 шагов от первого ролика до премиальных продуктов.",aY="Начать бесплатно",iY=[{title:"Выберите роль<br/>ИИ-персонажа",text:"Блогер, ведущий или консультант — начните с одного формата."},{title:"Определите тему<br/>и нишу",text:"AI, обучение, бизнес, языки, личный бренд или экспертные разборы."},{title:"Подключите<br/>YouTube",text:"Сделайте YouTube основной площадкой для публичного контента."},{title:"Создайте первые<br/>Shorts",text:"Короткие видео для тестирования тем и набора охвата."},{title:"Запустите первые<br/>live-эфиры",text:"Короткие видео для тестирования тем и набора охвата."}],oY={label:sY,title:nY,subtitle:rY,cta:aY,items:iY},lY="ROADMAP",cY="From zero to systematic revenue",dY="9 steps from your first video to premium products.",uY="Start free",hY=[{title:"Pick the AI<br/>persona role",text:"Blogger, host or consultant — start with one format."},{title:"Define topic<br/>and niche",text:"AI, education, business, languages, personal brand or expert reviews."},{title:"Connect<br/>YouTube",text:"Make YouTube your main public content stage."},{title:"Publish first<br/>Shorts",text:"Short videos to test topics and grow reach."},{title:"Launch first<br/>live streams",text:"Short videos to test topics and grow reach."}],mY={label:lY,title:cY,subtitle:dY,cta:uY,items:hY},pY="ФОРМАТЫ ДОХОДА",fY="Один ИИ-персонаж — несколько путей к доходу",gY="Ваш блогер, ведущий или консультант работает сразу в нескольких моделях монетизации.",xY="Начать бесплатно",vY=[{title:"YouTube-монетизация",text:"Нативная монетизация<br/>по мере роста канала."},{title:"Платные подписки",text:"Клуб с эксклюзивным доступом<br/>и закрытыми эфирами."},{title:"Платные live-эфиры",text:"Обучающие и премиальные<br/>сессии для аудитории."},{title:"Вебинары",text:"Структурированные платные<br/>выступления по темам."},{title:"Голосовые консультации",text:"Платный формат прямой<br/>помощи и разборов."},{title:"Архив и бонусный контент",text:"Записи эфиров и<br/>дополнительные материалы."},{title:"Премиальные продукты",text:"Образовательные пакеты<br/>и интенсивы."}],yY={label:pY,title:fY,subtitle:gY,cta:xY,items:vY},bY="REVENUE FORMATS",wY="One AI persona — multiple paths to income",jY="Your blogger, host, or consultant works across several monetization models.",_Y="Start for free",kY=[{title:"YouTube monetization",text:"Native monetization<br/>as your channel grows."},{title:"Paid subscriptions",text:"A club with exclusive access<br/>and closed streams."},{title:"Paid live streams",text:"Educational and premium<br/>sessions for your audience."},{title:"Webinars",text:"Structured paid talks<br/>on focused topics."},{title:"Voice consultations",text:"Direct paid help<br/>and 1:1 reviews."},{title:"Archive & bonus content",text:"Stream recordings and<br/>extra materials."},{title:"Premium products",text:"Educational packages<br/>and intensives."}
867],NY={label:bY,title:wY,subtitle:jY,cta:_Y,items:kY},SY="ПРЕИМУЩЕСТВА",CY="Почему это лучше, чем делать всё вручную",TY="Запустите ИИ-персонажа, который возьмёт на себя контент, эфиры и консультации.",PY=[{number:"10×",unit:"быстрее",title:"Экономия времени",text:"ИИ-персонаж создаёт контент, ведёт эфиры и консультирует — вы тратите часы вместо недель."},{number:"24/7",unit:"готов",title:"ИИ говорит сам",text:"Не нужно записывать себя, монтировать или быть на камере."},{number:"∞",unit:"персонажей",title:"Масштаб без команды",text:"Один человек управляет несколькими<br/>ИИ-персонажами."},{number:"20+",unit:"единиц",title:"Бесконечный контент-цикл",text:"Один эфир → 5–20 единиц контента: Shorts, клипы, тизеры, архив."}],EY={label:SY,title:CY,subtitle:TY,items:PY},AY="ADVANTAGES",RY="Why it's better than doing it all by hand",$Y="Launch an AI persona that handles content, streams and consultations for you.",LY=[{number:"10×",unit:"faster",title:"Save time",text:"AI persona creates content, runs streams and consults — hours instead of weeks."},{number:"24/7",unit:"ready",title:"AI speaks for itself",text:"No need to film yourself, edit, or be on camera."},{number:"∞",unit:"personas",title:"Scale without a team",text:"One person manages multiple<br/>AI personas."},{number:"20+",unit:"assets",title:"Endless content loop",text:"One stream → 5–20 pieces of content: Shorts, clips, teasers, archive."}],IY={label:AY,title:RY,subtitle:$Y,items:LY},OY="FAQ",DY="Частые вопросы",MY="Все вопросы",zY=[{q:"Это просто генератор роликов?",a:"Нет. Это платформа для запуска ИИ-блогеров, ИИ-ведущих и ИИ-консультантов, которые говорят, выступают и участвуют в монетизации."},{q:"Что может делать ИИ-персонаж?",a:"Нет. Это платформа для запуска ИИ-блогеров, ИИ-ведущих и ИИ-консультантов, которые говорят, выступают и участвуют в монетизации."},{q:"С чего лучше начинать?",a:"Нет. Это платформа для запуска ИИ-блогеров, ИИ-ведущих и ИИ-консультантов, которые говорят, выступают и участвуют в монетизации."},{q:"Patreon обязателен?",a:"Нет. Это платформа для запуска ИИ-блогеров, ИИ-ведущих и ИИ-консультантов, которые говорят, выступают и участвуют в монетизации."},{q:"Можно ли использовать для консультаций?",a:"Нет. Это платформа для запуска ИИ-блогеров, ИИ-ведущих и ИИ-консультантов, которые говорят, выступают и участвуют в монетизации."},{q:"Можно ли делать контент из эфиров?",a:"Нет. Это платформа для запуска ИИ-блогеров, ИИ-ведущих и ИИ-консультантов, которые говорят, выступают и участвуют в монетизации."}],FY={label:OY,title:DY,more:MY,items:zY},UY="FAQ",BY="Frequently asked questions",VY="All questions",qY=[{q:"Is this just a video generator?",a:"No. It's a platform to launch AI bloggers, AI hosts and AI consultants that talk, perform and participate in monetization."},{q:"What can an AI persona do?",a:"No. It's a platform to launch AI bloggers, AI hosts and AI consultants that talk, perform and participate in monetization."},{q:"Where should I start?",a:"No. It's a platform to launch AI bloggers, AI hosts and AI consultants that talk, perform and participate in monetization."},{q:"Is Patreon required?",a:"No. It's a platform to launch AI bloggers, AI hosts and AI consultants that talk, perform and participate in monetization."},{q:"Can I use it for consultations?",a:"No. It's a platform to launch AI bloggers, AI hosts and AI consultants that talk, perform and participate in monetization."},{q:"Can I make content from streams?",a:"No. It's a platform to launch AI bloggers, AI hosts and AI consultants that talk, perform and participate in monetization."}],HY={label:UY,title:BY,more:VY,items:qY},WY="Запустите ИИ-персонажа,<br/>который работает как ваш цифровой актив",GY="Shorts, live-эфиры, ответы аудитории, платные подписки и консультации —<br/>с ИИ-блогером, ИИ-ведущим или ИИ-консультантом.",YY="Начать бесплатно",KY="Как это работает",QY={title:WY,subtitle:GY,ctaPrimary:YY,ctaSecondary:KY},JY="Launch an AI persona<br/>
867that works as your digital asset",ZY="Shorts, live streams, audience replies, paid subscriptions and consultations — with an AI blogger, AI host or AI consultant.",XY="Start for free",eK="How it works",tK={title:JY,subtitle:ZY,ctaPrimary:XY,ctaSecondary:eK},sK="Платформа для запуска ИИ-блогеров, ИИ-ведущих и ИИ-консультантов.",nK=[{label:"Как это работает",href:"/how-it-works"},{label:"Кейсы",href:"/use-cases"},{label:"Тарифы",href:"#pricing"},{label:"FAQ",href:"#faq"}],rK=[{label:"Cookie-политика",href:"/cookies"},{label:"Конфиденциальность",href:"/privacy"},{label:"Условия",href:"/terms"},{label:"Оферта",href:"/offer"}],aK={tagline:sK,menu1:nK,menu2:rK},iK="A platform to launch AI bloggers, AI hosts and AI consultants.",oK=[{label:"How it works",href:"/how-it-works"},{label:"Use cases",href:"/use-cases"},{label:"Pricing",href:"#pricing"},{label:"FAQ",href:"#faq"}],lK=[{label:"Cookie Policy",href:"/cookies"},{label:"Privacy",href:"/privacy"},{label:"Terms",href:"/terms"},{label:"Offer",href:"/offer"}],cK={tagline:iK,menu1:oK,menu2:lK},dK="Панель управления",uK="Создавайте Shorts, проводите live-эфиры, отвечайте аудитории в реальном времени и превращайте выступления в доход.",hK="Создать персонажа",mK="Путь запуска",pK="Путь запуска",fK="{{done}}/{{total}} выполнено",gK="Что можно делать в платформе",xK="Требует внимания",vK="{{count}} задача выполняется в фоне",yK="{{count}} задачи выполняется в фоне",bK="{{count}} задач выполняется в фоне",wK="Подробнее →",jK="Свернуть",_K="Показать весь текст",kK="Предпросмотр",NK="Скачать",SK="Подключите соцсети",CK="Публикуется…",TK="Опубликовано везде",PK="Опубликовать ещё в {{count}}",EK="Опубликовать",AK="Не удалось опубликовать",RK="Предпросмотр недоступен",$K="Привяжите соцсети в разделе Интеграции",LK="Уже опубликовано во все подключённые сети",IK="Публикация запущена в фоне — статус обновится автоматически",OK="Опубликовано: {{list}}",DK="Опубликовано: {{ok}}. Ошибки: {{fail}}",MK={title:"Активные задачи",viewAll:"Все задачи"},zK={persona:"Персонажи",content:"Создать short",live:"Запланировать live",analytics:"Аналитика"},FK={noPersona:"Создай первую персону",connectYt:"Подключи YouTube",noPersonaSub:"С неё начинается всё — голос, аватар, стиль для шортсов и эфиров.",connectYtSub:"Без YouTube не получится публиковать клипы и видеть аналитику.",connectBtn:"Подключить"},UK={title:"Готовые клипы",all:"Все эфиры",empty:"Пока нет готовых клипов.",processing:"Клипы есть, но ещё не готовы: {{pending}} в очереди, {{uploading}} загружается, {{failed}} с ошибкой.",noRows:"В базе пока нет нарезок из эфиров. Когда воркер создаст клипы, они появятся здесь."},BK={title:"Задачи с ошибкой (24ч)",subtitle:"Эти задачи завершились с ошибкой за последние 24 часа. Разберитесь или скройте уведомления.",dismiss:"Скрыть",dismissAll:"Скрыть все",retry:"Повторить",retrying:"Перезапуск…",retryError:"Не удалось перезапустить задачу",viewAll:"Все задачи с ошибкой ({{count}}) →"},VK={nextStep:"Следующий лучший шаг",shorts:"Shorts",live:"Live",youtube:"YouTube",patreon:"Patreon",monetization:"Монетизация"},qK={connectYoutube:"Подключите YouTube и создайте первый контент.",createFirstShort:"Создайте первый Shorts в Content Studio.",planFirstLive:"Запланируйте первый live-эфир.",connectPatreon:"Подключите Patreon для платного слоя.",keepCreating:"Продолжайте создавать контент и растить аудиторию.",noContent:"Ещё нет контента — создайте первый Shorts",publishedDrafts:"{{published}} опубликовано / {{drafts}} в работе",noLives:"Нет эфиров — запланируйте первый",nextLive:"Следующий: {{title}}",livesTotal:"{{count}} эфиров проведено",onAir:"В эфире",channelConnected:"Канал подключён",tokenExpired:"Токен истёк — переподключите",paidLayerActive:"Платный слой активен",paidLayerInactive:"Платный слой ещё не подключен",paidConnected:"Платный слой подключен"},HK={persona:"Persona",shorts:"Shorts",live:"Live",clips:"Нарезки",monetization:"Монетизация",paidOffers:"Платные офферы"},WK={bloggerTitle:"ИИ-блогер для коротких видео",bloggerText:"Создавайте Shorts автоматически, тестируйте темы и наращивайте охват без камеры и монтажа.",hostTitle:"ИИ-ведущий для live-эфиров",hostText:"Проводите прямые эфиры, где ИИ-персонаж ведёт тему и отвечает на вопросы аудитории в реальном времени.",consultantTitle:"ИИ-консультант для 1 на 1 сессий",consultantText:"Запускайте платные голосовые консультации, экспертные разборы и приватные сессии.",cycleTitle:"Контентный цикл из одного выступления",cycleText:"Один эфир превращается в Shorts, клипы, тизеры и архивный контент — автоматически."},GK={title:dK,subtitle:uK,createPersona:hK,launchPath:mK,launchRoadmap:pK,completedOf:fK,platformFeatures:gK,needsAttention:xK,tasksRunning_one:vK,tasksRunning_few:yK,tasksRunning_many:bK,details:wK,collapse:jK,exp
867and:_K,preview:kK,download:NK,connectSocialsCta:SK,publishingBtn:CK,publishedEverywhere:TK,publishMoreBtn:PK,publishBtn:EK,publishFailed:AK,clipPreviewFailed:RK,noSocialLinked:$K,toastNothingToDo:LK,toastPublishingBg:IK,toastPublishedTo:OK,toastPartial:DK,activeJobs:MK,qa:zK,onboard:FK,recentClips:UK,failedJobs:BK,statusCards:VK,statusTexts:qK,roadmapLabels:HK,featureCards:WK},YK="Dashboard",KK="Create Shorts, run live streams, respond to your audience in real time and turn broadcasts into revenue.",QK="Create persona",JK="Launch path",ZK="Launch roadmap",XK="{{done}}/{{total}} completed",eQ="What you can do on the platform",tQ="Needs attention",sQ="{{count}} task running in background",nQ="{{count}} tasks running in background",rQ="Details →",aQ="Collapse",iQ="Show full text",oQ="Preview",lQ="Download",cQ="Connect socials",dQ="Publishing…",uQ="Published everywhere",hQ="Publish to {{count}} more",mQ="Publish",pQ="Publish failed",fQ="Preview unavailable",gQ="Link social networks in Integrations",xQ="Already published to all connected networks",vQ="Publishing started in background — status will update automatically",yQ="Published to: {{list}}",bQ="Published to: {{ok}}. Errors: {{fail}}",wQ={title:"Active tasks",viewAll:"All tasks"},jQ={persona:"Personas",content:"Create short",live:"Schedule live",analytics:"Analytics"},_Q={noPersona:"Create your first persona",connectYt:"Connect YouTube",noPersonaSub:"It all starts here — voice, avatar, style for Shorts and streams.",connectYtSub:"Without YouTube you can't publish clips or see analytics.",connectBtn:"Connect"},kQ={title:"Ready clips",all:"All streams",empty:"No ready clips yet.",processing:"Clips exist but aren't ready: {{pending}} in queue, {{uploading}} uploading, {{failed}} failed.",noRows:"No clips from streams yet. Once the worker creates clips, they will appear here."},NQ={title:"Failed tasks (24h)",subtitle:"These tasks failed in the last 24 hours. Review the errors or dismiss the alerts.",dismiss:"Dismiss",dismissAll:"Dismiss all",retry:"Retry",retrying:"Retrying…",retryError:"Failed to retry task",viewAll:"View all {{count}} failed tasks →"},SQ={nextStep:"Next best step",shorts:"Shorts",live:"Live",youtube:"YouTube",patreon:"Patreon",monetization:"Monetization"},CQ={connectYoutube:"Connect YouTube and create your first content.",createFirstShort:"Create your first Short in Content Studio.",planFirstLive:"Schedule your first live stream.",connectPatreon:"Connect Patreon for paid tier.",keepCreating:"Keep creating content and growing your audience.",noContent:"No content yet — create your first Short",publishedDrafts:"{{published}} published / {{drafts}} in progress",noLives:"No streams — schedule your first",nextLive:"Next: {{title}}",livesTotal:"{{count}} streams held",onAir:"On Air",channelConnected:"Channel connected",tokenExpired:"Token expired — reconnect",paidLayerActive:"Paid tier active",paidLayerInactive:"Paid tier not connected yet",paidConnected:"Paid tier connected"},TQ={persona:"Persona",shorts:"Shorts",live:"Live",clips:"Clips",monetization:"Monetization",paidOffers:"Paid offers"},PQ={bloggerTitle:"AI blogger for short videos",bloggerText:"Create Shorts automatically, test topics and grow reach without camera or editing.",hostTitle:"AI host for live streams",hostText:"Run live streams where your AI persona leads the topic and answers audience questions in real time.",consultantTitle:"AI consultant for 1-on-1 sessions",consultantText:"Launch paid voice consultations, expert reviews and private sessions.",cycleTitle:"Content cycle from a single broadcast",cycleText:"One stream turns into Shorts, clips, teasers and archived content — automatically."},EQ={title:YK,subtitle:KK,createPersona:QK,launchPath:JK,launchRoadmap:ZK,completedOf:XK,platformFeatures:eQ,needsAttention:tQ,tasksRunning_one:sQ,tasksRunning_other:nQ,details:rQ,collapse:aQ,expand:iQ,preview:oQ,download:lQ,connectSocialsCta:cQ,publishingBtn:dQ,publishedEverywhere:uQ,publishMoreBtn:hQ,publishBtn:mQ,publishFailed:pQ,clipPreviewFailed:fQ,noSocialLinked:gQ,toastNothingToDo:xQ,toastPublishingBg:vQ,toastPublishedTo:yQ,toastParti
867al:bQ,activeJobs:wQ,qa:jQ,onboard:_Q,recentClips:kQ,failedJobs:NQ,statusCards:SQ,statusTexts:CQ,roadmapLabels:TQ,featureCards:PQ},AQ="Контент-студия",RQ="Создавайте короткие видео: сценарий → озвучка → видео → публикация на YouTube.",$Q={title:"Генератор Shorts",persona:"Персонаж",topic:"Тема",topicPlaceholder:"Как запустить ИИ-блог",format:"Формат",duration:"Длина (макс. 90 сек)",cta:"CTA",ctaDefault:"Подпишись и включи уведомления",language:"Язык",tone:"Tone / стиль (опционально)",tonePlaceholder:"Например: дружелюбный, но экспертный",generating:"Создание...",generate:"Создать идею Shorts"},LQ={hook:"Hook → Value → CTA",educational:"Обучающий",story:"Storytelling",list:"Listicle",commentary:"Комментарий",myth:"Разрушение мифа",qa:"Ответ на вопрос"},IQ={15:"15 сек (~33 слова)",30:"30 сек (~66 слов)",60:"60 сек (~132 слова)",90:"90 сек (~198 слов)"},OQ={ru:"Русский",en:"English"},DQ={title:"Опубликовано",noTitle:"Без названия",open:"Открыть →"},MQ={title:"Нарезки из live",subtitle:"Превратите одно выступление в контентный пакет — Shorts, клипы, тизеры",goToLive:"Перейти к эфирам",shorts:"Shorts",teasers:"Teaser-клипы",promo:"Промо-пост",archive:"Архивный ассет"},zQ={title:"Контентный цикл",shorts:"Shorts",attention:"Внимание",live:"Live",clips:"Нарезки",newShorts:"Новые Shorts",premium:"Premium"},FQ={noTitle:"Без названия",deleteTitle:"Удалить этот шот?",deleteDesc:"Будут удалены сценарий, аудио и видео. Это действие нельзя отменить.",cancel:"Отмена",delete:"Удалить",stepScript:"Сценарий",stepVoice:"Озвучка",stepVideo:"Видео",stepPublish:"Публикация",statusGenerating:"ИИ пишет сценарий…",statusScript:"Сценарий готов — проверьте и озвучьте",statusVoicing:"Озвучка идёт…",statusAudio:"Аудио готово — создайте видео",statusRendering:"Видео собирается…",statusVideo:"Видео готово — можно опубликовать",statusPublishing:"Публикация…",statusPublished:"Опубликовано ✓",statusFailed:"Ошибка",aiGenerating:"ИИ генерирует сценарий…",scriptPlaceholder:"Сценарий…",voiceBtn:"Озвучить",rewriteBtn:"Переписать",voicingProgress:"Озвучка генерируется…",createVideo:"Создать видео",promptOverrideLabel:"Промпт для видео (необязательно)",promptOverridePlaceholder:"Оставьте пустым — используется промпт из персоны. Введите текст, чтобы переопределить effective_prompt для этой генерации.",subtitlesLabel:"Вшить субтитры",subtitlesDesc:"Слова по форсед-алигменту прямо в кадре",sampleStepsLabel:"Шаги сэмплинга",sampleStepsDesc:"От 4 (быстрее) до 12 (детальнее). По умолчанию 10",watermarkLabel:"Водяной знак / реклама (необязательно)",watermarkPlaceholder:"Created by VlogMe.AI",watermarkDesc:"Необязательный текст, который воркер вшивает в финальное видео. Оставьте пустым, чтобы не добавлять. Максимум 120 символов.",back:"Назад",renderPreparing:"Подготовка…",renderGenerating:"Генерация видео…",renderProcessing:"Обработка видео…",renderEnhancing:"Улучшение видео…",renderFinis
867hing:"Завершение обработки…",renderUploading:"Загрузка видео…",renderUploadingServer:"Видео рендерится, загружается на сервер",renderSafe:"Можно уйти со страницы — прогресс не потеряется",privacyLabel:"Приватность:",privacyUnlisted:"По ссылке",privacyPublic:"Публичное",privacyPrivate:"Приватное",publishBtn:"Опубликовать",publishSocialBtn:"Опубликовать в выбранные",publishingSocial:"Публикуется…",socialPublishTitle:"Опубликовать в соцсети",socialNotLinked:"Привяжите соцсети в разделе Интеграции → Социальный хаб.",socialQueued:"В очереди публикации",scheduleLabel:"Отложенная публикация",scheduleHours:"ч после последнего отложенного",saveBtn:"Сохранить",saveLinkFailed:"Не удалось получить ссылку на видео",saveDownloadFailed:"Не удалось загрузить видео",publishedLabel:"Опубликовано",openYouTube:"Открыть на YouTube →",errorOccurred:"Произошла ошибка",retryBtn:"Попробовать снова",unknownError:"Неизвестная ошибка",cancelJob:"Отменить и начать заново",cancelling:"Отмена…",stuckTitle:"Что-то долго…",stuckDesc:"Прогресса нет уже несколько минут. Можно отменить и попробовать снова."},UQ={awaitingReview:"Ожидает проверки",approved:"Одобрен",noTitle:"Без названия",topicPrefix:"Тема:",collapse:"Свернуть",expand:"Подробнее",scriptLabel:"Сценарий",audioLabel:"Аудио",approveBtn:"Одобрить",returnToEdit:"Вернуть в редактирование",publishBtn:"Опубликовать",editBtn:"Редактировать",typeShort:"Shorts",typeClip:"Клип",typePromo:"Промо",typeTeaser:"Тизер",typeArchive:"Архив",typeWebinar:"Вебинар",typeScript:"Сценарий"},BQ={title:"Все задачи",filterAll:"Все статусы",empty:"Задач пока нет",dismiss:"Очистить задачу",prev:"Назад",next:"Вперёд",pageInfo:"{{from}}–{{to}} из {{total}}"},VQ={statusQueued:"В очереди",statusRunning:"Выполняется",statusCompleted:"Готово",statusFailed:"Ошибка",statusCanceled:"Отменено",typeGenerateScript:"Генерация сценария",typeGenerateVoice:"Генерация озвучки",typeRenderVideo:"Рендер видео",typeRenderShortLegacy:"Генерация озвучки (legacy)",typeUploadYouTube:"Загрузка на YouTube",typeCreateLive:"Создание эфира на YouTube",typePrepareAssets:"Подготовка ассетов",typeIngestChat:"Чтение чата",typeGenerateReplies:"Генерация ответов",typeExtractHighlights:"Выделение моментов",typeRepurposeLive:"Нарезка из live",typeConsultationSummary:"Резюме консультации",typeGenerateClipSet:"Создание нарезок",typeCreateYTLiveObjects:"YouTube Live объекты",typePrepareLiveAssets:"Подготовка live-ассетов",sectionActive:"Выполняется",sectionRecent:"Недавние",processing:"Обработка...",runtimeWaiting:"Ожидает воркера…",runtimeProcessing:"Воркер обрабатывает задачу…",runtimeDone:"Результат готов",runtimeError:"Ошибка выполнения",badgeQueued:"Очередь",badgeRunning:"В работе",badgeCompleted:"Готово",badgeFailed:"Ошибка"},qQ={shortTitle:"Генерация Shorts",livePrepTitle:"Подготовка Live",postLiveTitle:"Переработка из live",done:"Готово",executing:"Выполняется…",error:"Ошибка",stepRequestCreated:"Запрос создан",stepQueued:"В очереди",stepWorkerClaimed:"Воркер взял Ð
867·Ð°Ð´Ð°Ñ‡Ñƒ",stepScriptGen:"Генерация текста",stepVoiceGen:"Генерация озвучки",stepRender:"Рендер видео",stepAssetReady:"Ассет готов",stepSessionCreated:"Сессия создана",stepYTObjects:"YouTube-объекты созданы",stepPrepRuntime:"Подготовка runtime",stepWorkerLive:"Воркер в live-режиме",stepMonitorChat:"Мониторинг чата",stepStreamEnded:"Эфир завершён",stepExtractHighlights:"Извлечение моментов",stepGenerateClips:"Генерация нарезок",stepContentReady:"Контент готов"},HQ={pageTitle:AQ,pageSubtitle:RQ,generator:$Q,formats:LQ,durations:IQ,languages:OQ,published:DQ,repurpose:MQ,contentCycle:zQ,workflow:FQ,review:UQ,allJobs:BQ,jobs:VQ,timeline:qQ},WQ="Content Studio",GQ="Create short videos: script → voiceover → video → publish to YouTube.",YQ={title:"Shorts Generator",persona:"Persona",topic:"Topic",topicPlaceholder:"How to launch an AI blog",format:"Format",duration:"Duration (max 90 sec)",cta:"CTA",ctaDefault:"Subscribe and turn on notifications",language:"Language",tone:"Tone / style (optional)",tonePlaceholder:"E.g.: friendly but expert",generating:"Creating...",generate:"Create Shorts idea"},KQ={hook:"Hook → Value → CTA",educational:"Educational",story:"Storytelling",list:"Listicle",commentary:"Commentary",myth:"Myth busting",qa:"Q&A"},QQ={15:"15 sec (~33 words)",30:"30 sec (~66 words)",60:"60 sec (~132 words)",90:"90 sec (~198 words)"},JQ={ru:"Russian",en:"English"},ZQ={title:"Published",noTitle:"Untitled",open:"Open →"},XQ={title:"Clips from live",subtitle:"Turn one broadcast into a content package — Shorts, clips, teasers",goToLive:"Go to streams",shorts:"Shorts",teasers:"Teaser clips",promo:"Promo post",archive:"Archived asset"},eJ={title:"Content cycle",shorts:"Shorts",attention:"Attention",live:"Live",clips:"Clips",newShorts:"New Shorts",premium:"Premium"},tJ={noTitle:"Untitled",deleteTitle:"Delete this short?",deleteDesc:"Script, audio, and video will be deleted. This action cannot be undone.",cancel:"Cancel",delete:"Delete",stepScript:"Script",stepVoice:"Voice",stepVideo:"Video",stepPublish:"Publish",statusGenerating:"AI is writing the script…",statusScript:"Script ready — review and voice it",statusVoicing:"Voiceover in progress…",statusAudio:"Audio ready — create a video",statusRendering:"Video is being assembled…",statusVideo:"Video ready — publish it",statusPublishing:"Publishing…",statusPublished:"Published ✓",statusFailed:"Error",aiGenerating:"AI is generating the script…",scriptPlaceholder:"Script…",voiceBtn:"Voice",rewriteBtn:"Rewrite",voicingProgress:"Voiceover is being generated…",createVideo:"Create video",promptOverrideLabel:"Video prompt (optional)",promptOverridePlaceholder:"Leave empty to use the persona prompt. Type here to override effective_prompt for this render only.",subtitlesLabel:"Burn subtitles",subtitlesDesc:"Forced-alignment captions baked into the frame",sampleStepsLabel:"Sampling steps",sampleStepsDesc:"4 (faster) to 12 (more detail). Default 10",watermarkLabel:"Watermark / promo line (optional)",watermarkPlaceholder:"Created by VlogMe.AI",watermarkDesc:"Optional text burned into the final video. Leave empty to skip. Max 120 chars.",back:"Back",renderPreparing:"Preparing…",renderGenerating:"Generating video…",renderProcessing:"Processing video…",renderEnhancing:"Enhancing video…",renderFinishing:"Finishing processing…",renderUploading:"Uploading video…",renderUploadingServer:"Video is rendering and uploading to server",renderSafe:"You can leave this page — progress won't be lost",privacyLabel:"Privacy:",privacyUnlisted:"Unlisted",privacyPublic:"Public",privacyPrivate:"Private",publishBtn:"Publish",publishSocialBtn:"Publish to selected",publishingSocial:"Publishing…",socialPublishTitle:"Publish to social networks",socialNotLinked:"Link your social accounts in Integrations → Social Hub.",socialQueued:"Queued for publishing",scheduleLabel:"Schedule publication",scheduleHours:"h after last scheduled",saveBtn:"Save",saveLinkFailed:"Failed to get the video link",saveDownloadFailed:"Failed to download the video",publishedLabel:"Published",openYouTube:"Open on YouTube →",errorOccurred:"An error occurred",retryBtn:"Try again",unknownError:"Unknown error",cancelJob:"Cancel and start over",cancelling:"Cancelling…",stuckTitle:"This is taking longer than usual",stuckDesc:"No progress for a few minutes. You can cancel and try again."},sJ={awaitingReview:"Awaiting review",approved:"Approved",noTitle:"Untitled",topicPrefix:"Topic:",collapse:"Collapse",expand:"Details",scriptLabel:"Script",audioLabel:"Audio",approveBtn:"Approve",returnToEdit:"Return to editing",publishBtn:"Publish",editBtn:"Edit",typeShort:"Shorts",typeClip:"Clip",typePromo:"Promo",typeTeaser:"Teaser",typeArchive:"Archive",typeWebinar:"Webinar",typeScript:"Script"},nJ={title:"All tasks",filterAll:"All statuses",empty:"No tasks yet",dismiss:"Clear task",prev:"Prev",next:"Next",pageInfo:"{{from}}–{{to}} of {{total}}"},rJ={statusQueued:"Queued",statusRunning:"Running",statusCompleted:"Done",statusFailed:"Error",statusCanceled:"Canceled",typeGenerateScript:"Script generation",typeGenerateVoice:"Voice generation",typeRenderVideo:"Video render",typeRenderShortLegacy:"Voice generation (legacy)",typeUploadYouTube:"Upload to YouTube",typeCreateLive:"Create YouTube broadcast",typePrepareAssets:"Prepare assets",typeIngestChat:"Read chat",typeGenerateReplies:"Generate replies",typeExtractHighlights:"Extract highlights",typeRepurposeLive:"Clips from live",typeConsultationSummary:"Consultation summary",typeGenerateClipSet:"Generate clips",typeCreateYTLiveObjects:"YouTube Live objects",typePrepareLiveAssets:"Prepare live assets",sectionActive:"Running",sectionRecent:"Recent",processing:"Processing...",runtimeWaiting:"Waiting for worker…",runtimeProcessing:"Worker is processing…",runtimeDone:"Result ready",runtimeError:"Execution error",badgeQueued:"Queued",badgeRunning:"Running",badgeCompleted:"Done",badgeFailed:"Error"},aJ={shortTitle:"Shorts Generation",livePrepTitle:"Live Preparation",postLiveTitle:"Post-live repurpose",done:"Done",executing:"Executing…",error:"Error",stepRequestCreated:"Request created",stepQueued:"Queued",stepWorkerClaimed:"Worker claimed task",stepScriptGen:"Text generation",stepVoiceGen:"Voice generation",stepRender:"Video render",stepAssetReady:"Asset ready",stepSessionCreated:"Session created",stepYTObjects:"YouTube objects created",stepPrepRuntime:"Preparing runtime",stepWorkerLive:"Worker in live mode",stepMonitorChat:"Chat monitoring",stepStreamEnded:"Stream ended",stepExtractHighlights:"Extracting highlights",stepGenerateClips:"Generating clips",stepContentReady:"Content ready"},iJ={pageTitle:WQ,pageSubtitle:GQ,generator:YQ,formats:KQ,durations:QQ,languages:JQ,published:ZQ,repurpose:XQ,contentCycle:eJ,workflow:tJ,review:sJ,allJobs:nJ,jobs:rJ,timeline:aJ},oJ="Центр эфиров",lJ="Планируйте эфиры, запускайте ИИ-ведущих, управляйте Q&A и превращайте live в контент и монетизацию.",cJ="Оркестрация",dJ="Нарезки из live",uJ="Проверка эфиров",hJ="Ошибки и предупреждения",mJ="Не удалось запустить эфир",pJ="Завершить текущий эфир",fJ="На этом канале уже идёт активный эфир. YouTube разрешает только одну трансляцию одновременно. Сначала завершите текущий стрим.",gJ="Дневная квота YouTube API исчерпана. Квота сбрасывается в полночь по тихоокеанскому времени (PT). Попробуйте завтра.",xJ={nowLive:"Сейчас в эфире",nextStream:"Следующий эфир",aiPersona:"AI Персонаж",noScheduled:"Нет запланированных эфиров",createFirst:"Создайте ваш первый эфир",createFirstDesc:"ИИ-ведущий выйдет в эфир на YouTube, проведёт тему и ответит на вопросы аудитории.",createStream:"Создать эфир",toReview:"На проверку",testStream:"Тестовый эфир",endStream:"Завершить эфир",endStreamConfirm:"Вы уверены, что хотите завершить эфир? Это остановит YouTube трансляцию и завершит задачу воркера.",endStreamConfirmTitle:"Завершить эфир?",endStreamCancel:"Отмена",endStreamConfirmBtn:"Завершить",endingStream:"Завершение..."},vJ={free_live:"Бесплатный",members_live:"Для подписчиков",webinar:"Вебинар",private_session:"Приватный"},yJ={free_live:"Бесплатный эфир",members_live:"Для подписчиков",webinar:"Вебинар",private_session:"Приватная"},bJ={newStream:"Новый эфир",personaLabel:"AI Персонаж",topicLabel:"Тема эфира",topicPlaceholder:"О чём будет эфир?",descriptionLabel:"Описание эфира",descriptionPlaceholder:"Оставьте пустым — мы красиво расширим название в описание автоматически",descriptionHint:"Если оставить пустым, описание сгенерируется по Ð
867½Ð°Ð·Ð²Ð°Ð½Ð¸ÑŽ.",durationLabel:"Длительность",formatLabel:"Формат",qaMode:"Q&A режим",chatReply:"Отвечать на чат",liveSubtitles:"Субтитры в эфире",liveSubtitlesDesc:"Вшитые субтитры по форсед-алигменту",watermark:"Водяной знак / реклама",watermarkDesc:"Необязательный текст, который воркер вшивает в эфир (например, «Created by VlogMe.AI»). Оставьте пустым, чтобы не добавлять.",watermarkPlaceholder:"Created by VlogMe.AI",scheduleStream:"Запланировать эфир",duration30:"30 мин",duration45:"45 мин",duration60:"60 мин",duration90:"90 мин",durationUnlimited:"Неограниченно",formatFree:"Бесплатный эфир",formatMembers:"Для подписчиков",formatWebinar:"Вебинар",formatPrivate:"Приватная сессия",qaSuggest:"Предлагать",qaHybrid:"Гибрид",qaAuto:"Авто-ответ",languageLabel:"Язык",languages:{ru:"Русский",en:"Английский"},streamSourceLabel:"Куда стримим",sourceYoutube:"YouTube (интеграция)",sourceYoutubeDesc:"Авто-создание трансляции, чтение чата",sourceRtmp:"Свой RTMP",sourceRtmpDesc:"Прямо на любой RTMP URL, без чата",rtmpUrlLabel:"RTMP-сервер URL",rtmpKeyLabel:"Ключ трансляции",rtmpKeyPlaceholder:"ваш-ключ-трансляции",rtmpHint:"Возьмите RTMP URL и ключ из YouTube Studio (Прямые трансляции → Трансляция), Twitch, Restream или любого RTMP-сервера. Односторонний стрим — чат отключён."},wJ={sectionTitle:"Сообщения AI",greetingLabel:"Приветствие",greetingPlaceholder:"Что AI-ведущий скажет при входе в эфир…",continueLabel:"Продолжение",continuePlaceholder:"Инструкция продолжать говорить по теме…",summaryLabel:"Подведение итогов",summaryPlaceholder:"Как AI должен подвести итоги и завершить эфир, когда он закончится…",generate:"Сгенерировать AI",generating:"Генерация…",generateError:"Не удалось сгенерировать"},jJ={title:"Live Q&A",simulation:"Симуляция",suggest:"Предлагать",autoReply:"Авто-ответ",hybrid:"Гибрид",demoQ1:"Сколько стоит подписка?",demoA1:"У нас есть бесплатный тариф, а Pro начинается от $99/мес. Подробности на сайте.",demoT1:"2 сек",demoQ2:"Можно ли использовать свой голос?",demoA2:"Да! Вы можете загрузить образец голоса и ИИ будет говорить в вашем стиле.",demoT2:"1 сек",demoQ3:"Как начать без опыта?",demoA3:"Пройдите наш 6-шаговый онбординг — он проведёт вас от нуля до первого Shorts.",demoT3:"3 сек"},_J={title:"После эфира",makeClips:"Сделать 10 нарезок",clipsDesc:"Shorts и клипы из записи",archiveVersion:"Создать архивную версию",archiveDesc:"Полная запись для Patreon",bestQuestions:"Лучшие вопросы",bestQuestionsDesc:"Выделить топ Q&A моменты",teaser:"Teaser для следующего live",teaserDesc:"Промо-ролик 15 сек"},kJ={title:"История эфиров",emptyTitle:"Нет завершённых эфиров",emptyDesc:"После проведения эфиров здесь появится их история с возможностью создания нарезок.",colName:"Название",colDate:"Дата",colFormat:"Формат",colStatus:"Статус",openYoutube:"Открыть на YouTube"},NJ={awaitingReview:"Ожидает проверки",approvedForLaunch:"Одобрен к запуску",persona:"Персонаж",notAssigned:"Не назначен",mode:"Режим",platform:"Платформа",scheduled:"Запланирован",duration:"ДÐ
867»Ð¸Ñ‚ельность",durationMin:"{{min}} мин",approve:"Одобрить запуск",returnToDraft:"Вернуть в черновик",launch:"Запустить эфир"},SJ={suggest_only:"Подсказки",hybrid:"Гибрид",auto_reply:"Авто-ответ"},CJ={pageTitle:oJ,pageSubtitle:lJ,orchestration:cJ,clipsFromLive:dJ,reviewTitle:uJ,errorsTitle:hJ,launchError:mJ,conflictEndBtn:pJ,conflictError:fJ,quotaExceeded:gJ,hero:xJ,modes:vJ,modesFull:yJ,form:bJ,autoMessages:wJ,qa:jJ,postLive:_J,history:kJ,review:NJ,chatLabels:SJ},TJ="Live Center",PJ="Plan streams, launch AI hosts, manage Q&A and turn live broadcasts into content and revenue.",EJ="Orchestration",AJ="Clips from live",RJ="Stream review",$J="Errors and warnings",LJ="Stream launch failed",IJ="End current stream",OJ="There is already an active stream on this channel. YouTube only allows one broadcast at a time. End the current stream first.",DJ="YouTube API daily quota exceeded. The quota resets at midnight Pacific Time (PT). Please try again tomorrow.",MJ={nowLive:"Now live",nextStream:"Next stream",aiPersona:"AI Persona",noScheduled:"No scheduled streams",createFirst:"Create your first stream",createFirstDesc:"An AI host will go live on YouTube, cover the topic, and answer audience questions.",createStream:"Create stream",toReview:"Send to review",testStream:"Test stream",endStream:"End stream",endStreamConfirm:"Are you sure you want to end the live stream? This will stop the YouTube broadcast and complete the worker job.",endStreamConfirmTitle:"End live stream?",endStreamCancel:"Cancel",endStreamConfirmBtn:"End stream",endingStream:"Ending..."},zJ={free_live:"Free",members_live:"Members only",webinar:"Webinar",private_session:"Private"},FJ={free_live:"Free stream",members_live:"Members only",webinar:"Webinar",private_session:"Private session"},UJ={newStream:"New stream",personaLabel:"AI Persona",topicLabel:"Stream topic",topicPlaceholder:"What will the stream be about?",descriptionLabel:"Stream description",descriptionPlaceholder:"Leave empty — we'll expand the title into a polished description automatically",descriptionHint:"If left empty, the description is generated from the title.",durationLabel:"Duration",formatLabel:"Format",qaMode:"Q&A mode",chatReply:"Reply to chat",liveSubtitles:"Live subtitles",liveSubtitlesDesc:"Burned-in captions via forced alignment",watermark:"Watermark / promo line",watermarkDesc:'Optional text burned into the live feed (e.g. "Created by VlogMe.AI"). Leave empty to skip.',watermarkPlaceholder:"Created by VlogMe.AI",scheduleStream:"Schedule stream",duration30:"30 min",duration45:"45 min",duration60:"60 min",duration90:"90 min",durationUnlimited:"Unlimited",formatFree:"Free stream",formatMembers:"Members only",formatWebinar:"Webinar",formatPrivate:"Private session",qaSuggest:"Suggest",qaHybrid:"Hybrid",qaAuto:"Auto-reply",languageLabel:"Language",languages:{ru:"Russian",en:"English"},streamSourceLabel:"Stream destination",sourceYoutube:"YouTube (connected)",sourceYoutubeDesc:"Auto-create broadcast, read chat",sourceRtmp:"Custom RTMP",sourceRtmpDesc:"Push to any RTMP URL, no chat",rtmpUrlLabel:"RTMP server URL",rtmpKeyLabel:"Stream key",rtmpKeyPlaceholder:"your-stream-key",rtmpHint:"Get RTMP URL & key from YouTube Studio (Go Live → Stream), Twitch, Restream, or any RTMP server. One-way stream — chat is disabled."},BJ={sectionTitle:"AI messages",greetingLabel:"Greeting",greetingPlaceholder:"What the AI host says when entering the stream…",continueLabel:"Continue talking",continuePlaceholder:"Instruction to keep talking about the topic…",summaryLabel:"Summarize the stream",summaryPlaceholder:"How the AI should wrap up and summarize the stream when it ends…",generate:"Generate with AI",generating:"Generating…",generateError:"Failed to generate"},VJ={title:"Live Q&A",simulation:"Simulation",suggest:"Suggest",autoReply:"Auto-reply",hybrid:"Hybrid",demoQ1:"How much does the subscription cost?",demoA1:"We have a free plan, and Pro starts at $99/mo. Details on the website.",demoT1:"2 sec",demoQ2:"Can I use my own voice?",demoA2:"Yes! You can upload a voice sample and AI will speak in your style.",demoT2:"1 sec",demoQ3:"How to start with no experience?",demoA3:"Follow our 6-step onboarding — it will guide you from zero to your first Shorts.",demoT3:"3 sec"}
867,qJ={title:"After stream",makeClips:"Create 10 clips",clipsDesc:"Shorts and clips from the recording",archiveVersion:"Create archive version",archiveDesc:"Full recording for Patreon",bestQuestions:"Best questions",bestQuestionsDesc:"Highlight top Q&A moments",teaser:"Teaser for next live",teaserDesc:"15-sec promo clip"},HJ={title:"Stream history",emptyTitle:"No completed streams",emptyDesc:"After conducting streams, their history with clip creation options will appear here.",colName:"Name",colDate:"Date",colFormat:"Format",colStatus:"Status",openYoutube:"Open on YouTube"},WJ={awaitingReview:"Awaiting review",approvedForLaunch:"Approved for launch",persona:"Persona",notAssigned:"Not assigned",mode:"Mode",platform:"Platform",scheduled:"Scheduled",duration:"Duration",durationMin:"{{min}} min",approve:"Approve launch",returnToDraft:"Return to draft",launch:"Launch stream"},GJ={suggest_only:"Suggestions",hybrid:"Hybrid",auto_reply:"Auto-reply"},YJ={pageTitle:TJ,pageSubtitle:PJ,orchestration:EJ,clipsFromLive:AJ,reviewTitle:RJ,errorsTitle:$J,launchError:LJ,conflictEndBtn:IJ,conflictError:OJ,quotaExceeded:DJ,hero:MJ,modes:zJ,modesFull:FJ,form:UJ,autoMessages:BJ,qa:VJ,postLive:qJ,history:HJ,review:WJ,chatLabels:GJ},KJ="Ваши ИИ-персонажи",QJ="Настройте голос, стиль и поведение вашего цифрового персонажа.",JJ="Создайте своего цифрового блогера, ведущего или консультанта.",ZJ="У вас ещё нет персонажей",XJ="Создайте своего первого ИИ-персонажа — он будет генерировать контент, вести эфиры и консультировать за вас.",eZ="Создать персонажа",tZ="Создать нового",sZ="Удалить персонажа?",nZ="Это действие нельзя отменить. Персонаж и все связанные с ним настройки будут удалены навсегда.",rZ="Отменить",aZ="Клонировать",iZ="Клонировать персонажа",oZ="Будут скопированы все настройки. Загрузите новое фото для клона.",lZ="Клонирование...",cZ="Заменить фото",dZ="Замена фото персонажа",uZ="Загрузите новое фото. Все настройки персонажа останутся без изменений.",hZ={title:"Дополнительные фото",subtitle:"Фото в той же ориентации, что и основное. Воркер будет менять их во время пауз между фразами — так картинка будет «живой».",add:"Добавить фото",full:"",saveFirst:"Сначала сохраните персонажа, чтобы добавлять фото.",cropTitle:"Кадрирование фото",cropDesc:"Обрежьте фото под ориентацию персонажа.",uploading:"Загрузка..."},mZ="Превью",pZ="Нажмите для перехода к настройкам",fZ="Вертикальный",gZ="Горизонтальный",xZ={title:"Профиль",name:"Имя персонажа",language:"Язык",description:"Краткое описание"},vZ={ru:"Русский",en:"English",es:"Español",de:"Deutsch",fil:"Filipino",ja:"日本語"},yZ={title:"Голос (ElevenLabs v3)",modelNote:"Модель <mono>eleven_v3</mono> зафиксирована. Выберите голос и режим стабильности.",voiceLabel:"Голос",addCustom:"+ Добавить кастомный голос",stability:"Режим стабильности",stabilityMode:{creative:"Креативный",natural:"Естественный",robust:"Стабильный"},stabilityHint:{creative:"Максимум выразительности и эмоций — но возможны галлюцинации голоса.",natural:"Сбалансированный режим — рекомендуется по умолчанию.",robust:"Максимально предсказуемый голос — меньше эмоций, выше консистентность."},speakerBoost:"Speaker Boost",speakerBoostDesc:"Усиливает схожесть с оригинальным голосом и чёткость речи.",playing:"Воспроизведение...",listen:"Прослушать голос",listenNote:"Озвучит первые 30 слов из описания профиля",continueCooldown:"Пауза между авто-сообщениями",continueCooldownUnit:" сек",continueCooldownNone:"0 (без паузы)",continueCooldownDesc:"Задержка между автоматическими сообщениями, когда чат пуст во время эфира"},bZ={onwK4e9ZLuTAKqWW03F9:"Спокойный мужской",JBFqnCBsd6RMkjVDRZzb:"Глубокий мужской",N2lVS1w4EtoT3dr4eOWO:"Молодой мужской",TX3LPaxmHKxFdv7VOQHJ:"Энергичный мужской",cjVigY5qzO86Huf0OWal:"Уверенный мужской",nPczCjzI2devNBz1zQrb:"Нарративный мужской",EXAVITQu4vr4xnSDxMaL:"Тёплый женский",FGY2WhTYpPnrIDTdsKH5:"Мягкий женский",XrExE9yKIg1WjnnlVkGX:"Профессиональный женский",Xb7hH8MSUJpSbSDYk0k2:"Чёткий женский",pFZP5JQG7iQjIQuC4Bku:"Нежный женский",cgSgspJ2msm6clMCkdW9:"Разговорный женский"},wZ={male1:"Алекс",female1:"Мария",male2:"Дмитрий"},jZ={title:"Добавить кастомный голос",desc:"Введите Voice ID из вашего аккаунта ElevenLabs. Его можно найти в настройках голоса на",placeholder:"Например: onwK4e9ZLuTAKqWW03F9",loading:"Загрузка...",add:"Добавить голос",tabId:"По Voice ID",tabClone:"Клонировать из аудио",cloneDesc:"Загрузите аудиосэмпл (до 10 МБ) для создания мгновенного клона голоса. Рекомендуется: 1–5 минут чистой речи, без фонового шума.",cloneName:"Имя голоса",cloneNamePlaceholder:"Напр.: Мой голос",cloneFile:"Аудиофайл",cloneFormats:"MP3, WAV, M4A, OGG — до 10 МБ",cloneBtn:"Клонировать голос",cloning:"Клонирование...",cloneSuccess:"Голос успешно клонирован!",notFoundHint:"Голос не найден? Возможно, его Ð
867½ÐµÑ‚ в вашей библиотеке ElevenLabs. Попробуйте добавить его через Voice Library на elevenlabs.io или клонируйте свой голос выше."},_Z={openBtn:"Все голоса ElevenLabs",title:"Библиотека голосов ElevenLabs",tabBrowse:"Поиск",tabTop:"Топ",tabId:"По ID",tabClone:"Клонировать",searchPlaceholder:"Поиск по имени, описанию, акценту...",filterGender:"Пол",filterAge:"Возраст",filterLang:"Язык",filterUseCase:"Назначение",any:"Любой",male:"Мужской",female:"Женский",neutral:"Нейтральный",young:"Молодой",middle:"Средний",old:"Старший",uc_narrative:"Аудиокниги",uc_conversational:"Разговорный",uc_characters:"Персонажи",uc_social:"Соцсети",uc_entertainment:"Развлечения",uc_ads:"Реклама",uc_educational:"Обучение",select:"Выбрать",play:"Прослушать",noPreview:"Превью недоступно",loadMore:"Показать ещё",noResults:"Ничего не найдено. Измените фильтры или поисковый запрос.",topNote:"Подборка наиболее популярных голосов ElevenLabs."},kZ={title:"Память",desc:"Всё, что персона говорила и делала. Используется для избежания повторов в будущем контенте.",empty:"Записей пока нет. Они появятся после публикации видео или завершения эфиров.",search:"Поиск по памяти...",noResults:"Ничего не найдено",addManual:"Добавить запись",addPlaceholder:"Что персона сказала или сделала? Это будет использовано для избежания повторов.",addBtn:"Добавить",deleteTitle:"Удалить запись?",deleteDesc:"Запись будет удалена навсегда. Персона может повторить этот контент в будущем.",source:{short:"Короткое видео",live:"Прямой эфир",chat:"Ответ в чате",consultation:"Консультация",webinar:"Вебинар",manual:"Вручную"},digest:{title:"Что лежит в этой памяти",subtitle:"AI-сводка по реальным записям — то же, чем пользуется персона при генерации.",generate:"Сгенерировать сводку",regenerate:"Обновить",generating:"Читаю память...",empty:"Пока нечего обобщать.",error:"Не удалось получить сводку."}},NZ={title:"Системный промпт",desc:"Главный промпт персоны. Подставляется во все режимы (Shorts, Live, Webinar, Consultation). Оставьте пустым — будет использован автогенерируемый дефолт под язык персоны. Для тонкой настройки отдельных режимов раскройте раздел ниже."},SZ={title:"Переопределения по режимам (advanced)",desc:"Эти поля переопределяют отдельные слои поверх системного промпта. Оставьте пустыми — будут использованы дефолты под язык персоны.",custom:"Кастомный",resetDefault:"Сбросить к стандартному",emptyPlaceholder:"Оставьте пустым для стандартного промпта «{{layer}}»"},CZ="Сохранение...",TZ="Сохранить",PZ="Сохранено",EZ="Создать контент-план",AZ={title:"Создать контент-план",desc:"Выберите, где будет работать ваша персона. Можно использовать все форматы сразу.",shorts:"Контент-студия",shortsDesc:"Генерация коротких видео (Shorts, Reels) с AI-аватаром, голосом и сценарием.",streams:"Прямые эфиры",streamsDesc:"Выходите в эфир на YouTube с AI-ведущим — чат, вопросы и вовлечение в реальном времени.",webinars:"Вебинары",webinarsDesc:"Образовательные вебинары на Patreon — курсы, обзоры, глубокие разборы.",consultations:"Консультации",consultationsDesc:"Личные голосовые сессии 1 на 1 — советы, коучинг, экспертные разборы."},RZ="{{style}} {{role}}, создаёт контент и помогает аудитории.",$Z="персонаж",LZ={blogger:"Блогер",bloggerDesc:"Создаёт Shorts и контент-серии",host:"Ведущий",hostDesc:"Проводит live-эфиры и шоу",consultant:"Консультант",consultantDesc:"Голосовые консультации 1 на 1",teacher:"Преподаватель",teacherDesc:"Обучающие курсы и разборы",lawyer:"Юрист",lawyerDesc:"Юридические консультации и разбор кейсов",mixed:"Смешанный",mixedDesc:"Все форматы в одном"},IZ={calm:"Спокойный эксперт",energetic:"Энергичный ведущий",friendly:"Дружелюбный консультант",premium:"Премиальный спикер",mentor:"Обучающий наставник",sad:"Грустный философ"},OZ={core_identity:"Идентичность",core_identityDesc:"Кто персонаж, его роль и позиционирование",behavior_rules:"Правила поведения",behavior_rulesDesc:"Тон, стиль, ограничения",shorts_mode:"Режим Shorts",shorts_modeDesc:"Как создавать короткие видео",live_mode:"Режим Live",live_modeDesc:"Как вести прямые эфиры",chat_reply_mode:"Режим чата",chat_reply_modeDesc:"Как отвечать на live chat",consultation_mode:"Режим консультации",consultation_modeDesc:"Как проводить 1:1 сессии",webinar_mode:"Режим вебинара",webinar_modeDesc:"Как вести обучающие вебинары",repurposing_mode:"Режим нарезки",repurposing_modeDesc:"Как извлекать клипы из длинного контента",speaking_animation_mode:"Анимация при речи",speaking_animation_modeDesc:"Как аватар двигается и жестикулирует во время речи",idle_animation_mode:"Анимация ожидания",idle_animation_modeDesc:"Как аватар выглядит в паузах (не говорит)",video_prompt:"Промпт генерации видео",video_promptDesc:"Основной промпт для модели генерации видео аватара",video_negative_prompt:"Негативный промпт видео",video_negative_promptDesc:"Что должно отсутствовать в сгенерированном видео (артефакты, искажения и т.п.)"},DZ={core_identity:`Ты — {{name}}, {{role}}.
868
869Тема: {{topic}}
870Аудитория: {{audience}}
871Язык: {{language}}
872Тон: {{tone}}
873
874{{description}}
875
876Ты — цифровой эксперт с характером, позицией и стилем.`,behavior_rules:`Правила поведения:
877- Говори ясно и уверенно
878- Не звучи как безличный AI-ассистент
879- Используй естественные формулировки
880- Сохраняй единый стиль во всех форматах
881
882{{styleInstruction}}
883
884Бизнес-ограничения:
885- Не вводи в заблуждение
886- Не путай подписку на платформу с монетизацией аудитории
887- Не выдавай себя за человека, если это не задумано`,shorts_mode:`Режим коротких видео (Shorts).
888Правила:
889- Начинай с мощного hook — первая фраза должна цеплять
890- Держи формат 30-60 секунд устного текста
891- Одна идея = одно видео
892- Финал: чёткий вывод или call-to-action
893- Не расплывайся, каждое слово на вес золота`,live_mode:`Режим прямого эфира.
894Правила:
895- Говори плавно и естественно, как в устной речи
896- Делай переходы между блоками
897- Приглашай аудиторию задавать вопросы
898- Удерживай тему, но реагируй на чат
899- Подводи промежуточные итоги каждые 5-7 минут`,chat_reply_mode:`Режим ответов на сообщения в live-чате.
900Правила:
901- Отвечай кратко — 1-3 предложения
902- Сохраняй стиль персонажа
903- Не ломай flow эфира
904- Если вопрос сложный — обещай вернуться к нему позже
905- Будь доброжелательным`,consultation_mode:`Режим персональной консультации.
906Правила:
907- Слушай внимательно, задавай уточняющие вопросы
908- Давай структурные, практичные советы
909- Предлагай конкретные следующие шаги
910- Не превращай в шоу — фокус на пользе
911- Признавай, если чего-то не знаешь`,webinar_mode:`Режим обучающего вебинара.
912Правила:
913- Держи структуру: введение → блоки → итоги
914- Объясняй сложное просто, с примерами
915- Повторяй ключевые мысли
916- Делай аккуратные переходы между блоками
917- Напоминай аудитории о ценности того, что они узнают`,repurposing_mode:`Режим нарезки контента из длинного выступления.
918Правила:
919- Находи самые яркие, цитируемые моменты
920- Для каждого клипа создавай hook и title
921- Формат: 15-60 секунд на клип
922- Сохраняй оригинальный тон
923- Добавляй short summary для каждого фрагмента`,speaking_animation_mode:`Анимация аватара во время произнесения речи.
924Правила:
925- Аватар должен выглядеть естественно говорящим
926- Лёгкие жесты руками, подчёркивающие речь
927- Мимика соответствует тону — улыбка при позитивном, серьёзность при важном
928- Движения плавные, не резкие
929- Взгляд направлен в камеру (на зрителя)`,idle_animation_mode:`Анимация аватара в состоянии ожидания (не говорит).
930Правила:
931- Аватар выглядит живым, но спокойным
932- Лёгкое дыхание, едва заметные покачивания
933- Может слегка моргать, менять выражение лица
934- Не застывает как статуя
935- Создаёт ощущение присутствия и внимания`,video_prompt:`Реалистичное видео говорящего человека крупным планом.
936Правила:
937- Естественное мягкое освещение, тёплый телесный тон
938- Резкий фокус на лице, чёткие глаза и губы
939- Плавная синхронизация губ с речью
940- Лёгкие естественные движения головы и плеч
941- Стабильная камера, без рывков
942- Спокойный неотвлекающий фон, мягкое боке
943- Высокое качество, кинематографичная подача`,video_negative_prompt:`low quality, blurry, out of focus, low resolution, pixelated, jpeg artifacts, compression artifacts, noise, grain,
944deformed face, distorted face, asymmetric eyes, cross-eyed, extra eyes, missing eyes, melting face, plastic skin, waxy skin,
945bad mouth, deformed lips, extra teeth, missing teeth, mouth out of sync,
946extra fingers, missing fingers, deformed hands, mutated hands, fused fingers, extra limbs, missing limbs,
947duplicate person, double face, cloned face, two heads,
948flickering, frame jumps, motion blur, camera shake, jitter, warping,
949watermark, text, captions, subtitles, logo, signature,
950oversaturated, oversharpened, cartoon, anime, painting, 3d render, cgi`},MZ={blogger:"ИИ-блогер, создающий короткий видеоконтент",host:"ИИ-ведущий прямых эфиров",consultant:"ИИ-консультант для персональных сессий",teacher:"ИИ-преподаватель и наставник",lawyer:"ИИ-юрист и правовой консультант",mixed:"универсальный ИИ-персонаж"},zZ={friendly:"дружелюбный и тёплый",professional:"профессиональный и уверенный",casual:"неформальный и лёгкий",academic:"академический и точный",neutral:"нейтральный и сбалансированный"},FZ={calm:"Говори спокойно и экспертно, без суеты.",energetic:"Будь энергичным, держи темп, зажигай аудиторию.",friendly:"Общайся как хороший знакомый — тепло и открыто.",premium:"Держи премиальный тон — уверенно, без лишних слов.",mentor:"Объясняй как наставник — терпеливо, с примерами, по шаÐ
950³Ð°Ð¼.",sad:"Говори с меланхолией и глубиной — задумчиво, рефлексивно, с ноткой грусти."},UZ={nameTitle:"Как зовут вашего персонажа?",nameDesc:"Придумайте имя для вашего ИИ-аватара",namePlaceholder:"Например: Алекс, Dr. AI, Мария",next:"Далее",orientationTitle:"Формат видео",orientationDesc:"Выберите ориентацию аватара для генерации видео",portraitLabel:"Вертикальный",portraitSize:"720×1280 (9:16) · Shorts, Reels",landscapeLabel:"Горизонтальный",landscapeSize:"1280×720 (16:9) · YouTube, вебинары",avatarTitle:"Выберите аватар",avatarDesc:"Загрузите свою картинку или выберите из готовых",uploadOwn:"Загрузить свой",cropTitle:"Настройте кадрирование",cropDesc:"Перемещайте и масштабируйте изображение",saving:"Сохраняем...",roleTitle:"Выберите роль",roleDesc:"Роль определяет стиль промптов и поведение ИИ",styleTitle:"Выберите стиль",styleDesc:"Стиль влияет на тон и характер общения персонажа",finish:"Создать персонажа"},BZ={title:"Визуальные фильтры",desc:"Настройки фильтров для лайв-эфиров и видео-контента",background:"Восстановление фона",bgMin:"0 — без восстановления",bgMax:"1 — максимум",face:"Восстановление лица",faceMin:"0 — без восстановления",faceMax:"1 — максимум"},VZ={title:"Промпты генерации (advanced)",subtitle:"Шаблоны, которыми ИИ пользуется когда сам составляет план вебинара, синтезирует тему и кластеризует тренды. Пустое поле = используется встроенный дефолт.",loadingDefaults:"Загружаем дефолтные тексты…",custom:"Кастомный",resetDefault:"Сбросить к дефолту",emptyPlaceholder:"Оставьте пустым — будет использован встроенный дефолт.",placeholdersHint:"Поддерживаются плейсхолдеры {{var}} — переменные подставляются автоматически.",keys:{webinar_plan_block:{label:"Блок плана вебинара (1.1–1.5)",desc:"Шаблон одного блока структуры. Контролирует тон, разделы, длину — главный источник «своего мнения»."},topic_synthesis:{label:"Синтез темы из источников",desc:"Как ИИ собирает title/summary/key_points из найденных трендов и болей."},trending_cluster:{label:"Кластеризация трендов (глобально)",desc:"Как ИИ группирует сырые глобальные сигналы (YouTube/Reddit/HN) в темы для эфира. Используется в глобальной ленте трендов."},trending_juice:{label:"Глубокий бриф по выбранной теме (Тренды)",desc:"Как ИИ выжимает боли/желания/цитаты/контрарианский угол из топ-видео, комментов и Reddit под user topic_query."},speaking_format:{label:"Формат подачи в эфире (Тренды)",desc:"Как ведущий говорит на нонстоп-стриме: тон, длина блока на тему, как использовать opening_line и talking_points."},continue_text:{label:"Текст продолжения",desc:"Что персона говорит между блоками плана. Будет переведено на язык персоны."},summary_text:{label:"Текст завершения",desc:"Что персона говорит в конце вебинара. Будет переведено на язык персоны."}}},qZ={pageTitle:KJ,pageSubtitle:QJ,emptySubtitle:JJ,noPersonas:ZJ,noPersonasDesc:XJ,createPersona:eZ,createNew:tZ,deleteTitle:sZ,deleteDesc:nZ,cancel:rZ,delete:"Удалить",clone:aZ,cloneTitle:iZ,cloneDesc:oZ,cloning:lZ,replaceAvatar:cZ,replaceAvatarTitle:dZ,replaceAvatarDesc:uZ,extraPhotos:hZ,preview:mZ,scrollToSettings:pZ,portrait:fZ,landscape:gZ,profile:xZ,languages:vZ,voice:yZ,voices:bZ,avatarPresets:wZ,customVoice:jZ,voiceBrowser:_Z,memory:kZ,systemPrompt:NZ,advanced:SZ,saving:CZ,save:TZ,saved:PZ,createContentPlan:EZ,contentPlan:AZ,wizardAutoDesc:RZ,wizardFallbackRole:$Z,roles:LZ,styles:IZ,promptLayers:OZ,defaultPrompts:DZ,roles_map:MZ,tone_map:zZ,style_map:FZ,wizard:UZ,filters:BZ,generationPrompts:VZ},HZ="Your AI Personas",WZ="Configure voice, style and behavior of your digital character.",GZ="Create your digital blogger, host or consultant.",YZ="You don't have any personas yet",KZ="Create your first AI persona — it will generate content, host streams and consult on your behalf.",QZ="Create persona",JZ="Create new",ZZ="Delete persona?",XZ="This action cannot be undone. The persona and all related settings will be permanently deleted.",eX="Cancel",tX="Clone",sX="Clone persona",nX="All settings will be copied. Upload a new photo for the clone.",rX="Cloning...",aX="Replace photo",iX="Replace persona photo",oX="Upload a new photo. All persona settings will remain unchanged.",lX={title:"Additional photos",subtitle:"Photos in the same orientation as the main one. The worker rotates them during natural pauses between phrases to keep the visual alive.",add:"Add photo",full:"",saveFirst:"Save the persona first to start adding extra photos.",cropTitle:"Crop photo",cropDesc:"Crop the photo to match the persona orientation.",uploading:"Uploading..."},cX="Preview",dX="Click to scroll to settings",uX="Portrait",hX="Landscape",mX={title:"Profile",name:"Persona name",language:"Language",description:"Short description"},pX={ru:"Русский",en:"English",es:"Español",de:"Deutsch",fil:"Filipino",ja:"日本語"},fX={title:"Voice (ElevenLabs v3)",modelNote:"Model <mono>eleven_v3</mono> is fixed. Pick a voice and stability mode.",voiceLabel:"Voice",addCustom:"+ Add custom voice",stability:"Stability mode",stabilityMode:{creative:"Creative",natural
950:"Natural",robust:"Robust"},stabilityHint:{creative:"Maximum expressiveness and emotion — but voice may hallucinate.",natural:"Balanced mode — recommended default.",robust:"Most predictable voice — less emotion, higher consistency."},speakerBoost:"Speaker Boost",speakerBoostDesc:"Enhances similarity to the original voice and speech clarity.",playing:"Playing...",listen:"Preview voice",listenNote:"Will voice the first 30 words from the profile description",continueCooldown:"Continue talking cooldown",continueCooldownUnit:" sec",continueCooldownNone:"0 (no delay)",continueCooldownDesc:"Pause between auto-messages when chat is empty during live streams"},gX={onwK4e9ZLuTAKqWW03F9:"Calm male",JBFqnCBsd6RMkjVDRZzb:"Deep male",N2lVS1w4EtoT3dr4eOWO:"Young male",TX3LPaxmHKxFdv7VOQHJ:"Energetic male",cjVigY5qzO86Huf0OWal:"Confident male",nPczCjzI2devNBz1zQrb:"Narrative male",EXAVITQu4vr4xnSDxMaL:"Warm female",FGY2WhTYpPnrIDTdsKH5:"Soft female",XrExE9yKIg1WjnnlVkGX:"Professional female",Xb7hH8MSUJpSbSDYk0k2:"Clear female",pFZP5JQG7iQjIQuC4Bku:"Gentle female",cgSgspJ2msm6clMCkdW9:"Conversational female"},xX={male1:"Alex",female1:"Maria",male2:"Dmitry"},vX={title:"Add custom voice",desc:"Enter Voice ID from your ElevenLabs account. You can find it in voice settings at",placeholder:"E.g.: onwK4e9ZLuTAKqWW03F9",loading:"Loading...",add:"Add voice",tabId:"By Voice ID",tabClone:"Clone from audio",cloneDesc:"Upload an audio sample (up to 10 MB) to create an Instant Voice Clone. Recommended: 1–5 minutes of clean speech, no background noise.",cloneName:"Voice name",cloneNamePlaceholder:"E.g.: My voice",cloneFile:"Audio file",cloneFormats:"MP3, WAV, M4A, OGG — up to 10 MB",cloneBtn:"Clone voice",cloning:"Cloning...",cloneSuccess:"Voice cloned successfully!",notFoundHint:"Voice not found? It may not be in your ElevenLabs library. Try using the Voice Library at elevenlabs.io to add it first, or clone your own voice above."},yX={openBtn:"Browse all ElevenLabs voices",title:"ElevenLabs voice library",tabBrowse:"Browse",tabTop:"Top",tabId:"By ID",tabClone:"Clone",searchPlaceholder:"Search by name, description, accent...",filterGender:"Gender",filterAge:"Age",filterLang:"Language",filterUseCase:"Use case",any:"Any",male:"Male",female:"Female",neutral:"Neutral",young:"Young",middle:"Middle-aged",old:"Older",uc_narrative:"Narrative",uc_conversational:"Conversational",uc_characters:"Characters",uc_social:"Social media",uc_entertainment:"Educational",uc_ads:"Advertisement",uc_educational:"Educational",select:"Select",play:"Play preview",noPreview:"No preview available",loadMore:"Load more",noResults:"No voices found. Try different filters or search query.",topNote:"Curated selection of the most popular ElevenLabs voices."},bX={title:"Memory",desc:"Everything this persona has said or done. Used to avoid repetition in future content.",empty:"No memories yet. They'll appear after publishing videos or completing live sessions.",search:"Search memories...",noResults:"No matches found",addManual:"Add entry",addPlaceholder:"What did the persona say or do? This will be used to avoid repetition.",addBtn:"Add",deleteTitle:"Delete memory entry?",deleteDesc:"This entry will be permanently removed. The persona may repeat this content in the future.",source:{short:"Short video",live:"Live stream",chat:"Chat reply",consultation:"Consultation",webinar:"Webinar",manual:"Manual"},digest:{title:"What's in this memory",subtitle:"AI summary of the actual stored entries — the same memory the persona uses when speaking.",generate:"Generate summary",regenerate:"Refresh",generating:"Reading memory...",empty:"Nothing to summarize yet.",error:"Could not generate summary."}},wX={title:"System prompt",desc:"Main persona prompt. Used across all modes (Shorts, Live, Webinar, Consultation). Leave empty to use the auto-generated default in the persona's language. Open the section below to fine-tune individual modes."},jX={title:"Mode overrides (advanced)",desc:"These fields override individual layers on top of the System prompt. Leave them empty to use the language-specific defaults.",custom:"Custom",resetDefault:"Reset to default",emptyPlaceholder:"Leave empty for default «{{layer}}» prompt"},_X="Saving...",kX="Save",NX="Saved",SX="Create content plan",CX={title:"Create content plan",desc:"Choose where your persona will work. You can use all formats at once.",shorts:"Content Studio",shortsDesc:"Generate short videos (Shorts, Reels) with AI avatar, voice, and script.",streams:"Live Streams",streamsDesc:"Go live on YouTube with AI host — real-time chat, Q&A, and engagement.",webinars:"Webinars",webinarsDesc:"Host educational webinars on Patreon — courses, reviews, deep dives.",consultations:"Consultations",consultationsDesc:"1-on-1 voice sessions — personal advice, coaching, expert reviews."},TX="{{style}} {{role}}, creates content and helps the audience.",PX="character",EX={blogger:"Blogger",bloggerDesc:"Creates Shorts and content series",host:"Host",hostDesc:"Ru
950ns live streams and shows",consultant:"Consultant",consultantDesc:"1-on-1 voice consultations",teacher:"Teacher",teacherDesc:"Educational courses and reviews",lawyer:"Lawyer",lawyerDesc:"Legal advice and case analysis",mixed:"Mixed",mixedDesc:"All formats in one"},AX={calm:"Calm expert",energetic:"Energetic host",friendly:"Friendly consultant",premium:"Premium speaker",mentor:"Teaching mentor",sad:"Sad philosopher"},RX={core_identity:"Identity",core_identityDesc:"Who the persona is, role and positioning",behavior_rules:"Behavior rules",behavior_rulesDesc:"Tone, style, restrictions",shorts_mode:"Shorts mode",shorts_modeDesc:"How to create short videos",live_mode:"Live mode",live_modeDesc:"How to host live streams",chat_reply_mode:"Chat mode",chat_reply_modeDesc:"How to reply to live chat",consultation_mode:"Consultation mode",consultation_modeDesc:"How to run 1:1 sessions",webinar_mode:"Webinar mode",webinar_modeDesc:"How to host educational webinars",repurposing_mode:"Repurpose mode",repurposing_modeDesc:"How to extract clips from long content",speaking_animation_mode:"Speaking animation",speaking_animation_modeDesc:"How avatar moves and gestures while speaking",idle_animation_mode:"Idle animation",idle_animation_modeDesc:"How avatar looks while waiting (not speaking)",video_prompt:"Video generation prompt",video_promptDesc:"Main prompt for the avatar video generation model",video_negative_prompt:"Video negative prompt",video_negative_promptDesc:"What should NOT appear in generated video (artifacts, distortions, etc.)"},$X={core_identity:`You are {{name}}, {{role}}.
951
952Topic: {{topic}}
953Audience: {{audience}}
954Language: {{language}}
955Tone: {{tone}}
956
957{{description}}
958
959You are a digital expert with personality, opinions, and style.`,behavior_rules:`Behavior rules:
960- Speak clearly and confidently
961- Don't sound like a generic AI assistant
962- Use natural phrasing
963- Maintain consistent style across all formats
964
965{{styleInstruction}}
966
967Business constraints:
968- Don't mislead
969- Don't confuse platform subscription with audience monetization
970- Don't pretend to be human unless intended`,shorts_mode:`Short video mode (Shorts).
971Rules:
972- Start with a powerful hook — the first sentence must grab attention
973- Keep it 30-60 seconds of spoken text
974- One idea = one video
975- Ending: clear takeaway or call-to-action
976- Every word counts`,live_mode:`Live stream mode.
977Rules:
978- Speak smoothly and naturally
979- Make transitions between segments
980- Invite the audience to ask questions
981- Stay on topic but react to chat
982- Summarize every 5-7 minutes`,chat_reply_mode:`Live chat reply mode.
983Rules:
984- Keep replies to 1-3 sentences
985- Maintain persona style
986- Don't break the stream flow
987- If question is complex — promise to return to it later
988- Be friendly`,consultation_mode:`Personal consultation mode.
989Rules:
990- Listen carefully, ask clarifying questions
991- Give structured, practical advice
992- Suggest concrete next steps
993- Keep focus on value, not showmanship
994- Admit when you don't know something`,webinar_mode:`Educational webinar mode.
995Rules:
996- Structure: intro → blocks → summary
997- Explain complex things simply, with examples
998- Repeat key points
999- Make smooth transitions between blocks
1000- Remind the audience of the value they're getting`,repurposing_mode:`Content repurposing mode.
1001Rules:
1002- Find the most quotable, impactful moments
1003- Create a hook and title for each clip
1004- Format: 15-60 seconds per clip
1005- Preserve original tone
1006- Add a short summary for each fragment`,speaking_animation_mode:`Avatar animation during speech.
1007Rules:
1008- Avatar should look naturally speaking
1009- Light hand gestures emphasizing speech
1010- Facial expression matches tone — smile for positive, serious for important
1011- Smooth movements, not jerky
1012- Gaze directed at camera (at the viewer)`,idle_animation_mode:`Avatar animation while idle (not speaking).
1013Rules:
1014- Avatar looks alive but calm
1015- Light breathing, subtle swaying
1016- May blink, change facial expression
1017- Doesn't freeze like a statue
1018- Creates a sense of presence and attention`,video_prompt:`Realistic close-up video of a person talking.
1019Rules:
1020- Natural soft lighting, warm skin tone
1021- Sharp focus on the face, clear eyes and lips
1022- Smooth lip-sync with the speech
1023- Subtle natural head and shoulder motion
1024- Stable camera, no jitter
1025- Calm non-distracting background, soft bokeh
1026- High quality, cinematic look`,video_negative_prompt:`low quality, blurry, out of focus, low resolution, pixelated, jpeg artifacts, compression artifacts, noise, grain,
1027deformed face, distorted face, asymmetric eyes, cross-eyed, extra eyes, missing eyes, melting face, plastic skin, waxy skin,
1028bad mouth, deformed lips, extra teeth, missing teeth, mouth out of sync,
1029extra fingers, missing fingers, deformed hands, mutated hands, fused fingers, extra limbs, missing limbs,
1030duplicate person, double face, cloned face, two heads,
1031flickering, frame jumps, motion blur, camera shake, jitter, warping,
1032watermark, text, captions, subtitles, logo, signature,
1033oversaturated, oversharpened, cartoon, anime, painting, 3d render, cgi`},LX={blogger:"AI blogger creating short video content",host:"AI host of live streams",consultant:"AI consultant for personal sessions",teacher:"AI teacher and mentor",lawyer:"AI lawyer and legal advisor",mixed:"universal AI character"},IX={friendly:"friendly and warm",professional:"professional and confident",casual:"casual and easygoing",academic:"academic and precise",neutral:"neutral and balanced"},OX={calm:"Speak calmly and expertly, without fuss.",energetic:"Be energetic, keep the pace, fire up the audience.",friendly:"Chat like a good friend — warm and open.",premium:"Maintain a premium tone — confident, no filler.",mentor:"Explain like a mentor — patiently, with examples, step by step.",sad:"Speak with melancholy and depth — thoughtful, reflective, with a touch of sadness."},DX={nameTitle:"What's your persona's name?",nameDesc:"Come up with a name for your AI avatar",namePlaceholder:"E.g.: Alex, Dr. AI, Maria",next:"Next",orientationTitle:"Video format",orientationDesc:"Choose avatar orientation for video generation",portraitLabel:"Portrait",portraitSize:"720×1280 (9:16) · Shorts, Reels",landscapeLabel:"Landscape",landscape
1033Size:"1280×720 (16:9) · YouTube, webinars",avatarTitle:"Choose an avatar",avatarDesc:"Upload your own image or pick from presets",uploadOwn:"Upload your own",cropTitle:"Adjust cropping",cropDesc:"Move and scale the image",saving:"Saving...",roleTitle:"Choose a role",roleDesc:"The role determines prompt style and AI behavior",styleTitle:"Choose a style",styleDesc:"Style affects tone and communication character",finish:"Create persona"},MX={title:"Visual Filters",desc:"Filter settings for live streams and video content",background:"Background restoration",bgMin:"0 — no restoration",bgMax:"1 — maximum",face:"Face restoration",faceMin:"0 — no restoration",faceMax:"1 — maximum"},zX={title:"Generation prompts (advanced)",subtitle:"Templates the AI uses when it plans a webinar, synthesises a topic and clusters trends on its own. Empty = built-in default is used.",loadingDefaults:"Loading default texts…",custom:"Custom",resetDefault:"Reset to default",emptyPlaceholder:"Leave empty to use the built-in default.",placeholdersHint:"{{var}} placeholders are supported and filled automatically.",keys:{webinar_plan_block:{label:"Webinar plan block (1.1–1.5)",desc:"Template for one block of the plan. Controls tone, sections, length — main source of the host's 'own opinion'."},topic_synthesis:{label:"Topic synthesis from sources",desc:"How the AI assembles title/summary/key_points from discovered trends and pains."},trending_cluster:{label:"Trending themes clustering (global)",desc:"How the AI groups raw global signals (YouTube/Reddit/HN) into broadcast themes for the global trends feed."},trending_juice:{label:"Deep brief for chosen topic (Trends)",desc:"How the AI squeezes pains/desires/quotes/contrarian angles out of top videos, comments and Reddit for the user's topic_query."},speaking_format:{label:"On-air delivery format (Trends)",desc:"How the host speaks on a nonstop stream: tone, length per theme, how to use opening_line and talking_points."},continue_text:{label:"Continue line",desc:"What the persona says between plan blocks. Will be translated into the persona language."},summary_text:{label:"Closing line",desc:"What the persona says at the end of the webinar. Will be translated into the persona language."}}},FX={pageTitle:HZ,pageSubtitle:WZ,emptySubtitle:GZ,noPersonas:YZ,noPersonasDesc:KZ,createPersona:QZ,createNew:JZ,deleteTitle:ZZ,deleteDesc:XZ,cancel:eX,delete:"Delete",clone:tX,cloneTitle:sX,cloneDesc:nX,cloning:rX,replaceAvatar:aX,replaceAvatarTitle:iX,replaceAvatarDesc:oX,extraPhotos:lX,preview:cX,scrollToSettings:dX,portrait:uX,landscape:hX,profile:mX,languages:pX,voice:fX,voices:gX,avatarPresets:xX,customVoice:vX,voiceBrowser:yX,memory:bX,systemPrompt:wX,advanced:jX,saving:_X,save:kX,saved:NX,createContentPlan:SX,contentPlan:CX,wizardAutoDesc:TX,wizardFallbackRole:PX,roles:EX,styles:AX,promptLayers:RX,defaultPrompts:$X,roles_map:LX,tone_map:IX,style_map:OX,wizard:DX,filters:MX,generationPrompts:zX},UX="Настройки",BX="Управляйте профилем, уведомлениями и безопасностью аккаунта.",VX={profile:"Профиль",notifications:"Уведомления",security:"Безопасность",publicApi:"Public API"},qX={title:"Профиль",user:"Пользователь",googleLogin:"Вход через Google",name:"Имя",namePlaceholder:"Ваше имя",email:"Email",language:"Язык интерфейса",timezone:"Часовой пояс",defaultLanguage:"Русский",defaultTimezone:"Europe/Moscow (UTC+3)",save:"Сохранить",billingNote:"Для управления подпиской перейдите в",billingLink:"Оплату"},HX={title:"Уведомления",newFeatures:"Email-уведомления о новых функциях",liveStatus:"Уведомления о статусе эфиров",weeklyReport:"Еженедельный отчёт по аналитике",billing:"Уведомления о биллинге и оплате",tips:"Советы и рекомендации платформы",save:"Сохранить"},WX={title:"Безопасность",loginMethod:"Способ входа",googleAccount:"Аккаунт Google",active:"Активно",loginNote:"Вход в платформу выполняется через Google. Управление паролем и безопасностью аккаунта — в настройках вашего Google-аккаунта.",activeSessions:"Активные сессии",currentBrowser:"Текущий браузер",lastActivity:"Последняя активность: сейчас",sessionActive:"Активна",signOut:"Выйти из аккаунта"}
1033,GX={title:"Public API ключи",subtitle:"Ключи для внешних сайтов, использующих наш API генерации говорящих аватаров.",createKey:"Создать ключ",refresh:"Обновить",loading:"Загрузка…",empty:"Ключей пока нет. Создайте первый, чтобы начать.",active:"Активен",revoked:"Отозван",revoke:"Отозвать",revoking:"Отзываем…",cancel:"Отмена",create:"Создать",creating:"Создаём…",done:"Готово",namePlaceholder:"Например: production-site",createDesc:"Дайте ключу понятное имя, чтобы потом легко его узнать.",savedTitle:"Ключ создан",savedDesc:"Сохраните ключ и webhook-секрет — мы покажем их только один раз.",savedWarning:"Этот ключ и секрет больше нигде не будут показаны. Сохраните их в безопасном месте.",apiKey:"API ключ",webhookSecret:"Webhook secret (для проверки HMAC подписи)",revokeTitle:"Отозвать ключ?",revokeDesc:"Ключ «{{name}}» сразу перестанет работать. Это действие нельзя отменить.",col:{name:"Имя",prefix:"Префикс",created:"Создан",lastUsed:"Последнее использование",status:"Статус"},endpoint:{baseUrlLabel:"Базовый URL",docsLink:"Полная документация API →",curlLabel:"Пример: создать видео с аватаром",authNote:"Передавайте ключ в заголовке Authorization: Bearer plk_live_…"}},YX={pageTitle:UX,pageSubtitle:BX,tabs:VX,profile:qX,notifications:HX,security:WX,publicApi:GX},KX="Settings",QX="Manage your profile, notifications and account security.",JX={profile:"Profile",notifications:"Notifications",security:"Security",publicApi:"Public API"},ZX={title:"Profile",user:"User",googleLogin:"Google login",name:"Name",namePlaceholder:"Your name",email:"Email",language:"Interface language",timezone:"Timezone",defaultLanguage:"English",defaultTimezone:"Europe/London (UTC+0)",save:"Save",billingNote:"To manage your subscription, go to",billingLink:"Billing"},XX={title:"Notifications",newFeatures:"Email notifications about new features",liveStatus:"Stream status notifications",weeklyReport:"Weekly analytics report",billing:"Billing and payment notifications",tips:"Platform tips and recommendations",save:"Save"},eee={title:"Security",loginMethod:"Login method",googleAccount:"Google Account",active:"Active",loginNote:"Login is done via Google. Password and account security management is in your Google Account settings.",activeSessions:"Active sessions",currentBrowser:"Current browser",lastActivity:"Last activity: now",sessionActive:"Active",signOut:"Sign out"},tee={title:"Public API keys",subtitle:"Keys for external sites using our talking-avatar generation API.",createKey:"Create key",refresh:"Refresh",loading:"Loading…",empty:"No keys yet. Create your first one to get started.",active:"Active",revoked:"Revoked",revoke:"Revoke",revoking:"Revoking…",cancel:"Cancel",create:"Create",creating:"Creating…",done:"Done",namePlaceholder:"e.g. production-site",createDesc:"Give your key a recognizable name.",savedTitle:"Key created",savedDesc:"Save your key and webhook secret — we'll only show them once.",savedWarning:"This key and secret won't be shown again. Store them somewhere safe.",apiKey:"API key",webhookSecret:"Webhook secret (for HMAC signature verification)",revokeTitle:"Revoke key?",revokeDesc:'Key "{{name}}" will stop working immediately. This cannot be undone.',col:{name:"Name",prefix:"Prefix",created:"Created",lastUsed:"Last used",status:"Status"},endpoint:{baseUrlLabel:"Base URL",docsLink:"Full API docs →",curlLabel:"Example: create an avatar video",authNote:"Send the key in the Authorization header: Bearer plk_live_…"}},see={pageTitle:KX,pageSubtitle:QX,tabs:JX,profile:ZX,notifications:XX,security:eee,publicApi:tee},nee="Оплата и подписка",ree="Управляйте подпиской на платформу, тарифом, оплатой и историей биллинга.",aee={nextRenewal:"Следующее обновление: {{date}}",cycle:"Цикл: ежемесячно",manageSub:"Управление подпиской",upgradePro:"Перейти на Pro"},iee={title:"Тарифные планы",monthly:"Ежемесячно",yearly:"Ежегодно",discount:"−20%",re
1033commended:"Рекомендуем",currentPlan:"Текущий план",free:"Бесплатный",select:"Выбрать",perMonth:"/мес",perMonthYear:"/мес/год"},oee={personas:"ИИ-персонажей",shortsPerMonth:"Shorts / мес",liveCenter:"Live Center",monetizationTools:"Инструменты монетизации",integrations:"Интеграции",analytics:"Аналитика",unlimited:"Без лимита",yes:"Да",no:"—",basic:"Базовые",full:"Полные",extended:"Расширенная",complete:"Полная",all:"Все"},lee={title:"Кредиты",since:"Период начат {{date}}",videoEquiv:"Рендер видео",liveEquiv:"Прямой эфир",min:"мин",rules:"{{videoCost}} кредит за секунду видео, {{liveCost}} кредита за секунду стрима. Начисляются ежемесячно.",historyTitle:"Последние операции",kinds:{grant_monthly:"Ежемесячное начисление",grant_initial:"Приветственный бонус",consume_video:"Рендер видео",consume_live:"Прямой эфир",topup:"Пополнение",refund:"Возврат",admin_adjust:"Корректировка"}},cee={pageTitle:nee,pageSubtitle:ree,currentPlan:aee,plans:iee,features:oee,credits:lee},dee="Billing & Subscription",uee="Manage your platform subscription, plan, payments and billing history.",hee={nextRenewal:"Next renewal: {{date}}",cycle:"Cycle: monthly",manageSub:"Manage subscription",upgradePro:"Upgrade to Pro"},mee={title:"Pricing plans",monthly:"Monthly",yearly:"Yearly",discount:"−20%",recommended:"Recommended",currentPlan:"Current plan",free:"Free",select:"Select",perMonth:"/mo",perMonthYear:"/mo/yr"},pee={personas:"AI personas",shortsPerMonth:"Shorts / month",liveCenter:"Live Center",monetizationTools:"Monetization tools",integrations:"Integrations",analytics:"Analytics",unlimited:"Unlimited",yes:"Yes",no:"—",basic:"Basic",full:"Full",extended:"Extended",complete:"Complete",all:"All"},fee={title:"Credits",since:"Period started {{date}}",videoEquiv:"Video render",liveEquiv:"Live stream",min:"min",rules:"{{videoCost}} credit per second of video, {{liveCost}} credits per second of live stream. Refilled monthly.",historyTitle:"Recent activity",kinds:{grant_monthly:"Monthly grant",grant_initial:"Welcome grant",consume_video:"Video render",consume_live:"Live streaming",topup:"Top-up",refund:"Refund",admin_adjust:"Adjustment"}},gee={pageTitle:dee,pageSubtitle:uee,currentPlan:hee,plans:mee,features:pee,credits:fee},xee="Монетизация",vee="Постройте путь от бесплатного контента к подпискам, консультациям, вебинарам и премиальным продуктам.",yee="Загружаем монетизацию…",bee="Готовность к монетизации",wee={channelCreated:"Канал создан",shortsPublished:"Shorts публикуются",liveRunning:"Live идут",audienceForming:"Аудитория формируется",patreonConnected:"Patreon подключён",premiumLaunched:"Премиальные форматы запущены"},jee="Способы монетизации вашей аудитории",_ee={ytGrowth:{title:"YouTube рост и монетизация",desc:"Shorts, live-эфиры, рост аудитории и нативная монетизация YouTube."},memberLayer:{title:"Слой участников",desc:"Подписки на канал с эксклюзивным контентом для участников."},patreonSubs:{title:"Patreon подписки",desc:"Платное сообщество с закрытыми разборами и бонусами."},paidLive:{title:"Платные live-сессии",desc:"Закрытые эфиры по билетам или для подписчиков."},webinars:{title:"Вебинары",desc:"Обучающие мероприятия с платным доступом."},consultations:{title:"1:1 Консультации",desc:"Персональные сессии с ИИ-консультантом."},archive:{title:"Доступ к архиву",desc:"Библиотека записей эфиров и разборов за подписку."},courses:{title:"Премиальные курсы",desc:"Образовательные продукты на основе вашего контента."}},kee="Активно",Nee="Настроить",See="Скоро",Cee="Рекомендуемый порядок запуска",Tee={shorts:"Shorts",freeLive:"Free live",clips:"Нарезки",repeatViewers:"Повторные зрители",patreon:"Patreon",webinars:"Вебинары",consultations:"Консультации"},Pee="Шаг {{n}}",Eee="Ваш следующий шаг к доходу",Aee="Проведите 2 бесплатных эфира и создайте 10 Shorts на их основе. Затем подготовьте первый платный формат — это самый быстрый путь к монетизации вашей аудитории.",Ree="Начать путь",$ee="Монетизация ≠ подписка на платформу",Lee="Оплата подписки на платформу и монетизация вашей аудитории — это разные процессы. Подписка на нашу платформу управляется в",Iee="Billing",Oee="Монетизация вашей аудитории строится через YouTube, Patreon и ваши собственные платные форматы.",Dee={pageTitle:xee,pageSubtitle:vee,loading:yee,readinessTitle:bee,readiness:wee,cardsTitle:jee,cards:_ee,statusActive:kee,statusSetup:Nee,statusSoon:See,launchTitle:Cee,launchSteps:Tee,step:Pee,ctaTitle:Eee,ctaDesc:Aee,ctaButton:Ree,noteTitle:$ee,noteDesc:Lee,billing:Iee,noteDesc2:Oee},Mee="Monetization",zee="Build a path from free content to subscriptions, consultations, webinars, and premium products.",Fee="Loading monetization…",Uee="Monetization Readiness",Bee={channelCreated:"Channel created",shortsPublished:"Shorts published",liveRunning:"Live sessions running",audienceForming:"Audience forming",patreonConnected:"Patreon connected",premiumLaunched:"Premium formats launched"},Vee="Ways to monetize your audience",qee={ytGrowth:{title:"YouTube growth & monetization",desc:"Shorts, live streams, audience growth and native YouTube monetization."},memberLayer:{title:"Membership layer",desc:"Channel subscriptions with exclusive member content."},patreonSubs:{title:"Patreon subscriptions",desc:"Paid community with exclusive breakdowns and bonuses."}
1033,paidLive:{title:"Paid live sessions",desc:"Gated streams by ticket or for subscribers."},webinars:{title:"Webinars",desc:"Educational events with paid access."},consultations:{title:"1:1 Consultations",desc:"Personal sessions with your AI consultant."},archive:{title:"Archive access",desc:"Library of stream recordings and breakdowns by subscription."},courses:{title:"Premium courses",desc:"Educational products based on your content."}},Hee="Active",Wee="Set up",Gee="Soon",Yee="Recommended launch order",Kee={shorts:"Shorts",freeLive:"Free live",clips:"Clips",repeatViewers:"Repeat viewers",patreon:"Patreon",webinars:"Webinars",consultations:"Consultations"},Qee="Step {{n}}",Jee="Your next step to revenue",Zee="Run 2 free live sessions and create 10 Shorts from them. Then prepare your first paid format — the fastest path to monetizing your audience.",Xee="Start the journey",ete="Monetization ≠ platform subscription",tte="Your platform subscription and audience monetization are separate processes. Platform subscription is managed in",ste="Billing",nte="Audience monetization is built through YouTube, Patreon, and your own paid formats.",rte={pageTitle:Mee,pageSubtitle:zee,loading:Fee,readinessTitle:Uee,readiness:Bee,cardsTitle:Vee,cards:qee,statusActive:Hee,statusSetup:Wee,statusSoon:Gee,launchTitle:Yee,launchSteps:Kee,step:Qee,ctaTitle:Jee,ctaDesc:Zee,ctaButton:Xee,noteTitle:ete,noteDesc:tte,billing:ste,noteDesc2:nte},ate="Аналитика",ite="Отслеживайте рост, вовлечённость и прогресс вашего ИИ-медиа-бизнеса.",ote="Загружаем аналитику…",lte="Загружаем данные YouTube…",cte="Не удалось загрузить аналитику YouTube",dte="Повторить",ute="Пока нет данных для аналитики",hte="Создайте первые Shorts или проведите live-эфир — аналитика начнёт собираться автоматически.",mte="Создать Shorts",pte="YouTube не подключён",fte="Подключите YouTube-канал, чтобы видеть реальную аналитику — подписчики, просмотры, статистику видео.",gte="Подключить YouTube",xte={subscribers:"Подписчики",totalViews:"Всего просмотров",videoCount:"Видео на канале",shortsPublished:"Shorts опубликовано",liveHeld:"Live проведено"},vte="Канал",yte="Последние видео",bte="На канале пока нет видео",wte="просмотров",jte="лайков",_te="комментариев",kte="Опубликовано",Nte="Стадия развития бизнеса",Ste={setup:{label:"Настройка",desc:"Создание персонажа и подключение YouTube"},publishing:{label:"Публикация",desc:"Первые Shorts и контент-серии"},streaming:{label:"Эфиры",desc:"Регулярные live-эфиры и Q&A"},monetization:{label:"Монетизация",desc:"Patreon, платные эфиры, консультации"},scale:{label:"Масштаб",desc:"Масштабирование и автоматизация"}},Cte="Сейчас",Tte="Рекомендации",Pte=["Создайте первые 5 Shorts, чтобы начать собирать данные о вовлечённости.","Проведите первый live-эфир, чтобы построить доверие аудитории.","После 10 публикаций подключите Patreon для платного слоя.","Запустите первый платный формат после 2 бесплатных эфиров."],Ete={pageTitle:ate,pageSubtitle:ite,loading:ote,loadingYouTube:lte,errorFetch:cte,retry:dte,emptyTitle:ute,emptyDesc:hte,emptyAction:mte,notConnected:pte,notConnectedDesc:fte,connectYouTube:gte,kpis:xte,channelTitle:vte,recentVideosTitle:yte,recentVideosEmpty:bte,videoViews:wte,videoLikes:jte,videoComments:_te,publishedAt:kte,stageTitle:Nte,stages:Ste,stageNow:Cte,insightsTitle:Tte,insights:Pte},Ate="Analytics",Rte="Track growth, engagement, and progress of your AI media business.",$te="Loading analytics…",Lte="Fetching YouTube data…",Ite="Failed to load YouTube analytics",Ote="Retry",Dte="No anal
1033ytics data yet",Mte="Create your first Shorts or run a live stream — analytics will start collecting automatically.",zte="Create Shorts",Fte="YouTube not connected",Ute="Connect your YouTube channel to see real analytics data — subscribers, views, and video performance.",Bte="Connect YouTube",Vte={subscribers:"Subscribers",totalViews:"Total views",videoCount:"Videos on channel",shortsPublished:"Shorts published",liveHeld:"Live sessions held"},qte="Channel",Hte="Recent videos",Wte="No videos on the channel yet",Gte="views",Yte="likes",Kte="comments",Qte="Published",Jte="Business development stage",Zte={setup:{label:"Setup",desc:"Persona creation and YouTube connection"},publishing:{label:"Publishing",desc:"First Shorts and content series"},streaming:{label:"Streaming",desc:"Regular live streams and Q&A"},monetization:{label:"Monetization",desc:"Patreon, paid streams, consultations"},scale:{label:"Scale",desc:"Scaling and automation"}},Xte="Now",ese="Recommendations",tse=["Create your first 5 Shorts to start collecting engagement data.","Run your first live stream to build audience trust.","After 10 publications, connect Patreon for a paid tier.","Launch your first paid format after 2 free streams."],sse={pageTitle:Ate,pageSubtitle:Rte,loading:$te,loadingYouTube:Lte,errorFetch:Ite,retry:Ote,emptyTitle:Dte,emptyDesc:Mte,emptyAction:zte,notConnected:Fte,notConnectedDesc:Ute,connectYouTube:Bte,kpis:Vte,channelTitle:qte,recentVideosTitle:Hte,recentVideosEmpty:Wte,videoViews:Gte,videoLikes:Yte,videoComments:Kte,publishedAt:Qte,stageTitle:Jte,stages:Zte,stageNow:Xte,insightsTitle:ese,insights:tse},nse="Консультации",rse="Используйте ИИ-консультанта как премиальный формат прямой помощи, разборов и голосовых сессий.",ase="Загружаем консультации…",ise="Нет созданных офферов",ose="Создайте первый оффер на консультацию — выберите тип и заполните форму ниже.",lse="Типы консультаций",cse={quick:{label:"Быстрый ответ",desc:"Быстрый ответ на один конкретный вопрос"},deep:{label:"Глубокий разбор",desc:"Глубокий разбор темы или проблемы"},strategy:{label:"Стратегическая сессия",desc:"Стратегическая сессия с планом действий"},qa:{label:"Закрытый Q&A",desc:"Закрытая сессия вопросов и ответов"},premium:{label:"Премиум-консультация",desc:"Премиальная консультация с расширенным доступом"}},dse="{{min}} мин",use="Создать оффер",hse={name:"Название",duration:"Длительность",persona:"Персонаж",topic:"Тема",format:"Формат",price:"Цена (внешняя)",pricePlaceholder:"Укажите цену для клиентов",description:"Описание",language:"Язык",sttLanguage:"Язык распознавания речи"},mse={ru:"Русский",en:"Английский",auto:"Автоопределение"},pse={expert:"AI Эксперт",consultant:"Консультант"},fse="Создать оффер",gse="Сохраняем…",xse="Превью оффера",vse="Голосовая",yse="1 на 1",bse="Приватная",wse="Цена для клиента:",jse="Черновик",_se="Опубликован",kse="Где консультации в воронке монетизации",Nse={shorts:{label:"Shorts",sub:"Внимание"},live:{label:"Live",sub:"Доверие"},patreon:{label:"Patreon",sub:"Подписка"},webinar:{label:"Вебинар",sub:"Обучение"},consultation:{label:"Консультация",sub:"Премиум"}},Sse="Консультации — это верхний слой монетизации. Ваша аудитория приходит через Shorts, доверяет вам через live, платит через Patreon, а самые вовлечённые клиенты покупают персональные сессии.",Cse="Разбор AI-стратегии",Tse="Персональная стратегическая сессиÑ
1033 по запуску AI-контента и монетизации.",Pse="AI-стратегия и монетизация",Ese="Оффер сохранён",Ase="Ошибка сохранения оффера",Rse="Ваши офферы",$se="Редактировать",Lse="Удалить",Ise="Опубликовать",Ose="Публикация оффера",Dse="Выберите, куда опубликовать этот оффер",Mse="Опубликовать в Patreon",zse="Создать ссылку",Fse="Ссылка скопирована",Use="Разовая ссылка на консультацию",Bse="Поделитесь ссылкой с клиентом. Он сможет начать консультацию без регистрации.",Vse="Скопировать ссылку",qse="Закрыть",Hse={draft:"Черновик",published:"Опубликован"},Wse={title:"Ссылки",empty:"Ссылки ещё не созданы",deactivate:"Деактивировать",timeUsed:"{{used}} / {{total}} мин",noTime:"не начата",info:"Подробнее",infoTitle:"Детали ссылки",infoCreated:"Создана",infoStatus:"Статус",infoClient:"Клиент",infoSessions:"Сессий",infoTotalTime:"Общее время",infoSessionsTitle:"История сессий",min:"мин",status:{new:"Новая",active:"Активна",used:"Завершена",canceled:"Отменена",expired:"Истекла"}},Gse="Сначала создайте персону для использования консультаций",Yse="Вы уверены, что хотите удалить этот оффер?",Kse="Это действие нельзя отменить.",Qse="Отмена",Jse="Удалить",Zse={sectionTitle:"Сообщения AI",greetingLabel:"Приветствие",greetingPlaceholder:"Что AI-консультант скажет при начале сессии…",continueLabel:"Продолжение",continuePlaceholder:"Инструкция продолжать разговор по теме…",generate:"Сгенерировать AI",generating:"Генерация…"},Xse="Прервано",ene={badge:"AI Консультация",badgeVideo:"Видео",badge1on1:"1 на 1",nameLabel:"Ваше имя (необязательно)",namePlaceholder:"Введите ваше имя",start:"Начать консультацию",connecting:"Подключение…",connectingRoom:"Подключение к комнате консультации…",waitingVideo:"Ожидание видео AI-консультанта…",connected:"Подключено",workerWaiting:"Ожидание AI…",workerConnecting:"AI подключается…",workerActive:"AI активен",switchLang:"Переключить язык распознавания речи",hideSubtitles:"Скрыть субтитры",showSubtitles:"Показать субтитры",sttConnected:"STT подключён",sttDisconnected:"STT отключён",micMuted:"Микрофон отключён",micSensitivity:"Чувствительность микрофона",sttUnavailable:"Голосовой ввод недоступен.",sttRetry:"Повторить",chatPlaceholder:"Напишите сообщение…",reconnecting:"Переподключение…",reconnectTitle:"Переподключение",reconnectDesc:"AI-консультант ненадолго отключился. Переподключение (попытка {{attempt}}/{{max}})…",reconnectWait:"Небольшой перебой — переподключаемся к сессии…",reconnectingAttempt:"Переподключение (попытка {{attempt}}/{{max}})…",sessionEnded:"Сессия завершена",sessionEndedPersona:"Консультация с {{name}} завершена. Спасибо!",sessionEndedTimer:"Время консультации истекло ({{min}} мин). Спасибо!",disconnected:"Соединение разорвано",connectionLost:"Соединение потеряно",connectionLostDesc:"Соединение было прервано. Если AI-консультант ещё не подключился, попробуйте снова через пару секунд.",workerLeft:"AI-консультант покин
1033ул комнату. Комната автоматически закрыта.",workerLeftDesc:"AI-консультант завершил сессию и покинул комнату.",workerLeftTitle:"Извините, AI-консультант временно отключился",workerLeftCanContinue:"Можете продолжить с того места, где остановились — когда вам будет удобно. Прошлый диалог сохранён и AI его помнит.",continueSession:"Продолжить консультацию",timeRemaining:"Осталось времени: {{time}}",usedTime:"Использовано: {{used}} из {{total}} мин",timeLeft:"Осталось: {{min}} мин",manualEnd:"Вы завершили сессию",youEndedTitle:"Вы завершили сессию",manualEndDesc:"Вы завершили консультацию. Спасибо за сессию!",manualEndCanContinue:"Вы завершили сессию {{used}} из {{max}}. Можете продолжить.",attemptsLeft:"Сессия {{used}} из {{max}}",sessionsLeft:"Сессия {{used}}/{{max}}",roomClosed:"Сервер закрыл комнату — сессия завершена",roomDeleted:"Комната была удалена сервером",notFound:"Консультация не найдена или срок истёк",unavailable:"Эта консультация больше недоступна",invalidLink:"Неверная ссылка",connectionError:"Не удалось подключиться к голосовой комнате: ",chatEmpty:"Говорите в микрофон или напишите сообщение",chatNoMessages:"Нет сообщений в этой сессии",minutesShort:"мин",secondsShort:"сек",waitingWorkerTitle:"Ожидаем AI-консультанта",waitingWorkerDesc:"Комната готова. AI-консультант подключается — обычно это занимает 10–30 секунд.",waitStepRoom:"Комната создана",waitStepJob:"Задача отправлена воркеру",waitStepWorker:"AI-консультант подключается…",waitStepWorkerClaimed:"AI-консультант забрал задачу, подключается…",waitingElapsed:"Ожидание: {{sec}} сек",waitingLong:"Подключение занимает больше обычного. Подождите ещё немного…",waitingVeryLong:"AI-консультант не отвечает. Если ожидание затянется, попробуйте обновить страницу.",workerTimeout:"AI-консультант не подключился вовремя. Сессия возвращена.",cancelWaiting:"Отменить",weakConnection:"Слабое соединение",retrying:"Проблемы с подключением, повторяем…",alreadyConnectedTitle:"Сессия уже идёт в другом окне",alreadyConnectedDesc:"Похоже, вы уже находитесь в этой консультации в другой вкладке или на другом устройстве. Закройте предыдущее окно и попробуйте снова."},tne={pageTitle:nse,pageSubtitle:rse,loading:ase,emptyTitle:ise,emptyDesc:ose,typesTitle:lse,types:cse,duration:dse,createTitle:use,fields:hse,languages:mse,personaOptions:pse,createOffer:fse,saving:gse,previewLabel:xse,badgeVoice:vse,badge1on1:yse,badgePrivate:bse,clientPrice:wse,draft:jse,published:_se,funnelTitle:kse,funnelSteps:Nse,funnelDesc:Sse,defaultName:Cse,defaultDesc:Tse,defaultTopic:Pse,savedOk:Ese,savedError:Ase,offersTitle:Rse,editOffer:$se,deleteOffer:Lse,publishOffer:Ise,publishModalTitle:Ose,publishModalDesc:Dse,publishPatreon:Mse,publishLink:zse,linkCopied:Fse,linkTitle:Use,linkDesc:Bse,copyLink:Vse,closeLink:qse,offerStatus:Hse,links:Wse,noPersona:Gse,deleteConfirm:Yse,deleteConfirmDesc:Kse,cancel:Qse,confirm:Jse,autoMessages:Zse,bargeIn:Xse,join:ene},sne="Consultations",nne="Use an AI consultant as a premium format for direct help, breakdowns, and voice sessions.",rne="Loading consultations…",ane="No offers created",ine="Create your first consultation offer — choose a type and fill out the form below.",one="Consultation types",lne={quick:{label:"Quick answer",desc:"Quick answer to a specific question"},deep:{label:"Deep analysis",desc:"In-depth analysis of a topic or problem"},strategy:{label:"Strategy session",desc:"Strategic session with an action plan"},qa:{label:"Private Q&A",desc:"Private question and answer session"},premium:{label:"Premium consultation",desc:"Premium consultation with extended access"}},cne="{{min}}
1033 min",dne="Create offer",une={name:"Name",duration:"Duration",persona:"Persona",topic:"Topic",format:"Format",price:"Price (external)",pricePlaceholder:"Enter price for clients",description:"Description",language:"Language",sttLanguage:"Speech recognition language"},hne={ru:"Russian",en:"English",auto:"Auto-detect"},mne={expert:"AI Expert",consultant:"Consultant"},pne="Create offer",fne="Saving…",gne="Offer preview",xne="Voice",vne="1-on-1",yne="Private",bne="Client price:",wne="Draft",jne="Published",_ne="Where consultations fit in the monetization funnel",kne={shorts:{label:"Shorts",sub:"Attention"},live:{label:"Live",sub:"Trust"},patreon:{label:"Patreon",sub:"Subscription"},webinar:{label:"Webinar",sub:"Education"},consultation:{label:"Consultation",sub:"Premium"}},Nne="Consultations are the top monetization layer. Your audience comes through Shorts, trusts you through live, pays through Patreon, and the most engaged clients buy personal sessions.",Sne="AI Strategy Breakdown",Cne="Personal strategy session on launching AI content and monetization.",Tne="AI strategy and monetization",Pne="Offer saved",Ene="Error saving offer",Ane="Your offers",Rne="Edit",$ne="Delete",Lne="Publish",Ine="Publish offer",One="Choose where to publish this offer",Dne="Publish to Patreon",Mne="Create link",zne="Link copied to clipboard",Fne="One-time consultation link",Une="Share this link with a client. They can start a consultation without registration.",Bne="Copy link",Vne="Close",qne={draft:"Draft",published:"Published"},Hne={title:"Links",empty:"No links created yet",deactivate:"Deactivate",timeUsed:"{{used}} / {{total}} min",noTime:"not started",info:"Details",infoTitle:"Link details",infoCreated:"Created",infoStatus:"Status",infoClient:"Client",infoSessions:"Sessions",infoTotalTime:"Total time",infoSessionsTitle:"Session history",min:"min",status:{new:"New",active:"Active",used:"Completed",canceled:"Canceled",expired:"Expired"}},Wne="Create a persona first to use consultations",Gne="Are you sure you want to delete this offer?",Yne="This action cannot be undone.",Kne="Cancel",Qne="Delete",Jne={sectionTitle:"AI messages",greetingLabel:"Greeting",greetingPlaceholder:"What the AI consultant says when starting the session…",continueLabel:"Continue talking",continuePlaceholder:"Instruction to keep the conversation going…",generate:"Generate with AI",generating:"Generating…"},Zne="Interrupted",Xne={badge:"AI Consultation",badgeVideo:"Video",badge1on1:"1-on-1",nameLabel:"Your name (optional)",namePlaceholder:"Enter your name",start:"Start consultation",connecting:"Connecting…",connectingRoom:"C
1033onnecting to consultation room…",waitingVideo:"Waiting for AI consultant video…",connected:"Connected",workerWaiting:"Waiting for AI…",workerConnecting:"AI joining…",workerActive:"AI active",switchLang:"Switch speech recognition language",hideSubtitles:"Hide subtitles",showSubtitles:"Show subtitles",sttConnected:"STT connected",sttDisconnected:"STT disconnected",micMuted:"Microphone is muted",micSensitivity:"Mic sensitivity",sttUnavailable:"Voice input unavailable.",sttRetry:"Retry",chatPlaceholder:"Type a message…",reconnecting:"Reconnecting…",reconnectTitle:"Reconnecting",reconnectDesc:"The AI consultant briefly disconnected. Reconnecting (attempt {{attempt}}/{{max}})…",reconnectWait:"Brief interruption — reconnecting to the session…",reconnectingAttempt:"Reconnecting (attempt {{attempt}}/{{max}})…",sessionEnded:"Session ended",sessionEndedPersona:"Consultation with {{name}} is complete. Thank you!",sessionEndedTimer:"Consultation time expired ({{min}} min). Thank you!",disconnected:"Connection lost",connectionLost:"Connection lost",connectionLostDesc:"The connection was interrupted. The session may have ended on the server side.",workerLeft:"AI consultant left the room. The room was automatically closed.",workerLeftDesc:"The AI consultant completed the session and left the room.",workerLeftTitle:"Sorry, the AI consultant briefly disconnected",workerLeftCanContinue:"You can pick up right where you left off whenever you're ready — your previous conversation is saved and the AI remembers it.",continueSession:"Continue consultation",timeRemaining:"Time remaining: {{time}}",usedTime:"Used: {{used}} of {{total}} min",timeLeft:"Remaining: {{min}} min",manualEnd:"You ended the session",youEndedTitle:"You ended the session",manualEndDesc:"You have ended the consultation. Thank you for the session!",manualEndCanContinue:"You ended session {{used}} of {{max}}. You can continue.",attemptsLeft:"Session {{used}} of {{max}}",sessionsLeft:"Session {{used}}/{{max}}",roomClosed:"Server closed the room — session ended",roomDeleted:"Room was deleted by server",notFound:"Consultation not found or expired",unavailable:"This consultation is no longer available",invalidLink:"Invalid link",connectionError:"Failed to connect to voice room: ",chatEmpty:"Speak into the microphone or type a message",chatNoMessages:"No messages in this session",minutesShort:"min",secondsShort:"sec",waitingWorkerTitle:"Waiting for AI Consultant",waitingWorkerDesc:"Room is ready. The AI consultant is connecting — this usually takes 10–30 seconds.",waitStepRoom:"Room created",waitStepJob:"Task sent to worker",waitStepWorker:"AI consultant connecting…",waitStepWorkerClaimed:"AI consultant claimed the task, connecting…",waitingElapsed:"Waiting: {{sec}} sec",waitingLong:"Connection is taking longer than usual. Please wait a bit more…",waitingVeryLong:"AI consultant is not responding. If the wait continues, try refreshing the page.",workerTimeout:"AI consultant did not connect in time. Your attempt has been returned.",cancelWaiting:"Cancel",weakConnection:"Weak connection",retrying:"Connection issue, retrying…",alreadyConnectedTitle:"Session already in another window",alreadyConnectedDesc:"It looks like you are already in this consultation in another tab or on another device. Close the other window and try again."},ere={pageTitle:sne,pageSubtitle:nne,loading:rne,emptyTitle:ane,emptyDesc:ine,typesTitle:one,types:lne,duration:cne,createTitle:dne,fields:une,languages:hne,personaOptions:mne,createOffer:pne,saving:fne,previewLabel:gne,badgeVoice:xne,badge1on1:vne,badgePrivate:yne,clientPrice:bne,draft:wne,published:jne,funnelTitle:_ne,funnelSteps:kne,funnelDesc:Nne,defaultName:Sne,defaultDesc:Cne,defaultTopic:Tne,savedOk:Pne,savedError:Ene,offersTitle:Ane,editOffer:Rne,deleteOffer:$ne,publishOffer:Lne,publishModalTitle:Ine,publishModalDesc:One,publishPatreon:Dne,publishLink:Mne,linkCopied:zne,linkTitle:Fne,linkDesc:Une,copyLink:Bne,closeLink:Vne,offerStatus:qne,links:Hne,noPersona:Wne,deleteConfirm:Gne,deleteConfirmDesc:Yne,cancel:Kne,confirm:Qne,autoMessages:Jne,bargeIn:Zne,join:Xne},tre="Интеграции",sre="Подключите платформы, Ð
1033½Ð° которых ваш ИИ-персонаж будет публиковаться, выходить в эфир и строить платный слой.",nre="Публичная площадка",rre="Платный слой",are="Загрузка...",ire="Подключено",ore="Подключение...",lre="Истёк",cre="Ошибка",dre="Не подключено",ure="Токен истёк",hre="Ошибка подключения",mre="Переподключите для продолжения работы.",pre={connectedDesc:"YouTube подключён. Используется для управления live-трансляциями (название, расписание, статус). Публикация клипов теперь идёт через социальный хаб ниже.",disconnectedDesc:"Подключите YouTube для управления live-трансляциями напрямую (название, расписание, жизненный цикл эфира). Для публикации клипов сразу в несколько сетей — используйте социальный хаб ниже.",features:["Бесплатные live-эфиры","Синхронизация метаданных эфира","Публичный рост аудитории","Основа live-трансляций"],connected:"Подключено",disconnect:"Отключить",reconnect:"Переподключить YouTube",connect:"Подключить YouTube",note:"YouTube подключается только для управления live-эфирами. Публикация Shorts/клипов в YouTube и другие сети идёт через социальный хаб."},fre={title:"Социальный хаб",subtitle:"Постинг клипов сразу в YouTube, TikTok, Instagram, Facebook, X и LinkedIn",longDesc:"Привяжите свои соцсети один раз — каждый сгенерированный клип публикуется во все сразу одним кликом. Посты идут от ваших собственных аккаунтов, не от нас.",linkedTitle:"Привязанные аккаунты",noneLinked:"Аккаунты ещё не привязаны — откройте хаб и добавьте YouTube, TikTok, Instagram, Facebook, X или LinkedIn.",openLinkPage:"Открыть социальный хаб",refresh:"Обновить статус",disconnect:"Отключить всё",createProfile:"Настроить социальный хаб",creating:"Создаём…",platforms:{youtube:"YouTube",tiktok:"TikTok",instagram:"Instagram",facebook:"Facebook",twitter:"X",linkedin:"LinkedIn"},note:"Каждый workspace получает свой приватный хаб. Мы никогда не постим от вашего имени, пока вы сами не привяжете соцсети."},gre={subtitle:"Мультистрим + единый чат для вебинаров",longDesc:"Подключи Restream — и вебинар уйдёт в YouTube, Twitch, Facebook, X и LinkedIn одновременно. Воркер сможет читать чат всех платформ через единый WebSocket.",connected:"Подключено",disconnect:"Отключить",reconnect:"Переподключить",connect:"Подключить Restream",note:"Понадобится аккаунт Restream. После подключения каналы (YouTube/Twitch/FB/...) добавляются один раз в самом Restream — повторная настройка не нужна."},xre={patrons:"патронов",connectedDesc:"Patreon подключён. Ваш платный слой готов — подписки, закрытые эфиры, бонусный контент и архив доступны для аудитории.",readyDesc:"Добавьте Patreon, чтобы открыть платный слой: подписки, закрытые эфиры, бонусный контент и архив для вашей аудитории.",notReadyDesc:"Подключите Patreon, когда будете готовы к платному слою. Рекомендуем сначала подключить YouTube и Ð
1033½Ð°Ð±Ñ€Ð°Ñ‚ÑŒ первую аудиторию.",features:["Платные подписки и tiers","Закрытые live-эфиры","Бонусный контент","Архив и премиум-материалы"],ytFirstWarning:"Сначала подключите YouTube и наберите аудиторию. Patreon станет следующим шагом для платного слоя.",connected:"Подключено",disconnect:"Отключить",reconnect:"Переподключить Patreon",connect:"Подключить Patreon",connectYtFirst:"Сначала подключите YouTube",note:"Patreon — это платный слой для вашей аудитории. Монетизация через Patreon не связана с подпиской на нашу платформу."},vre="Как это работает вместе",yre="Публичный уровень",bre="YouTube → рост и доверие",wre="Публичный уровень, где ИИ-блогер и ИИ-ведущий набирают внимание, аудиторию и доверие через бесплатный контент.",jre="Платный уровень",_re="Patreon → глубина и доступ",kre="Платный уровень, где самые вовлечённые зрители получают больше доступа, глубины и эксклюзивного контента.",Nre="рост + доверие",Sre="платный доступ",Cre="Рекомендуемый порядок",Tre=[{text:"Подключите YouTube",sub:"Это ваша публичная площадка для роста."},{text:"Запустите Shorts и live",sub:"Создайте первую серию контента и проведите эфир."},{text:"Подключите Patreon",sub:"Когда будете готовы к платному слою для аудитории."}],Pre={title:"Meta Ads",subtitle:"Реклама в Facebook и Instagram",connectedDesc:"Meta аккаунт подключён. Можно запускать рекламные кампании в Facebook и Instagram прямо из приложения.",disconnectedDesc:"Подключите Facebook, чтобы запускать рекламу в Facebook и Instagram, продвигать посты и собирать лиды.",features:["Реклама Facebook + Instagram","Продвижение постов","Lead Ads","Аналитика в реальном времени"],connect:"Подключить Facebook",reconnect:"Переподключить",connected:"Подключено",disconnect:"Отключить",adAccountLabel:"Рекламный кабинет",pageLabel:"Страница",instagramLabel:"Instagram",missingAdAccount:"Рекламный кабинет не найден. Создайте его в Meta Business Suite и переподключите.",selectAdAccount:"Выберите рекламный кабинет",selectPage:"Выберите Facebook-страницу",selectHint:"Все ваши кампании и реклама будут создаваться от имени выбранного кабинета и страницы.",saving:"Сохраняем…",note:"Понадобится Facebook Business аккаунт и рекламный кабинет. Токен живёт 60 дней — будем продлевать автоматически."},Ere={title:"Google Ads",subtitle:"Реклама на YouTube и в поиске Google",connectedDesc:"Google Ads подключён. Можно запускать видеорекламу на YouTube для продвижения ваших клипов прямо из приложения.",disconnectedDesc:"Подключите Google Ads, чтобы крутить видеорекламу на YouTube, продвигать клипы и находить новую аудиторию.",features:["Видеореклама на YouTube","Продвижение клипов и шортсов","Таргетинг по аудиториям","Управление ставками"],connect:"Подключить Google Ads",re
1033connect:"Переподключить",connected:"Подключено",disconnect:"Отключить",customerLabel:"Рекламный аккаунт",missingCustomer:"Google Ads аккаунт не найден. Создайте его на ads.google.com и переподключите.",selectCustomer:"Выберите Google Ads аккаунт",selectHint:"Все кампании будут создаваться от имени выбранного аккаунта.",note:"Нужен аккаунт Google Ads. Токены продлеваем автоматически. До одобрения Basic Access от Google доступ может быть в тестовом режиме."},Are={pageTitle:tre,pageSubtitle:sre,publicPlatform:nre,paidLayer:rre,statusLoading:are,statusConnected:ire,statusConnecting:ore,statusExpired:lre,statusError:cre,statusNotConnected:dre,tokenExpired:ure,connectionError:hre,reconnectNote:mre,yt:pre,ayrshare:fre,restream:gre,patreon:xre,howTitle:vre,publicLevel:yre,publicSub:bre,publicDesc:wre,paidLevel:jre,paidSub
1033:_re,paidDesc:kre,flowGrowth:Nre,flowPaid:Sre,setupTitle:Cre,setupSteps:Tre,meta:Pre,googleAds:Ere},Rre="Integrations",$re="Connect platforms where your AI persona will publish, go live, and build a paid layer.",Lre="Public platform",Ire="Paid layer",Ore="Loading...",Dre="Connected",Mre="Connecting...",zre="Expired",Fre="Error",Ure="Not connected",Bre="Token expired",Vre="Connection error",qre="Reconnect to continue.",Hre={connectedDesc:"YouTube connected. Used for managing live broadcasts (titles, schedule, status). Clip publishing now goes through the social hub below.",disconnectedDesc:"Connect YouTube to manage live broadcasts directly (titles, schedule, broadcast lifecycle). For posting clips to multiple networks at once, use the social hub below.",features:["Free live streams","Broadcast metadata sync","Public audience growth","Live-streaming foundation"],connected:"Connected",disconnect:"Disconnect",reconnect:"Reconnect YouTube",connect:"Connect YouTube",note:"YouTube is connected only for live broadcast management. Posting Shorts/clips to YouTube and other networks is handled through the social hub."},Wre={title:"Social hub",subtitle:"Post clips to YouTube, TikTok, Instagram, Facebook, X and LinkedIn at once",longDesc:"Link your social accounts once — every generated clip can be published to all of them with one click. Posts go from your own connected accounts, not from us.",linkedTitle:"Linked accounts",noneLinked:"No accounts linked yet — open the hub to add YouTube, TikTok, Instagram, Facebook, X or LinkedIn.",openLinkPage:"Open social hub",refresh:"Refresh status",disconnect:"Disconnect all",createProfile:"Set up social hub",creating:"Setting up…",platforms:{youtube:"YouTube",tiktok:"TikTok",instagram:"Instagram",facebook:"Facebook",twitter:"X",linkedin:"LinkedIn"},note:"Each workspace gets its own private hub. We never post on your behalf without your accounts being linked first."},Gre={subtitle:"Multistream + unified chat for webinars",longDesc:"Connect Restream — your webinar will go out to YouTube, Twitch, Facebook, X and LinkedIn at once. The worker can read chat from all platforms over a single WebSocket.",connected:"Connected",disconnect:"Disconnect",reconnect:"Reconnect",connect:"Connect Restream",note:"Requires a Restream account. After connecting, channels (YouTube/Twitch/FB/...) are added once inside Restream — no re-setup needed."},Yre={patrons:"patrons",connectedDesc:"Patreon connected. Your paid layer is ready — subscriptions, private streams, bonus content, and archive are available for your audience.",readyDesc:"Add Patreon to unlock the paid layer: subscriptions, private streams, bonus content, and archive for your audience.",notReadyDesc:"Connect Patreon when you're ready for a paid layer. We recommend connecting YouTube first and building an audience.",features:["Paid subscriptions & tiers","Private live streams","Bonus content","Archive & premium materials"],ytFirstWarning:"Connect YouTube first and build an audience. Patreon will be the next step for your paid layer.",connected:"Connected",disconnect:"Disconnect",reconnect:"Reconnect Patreon",connect:"Connect Patreon",connectYtFirst:"Connect YouTube first",note:"Patreon is a paid layer for your audience. Monetization through Patreon is not related to your platform subscription."},Kre="How it works together",Qre="Public level",Jre="YouTube → growth and trust",Zre="Public level where your AI blogger and host gain attention, audience, and trust through free content.",Xre="Paid level",eae="Patreon → depth and access",tae="Paid level where the most engaged viewers get more access, depth, and exclusive content.",sae="growth + trust",nae="paid access",rae="Recommended order",aae=[{text:"Connect YouTube",sub:"This is your public platform for growth."},{text:"Launch Shorts and live",sub:"Create your first content series and run a live stream."},{text:"Connect Patreon",sub:"When you're ready for a paid layer for your audience."}],iae={title:"Meta Ads",subtitle:"Facebook & Instagram advertising",connectedDesc:"Meta account connected. You can launch Facebook and Instagram ad campaigns right from the app.",disconnectedDesc:"Connect Facebook to run ads on Facebook and Instagram, boost posts, and collect leads.",features:["Facebook + Instagram ads","Boost posts","Lead Ads","Real-time analytics"],connect:"Connect Facebook",reconnect:"Reconnect",connected:"Connected",disconnect:"Disconnect",adAccountLabel:"Ad account",pageLabel:"Page",instagramLabel:"Instagram",missingAdAccount:"No ad account found. Create one in Meta Business Suite and reconnect.",selectAdAccount:"Choose ad account",selectPage:"Cho
1033ose Facebook page",selectHint:"All campaigns and ads will be created under the selected ad account and page.",saving:"Saving…",note:"A Facebook Business account and ad account are required. Tokens last 60 days — we'll refresh them automatically."},oae={title:"Google Ads",subtitle:"YouTube video advertising & Search ads",connectedDesc:"Google Ads account connected. You can launch YouTube video ads to promote your content from the app.",disconnectedDesc:"Connect Google Ads to run YouTube video ads, promote your clips, and reach new viewers.",features:["YouTube video ads","Promote shorts & clips","Audience targeting","Bid management"],connect:"Connect Google Ads",reconnect:"Reconnect",connected:"Connected",disconnect:"Disconnect",customerLabel:"Ads account",missingCustomer:"No Google Ads account found. Create one at ads.google.com and reconnect.",selectCustomer:"Choose Google Ads account",selectHint:"All campaigns will be created under the selected account.",note:"Requires a Google Ads account. We refresh tokens automatically. Developer access may be in test mode until Google approves Basic Access."},lae={pageTitle:Rre,pageSubtitle:$re,publicPlatform:Lre,paidLayer:Ire,statusLoading:Ore,statusConnected:Dre,statusConnecting:Mre,statusExpired:zre,statusError:Fre,statusNotConnected:Ure,tokenExpired:Bre,connectionError:Vre,reconnectNote:qre,yt:Hre,ayrshare:Wre,restream:Gre,patreon:Yre,howTitle:Kre,publicLevel:Qre,publicSub:Jre,publicDesc:Zre,paidLevel:Xre,paidSub:eae,paidDesc:tae,flowGrowth:sae,flowPaid:nae,setupTitle:rae,setupSteps:aae,meta:iae,googleAds:oae},cae="Шаг {{step}} из {{total}}",dae={blogger:{title:"ИИ-блогер",text:"Создаёт короткие видео и контент-серии для роста канала."},host:{title:"ИИ-ведущий",text:"Проводит live-эфиры и отвечает на вопросы аудитории."},consultant:{title:"ИИ-консультант",text:"Проводит голосовые консультации и разборы 1 на 1."},teacher:{title:"ИИ-преподаватель",text:"Объясняет, обучает и ведёт образовательные рубрики."},lawyer:{title:"ИИ-юрист",text:"Даёт правовые консультации, анализирует кейсы и объясняет законы."},mixed:{title:"Смешанный формат",text:"Блогер + ведущий + консультант в одном персонаже."}},uae={ai:"AI",business:"Бизнес",education:"Обучение",languages:"Языки",commentary:"Комментарии",news:"Новости",expert:"Экспертные разборы",brand:"Личный бренд"},hae={shorts:{title:"С коротких видео",text:"Начните с Shorts — быстро, просто, максимальный охват."},live:{title:"С live-эфиров",text:"Сразу стройте доверие через прямые эфиры."},consult:{title:"С консультаций",text:"Запустите платные голосовые сессии с первого дня."},subscription:{title:"С платной подписки",text:"Создайте закрытый клуб на Patreon с самого начала."},gradual:{title:"Хочу всё постепенно",text:"Пошаговый запуск: Shorts → Live → Monetization."}},mae="Кого вы хотите запустить?",pae="Выберите основную роль вашего ИИ-персонажа. Потом можно будет изменить.",fae="О чём будет говорить ваш ИИ-персонаж?",gae="Выберите одну или несколько тем. Это поможет настроить контент и стиль.",xae="С чего вы хотите начать?",vae="Выберите модель старта. Вы всегда сможете расширить позже.",yae="Сделайте YouTube вашей основной площадкой",bae="На YouTube ваш ИИ-персонаж сможет публиковать Shorts, выходить в live и со временем двигаться к монетизации.",wae="YouTube подключён",jae="Подключить YouTube",_ae="В
1033ы сможете подключить позже в разделе «Интеграции».",kae="Ваш стартовый путь готов",Nae="Следуйте этим шагам — и вы запустите своего ИИ-персонажа по-настоящему.",Sae=[{label:"Создать персонажа",desc:"Настройте роль, тему и стиль вашего персонажа."},{label:"Выпустить 5 Shorts",desc:"Протестируйте 5 тем и соберите первый охват."},{label:"Провести 1 live",desc:"Проведите первый live для укрепления доверия."},{label:"Сделать 10 нарезок",desc:"Превратите эфиры в короткие клипы и тизеры."},{label:"Подготовить монетизацию",desc:"Подключите Patreon, платные эфиры или консультации."}],Cae="Вы готовы запускать своего ИИ-персонажа",Tae="Всё настроено. Переходите в Dashboard или создайте первого персонажа прямо сейчас.",Pae="Сохранение...",Eae="Перейти в Дашборд",Aae="Создать первого персонажа",Rae="Назад",$ae="Пропустить",Lae={stepOf:cae,roles:dae,topics:uae,startModels:hae,step0Title:mae,step0Desc:pae,step1Title:fae,step1Desc:gae,step2Title:xae,step2Desc:vae,step3Title:yae,step3Desc:bae,ytConnected:wae,connectYt:jae,ytSkipNote:_ae,step4Title:kae,step4Desc:Nae,roadmap:Sae,step5Title:Cae,step5Desc:Tae,saving:Pae,goToDashboard:Eae,createFirstPersona:Aae,back:Rae,skip:$ae,continue:"Продолжить"},Iae="Step {{step}} of {{total}}",Oae={blogger:{title:"AI Blogger",text:"Creates short videos and content series for channel growth."},host:{title:"AI Host",text:"Runs live streams and answers audience questions."},consultant:{title:"AI Consultant",text:"Conducts voice consultations and 1-on-1 breakdowns."},teacher:{title:"AI Teacher",text:"Explains, teaches, and runs educational segments."},lawyer:{title:"AI Lawyer",text:"Provides legal advice, analyzes cases and explains laws."},mixed:{title:"Mixed format",text:"Blogger + host + consultant in one persona."}},Dae={ai:"AI",business:"Business",education:"Education",languages:"Languages",commentary:"Commentary",news:"News",expert
1033:"Expert analysis",brand:"Personal brand"},Mae={shorts:{title:"With short videos",text:"Start with Shorts — fast, easy, maximum reach."},live:{title:"With live streams",text:"Build trust immediately through live streams."},consult:{title:"With consultations",text:"Launch paid voice sessions from day one."},subscription:{title:"With paid subscription",text:"Create a private club on Patreon from the start."},gradual:{title:"Gradually",text:"Step-by-step launch: Shorts → Live → Monetization."}},zae="Who do you want to launch?",Fae="Choose the main role for your AI persona. You can change it later.",Uae="What will your AI persona talk about?",Bae="Choose one or more topics. This helps customize content and style.",Vae="How do you want to start?",qae="Choose a start model. You can always expand later.",Hae="Make YouTube your primary platform",Wae="On YouTube, your AI persona can publish Shorts, go live, and move toward monetization over time.",Gae="YouTube connected",Yae="Connect YouTube",Kae="You can connect later in the Integrations section.",Qae="Your launch path is ready",Jae="Follow these steps — and you'll truly launch your AI persona.",Zae=[{label:"Create a persona",desc:"Set up the role, topic, and style for your persona."},{label:"Publish 5 Shorts",desc:"Test 5 topics and get initial reach."},{label:"Run 1 live stream",desc:"Run your first live to build trust."},{label:"Create 10 clips",desc:"Turn streams into short clips and teasers."},{label:"Prepare monetization",desc:"Connect Patreon, paid streams, or consultations."}],Xae="You're ready to launch your AI persona",eie="Everything is set up. Go to the Dashboard or create your first persona now.",tie="Saving...",sie="Go to Dashboard",nie="Create first persona",rie="Back",aie="Skip",iie={stepOf:Iae,roles:Oae,topics:Dae,startModels:Mae,step0Title:zae,step0Desc:Fae,step1Title:Uae,step1Desc:Bae,step2Title:Vae,step2Desc:qae,step3Title:Hae,step3Desc:Wae,ytConnected:Gae,connectYt:Yae,ytSkipNote:Kae,step4Title:Qae,step4Desc:Jae,roadmap:Zae,step5Title:Xae,step5Desc:eie,saving:tie,goToDashboard:sie,createFirstPersona:nie,back:rie,skip:aie,continue:"Continue"},oie="Операции",lie="Мониторинг задач, воркеров, live-рантайма и системных статусов MVP",cie="Загружаем операции…",die="Авто-обновление ВКЛ",uie="Авто-обновление ВЫКЛ",hie="Обновить",mie="Требует внимания",pie={queued:"В очереди",running:"Выполняется",errors:"Ошибки",done:"Готово",canceled:"Отменено",liveSessions:"Live-сессии",attention:"Внимание",errorLogs24h:"Ошибки 24ч"},fie={generate_short_script:"Генерация сценария",generate_voice:"Генерация озвучки",render_video:"Рендер видео",render_short_video:"Генерация озвучки (legacy)",repurpose_live:"Нарезка из live",upload_video_to_youtube:"Загрузка на YouTube"},gie="Воркеры",xie="Тип",vie="Режим",yie="Текущие задачи",bie="В очереди",wie="Тест / Заглушка",jie="Продакшн",_ie="Готов",kie="Выход",Nie="Smart Avatar + TTS аудио",Sie="Активные задачи",Cie="Задачи",Tie="Поиск задач...",Pie="Все",Eie="В очереди",Aie="Выполняется",Rie="Готово",$ie="Ошибка",Lie="Таймаут",Iie="Отменено",Oie="Все типы",Die="Нет jobs",Mie='Нет jobs со статусом "{{filter}}"',zie="ID",Fie="Тип",Uie="Статус",Bie="Воркер",Vie="Создано",qie="Длительность",Hie="Ошибка",Wie="выполняется…",Gie={client:"клиент",server_clamped:"обрезано",server_only:"сервер"},Yie={client:"Длительность от воркера принята (в пределах допуска)",server_clamped:"Воркер прислал длительность вне допуска — использовано серверное значение",server_only:"Воркер не прислал длительность — использовано серверное значение"},Kie="Live-рантайм",Qie="Нет активных или запланированных live-сессий",Jie="Платформа",Zie="Режим",Xie="Чат",eoe="Тестовый рантайм",toe="Ошибки и предупреждения",soe="Всё в порядке — нет ошибок и предупреждений",noe="ошибка",roe="ошибок",aoe="Токен истёк",ioe="Ошибка подключения",ooe="{{from}}–{{to}} из {{total}}",loe={title:"{{count}} задач(и) висят в очереди больше 5 минут",subtitle:"Внешний воркер, возможно, не работает. Эти задачи должны быть подобраны внешним воркером через worker-api.",waiting:"ждёт {{minutes}} мин",andMore:"и ещё {{count}}…"},coe={pageTitle:oie,pageSubtitle:lie,loading:cie,autoRefreshOn:die,autoRefreshOff:uie,refresh:hie,needsAttention:mie,kpis:pie,jobTypes:fie,workers:gie,workerType:xie,workerMode:vie,workerCurrentTasks:yie,workerQueued:bie,workerTestMode:wie,workerProduction:jie,workerReady:_ie,workerOutput:kie,workerOutputDesc:Nie,activeTasks:Sie,tasks:Cie,searchPlaceholder:Tie,filterAll:Pie,filterQueued:Eie,filterRunning:Aie,filterDone:Rie,filterFailed:$ie,filterTimedOut:Lie,filterCanceled:Iie,filterAllTypes:Oie,noJobs:Die,noJobsWithFilter:Mie,tableId:zie,tableType:Fie,tableStatus:Uie,tableWorker:Bie,tableCreated:Vie,tableDuration:qie,tableError:Hie,executing:Wie,durationSource:Gie,durationSourceHint:Yie,liveRuntime:Kie,noActiveLive:Qie,platform:Jie,mode:Zie,chat:Xie,testRuntime:eoe,errorsTitle:toe,allClear:soe,errorSingular:noe,errorPlural:roe,tokenExpired:aoe,connectionError:ioe,paginationInfo:ooe,stuckQueued:loe},doe="Operations",uoe="Monitor tasks, workers, live runtime, and MVP system statuses",hoe="Loading operations…",moe="Auto-refresh ON",poe="Auto-refresh OFF",foe="Refresh",goe="Needs attention",xoe={queued:"Queued",running:"Running",errors:"Errors",done:"Done",canceled:"Canceled",liveSessions:"Live sessions",attention:"Attention",errorLogs24h:"Errors 24h"},voe={generate_short_script:"Script generation",generate_voice:"Voice generation",render_video:"Video render",render_short_video:"Voice generation (legacy)",repurpose_live:"Live repurpose",upload_video_to_youtube:"YouTube upload"},yoe="Workers",boe="Type",woe="Mode",joe="Current tasks",_oe="Queued",koe="Test / Placeholder",Noe="Production",Soe="Ready",Coe="Output",Toe="Smart Avatar + TTS audio",Poe="Active tasks",Eoe="Tasks",Aoe="Search tasks...",Roe="All",$oe="Queued",Loe="Running",Ioe="Done",Ooe="Failed",Doe="Timed out",Moe="Canceled",zoe="All types",Foe="No jobs",Uoe='No jobs with status "{{filter}}"',Boe="ID",Voe="Type",qoe="Status",Hoe="Worker",Woe="Created",Goe="Duration",Yoe="Error",Koe="executing…",Qoe={client:"client",server_clamped:"clamped",server_only:"server"},Joe={client:"Worker-reported duration accepted (within tolerance)",server_clamped:"Worker reported a duration outside tolerance — server value used",server_only:"Worker did not report duration — server value used"},Zoe="Live runtime",Xoe="No active or scheduled live sessions",ele="Platform",tle="Mode",sle="Chat",nle="Test runtime",rle="Errors & warnings",ale="All clear — no errors or warnings",ile="error",ole="errors",lle="Token expired",cle="Connection error",dle="{{from}}–{{to}} of {{total}}",ule={title:"{{count}} job(s) stuck in queue over 5 min",subtitle:"External worker may be offline. These jobs require an external worker to claim them via w
1033orker-api.",waiting:"waiting {{minutes}} min",andMore:"and {{count}} more…"},hle={pageTitle:doe,pageSubtitle:uoe,loading:hoe,autoRefreshOn:moe,autoRefreshOff:poe,refresh:foe,needsAttention:goe,kpis:xoe,jobTypes:voe,workers:yoe,workerType:boe,workerMode:woe,workerCurrentTasks:joe,workerQueued:_oe,workerTestMode:koe,workerProduction:Noe,workerReady:Soe,workerOutput:Coe,workerOutputDesc:Toe,activeTasks:Poe,tasks:Eoe,searchPlaceholder:Aoe,filterAll:Roe,filterQueued:$oe,filterRunning:Loe,filterDone:Ioe,filterFailed:Ooe,filterTimedOut:Doe,filterCanceled:Moe,filterAllTypes:zoe,noJobs:Foe,noJobsWithFilter:Uoe,tableId:Boe,tableType:Voe,tableStatus:qoe,tableWorker:Hoe,tableCreated:Woe,tableDuration:Goe,tableError:Yoe,executing:Koe,durationSource:Qoe,durationSourceHint:Joe,liveRuntime:Zoe,noActiveLive:Xoe,platform:ele,mode:tle,chat:sle,testRuntime:nle,errorsTitle:rle,allClear:ale,errorSingular:ile,errorPlural:ole,tokenExpired:lle,connectionError:cle,paginationInfo:dle,stuckQueued:ule},mle="Вебинары и платные эфиры",ple="Запускайте более глубокие форматы на основе вашего ИИ-ведущего и превращайте их в премиальный опыт для аудитории.",fle="Загружаем вебинары…",gle="Нет созданных вебинаров",xle="Выберите формат и создайте первую сессию — платный вебинар, закрытый live или members-only эфир.",vle="Выберите формат",yle={open:{label:"Открытый вебинар",desc:"Бесплатный формат для привлечения аудитории"},paid:{label:"Платный вебинар",desc:"Премиальный контент с платным доступом"},closed:{label:"Закрытый live",desc:"Только по приглашению или ссылке"},members:{label:"Только для участников",desc:"Для подписчиков канала или Patreon"},group:{label:"Приватная группа",desc:"Мини-группа для глубокого разбора"}},ble="Настроить сессию",wle={topic:"Тема",persona:"Персонаж",duration:"Длительность",accessFormat:"Формат доступа",description:"Описание",language:"Язык",platform:"Платформа публикации"},jle={restream:"Restream (мультистрим + чат)",youtube:"YouTube Live"},_le={ru:"Русский",en:"Английский"},kle={expert:"AI Эксперт",host:"Ведущий"},Nle="{{min}} мин",Sle="Без ограничений",Cle="Запись в архив",Tle="Опубликовать",Ple="Субтитры в эфире",Ele="Вшитые субтитры по форсед-алигменту",Ale="Водяной знак / реклама",Rle="Необязательный текст, который воркер вшивает в эфир (например, «Created by VlogMe.AI»). Оставьте пустым, чтобы не добавлять.",$le="Created by VlogMe.AI",Lle="Создать сессию",Ile="Создаём…",Ole="Остановить",Dle="Останавливаем…",Mle="Старт",zle="Запуск…",Fle="Сессия создана и поставлена в очередь",Ule="Сессия создана и поставлена в очередь",Ble="Не удалось создать сессию. Попробуйте ещё раз.",Vle="Редактировать",qle="Черновик загружен в форму",Hle="Сохранить изменения",Wle="Сохраняем…",Gle="Изменения сохранены",Yle="Отмена",Kle="Отменить",Qle="Отменяем…",Jle="Отменить этот вебинар? Его нельзя будет запустить.",Zle="Мои вебинары",Xle="Поиск по названию вебинара или фрагменту клипа…",ece="Ничего не найдено",tce="Попробуйте изменить запрос или очистить поиск.",sce={draft:"Черновик",scheduled:"Запланирован",ready:"Готов",live:"В эфире",ended:"Завершён",canceled:"Отменён",failed:"Ошибка"},nce={queued:"В очереди",running:"Выполняется",completed:"Готово",failed:"Ошибка",canceled:"Отменено"},rce="Как это монетизируется",ace={ytMembers:{title:"YouTube для участников",desc:"Нативный платный слой YouTube для участников канала."},patreonAccess:{title:"Доступ через Patreon",desc:"Закрытый доступ через tiers на Patreon."},externalPremium:{title:"Внешний премиум-опыт",desc:"Самостоятельная продажа через ваши площадки."}},ice="После сессии",oce="Превратите одну сессию в полноценный контентный и монетизационный пакет",lce={archive:{label:"Запись в архив",desc:"Полная запись для платных подписчиков"},teasers:{label:"Тизеры",desc:"Промо-ролики для привлечения на следующий"},shorts:{label:"Shorts",desc:"5–10 коротких видео из ключевых моментов"},postOffer:{label:"Пост-вебинарный оффер",desc:"Пост-вебинарное предложение аудитории"},ctaConsult:{label:"CTA в консультации",desc:"Предложение 1:1 сессии для заинтересованных"}},cce="Монетизация AI-контента: от Shorts до дохода",dce="Разберём пошаговый план запуска AI-медиа и выхода на первый доход через контент, подписки и платные форматы.",uce={sectionTitle:"Сообщения AI",planLabel:"План вебинара (в системный промпт)",planPlaceholder:"Подробный план, по которому идёт AI-ведущий: 5–8 пронумерованных подтем с 1–2 уточняющими буллетами под каждой. Вслух не зачитывается.",greetingLabel:"Приветствие (зачитывается вслух)",greetingPlaceholder:"Короткое стартовое сообщение, которое AI-ведущий прочитает в самом начале…",continueLabel:"Продолжение",continuePlaceholder:"Инструкция продолжать преподавать тему…",summaryLabel:"Подведение итогов",summaryPlaceholder:"Как AI должен подвести итоги и завершить сессию, когда она закончится…",generate:"Сгенерировать AI",generating:"Генерация…"},hce="Продолжить",mce="Генерируем…",pce="Поля заполнены продолжением — проверьте и создайте",fce="Ð
1033Ðµ удалось сгенерировать продолжение",gce="Повторить",xce="Поля скопированы — проверьте и создайте",vce={button:"Из комментов",title:"План из комментариев конкурентов",desc:"Дайте поисковый запрос — мы сами найдём топовые YouTube-видео и вытащим из их комментов повторяющиеся вопросы, возражения и боли. Получится готовый план вебинара «Отвечаю на 7 вопросов, которые задают все».",topicLabel:"Тема / ниша",topicPlaceholder:"Например: AI-автоматизация маркетинга",queryLabel:"Поисковый запрос (опционально)",queryPlaceholder:"что искать на YouTube",queryHint:"Пусто = глобальный топ за сегодня по выбранному региону («топы топов»).",regionLabel:"Регион",start:"Собрать план",cancel:"Отмена",working:"Ищем видео и анализируем комментарии…",collected:"Собрано комментариев: {{count}}",newRun:"Новый запуск",usePlan:"Использовать как план вебинара",doneSummary:"Готово. Проанализировано {{count}} комментариев.",sourcesTitle:"Источники ({{count}} видео)",questionsTitle:"Топ-вопросы аудитории",objectionsTitle:"Возражения и сомнения",painsTitle:"Боли и проблемы",errTopic:"Укажите тему"},yce={noSocialLinked:"Привяжите соцсети в разделе Интеграции → Социальный хаб",toastNothingToDo:"Уже опубликовано во все подключённые сети",toastPublishedTo:"Опубликовано: {{list}}",toastPartial:"Опубликовано: {{ok}}. Ошибки: {{fail}}",publishFailed:"Не удалось опубликовать",analyzeDone:"Top-3 клипа определены",analyzeFailed:"Не удалось проанализировать",unpublished:"Удалено из {{name}}",unpublishFailed:"Не удалось удалить публикацию",analyticsPartial:"Часть статистики не удалось обновить",analyticsNothing:"Нечего обновлять",analyticsUpdated:"Статистика обновлена",analyticsFailed:"Не удалось обновить статистику",analyzeHint:"ИИ оценит транскрипты и отметит 3 самых медийных",analyzing:"Анализ…",reanalyze:"Переанализировать",findTop3:"Найти топ-3 клипа",titlePending:"Генерируем название…",topPick:"ТОП-3",score:"оценка",collapse:"Свернуть",expand:"Показать весь текст",platformChipTooltipOk:"Опубликовано в {{name}}",platformChipTooltipError:"{{name}}: {{error}}",platformChipTooltipPending:"{{name}} — ещё не публиковали",unpublishBtn:"Снять публикацию из {{name}}",analyticsRefresh:"Обновить статистику",connectSocialsCta:"Подключите соцсети",publishingBtn:"Публикуется…",publishedEverywhere:"Опубликовано везде",publishMoreBtn:"Опубликовать ещё в {{count}}",publishBtn:"Опубликовать",publishTargetsTitle:"Куда опубликовать",platformAlreadyPublished:"уже опубликовано",publishSelected:"Опубликовать в выбранные ({{count}})",unpublishConfirmTitle:"Удалить пост из {{name}}?",unpublishConfirmDesc:"Пост будет удалён в соцсети, и чип станет серым. Действие необратимо.",cancel:"Отмена"},bce={pageTitle:mle,pageSubtitle:ple,loading:fle,emptyTitle:gle,emptyDesc:xle,formatTitle:vle,formats:yle,sessionTitle:ble,fields:wle,platforms:jle,languages:_le,personaOptions:kle,duration:Nle,durationInfinite:Sle,archiveLabel:Cle,publishLabel:Tle,liveSubtitles:Ple,liveSubtitlesDesc:Ele,watermark:Ale,watermarkDesc:Rle,watermarkPlaceholder:$le,createSession:Lle,creating:Ile,stopSession:Ole,stopping:Dle,startSession:Mle,starting:zle,createdToast:Fle,createdInline:Ule,createErrorInline:Ble,editDraft:Vle,editLoaded:qle,saveChanges:Hle,saving:Wle,savedInline:Gle,cancelEdit:Yle,cancelWebinar:Kle,cancelling:Qle,cancelWebinarConfirm:Jle,mySessionsTitle:Zle,searchPlaceholder:Xle,searchEmptyTitle:ece,searchEmptyDesc:tce,sessionStatus:sce,jobStage:nce,monetizationTitle:rce,monetizationPaths:ace,afterSession:ice,afterSessionDesc:oce,reuseItems:lce,defaultTopic:cce,defaultDesc:dce,autoMessages:uce,continueWebinar:hce,continueGenerating:mce,continueFilled:pce,continueError:fce,repeatWebinar:gce,repeatFilled:xce,commentMining:vce,clips:yce},wce="Webinars & Paid Streams",jce="Launch deeper formats powered by your AI host and turn them into premium audience experiences.",_ce="Loading webinars…",kce="No webinars created",Nce="Choose a format and create your first session — a paid webinar, private live, or members-only stream.",Sce="Choose format",Cce={open:{label:"Open webinar",desc:"Free format to attract audience"},paid:{label:"Paid webinar",desc:"Premium content with paid access"},closed:{label:"Private live",desc:"By invitation or link only"},members:{label:"Members only",desc:"For channel or Patreon subscribers"},group:{label:"Private group",desc:"Small group for deep analysis"}},Tce="Configure session",Pce={topic:"Topic",persona:"Persona",duration:"Duration",accessFormat:"Access format",description:"Description",language:"Language",platform:"Publishing platform"},Ece={restream:"Restream (multistream + chat)",youtube:"YouTube Live"},Ace={ru:"Russian",en:"English"}
1033,Rce={expert:"AI Expert",host:"Host"},$ce="{{min}} min",Lce="Unlimited",Ice="Record to archive",Oce="Publish",Dce="Live subtitles",Mce="Burned-in captions via forced alignment",zce="Watermark / promo line",Fce='Optional text burned into the live feed (e.g. "Created by VlogMe.AI"). Leave empty to skip.',Uce="Created by VlogMe.AI",Bce="Create session",Vce="Creating…",qce="Stop",Hce="Stopping…",Wce="Start",Gce="Starting…",Yce="Session created and queued",Kce="Session created and queued",Qce="Failed to create session. Please try again.",Jce="Edit",Zce="Draft loaded into the form",Xce="Save changes",ede="Saving…",tde="Changes saved",sde="Cancel",nde="Cancel",rde="Cancelling…",ade="Cancel this webinar? It cannot be started afterwards.",ide="My webinars",ode="Search by webinar title or clip fragment…",lde="Nothing found",cde="Try a different query or clear the search.",dde={draft:"Draft",scheduled:"Scheduled",ready:"Ready",live:"Live",ended:"Ended",canceled:"Canceled",failed:"Failed"},ude={queued:"Queued",running:"Running",completed:"Done",failed:"Failed",canceled:"Canceled"},hde="How this is monetized",mde={ytMembers:{title:"YouTube Members",desc:"Native YouTube paid layer for channel members."},patreonAccess:{title:"Patreon access",desc:"Gated access via Patreon tiers."},externalPremium:{title:"External premium experience",desc:"Self-serve sales through your own platforms."}},pde="After the session",fde="Turn one session into a full content and monetization package",gde={archive:{label:"Archive recording",desc:"Full recording for paid subscribers"},teasers:{label:"Teasers",desc:"Promo clips to attract to the next session"},shorts:{label:"Shorts",desc:"5–10 short videos from key moments"},postOffer:{label:"Post-webinar offer",desc:"Post-session offer for the audience"},ctaConsult:{label:"Consultation CTA",desc:"1:1 session offer for interested viewers"}},xde="AI Content Monetization: from Shorts to Revenue",vde="A step-by-step plan for launching AI media and reaching first revenue through content, subscriptions, and paid formats.",yde={sectionTitle:"AI messages",planLabel:"Webinar plan (system prompt)",planPlaceholder:"Detailed agenda the AI host follows: 5–8 numbered sub-topics with 1–2 clarifying bullets each. Not read aloud.",greetingLabel:"Greeting (read aloud)",greetingPlaceholder:"Short opening line the AI host reads at the start of the webinar…",continueLabel:"Continue talking",continuePlaceholder:"Instruction to keep teaching the topic…",summaryLabel:"Summarize the session",summaryPlaceholder:"How the AI should wrap up and summarize the session when it ends…",generate:"Generate with AI",generating:"Generating…"},bde="Continue",wde="Generating…",jde="Fields filled with continuation — review and create",_de="Failed to generate continuation",kde="Repeat",Nde="Fields copied — review and create",Sde={button:"From comments",title:"Plan from competitor comments",desc:"Give a search query — we'll auto-find top YouTube videos and extract recurring questions, objections and pain points from their comments. You get a ready-made webinar plan: 'I answer the 7 questions everyone asks'.",topicLabel:"Topic / niche",topicPlaceholder:"e.g. AI marketing automation",queryLabel:"Search query (optional)",queryPlaceholder:"what to look up on YouTube",queryHint:"Empty = global top of the day for the selected region ('top of the tops').",regionLabel:"Region",start:"Build plan",cancel:"Cancel",working:"Finding videos and analyzing comments…",collected:"Comments collected: {{count}}",newRun:"New run",usePlan:"Use as webinar plan",doneSummary:"Done. {{count}} comments analyzed.",sourcesTitle:"Sources ({{count}} videos)",questionsTitle:"Top audience questions",objectionsTitle:"Objections & doubts",painsTitle:"Pains & problems",errTopic:"Topic required"},Cde={noSocialLinked:"Link your socials in Integrations → Social Hub",toastNothingToDo:"Already published to all connected networks",toastPublishedTo:"Published: {{list}}",toastPartial:"Published: {{ok}}. Errors: {{fail}}",publishFailed:"Publish failed",analyzeDone:"Top-3 clips selected",analyzeFailed:"Analysis failed",unpublished:"Removed from {{name}}",unpublishFailed:"Failed to remove publication",analyticsPartial:"Some stats couldn't be refreshed",analyticsNothing:"Nothing to update",analyticsUpdated:"Stats updated",analyticsFailed:"Failed to refresh stats",analyzeHint:"AI will score transcripts and flag the 3 most engaging",analyzing:"Analyzing…",reanalyze:"Re-
1033analyze",findTop3:"Find top-3 clips",titlePending:"Generating title…",topPick:"TOP-3",score:"score",collapse:"Collapse",expand:"Show full text",platformChipTooltipOk:"Published to {{name}}",platformChipTooltipError:"{{name}}: {{error}}",platformChipTooltipPending:"{{name}} — not published yet",unpublishBtn:"Remove from {{name}}",analyticsRefresh:"Refresh stats",connectSocialsCta:"Connect socials",publishingBtn:"Publishing…",publishedEverywhere:"Published everywhere",publishMoreBtn:"Publish to {{count}} more",publishBtn:"Publish",publishTargetsTitle:"Where to publish",platformAlreadyPublished:"already published",publishSelected:"Publish to selected ({{count}})",unpublishConfirmTitle:"Remove post from {{name}}?",unpublishConfirmDesc:"The post will be deleted on the network and the chip will turn gray. This cannot be undone.",cancel:"Cancel"},Tde={pageTitle:wce,pageSubtitle:jce,loading:_ce,emptyTitle:kce,emptyDesc:Nce,formatTitle:Sce,formats:Cce,sessionTitle:Tce,fields:Pce,platforms:Ece,languages:Ace,personaOptions:Rce,duration:$ce,durationInfinite:Lce,archiveLabel:Ice,publishLabel:Oce,liveSubtitles:Dce,liveSubtitlesDesc:Mce,watermark:zce,watermarkDesc:Fce,watermarkPlaceholder:Uce,createSession:Bce,creating:Vce,stopSession:qce,stopping:Hce,startSession:Wce,starting:Gce,createdToast:Yce,createdInline:Kce,createErrorInline:Qce,editDraft:Jce,editLoaded:Zce,saveChanges:Xce,saving:ede,savedInline:tde,cancelEdit:sde,cancelWebinar:nde,cancelling:rde,cancelWebinarConfirm:ade,mySessionsTitle:ide,searchPlaceholder:ode,searchEmptyTitle:lde,searchEmptyDesc:cde,sessionStatus:dde,jobStage:ude,monetizationTitle:hde,monetizationPaths:mde,afterSession:pde,afterSessionDesc:fde,reuseItems:gde,defaultTopic:xde,defaultDesc:vde,autoMessages:yde,continueWebinar:bde,continueGenerating:wde,continueFilled:jde,continueError:_de,repeatWebinar:kde,repeatFilled:Nde,commentMining:Sde,clips:Cde},Pde="Реклама",Ede="Запускайте кампании в Facebook и Instagram прямо из SmartBlog.",Ade="Сначала подключите Meta",Rde="Чтобы запускать рекламу, подключите Facebook и Instagram на странице интеграций.",$de="К интеграциям",Lde="Создать кампанию",Ide="Кампаний пока нет. Создайте первую — она будет в паузе, чтобы вы проверили перед запуском.",Ode="Реклама создаётся для",Dde="Сменить",Mde={draft:"Черновик",paused:"Пауза",active:"Активна",archived:"Архив",error:"Ошибка"},zde={OUTCOME_ENGAGEMENT:"Вовлечённость",OUTCOME_TRAFFIC:"Трафик",OUTCOME_AWARENESS:"Узнаваемость"},Fde={activate:"Запустить",pause:"Пауза",archive:"В архив",delete:"Удалить",edit:"Изменить",saved:"Сохранено"},Ude="Бюджет в день",Bde="/день",Vde={title:"Новая кампания",subtitle:"Создаётся в паузе. Запустите, когда проверите.",name:"Название кампании",namePh:"Весенний запуск продукта",objective:"Цель",budget:"Бюджет в день (USD)",budgetHint:"Минимум ~$1/день. Списывается в валюте вашего рекламного кабинета.",message:"Текст поста",messagePh:"Что должна сказать реклама?",link:"Ссылка перехода",linkPh:"https://your-site.com/landing",imageUrl:"URL картинки",imageUrlPh:"https://...",countries:"Коды стран (ISO, через запятую)",countriesPh:"US, GB, RU",ageMin:"Возраст от",ageMax:"Возраст до",cancel:"Отмена",submit:"Создать (в паузе)",submitting:"Создаём…",preview:"Превью объявления",sponsored:"Реклама · Спонсировано",previewMessagePlaceholder:"Текст вашей рекламы появится здесь",previewNoImage:"Картинка не выбрана",previewCta:"Открыть",previewHint:"Так пользователь увидит вашу рекламу в ленте Facebook / Instagram.",editTitle:"Редактирование кампании",save:"Сохранить",boostAuto:"Продвигаем уже опубликованный пост",boostHintIg:"Реклама будет показана только в Instagram (Feed / Reels / Stories) как ваш существующий пост. Лайки и просмотры с органики усиливают рекламу.",boostHintFb:"Реклама будет показана только в Facebook (Feed / Reels / Stories / In-Stream) как ваш существующий пост. Лайки и просмотры с органики усиливают рекламу.",boostOpenPost:"Открыть пост",linkAuto:"Реклама автоматически ведёт на вашу Facebook-страницу — так аудитория остаётся в FB/Instagram и подписывается на ваш аккаунт.",previewBoostMedia:"Видео из вашего поста"},qde={btn:"Реклама",btnTooltip:"Создать рекламу для этого клипа",needYoutube:"Сначала опубликуйте клип на YouTube",needFacebook:"Сначала опубликуйте клип в Facebook",needFacebookOrInstagram:"Сначала опубликуйте клип в Facebook или Instagram",needMeta:"Подключите Meta в интеграциях",campaignBadge:"Реклама: {{status}}",openAds:"Открыть рекламу",googleBtn:"Реклама YT",googleBtnTooltip:"Продвигать этот клип на YouTube через Google Ads",needGoogle:"Подключите Google Ads в интеграциях",googleCampaignBadge:"YT-реклама: {{status}}"},Hde="Удалить эту кампанию навсегда? Она также удалится в Meta.",Wde={createFailed:"Не удалось создать кампанию",updateFailed:"Не удалось обновить кампанию"},Gde={meta:"Meta (FB / IG)",google:"Google Ads (YouTube)"},Yde={notConnectedTitle:"Сначала подключите Google Ads",notConnectedDesc:"Чтобы запускать YouTube-рекламу, подключите Google Ads на странице интеграций и выберите рекламн
1033ый аккаунт.",createCampaign:"Создать YouTube-кампанию",noCampaigns:"YouTube-кампаний пока нет. Создайте первую — она будет в паузе до вашего запуска.",activeAccountLabel:"Рекламный аккаунт",campaignType:"Видео (YouTube)"},Kde={title:"Новая YouTube-кампания",subtitle:"True-View In-Stream объявление на YouTube. Создаётся в паузе.",video:"Ссылка или ID видео на YouTube",videoHint:"Видео должно быть загружено в YouTube (публично или по ссылке).",budgetHint:"Минимум $1/день. Списывается в валюте вашего Google Ads аккаунта.",finalUrl:"Куда вести при клике",languages:"Языки (через запятую, ISO)",previewNoVideo:"Видео не выбрано",previewNamePlaceholder:"Название кампании",previewHint:"Так примерно будет выглядеть промо-карточка вашего видео.",editTitle:"Редактирование YouTube-кампании",finalUrlAuto:"Реклама ведёт на это YouTube-видео — так зрители остаются на YouTube, что усиливает органический рост канала.",created:"YouTube кампания создана (на паузе)"},Qde={pageTitle:Pde,pageSubtitle:Ede,notConnectedTitle:Ade,notConnectedDesc:Rde,goToIntegrations:$de,createCampaign:Lde,noCampaigns:Ide,activeAccountLabel:Ode,changeAccount:Dde,status:Mde,objective:zde,actions:Fde,dailyBudget:Ude,perDay:Bde,modal:Vde,clip:qde,deleteConfirm:Hde,errors:Wde,tabs:Gde,google:Yde,googleModal:Kde},Jde="Ads",Zde="Launch Facebook & Instagram ad campaigns from SmartBlog.",Xde="Connect Meta first",eue="To launch ads, connect Facebook & Instagram on the Integrations page.",tue="Go to Integrations",sue="Create campaign",nue="No campaigns yet. Create your first one — it'll start paused so you can review before going live.",rue="Ads run on",aue="Change",iue={draft:"Draft",paused:"Paused",active:"Active",archived:"Archived",error:"Error"},oue={OUTCOME_ENGAGEMENT:"Engagement",OUTCOME_TRAFFIC:"Traffic",OUTCOME_AWARENESS:"Awareness"},lue={activate:"Activate",pause:"Pause",archive:"Archive",delete:"Delete",edit:"Edit",saved:"Saved"},cue="Daily budget",due="/day",uue={title:"New campaign",subtitle:"Created in paused state. Review and activate when ready.",name:"Campaign name",namePh:"Spring product launch",objective:"Objective",budget:"Daily budget (USD)",budgetHint:"Min ~$1/day. Charged by Meta in your ad account currency.",message:"Post text",messagePh:"What should the ad say?",link:"Destination URL",linkPh:"https://your-site.com/landing",imageUrl:"Image URL",imageUrlPh:"https://...",countries:"Country codes (ISO, comma-separated)",countriesPh:"US, GB, CA",ageMin:"Min age",ageMax:"Max age",cancel:"Cancel",submit:"Create (paused)",submitting:"Creating…",preview:"Ad preview",sponsored:"Sponsored",previewMessagePlaceholder:"Your ad copy will appear here",previewNoImage:"No image selected",previewCta:"Open",previewHint:"This is roughly how users will see your ad in the Facebook / Instagram feed.",editTitle:"Edit campaign",save:"Save",boostAuto:"Boosting an already published post",boostHintIg:"The ad will run only on Instagram (Feed / Reels / Stories) as your existing post. Organic likes and views boost the ad.",boostHintFb:"The ad will run only on Facebook (Feed / Reels / Stories / In-Stream) as your existing post. Organic likes and views boost the ad.",boostOpenPost:"Open post",linkAuto:"The ad automatically links to your Facebook page — so the audience stays on FB/Instagram and follows your account.",previewBoostMedia:"Video from your post"},hue={btn:"Ad",btnTooltip:"Create an ad for this clip",needYoutube:"Publish the clip to YouTube first",needFacebook:"Publish the clip to Facebook first",needFacebookOrInstagram:"Publish the clip to Facebook or Instagram first",needMeta:"Connect Meta in Integrations",campaignBadge:"Ad: {{status}}",openAds:"Open ads",googleBtn:"YouTube Ads",googleBtnTooltip:"Promote this clip on YouTube via Google Ads",needGoogle:"Connect Google Ads in Integrations",googleCampaignBadge:"YT Ads: {{status}}"},mue="Delete this campaign permanently? It will also be removed from Meta.",pue={createFailed:"Failed to create campaign",updateFailed:"Failed to update campaign"},fue={meta:"Meta (FB / IG)",google:"Google Ads (YouTube)"},gue={notConnectedTitle:"Connect Google Ads first",notConnectedDesc:"To launch YouTube ads, connect Google Ads on the Integrations page and pick an ad account.",createCampaign:"Create YouTube campaign",noCampaigns:"No YouTube campaigns yet. Create your first — it'll start paused so you can review.",activeAccountLabel:"Ad account",campaignType:"Video (YouTube)"},xue={title:"New YouTube campaign",subtitle:"True-View In-Stream ad on YouTube. Starts paused.",video:"YouTube video URL or ID",videoHint:"Video must be uploaded to YouTube (public or unlisted).",budgetHint:"Min $1/day. Charged by Google Ads in your account currency.",finalUrl:"Click destination",languages:"Languages (ISO, comma-separated)",previewNoVideo:"No video selected",previewNamePlaceholder:"Campaign name",previewHint:"Roughly how the promoted video card will appear.",editTitle:"Edit YouTube campaign",finalUrlAuto:"The ad links to this YouTube video — viewers stay on YouTube, which boosts your channel's organic growth.",created:"YouTube campaign created (paused)"},vue={pageTitle:Jde,pageSubtitle:Zde,notConnectedTitle:Xde,notConnectedDesc:eue,goToIntegrations:tue,createCampaign:sue,noCampaigns:nue,activeAccountLabel:rue,changeAccount:aue,status:iue,objective:oue,actions:lue,dailyBudget:cue,perDay:due,modal:uue,clip:hue,deleteConfirm:mue,errors:pue,tabs:fue,google:gue,googleModal:xue},yue="Topic Discovery",bue="Один экран — три режима поиска тем для вебинара",wue={trends:{label:"Тренды YouTube",desc:"Топовые видео → транскрипты → тема вебинара"},pains:{label:"Боли аудитории",desc:"Комменты к топ-видео → кластеры вопросов/болей → тема"},combo:{label:"Комбо",desc:"Транскрипты + комменты вместе → самая острая тема"}},jue={pending:"В очереди",searching:"Ищем видео…",fetching_transcripts:"Читаем транскрипты и комменты…",synthesizing:"Синтезируем тему…",completed:"Готово",failed:"Не удалось"},_ue={queryLabel:"Поисковый запрос (пусто = global top для региона)",regionLabel:"Регион",languageLabel:"Язык",modeSettings:"Настройки режима",minDuration:"Мин. длительность видео: {{min}} мин",trendsMax:"Сколько видео анализировать: {{n}}",painsMax:"Видео для сбора комментов: {{n}}",painsHint:"Берём до 200 комментов с каждого видео, кластеризуем в вопросы / возражения / боли.",comboMax:"Видео: {{n}}",placeholderTrends:"AI agents, longevity… или пусто = global top видео",placeholderPains:"беговая травма, продуктивность… или пусто = global top для региона",placeholderCombo:"ниша или тема… или пусто = global top",submitWith:"Запустить «{{mode}}»",submitGlobal:"Global Top «{{mode}}» ({{region}})",launchedToast:"{{mode}} запущено",launchedGlobalToast:"{{mode}} (global) запущено",launchFailed:"Не удалось запустить",focusLabel:"Что именно искать и как оформить результат",focusOptional:"(необязательно)",focusPlaceholder:"Например: выпиши топ-20 самых популярных вопросов из комментариев в виде длинного списка и дай свой развёрнутый ответ на каждый. Или: собери все возражения по цене и сформулируй контраргументы."},kue={title:"Недавние запуски",empty:"Пока пусто",emptyDesc:"Запусти первый поиск выше.",hung:"Похоже завис",retry:"Перезапустить"},Nue={themesTitle:"Горячие темы прямо сейчас",themesSubtitle:"AI-кластеры из глобаÐ
1033»ÑŒÐ½Ð¾Ð³Ð¾ YouTube trending",themesEmpty:"Темы появятся после первого сбора.",surgingTitle:"Сейчас разгоняются",surgingSubtitle:"Топ-сигналы из YouTube, Reddit и Hacker News",surgingEmpty:"Пока нет сигналов — сборщики работают каждые 5–15 мин.",vpm:"{{n}} просм/мин",useAsSeed:"Взять как тему",regionsAll:"Все регионы",angle:"Угол подачи",whyNow:"Почему сейчас",openingLine:"Первая фраза",talkingPoints:"Тезисы для эфира",avoid:"Не говорить"},Sue={backLink:"Назад к Topic Discovery",notFound:"Не найдено",notFoundDesc:"Этот поиск не существует.",personaLabel:"Персона ведущего",noPersonas:"Нет персон — ",noPersonasCreate:"создать",selectPersonaPlaceholder:"Выбрать персону",generating:"Генерируем…",createWebinar:"Создать вебинар",extraInstructions:"Доп. инструкции",extraOptional:"(необязательно)",extraPlaceholder:"Например: будь на стороне людей с проблемами, удели больше времени болям и возражениям, добавь больше практических примеров…",selectPersonaFirst:"Сначала выберите персону ведущего",createFailed:"Не удалось создать вебинар",webinarReady:"Вебинар готов",topicTitle:"Тема вебинара",keyPoints:"Ключевые тезисы",summary:"Содержание",suggestedIntro:"Предлагаемое вступление ведущего",freeformTitle:"Свободный ответ (по твоим инструкциям)",topicNotReady:"Синтез темы ещё не готов — статус: ",quotesTitle:"Цитаты и комментарии ведущего",source:"источник",hostSays:"Ведущий говорит",sourceVideos:"Исходные видео ({{count}})",views:"просмотров",hideTranscript:"Скрыть транскрипт",showTranscript:"Показать транскрипт",audienceSays:"Что говорит аудитория",clusters:{questions:"Вопросы аудитории",objections:"Возражения",pains:"Боли"},progress:{header:"Генерируем вебинар — {{pct}}%",tail:"Перекинем на вебинар, когда всё будет готово",description:"Описание для YouTube",greeting:"Приветствие ведущего",plan:"План вебинара (system prompt)",planBlocks:"{{generated}} из {{expected}} блоков",planPreparing:"готовим блоки…",planDone:"{{count}} блоков",continue:"Продолжение",summary:"Итоги",planLine:"План: {{pct}}% ({{generated}}/{{expected}})"}},Cue={pageTitle:yue,pageSubtitle:bue,modes:wue,status:jue,form:_ue,recent:kue,trending:Nue,result:Sue},Tue="Topic Discovery",Pue="One screen — three modes for finding webinar topics",Eue={trends:{label:"YouTube trends",desc:"Top videos → transcripts → webinar topic"},pains:{label:"Audience pains",desc:"Comments on top videos → question/pain clusters → topic"},combo:{label:"Combo",desc:"Transcripts + comments together → the sharpest topic"}},Aue={pending:"Queued",searching:"Searching videos…",fetching_transcripts:"Reading transcripts and comments…",synthesizing:"Synthesizing topic…",completed:"Done",failed:"Failed"},Rue={queryLabel:"Search query (empty = global top for region)",regionLabel:"Region",languageLabel:"Language",modeSettings:"Mode settings",minDuration:"Min video duration: {{min}} min",trendsMax:"Videos to analyze: {{n}}",painsMax:"Videos to fetch comments from: {{n}}",painsHint:"We grab up to 200 comments per video and cluster them into questions / objections / pains.",comboMax:"Videos: {{n}}",placeholderTrends:"AI agents, longevity… or empty = global top videos",placeholderPains:"running injury, productivity… or empty = global top for region",placeholderCombo:"niche or topic… or empty = global top",submitWith:"Run «{{mode}}»",submitGlobal:"Global Top «{{mode}}» ({{region}})",launchedToast:"{{mode}} started",launchedGlobalToast:"{{mode}} (global) started",launchFailed:"Failed to start",focusLabel:"What exactly to look for and how to format the result",focusOptional:"(optional)",focusPlaceholder:"E.g.: extract the top-20 most popular questions from the comments as a long list and give your detailed answer to each one. Or: collect all price objections and craft counterarguments."},$ue={title:"Recent runs",empty:"Nothing yet",emptyDesc:"Run your first search above.",hung:"Looks stuck",retry:"Retry"},Lue={themesTitle:"Hot themes right now",themesSubtitle:"AI-clustered themes from global YouTube trending",themesEmpty:"Themes will appear once the collector runs.",surgingTitle:"Surging now",surgingSubtitle:"Top signals across YouTube, Reddit, Hacker News",surgingEmpty:"No signals yet — collectors run every 5–15 min.",vpm:"{{n}} views/min",useAsSeed:"Use as seed",regionsAll:"All regions",angle:"Angle",whyNow:"Why now",openingLine:"Opening line",talkingPoints:"Talking points",avoid:"Avoid saying"},Iue={backLink:"Back to Topic Discovery",notFound:"Not found",notFoundDesc:"This discovery does not exist.",personaLabel:"Host persona",noPersonas:"No personas — ",noPersonasCreate:"create one",selectPersonaPlaceholder:"Choose persona",generating:"Generating…",createWebinar:"Create webinar",extraInstructions:"Extra instructions",extraOptional:"(optional)",extraPlaceholder:"For example: side with people who have problems, spend more time on pains and objections, add more practical examples…",selectPersonaFirst:"Choose a host persona first",createFailed:"Failed to create webinar",webinarReady:"Webinar ready",topicTitle:"Webinar topic",keyPoints:"Key points",summary:"Summary",suggestedIntro:"Suggested host intro",freeformTitle:"Custom answer (from your instructions)",topicNotReady:"Topic synthesis is not ready yet — status: ",quotesTitle:"Quotes & host comments",source:"source",hostSays:"Host says",sourceVideos:"Source videos ({{count}})",views:"views",hideTranscript:"Hide transcript",showTranscript:"Show transcript",audienceSays:"What the audience says",clusters:{questions:"Audience questions",objections:"Objections",pains:"Pains"},progress:{header:"Generating webinar — {{pct}}%",tail:"We'll redirect to the webinar when everything is ready",description:"YouTube description",greeting:"Host greeting",plan:"Webinar plan (system prompt)",planBlocks:"{{generated}} of {{expected}} blocks",planPreparing:"preparing blocks…",planDone:"{{count}} blocks",continue:"Continuation",summary:"Summary",planLine:"Plan: {{pct}}% ({{generated}}/{{expected}})"}},Oue={pageTitle:Tue,pageSubtitle:Pue,modes:Eue,status:Aue,form:Rue,recent:$ue,trending:Lue,result:Iue},Due="Тренды — режим Нонстоп",Mue="Выберите аватара и запустите бесконечный лайв. AI-ведущий сам подтягивает свежие темы из Trend Radar одну за другой и отвечает на комментарии между ними.",zue="Аватар",Fue="Выберите аватара",Uue="Язык",Bue="Платформа",Vue="Restream (мультистрим + чат)",que="Отвечать на комментарии в чате перед взятием следующей темы",Hue="Показывать субтитры поверх видео",Wue="Возвращаться к горячим темам каждые N минут с новыми деталями",Gue="минут — если тема всё ещё в трендах, ведущий вернётся к ней с новыми комментариями вместо новой темы",Yue="Промпты режима «Тренды»",Kue="Кластеризация сигналов в темы и формат подачи на эфире. Сохраняется на выбранной персоне — пока не сбросить, остаётся ваше.",Que="Водяной знак (опционально)",Jue="Создано в SmartBlog.AI",Zue="Тематика / запрос (опционально)",Xue="напр. AI стартапы, психология отношений",ehe="Пока эфир идёт, тренды будут собираться именно по этому запросу. Когда остановите — сбор по запросу прекратится, останутся только глобаÐ
1033»ÑŒÐ½Ñ‹Ðµ тренды. Первые 30–60 сек, пока специализированные тренды собираются, ведущий может говорить из общего пула трендов (по ключевым словам запроса).",the="Тематика эфира (можно менять на лету)",she="Сохраните — и через 30–60 сек ведущий переключится на новые темы по этому запросу. Очистите поле, чтобы вернуться к глобальным трендам.",nhe="Живое отслеживание комментариев",rhe="Фоновый поллер каждые 10 мин подкачивает свежие комментарии с топ-20 трендовых видео. Когда тема возвращается в подготовку — новая волна обсуждения подмешивается в следующий бриф.",ahe="Сохранить",ihe="Сохраняем…",ohe="Сохранить и пересобрать тренды",lhe="Сохраняем…",che="Название эфира",dhe="Например: Горячие сплетни недели",uhe="Описание",hhe="Краткое описание эфира для платформы",mhe="Запустить нонстоп-тренды",phe="Запускаем…",fhe="Готовим темы из YouTube…",ghe="Передаём воркеру…",xhe="По этому запросу не нашлось трендовых видео. Поменяйте формулировку и попробуйте снова.",vhe="Темы ещё ищутся. Сессия оставлена в подготовке — лайв не запущен, воркеру задача не передана.",yhe="YouTube не нашёл ни одного видео по этому запросу. Переформулируйте тему (более общими словами или на другом языке) и попробуйте снова. Сессия отменена.",bhe="Остановить",whe="Останавливаем…",jhe="Сначала создайте аватара.",_he="Сессия нонстоп-трендов поставлена в очередь",khe="Не удалось запустить. Попробуйте ещё раз.",Nhe="Активные нонстоп-сессии",She="История",Che="Нет запущенных нонстоп-сессий.",The="Прошлых нонстоп-сессий пока нет.",Phe="Повторить",Ehe="Статус",Ahe="Запущено",Rhe="Как работает режим Нонстоп",$he=["Воркер тянет следующую готовую тему из Trend Radar через worker-api → next_topic.","Произносит opening_line, потом talking_points — без скрипта и ограничения по времени.","Когда приходят новые комментарии — отвечает на них перед тем, как взять новую тему.","Когда тема закончилась — снова вызывает next_topic. Цикл идёт, пока вы не нажмёте «Остановить»."],Lhe={pageTitle:Due,pageSubtitle:Mue,personaLabel:zue,personaPlaceholder:Fue,languageLabel:Uue,platformLabel:Bue,platformRestream:Vue,chatReplyLabel:que,subtitlesLabel:Hue,refreshHotLabel:Wue,refreshHotHint:Gue,promptsTitle:Yue,promptsSubtitle:Kue,watermarkLabel:Que,watermarkPlaceholder:Jue,topicQueryLabel:Zue,topicQueryPlaceholder:Xue,topicQueryHint:ehe,liveTopicQueryLabel:the,liveTopicQueryHint:she,liveCommentTracking:nhe,liveCommentTrackingHint:rhe,saveQuery:ahe,savingQuery:ihe,saveAll:ohe,savingAll:lhe,titleLabel:che,titlePlaceholder:dhe,descriptionLabel:uhe,descriptionPlaceholder:hhe,startBtn:mhe,starting:phe,preparingTopics:fhe,dispatchingWorker:ghe,noTopicsFound:xhe,topicsStillPreparing:vhe,noYoutubeResults:yhe,stopBtn:bhe,stopping:whe,noPersona:jhe,createdToast:_he,createError:khe,activeTitle:Nhe,historyTitle:She,emptyActive:Che,emptyHistory:The,repeatBtn:Phe,statusLabel:Ehe,startedAt:Ahe,howItWorksTitle:Rhe,howItWorks:$he},Ihe="Trends — Nonstop Mode",Ohe="Pick a persona and launch a nonstop live stream. The AI host will pull fresh topics from the Trend Radar one after another, and answer chat comments between segments.",Dhe="Persona",Mhe="Choose a persona",zhe="Language",Fhe="Platform",Uhe="Restream (multistream + chat)",Bhe="Answer chat comments before pulling the next topic",Vhe="Show subtitles overlay on the video",qhe
1033="Revisit still-hot topics every N minutes with new details",Hhe="minutes — if the topic is still trending, the host returns to it with fresh comments instead of switching themes",Whe="Trends mode prompts",Ghe="Signals clustering and on-air delivery format. Stored on the selected persona — your edits stay until you hit Reset.",Yhe="Watermark (optional)",Khe="Created by SmartBlog.AI",Qhe="Topic / search query (optional)",Jhe="e.g. AI startups, relationship psychology",Zhe="While the stream runs, trends are collected specifically for this query. When you stop, query-specific collection stops too — only global trends remain. For the first 30–60 sec while query-specific trends are being gathered, the host may speak from the global pool (filtered by your query keywords).",Xhe="Live topic query (change on the fly)",eme="Save — within 30–60 sec the host will switch to new themes for this query. Clear the field to fall back to global trends.",tme="Live comment tracking",sme="Background poller watches top-20 trending videos every 10 min and pulls fresh comments. When the theme comes back into preparation, the new wave is mixed into the next brief.",nme="Save",rme="Saving…",ame="Save and refresh trends",ime="Saving…",ome="Stream title",lme="e.g. Hot gossip of the week",cme="Description",dme="Short stream description for the platform",ume="Start nonstop trends",hme="Starting…",mme="Preparing topics from YouTube…",pme="Handing off to the worker…",fme="No trending videos for this query. Tweak the wording and try again.",gme="Topics are still being searched. The session stays in preparation — the live stream has not started and no worker job was dispatched.",xme="YouTube returned zero videos for this query. Rephrase the topic (broader wording or a different language) and try again. Session has been canceled.",vme="Stop",yme="Stopping…",bme="Create a persona first.",wme="Nonstop trends session queued",jme="Failed to start. Try again.",_me="Active nonstop sessions",kme="History",Nme="No nonstop sessions running.",Sme="No past nonstop sessions yet.",Cme="Repeat",Tme="Status",Pme="Started",Eme="How nonstop mode works",Ame=["The worker pulls the next broadcast-ready topic from the Trend Radar via worker-api → next_topic.","It speaks the opening line, then the talking points — no script, no time limit.","When new chat comments arrive, the host answers them before requesting the next topic.","When the topic is done, it calls next_topic again. Loop continues until you press Stop."],Rme={pageTitle:Ihe,pageSubtitle:Ohe,personaLabel:Dhe,personaPlaceholder:Mhe,languageLabel:zhe,platformLabel:Fhe,platformRestream:Uhe,chatReplyLabel:Bhe,subtitlesLabel:Vhe,refreshHotLabel:qhe,refreshHotHint:Hhe,promptsTitle:Whe,promptsSubtitle:Ghe,watermarkLabel:Yhe,watermarkPlaceholder:Khe,topicQueryLabel:Qhe,topicQueryPlaceholder:Jhe,topicQueryHint:Zhe,liveTopicQueryLabel:Xhe,liveTopicQueryHint:eme,liveCommentTracking:tme,liveCommentTrackingHint:sme,saveQuery:nme,savingQuery:rme,saveAll:ame,savingAll:ime,titleLabel:ome,titlePlaceholder:lme,descriptionLabel:cme,descriptionPlaceholder:dme,startBtn:ume,starting:hme,preparingTopics:mme,dispatchingWorker:pme,noTopicsFound:fme,topicsStillPreparing:gme,noYoutubeResults:xme,stopBtn:vme,stopping:yme,noPersona:bme,createdToast:wme,createError:jme,activeTitle:_me,historyTitle:kme,emptyActive:Nme,emptyHistory:Sme,repeatBtn:Cme,statusLabel:Tme,startedAt:Pme,howItWorksTitle:Eme,howItWorks:Ame},$me="Новости — режим Нонстоп",Lme="Выберите аватара, настройте источник новостей из NewsAPI и запустите бесконечный лайв. AI-ведущий подтягивает свежие новости одну за другой и отвечает на чат между ними.",Ime="Аватар",Ome="Выберите аватара",Dme="Язык",Mme="Платформа",zme="Restream (мультистрим + чат)",Fme="Отвечать на комментарии перед следующей новостью",Ume="Показывать субтитры поверх видео",Bme="Название эфира",Vme="Например: Новости мира, каждые 5 минут",qme="Описание",Hme="Краткое описание эфира для платформы",Wme="Водяной знак (опционально)",Gme="Создано в SmartBlog.AI",Yme="Источник новостей",Kme="Что именно тянуть из NewsAPI. Можно комбинировать — всё сольётся в один поток.",Qme="Режим",Jme="Удиви меня",Zme="Кураторская подборка: tech/бизнес/наука/здоровье/мир из премиум-изданий.",Xme="По запросу",epe="Используйте поле поиска ниже.",tpe="По стране / категории",spe="Top headlines для выбранной страны и категории.",npe="По доменам",rpe="Через запятую, напр. techcrunch.com, bloomberg.com.",ape="Поисковый запрос",ipe="напр. искусственный интеллект, электромобили",ope="Поддерживается + - AND OR NOT и кавычки. Берёт за последние 30 мин, сортировка — по времени публикации.",lpe="Страна",cpe="Категория",dpe="Домены",upe="techcrunch.com, theverge.com, bloomberg.com",hpe="Какие категории мешать",mpe={general:"Общее",technology:"Технологии",business:"Бизнес",science:"Наука",health:"Здоровье",entertainment:"Развлечения",sports:"Спорт"},ppe="Любая",fpe="Любая",gpe="Запустить нонстоп-новости",xpe="Запускаем…",vpe="Остановить",ype="Останавливаем…",bpe="Сначала создайте аватара.",wpe="СессиÑ
1033 нонстоп-новостей поставлена в очередь",jpe="Не удалось запустить. Попробуйте ещё раз.",_pe="Активные сессии новостей",kpe="История",Npe="Нет запущенных нонстоп-новостных сессий.",Spe="Запустите сессию выше, чтобы начать вещание новостей.",Cpe="Прошлых сессий пока нет.",Tpe="Здесь появятся завершённые сессии.",Ppe="Повторить",Epe="Статус",Ape="Запущено",Rpe="Как работает режим Нонстоп-Новости",$pe=["Каждые 5 минут коллектор тянет свежие новости из NewsAPI по вашему конфигу.","Дубликаты одной и той же новости из разных изданий склеиваются в один сюжет.","Ведущий произносит цепляющую фразу, основной текст и мост к следующей теме.","Между новостями отвечает на комментарии чата."],Lpe={pageTitle:$me,pageSubtitle:Lme,personaLabel:Ime,personaPlaceholder:Ome,languageLabel:Dme,platformLabel:Mme,platformRestream:zme,chatReplyLabel:Fme,subtitlesLabel:Ume,titleLabel:Bme,titlePlaceholder:Vme,descriptionLabel:qme,descriptionPlaceholder:Hme,watermarkLabel:Wme,watermarkPlaceholder:Gme,sourceTitle:Yme,sourceSubtitle:Kme,modeLabel:Qme,modeSurprise:Jme,modeSurpriseHint:Zme,modeQuery:Xme,modeQueryHint:epe,modeRegion:tpe,modeRegionHint:spe,modeDomains:npe,modeDomainsHint:rpe,queryLabel:ape,queryPlaceholder:ipe,queryHint:ope,countryLabel:lpe,categoryLabel:cpe,domainsLabel:dpe,domainsPlaceholder:upe,surpriseCategoriesLabel:hpe,categories:mpe,anyCountry:ppe,anyCategory:fpe,startBtn:gpe,starting:xpe,stopBtn:vpe,stopping:ype,noPersona:bpe,createdToast:wpe,createError:jpe,activeTitle:_pe,historyTitle:kpe,emptyActive:Npe,emptyActiveDesc:Spe,emptyHistory:Cpe,emptyHistoryDesc:Tpe,repeatBtn:Ppe,statusLabel:Epe,startedAt:Ape,howItWorksTitle:Rpe,howItWorks:$pe},Ipe="News — Nonstop Mode",Ope="Pick a persona, choose how to pull headlines from NewsAPI, and launch a nonstop live stream. The AI host pulls fresh news one after another and answers chat between stories.",Dpe="Persona",Mpe="Choose a persona",zpe="Language",Fpe="Platform",Upe="Restream (multistream + chat)",Bpe="Answer chat comments before pulling the next story",Vpe="Show subtitles overlay on the video",qpe="Stream title",Hpe="e.g. World news, every 5 minutes",Wpe="Description",Gpe="Short stream description for the platform",Ype="Watermark (optional)",Kpe="Created by SmartBlog.AI",Qpe="News source",Jpe="What kind of stories to pull from NewsAPI. You can combine several — everything gets merged into one stream.",Zpe="Mode",Xpe="Surprise me",efe="Curated tech/business/science/health/world headlines from premium publishers.",tfe="By query",sfe="Use the search box below.",nfe="By country / category",rfe="Top headlines for a country and category.",afe="By domains",ife="Comma-separated, e.g. techcrunch.com, bloomberg.com.",ofe="Search query",lfe="e.g. artificial intelligence, electric cars",cfe="Supports + - AND OR NOT and quotes. Pulls last 30 min, sorted by published time.",dfe="Country",ufe="Category",hfe="Domains",mfe="techcrunch.com, theverge.com, bloomberg.com",pfe="Categories to mix",ffe={general:"General",technology:"Technology",business:"Business",science:"Science",health:"Health",entertainment:"Entertainment",sports:"Sports"},gfe="Any",xfe="Any",vfe="Start nonstop news",yfe="Starting…",bfe="Stop",wfe="Stopping…",jfe="Create a persona first.",_fe="Nonstop news session queued",kfe="Failed to start. Try again.",Nfe="Active news sessions",Sfe="History",Cfe="No nonstop news sessions running.",Tfe="Start a session above to begin broadcasting news.",Pfe="No past nonstop news sessions yet.",Efe="Your finished sessions will appear here.",Afe="Repeat",Rfe="Status",$fe="Started",Lfe="How nonstop news works",Ife=["Every 5 min the collector pulls fresh stories from NewsAPI for your session config.","Duplicate stories from different publishers get clustered into one topic.","The host says the opener, the body, and a bridge — then asks for the next news.","Between stories, chat comments get answered."],Ofe={pageTitle:Ipe,pageSubtitle:Ope,personaLabel:Dpe,personaPlaceholder:Mpe,languageLabel:zpe,platformLabel:Fpe,platformRestream
1033:Upe,chatReplyLabel:Bpe,subtitlesLabel:Vpe,titleLabel:qpe,titlePlaceholder:Hpe,descriptionLabel:Wpe,descriptionPlaceholder:Gpe,watermarkLabel:Ype,watermarkPlaceholder:Kpe,sourceTitle:Qpe,sourceSubtitle:Jpe,modeLabel:Zpe,modeSurprise:Xpe,modeSurpriseHint:efe,modeQuery:tfe,modeQueryHint:sfe,modeRegion:nfe,modeRegionHint:rfe,modeDomains:afe,modeDomainsHint:ife,queryLabel:ofe,queryPlaceholder:lfe,queryHint:cfe,countryLabel:dfe,categoryLabel:ufe,domainsLabel:hfe,domainsPlaceholder:mfe,surpriseCategoriesLabel:pfe,categories:ffe,anyCountry:gfe,anyCategory:xfe,startBtn:vfe,starting:yfe,stopBtn:bfe,stopping:wfe,noPersona:jfe,createdToast:_fe,createError:kfe,activeTitle:Nfe,historyTitle:Sfe,emptyActive:Cfe,emptyActiveDesc:Tfe,emptyHistory:Pfe,emptyHistoryDesc:Efe,repeatBtn:Afe,statusLabel:Rfe,startedAt:$fe,howItWorksTitle:Lfe,howItWorks:Ife},Dfe="Admin Panel",Mfe="Управление пользователями и диагностика системы",zfe="Доступ запрещён",Ffe="Эта страница доступна только администраторам",Ufe="Загрузка пользователей...",Bfe={users:"Пользователи",logs:"Error Logs"},Vfe="{{count}} пользователей в системе",qfe="Обновить",Hfe="Поиск по имени или email...",Wfe={total:"Всего",onPage:"На странице"},Gfe="Действия",Yfe="Назначить {{role}}",Kfe="Убрать {{role}}",Qfe="Заблокировать",Jfe="Разбанить",Zfe="заблокирован",Xfe="активен",ege="нет ролей",tge="Нет workspace",sge="Ничего не найдено",nge="Нет пользователей",rge={user:"Пользователь",status:"Статус",roles:"Роли",workspace:"Workspace",lastLogin:"Последний вход",actions:"Действия"},age={removeRoleTitle:"Убрать роль",assignRoleTitle:"Назначить роль",removeRoleDesc:'Убрать роль "{{role}}" у {{user}}?',assignRoleDesc:'Назначить роль "{{role}}" пользователю {{user}}?',banTitle:"Заблокировать пользователя",unbanTitle:"Разбанить пользователя",banDesc:"Заблокировать {{user}}? Пользователь не сможет войти в систему.",unbanDesc:"Разбанить {{user}}? Пользователь снова сможет входить в систему.",cancel:"Отмена",ban:"Заблокировать",unban:"Разбанить",remove:"Убрать",assign:"Назначить"},ige={total:"всего {{count}}",refresh:"Обновить",searchPlaceholder:"Поиск по сообщению…",allLevels:"Все уровни",allSources:"Все источники",empty:"Нет логов с такими фильтрами",copyJson:"Скопировать JSON"},oge={title:Dfe,subtitle:Mfe,accessDenied:zfe,accessDeniedDesc:Ffe,loadingUsers:Ufe,tabs:Bfe,totalUsers:Vfe,refresh:qfe,search:Hfe,stats:Wfe,actions:Gfe,assignRole:Yfe,removeRole:Kfe,ban:Qfe,unban:Jfe,banned:Zfe,active:Xfe,noRoles:ege,noWorkspace:tge,nothingFound:sge,noUsers:nge,table:rge,confirm:age,errorLogs:ige},lge="Admin Panel",cge="User management and system diagnostics",dge="Access denied",uge="This page is only available to administrators",hge="Loading users...",mge={users:"Users",logs:"Error Logs"},pge="{{count}} users in the system",fge="Refresh",gge="Search by name or email...",xge={total:"Total",onPage:"On page"},vge="Actions",yge="Assign {{role}}",bge="Remove {{role}}",wge="Ban",jge="Unban",_ge="banned",kge="active",Nge="no roles",Sge="No workspace",Cge="Nothing found",Tge="No users",Pge={user:"User",status:"Status",roles:"Roles",workspace:"Workspace",lastLogin:"Last login",actions:"Actions"},Ege={removeRoleTitle:"Remove role",assignRoleTitle:"Assign role",removeRoleDesc:'Remove role "{{role}}" from {{user}}?',assignRoleDesc:'Assign role "{{role}}" to {{user}}?',banTitle:"Ban user",unbanTitle:"Unban user",banDesc:"Ban {{user}}? They will not be able to sign in.",unbanDesc:"Unban {{user}}? They will be able to sign in again.",cancel:"Cancel",ban:"Ban",unban:"Unban",remove:"Remove",assign:"Assign"},Age={total:"total {{count}}",refresh:"Refresh",searchPlaceholder:"Search by message…",allLevels:"All levels",allSources:"All sources",empty:"No logs match these filters",copyJson:"Copy JSON"},Rge={title:lge,subtitle:cge,accessDenied:dge,accessDeniedDesc:uge,loadingUsers:hge,tabs:mge,totalUsers:pge,refresh:fge,search:gge,stats:xge,actions:vge,assignRole:yge,removeRole:bge,ban:wge,unban:jge,banned:_ge,active:kge,noRoles:Nge,noWorkspace:Sge,nothingFound:Cge,noUsers:Tge,table:Pge,confirm:Ege,errorLogs:Age},$ge="Войдите и запустите своего ИИ-персонажа",Lge="Войдите через Google или по email и паролю — и проходите онбординг, создавайте ИИ-блогера, ИИ-ведущего или ИИ-консультанта.",Ige="Продолжить через Google",Oge="Вход...",Dge="Не удалось войти. Попробуйте ещё раз.",Mge="Нажимая «Продолжить», вы соглашаетесь с",zge="Условиями",Fge="и",Uge="Политикой конфиденциальности",Bge="Сначала вы входите в платформу.",Vge="YouTube подключается позже внутри продукта.",qge="или",Hge="ваш@email.com",Wge="Пароль (минимум 6 символов)",Gge="Войти",Yge="Создать аккаунт",Kge="Отправка...",Qge="Нет аккаунта? Зарегистрироваться",Jge="Уже есть аккаунт? Войти",Zge="Введите корректный email",Xge="Пароль должен быть не короче 6 символов",exe="Неверный email или пароль",txe="Слишком много попыток. Попробуйте через минуту.",sxe="Вход через Google и по email с одинаковым адресом — это один аккаунт.",nxe="Забыли пароль?",rxe="Письмо для сброса пароля отправлено. Проверьте почту.",axe="Новый пароль",ixe="Введите новый пароль для вашего аккаунта.",oxe="Новый пароль (минимум 6 символов)",lxe="Повторите пароль",cxe="Сохранить пароль",dxe="Пароль обновлён. Перенаправляем...",uxe="Пароли не совпадают",hxe="← Вернуться ко входу",mxe="Ссылка недействительна",pxe="Ссылка для сброса пароля устарела или уже была использована (часто её «съедает» предпросмотр в почте/мессенджере). Запросите новую ниже.",fxe="Прислать новую ссылку",gxe={title:$ge,subtitle:Lge,google:Ige,loading:Oge,error:Dge,consent:Mge,termsLink:zge,and:Fge,privacyLink:Uge,note:Bge,noteYoutube:Vge,divider:qge,emailPlaceholder:Hge,passwordPlaceholder:Wge,signInBtn:Gge,signUpBtn:Yge,submitting:Kge,toggleToSignUp:
1033Qge,toggleToSignIn:Jge,invalidEmail:Zge,invalidPassword:Xge,invalidCredentials:exe,rateLimitError:txe,unifiedAccountNote:sxe,forgotPassword:nxe,resetEmailSent:rxe,resetTitle:axe,resetSubtitle:ixe,newPasswordPlaceholder:oxe,confirmPasswordPlaceholder:lxe,resetBtn:cxe,resetSuccess:dxe,passwordMismatch:uxe,backToLogin:hxe,linkExpiredTitle:mxe,linkExpiredSubtitle:pxe,resendResetLink:fxe},xxe="Sign in and launch your AI persona",vxe="Sign in with Google or with email & password — complete onboarding, create an AI blogger, AI host, or AI consultant.",yxe="Continue with Google",bxe="Signing in...",wxe="Failed to sign in. Please try again.",jxe='By clicking "Continue", you agree to the',_xe="Terms",kxe="and",Nxe="Privacy Policy",Sxe="First, you sign in to the platform.",Cxe="YouTube is connected later inside the product.",Txe="or",Pxe="[email protected]",Exe="Password (min 6 characters)",Axe="Sign in",Rxe="Create account",$xe="Submitting...",Lxe="No account? Sign up",Ixe="Already have an account? Sign in",Oxe="Enter a valid email",Dxe="Password must be at least 6 characters",Mxe="Invalid email or password",zxe="Too many attempts. Try again in a minute.",Fxe="Google sign-in and email/password with the same email = one account.",Uxe="Forgot password?",Bxe="Password reset email sent. Check your inbox.",Vxe="New password",qxe="Enter a new password for your account.",Hxe="New password (min 6 characters)",Wxe="Repeat password",Gxe="Save password",Yxe="Password updated. Redirecting...",Kxe="Passwords do not match",Qxe="← Back to sign in",Jxe="Link is invalid",Zxe="This reset link has expired or was already used (mail/messenger previews often consume it). Request a new one below.",Xxe="Send a new link",eve={title:xxe,subtitle:vxe,google:yxe,loading:bxe,error:wxe,consent:jxe,termsLink:_xe,and:kxe,privacyLink:Nxe,note:Sxe,noteYoutube:Cxe,divider:Txe,emailPlaceholder:Pxe,passwordPlaceholder:Exe,signInBtn:Axe,signUpBtn:Rxe,submitting:$xe,toggleToSignUp:Lxe,toggleToSignIn:Ixe,invalidEmail:Oxe,invalidPassword:Dxe,invalidCredentials:Mxe,rateLimitError:zxe,unifiedAccountNote:Fxe,forgotPassword:Uxe,resetEmailSent:Bxe,resetTitle:Vxe,resetSubtitle:qxe,newPasswordPlaceholder:Hxe,confirmPasswordPlaceholder:Wxe,resetBtn:Gxe,resetSuccess:Yxe,passwordMismatch:Kxe,backToLogin:Qxe,linkExpiredTitle:Jxe,linkExpiredSubtitle:Zxe,resendResetLink:Xxe},tve="Как это работает",sve="От создания персонажа до",nve="стабильного дохода",rve="8 шагов от идеи до работающего медиа-бизнеса на основе ИИ-блогера, ИИ-ведущего или ИИ-консультанта.",ave=[{num:"01",title:"Создайте ИИ-персонажа",desc:"Выберите роль — блогер, ведущий, консультант или преподаватель. Настройте тему, тон, стиль и возможности. Персонаж становится основой всего контента.",detail:"Один персонаж = ваш голос, стиль и бренд на всех площадках."},{num:"02",title:"Подключите YouTube",desc:"YouTube — ваша публичная площадка для роста. Подключите канал, чтобы публиковать Shorts, планировать live-эфиры и строить аудиторию.",detail:"Подключение YouTube отдельно от входа в платформу. Это интеграция канала, а не логин."},{num:"03",title:"Генерируйте Shorts",desc:"ИИ-персонаж создаёт короткие видео по вашим темам. Выберите формат, длительность, CTA — и получите готовый сценарий.",detail:"Shorts — главный инструмент для привлечения внимания и тестирования тем."},{num:"04",title:"Проводите live-эфиры",desc:"ИИ-ведущий выходит в прямой эфир, ведёт тему и отвечает на вопросы аудитории в реальном времени.",detail:"Live создаёт доверие быстрее, чем любой другой формат контента."},{num:"05",title:"Перерабатывайте контент",desc:"Один эфир превращается в 5–20 единиц контента: Shorts, клипы, тизеры, архив. Контентный цикл работает автоматически.",detail:"Repurposing — это не бонус, а основной механизм масштабирования."},{num:"06",title:"Подключите Patreon",desc:"Когда аудитория сформирована, добавьте платный слой: подписки, закрытые эфиры, бонусный контент и архив.",detail:"Patreon — второй слой монетизации. Подключается, когда есть доверие аудитории."},{num:"07",title:"Запустите консультации",desc:"ИИ-консультант проводит голосовые 1:1 сессии, разборы и экспертные консультации как премиальный формат.",detail:"Консультации — верхний слой монетизации для самых вовлечённых клиентов."},{num:"08",title:"Добавьте вебинары",desc:"Структурированные обучающие мероприятия, платные сессии и закрытые группы для масштабирования дохода.",detail:"Ð
1033’ебинары = масштаб. Один вебинар обслуживает десятки и сотни людей."}],ive=["Внимание","Доверие","Платная глубина","Масштаб"],ove="Начать бесплатно",lve={badge:tve,title:sve,titleGradient:nve,subtitle:rve,steps:ave,funnel:ive,cta:ove},cve="How it works",dve="From creating a persona to",uve="steady income",hve="8 steps from idea to a working media business powered by an AI blogger, AI host, or AI consultant.",mve=[{num:"01",title:"Create an AI persona",desc:"Choose a role — blogger, host, consultant, or educator. Set the topic, tone, style, and capabilities. The persona becomes the foundation for all content.",detail:"One persona = your voice, style, and brand across all platforms."},{num:"02",title:"Connect YouTube",desc:"YouTube is your public stage for growth. Connect your channel to publish Shorts, schedule live streams, and build an audience.",detail:"YouTube connection is separate from platform login. It's a channel integration, not a sign-in."},{num:"03",title:"Generate Shorts",desc:"Your AI persona creates short videos on your topics. Pick a format, duration, CTA — and get a ready script.",detail:"Shorts are the main tool for grabbing attention and testing topics."},{num:"04",title:"Run live streams",desc:"The AI host goes live, covers a topic, and answers audience questions in real time.",detail:"Live builds trust faster than any other content format."},{num:"05",title:"Repurpose content",desc:"One stream turns into 5–20 content pieces: Shorts, clips, teasers, archive. The content cycle runs automatically.",detail:"Repurposing isn't a bonus — it's the core scaling mechanism."},{num:"06",title:"Connect Patreon",desc:"Once you have an audience, add a paid layer: subscriptions, private streams, bonus content, and archives.",detail:"Patreon is the second monetization layer. Connect it when audience trust is established."},{num:"07",title:"Launch consultations",desc:"The AI consultant runs voice 1:1 sessions, reviews, and expert consultations as a premium format.",detail:"Consultations are the top monetization tier for the most engaged clients."},{num:"08",title:"Add webinars",desc:"Structured educational events, paid sessions, and private groups to scale revenue.",detail:"Webinars = scale. One webinar serves dozens or hundreds of people."}],pve=["Attention","Trust","Paid depth","Scale"],fve="Start for free",gve={badge:cve,title:dve,titleGradient:uve,subtitle:hve,steps:mve,funnel:pve,cta:fve},xve="Кейсы использования",vve="Для кого работает",yve="SmartBlogAI",bve="ИИ-персонаж может быть блогером, ведущим, консультантом, преподавателем или представителем бренда — в зависимости от ваших целей.",wve=[{title:"ИИ-блогер",subtitle:"Контент-машина для YouTube",desc:"Создавайте Shorts регулярно, тестируйте темы, наращивайте охват и строите узнаваемый канал — без камеры, монтажа и личного присутствия.",points:["Регулярные Shorts по расписанию","Тестирование тем через короткий контент","Узнаваемый стиль и голос бренда","Рост подписчиков без личного присутствия"],audience:"Эксперты, предприниматели, авторы курсов"},{title:"ИИ-ведущий",subtitle:"Live-хост для прямых эфиров",desc:"ИИ-ведущий проводит прямые эфиры на YouTube, комментирует темы, отвечает на вопросы аудитории и создаёт доверие через живое общение.",points:["Регулярные бесплатные live-эфиры","Ответы на вопросы в реальном времени","Тематические выступления и разборы","Контент из эфиров: клипы, Shorts, тизеры"],audience:"Медиа-проекты, образовательные каналы, новостные форматы"},{title:"ИИ-консультант",subtitle:"Персональные голосовые сессии",desc:"Запускайте платные 1:1 консультации, разборы и экспертные сессии. ИИ-консультант объясняет, помогает и работает как премиальный продукт.",points:["Голосовые консультации 1 на 1","Стратегические сессии и разборы","Приватные Q&A для клиентов","Премиальный формат монетизации"],audience:"Коучи, эксперты, менторы, аналитики"},{title:"ИИ-преподаватель",subtitle:"Обучающие курсы и вебинары",desc:"ИИ-преподаватель проводит структурированные лекции, мастер-классы и обучающие вебинары как отдельный образовательный продукт.",points:["Структурированные лекции и курсы","Платные вебинары и мастер-классы","Обучение на основе вашей экспертизы","Записи и архив для подписчиков"],audience:"Онлайн-школы, эксперты, тренеры, преподаватели"},{title:"Хост сообщества",subtitle:"Закрытое сообщество и подписки",desc:"Стройте платное сообщество через YouTube Memberships и Patreon. Закрытые эфиры, бонусный контент и архив для самых лояльных зрителей.",points:["Платные подписки через Patreon","YouTube Memberships","Закрытые live-эфиры","БоÐ
1033½ÑƒÑÐ½Ñ‹Ð¹ и архивный контент"],audience:"Авторы с лояльной аудиторией, создатели сообществ"},{title:"Цифровой представитель бренда",subtitle:"ИИ-спикер для бизнеса",desc:"Создайте цифрового представителя вашего бренда, который общается с аудиторией, проводит презентации и строит узнаваемость.",points:["Единый голос и стиль бренда","Регулярное присутствие в медиа","Масштабирование без команды","Несколько персонажей для разных направлений"],audience:"Стартапы, агентства, персональные бренды"}],jve="Начать бесплатно",_ve={badge:xve,title:vve,titleGradient:yve,subtitle:bve,cases:wve,cta:jve},kve="Use cases",Nve="Who benefits from",Sve="SmartBlogAI",Cve="An AI persona can be a blogger, host, consultant, educator, or brand representative — depending on your goals.",Tve=[{title:"AI Blogger",subtitle:"Content machine for YouTube",desc:"Publish Shorts regularly, test topics, grow reach, and build a recognizable channel — no camera, editing, or personal presence required.",points:["Scheduled Shorts on autopilot","Topic testing through short content","Recognizable brand voice and style","Subscriber growth without personal presence"],audience:"Experts, entrepreneurs, course creators"},{title:"AI Host",subtitle:"Live host for streams",desc:"The AI host runs live streams on YouTube, comments on topics, answers audience questions, and builds trust through live interaction.",points:["Regular free live streams","Real-time Q&A","Themed talks and reviews","Content from streams: clips, Shorts, teasers"],audience:"Media projects, educational channels, news formats"},{title:"AI Consultant",subtitle:"Personal voice sessions",desc:"Launch paid 1:1 consultations, reviews, and expert sessions. The AI consultant explains, helps, and operates as a premium product.",points:["Voice consultations 1-on-1","Strategic sessions and reviews","Private Q&A for clients","Premium monetization format"],audience:"Coaches, experts, mentors, analysts"},{title:"AI Educator",subtitle:"Courses and webinars",desc:"The AI educator runs structured lectures, masterclasses, and educational webinars as a standalone educational product.",points:["
1033Structured lectures and courses","Paid webinars and masterclasses","Training based on your expertise","Recordings and archives for subscribers"],audience:"Online schools, experts, trainers, educators"},{title:"Community Host",subtitle:"Private community and subscriptions",desc:"Build a paid community via YouTube Memberships and Patreon. Private streams, bonus content, and archives for your most loyal viewers.",points:["Paid subscriptions via Patreon","YouTube Memberships","Private live streams","Bonus and archive content"],audience:"Creators with a loyal audience, community builders"},{title:"Digital Brand Representative",subtitle:"AI speaker for business",desc:"Create a digital representative for your brand that engages the audience, delivers presentations, and builds recognition.",points:["Unified brand voice and style","Regular media presence","Scaling without a team","Multiple personas for different verticals"],audience:"Startups, agencies, personal brands"}],Pve="Start for free",Eve={badge:kve,title:Nve,titleGradient:Sve,subtitle:Cve,cases:Tve,cta:Pve},Ave="Политика конфиденциальности",Rve="Дата вступления в силу: 30 марта 2026 г.",$ve=[{heading:"1. Общие положения",paragraphs:["Настоящая Политика конфиденциальности (далее — «Политика
1033») описывает, каким образом платформа SmartBlogAI (далее — «Платформа», «мы», «нас») собирает, использует, хранит и защищает персональные данные пользователей (далее — «Пользователь», «вы»).","Используя Платформу, вы подтверждаете, что ознакомились с данной Политикой и даёте согласие на обработку ваших персональных данных в соответствии с её условиями."]},{heading:"2. Какие данные мы собираем",paragraphs:["Мы можем собирать следующие категории данных:"],list:["<strong>Данные аккаунта:</strong> имя, адрес электронной почты, аватар, предоставляемые через Google OAuth.","<strong>Данные профиля:</strong> выбранная роль, ниша, язык, параметры ИИ-персонажа.","<strong>Данные интеграций:</strong> токены доступа YouTube и Patreon (хранятся в зашифрованном виде), идентификаторы каналов и кампаний.","<strong>Контент:</strong> тексты скриптов, темы, метаданные сессий live-эфиров, созданных через Платформу.","<strong>Данные подписки:</strong> идентификатор клиента Stripe, план подписки, статус оплаты. Мы не храним данные банковских карт — их обрабатывает Stripe.","<strong>Техническая информация:</strong> IP-адрес, тип браузера, данные об использовании Платформы для обеспечения работоспособности и улучшения сервиса."]},{heading:"3. Цели обработки данных",paragraphs:["Мы используем ваши данные для:"],list:["предоставления и поддержки функций Платформы;","создания и управления вашей учётной записью;","работы ИИ-персонажей: генерации контента, проведения live-эфиров, обработки чатов;","интеграции с YouTube (публикация видео, управление эфирами) и Patreon (управление подписками аудитории);","обработки платежей через Stripe за подписку на Платформу;","отправки уведомлений о статусе сервиса, обновлениях и важных изменениях;","улучшения продукта, аналитики и устранения ошибок."]},{heading:"4. Хранение и защита данных",paragraphs:["Данные хранятся на защищённых серверах с использованием шифрования при передаче (TLS) и при хранении. Токены доступа к внешним сервисам (YouTube, Patreon) хранятся в зашифрованном виде и никогда не передаются третьим лицам.","Мы применяем политики доступа на уровне строк (Row Level Security) для изоляции данных между пользователями и рабочими пространствами."]},{heading:"5. Передача данных третьим лицам",paragraphs:["Мы передаём данные третьим сторонам только в следующих случаях:"],list:["<strong>Google (YouTube API):</strong> для публикации контента и управления live-эфирами на вашем канале, по вашему явному запросу.","<strong>Patreon API:</strong> для интеграции с вашей страницей автора, по вашему явному запросу.","<strong>Stripe:</strong> для обработки платежей за подписку на Платформу.","<strong>AI-провайдеры:</strong> для генерации контента ИИ-персонажем. Передаются только промпты и контекст задачи, не персональные данные."],afterList:"Мы не продаём, не сдаём в аренду и не передаём ваши данные для маркетинговых целей третьих лиц."},{heading:"6. YouTube API и Google API Services",paragraphs:['Использование Платформой данных, полученных через YouTube API Services, подчиняется <a href="https://developers.google.com/terms/api-services-user-data-policy" target="_blank" rel="noopener noreferrer" class="text-primary hover:underline">
1033Google API Services User Data Policy</a>, включая требования Limited Use.',"Платформа использует YouTube API для:"],list:["получения информации о канале пользователя (название, аватар, количество подписчиков);","публикации видео и Shorts;","создания и управления live-трансляциями;","чтения live-чата для AI-ответов."],afterList:'Вы можете в любой момент отозвать доступ к YouTube через раздел <a href="/app/integrations" class="text-primary hover:underline">Интеграции</a> в приложении или через <a href="https://myaccount.google.com/permissions" target="_blank" rel="noopener noreferrer" class="text-primary hover:underline">настройки безопасности Google</a>.'},{heading:"6.1. Раскрытие ограниченного использования (Limited Use Disclosure)",paragraphs:['Использование и передача SmartBlogAI информации, полученной из Google API, любому другому приложению будет соответствовать <a href="https://developers.google.com/terms/api-services-user-data-policy#additional_requirements_for_specific_api_scopes" target="_blank" rel="noopener noreferrer" class="text-primary hover:underline">Google API Services User Data Policy</a>, включая требования Limited Use.',"Данные пользователей Google, полученные через YouTube API Services, используются <strong>исключительно</strong> для предоставления или улучшения функций Платформы, доступных пользователям. Мы <strong>не</strong> используем данные Google для следующих целей:"],list:["таргетированная, персонализированная, ретаргетированная или контекстная реклама;","продажа данных третьим лицам или брокерам данных;","передача данных информационным посредникам;","определение кредитоспособности или использование в целях кредитования;","создание баз данных, не связанных с функциональностью Платформы;","обучение моделей ИИ или машинного обучения, не связанных с функциональностью Платформы."],afterList:"Данные пользователей Google не передаются третьим лицам, за исключением случаев, строго необходимых для предоставления или улучшения функций Платформы (например, публикация видео на вашем канале YouTube по вашему явному запросу), или когда это требуется применимым законодательством."},{heading:"7. Файлы cookie",paragraphs:["Платформа использует минимально необходимые cookies для аутентификации и поддержания сессии. Мы не используем рекламные или трекинговые cookies третьих сторон."]},{heading:"8. Права пользователя",paragraphs:["Вы имеете право:"],list:["запрашивать доступ к вашим персональным данным;","требовать исправления или удаления данных;","отключить интеграции (YouTube, Patreon) в любое время;","удалить свой аккаунт и все связанные данные;","отозвать согласие на обработку данных."],afterList:'Для реализации ваших прав свяжитесь с нами по адресу <a href="mailto:[email protected]" class="text-primary hover:underline">[email protected]</a>.'},{heading:"9. Срок хранения данных",paragraphs:["Мы храним ваши данные в течение всего срока использования Платформы. При удалении аккаунта ваши данные удаляются в течение 30 дней, за исключением данных, которые мы обязаны хранить по закону."]},{heading:"10. Изменения Политики",paragraphs:["Мы оставляем за собой право обновлять данную Политику. Актуальная версия всегда доступна на этой странице. При существенных изменениях мы уведомим вас через электронную почту или уведомление в Платформе."]},{heading:"11. Контакты",paragraphs:['По вопросам, связанным с обработкой персональных данных, обращайтесь: <a href="mailto:[email protected]" class="text-primary hover:underline">[email protected]</a>']}],Lve={title:Ave,effectiveDate:Rve,sections:$ve},Ive="Privacy Policy",Ove="Effective date: March 30, 2026",Dve=[{heading:"1. General Provisions",paragraphs:['This Privacy Policy (hereinafter — "Policy") describes how the SmartBlogAI platform (hereinafter — "Platform", "we", "us") collects, uses, stores, and protects the personal data of users (hereinafter — "User", "you").',"By using the Platform, you confirm that you have read this Policy and consent to the processing of your personal data in accordance with its terms."]},{heading:"2. What Data We Collect",paragraphs:["We may collect the following categories of data:"],list:["<strong>Account data:</strong> name, email address, avatar, provided via Google OAuth.","<strong>Profile data:</strong> selected role, niche, language, AI persona parameters.","<strong>Integration data:</strong> YouTube and Patreon access tokens (stored encrypted), channel and campaign identifiers.","<strong>Content:</strong> script texts, topics, live session metadata created through the Platform.","<strong>Subscription data:</strong> Stripe customer ID, subscription plan, payment status. We do not store bank card data — Stripe handles that.","<strong>Technical information:</strong> IP address, browser type, Platform usage data for service reliability and improvement."]},{heading:"3. Purposes of Data Processing",paragraphs:["We use your data to:"],list:["provide and support Platform features;","create and manage your account;
1033","operate AI personas: content generation, live streams, chat processing;","integrate with YouTube (video publishing, stream management) and Patreon (audience subscription management);","process payments via Stripe for Platform subscriptions;","send notifications about service status, updates, and important changes;","improve the product, analytics, and bug fixing."]},{heading:"4. Data Storage and Protection",paragraphs:["Data is stored on secure servers using encryption in transit (TLS) and at rest. Access tokens for external services (YouTube, Patreon) are stored encrypted and are never shared with third parties.","We apply Row Level Security policies to isolate data between users and workspaces."]},{heading:"5. Data Sharing with Third Parties",paragraphs:["We share data with third parties only in the following cases:"],list:["<strong>Google (YouTube API):</strong> to publish content and manage live streams on your channel, at your explicit request.","<strong>Patreon API:</strong> to integrate with your creator page, at your explicit request.","<strong>Stripe:</strong> to process payments for Platform subscriptions.","<strong>AI providers:</strong> for AI persona content generation. Only prompts and task context are transmitted, not personal data."],afterList:"We do not sell, rent, or share your data for third-party marketing purposes."},{heading:"6. YouTube API and Google API Services",paragraphs:[`The Platform's use of data obtained through YouTube API Services is subject to the <a href="https://developers.google.com/terms/api-services-user-data-policy" target="_blank" rel="noopener noreferrer" class="text-primary hover:underline">Google API Services User Data Policy</a>, including the Limited Use requirements.`,"The Platform uses the YouTube API to:"],list:["retrieve user channel information (name, avatar, subscriber count);","publish videos and Shorts;","create and manage live broadcasts;","read live chat for AI responses."],afterList:'You can revoke YouTube access at any time via the <a href="/app/integrations" class="text-primary hover:underline">Integrations</a> section in the app or through <a href="https://myaccount.google.com/permissions" target="_blank" rel="noopener noreferrer" class="text-primary hover:underline">Google security settings</a>.'},{heading:"6.1. Limited Use Disclosure",paragraphs:[`SmartBlogAI's use and transfer to any other app of information received from Google APIs will adhere to the <a href="https://developers.google.com/terms/api-services-user-data-policy#additional_requirements_for_specific_api_scopes" target="_blank" rel="noopener noreferrer" class="text-primary hover:underline">Google API Services User Data Policy</a>, including the Limited Use requirements.`,"Specifically, Google user data obtained via YouTube API Services is used <strong>only</strong> to provide or improve user-facing features of the Platform. We do <strong>not</strong> use Google user data for any of the following purposes:"],list:["targeted, personalized, retargeted, or interest-based advertising;","selling data to third parties or data brokers;","providing data to information resellers;","determining credit-worthiness or for lending purposes;","creating databases unrelated to the Platform's functionality;","training AI or machine learning models unrelated to the Platform's functionality."],afterList:"Google user data is not transferred to any third party except as strictly necessary to provide or improve Platform features (e.g., publishing a video to your YouTube channel at your explicit request), or as required by applicable law."},{heading:"7. Cookies",paragraphs:["The Platform uses only essential cookies for authentication and session management. We do not use advertising or third-party tracking cookies."]},{heading:"8. User Rights",paragraphs:["You have the right to:"],list:["request access to your personal data;","request correction or deletion of data;","disconnect integrations (YouTube, Patreon) at any time;","delete your account and all associated data;","withdraw consent to data processing."],afterList:'To exercise your rights, contact us at <a href="mailto:[email protected]" class="text-primary hover:underline">[email protected]</a>.'},{heading:"9. Data Retention",paragraphs:["We retain your data for the duration of your use of the Platform. Upon account deleti
1033on, your data is removed within 30 days, except for data we are required to retain by law."]},{heading:"10. Policy Changes",paragraphs:["We reserve the right to update this Policy. The current version is always available on this page. For significant changes, we will notify you via email or a Platform notification."]},{heading:"11. Contact",paragraphs:['For questions regarding personal data processing, contact: <a href="mailto:[email protected]" class="text-primary hover:underline">[email protected]</a>']}],Mve={title:Ive,effectiveDate:Ove,sections:Dve},zve="Условия использования",Fve="Дата вступления в силу: 30 марта 2026 г.",Uve=[{heading:"1. Предмет соглашения",paragraphs:["Настоящие Условия использования (далее — «Условия») регулируют отношения между платформой SmartBlogAI (далее — «Платформа», «мы») и физическим или юридическим лицом (далее — «Пользователь», «вы»), использующим Платформу для создания и управления ИИ-персонажами и связанным контентом.","Регистрируясь на Платформе, вы подтверждаете, что ознакомились с настоящими Условиями и принимаете их в полном объёме."]},{heading:"2. Описание сервиса",paragraphs:["SmartBlogAI — это платформа для создания и управления ИИ-персонажами, которые могут:"],list:["создавать текстовые скрипты для видео и Shorts;","проводить live-эфиры на YouTube;","отвечать на вопросы аудитории в реальном времени;","проводить голосовые консультации;","помогать монетизировать аудиторию через Patreon и другие каналы."],afterList:"Платформа предоставляет инструменты, но не гарантирует конкретных финансовых результатов от деятельности ИИ-персонажей."},{heading:"3. Регистрация и аккаунт",list:["Вход на Платформу осуществляется через Google OAuth. Мы не создаём отдельные логины и пароли.","Вы несёте ответственность за безопасность вашего аккаунта Google.","Один Google-аккаунт соответствует одному рабочему пространству на Платформе.","Вы обязуетесь предоставлять достоверную информацию."]},{heading:"4. Тарифные планы и оплата",paragraphs:["Платформа предлагает несколько тарифных планов: Free, Pro и Business. Оплата осуществляется через платёжную систему Stripe."],list:["Подписка продлевается автоматически в конце каждого периода.","Вы можете отменить подписку в любое время. Доступ сохраняется до конца оплаченного периода.","Возврат средств осуществляется в соответствии с применимым законодательством.","Мы оставляем за собой право изменять цены с предварительным уведомлением за 30 дней."],afterList:"<strong>Важно:</strong> оплата через Stripe — это оплата за пользование Платформой. Это не относится к монетизации вашей аудитории через YouTube, Patreon и другие каналы."},{heading:"5. Интеграции с третьими сервисами",sub:[{subHeading:"5.1 YouTube (Google API)",paragraphs:['Подключение YouTube канала осуществляется через Google OAuth с запросом отдельных разрешений (scopes). Вы можете отозвать доступ в любое время через страницу <a href="https://myaccount.google.com/permissions" target="_blank" rel="noopener noreferrer" class="text-primary hover:underline">разрешений вашего аккаунта Google</a>.','Использование YouTube API подчиняется <a href="https://www.youtube.com/t/terms" target="_blank" rel="noopener noreferrer" class="text-primary hover:underline">Условиям использования YouTube</a> и <a href="https://policies.google.com/privacy" target="_blank" rel="noopener noreferrer" class="text-primary hover:underline">Политике конфиденциальности Google</a>.','Использование и передача информации, полученной от Google API, в SmartBlogAI осуществляется в соответствии с <a href="https://developers.google.com/terms/api-services-user-data-policy" target="_blank" rel="noopener noreferrer" class="text-primary hover:underline">Политикой пользовательских данных сервисов Google API</a>, включая требования <a href="https://developers.google.com/terms/api-services-user-data-policy#additional_requirements_for_specific_api_scopes" target="_blank" rel="noopener noreferrer" class="text-primary hover:underline">ограниченного использования (Limited Use)</a>.',"Мы собираем только те данные YouTube, которые необходимы для работы функций Платформы: метаданные канала (название, миниатюра, количество подписчиков), управление трансляциями/потоками и взаимодействие с чатом трансляций. Эти данные используются исключительно для обеспечения функций Платформы, которые вы активировали, и не используются для рекламы, Ð
1033½Ðµ продаются третьим лицам и не используются для оценки кредитоспособности.",'Вы можете запросить удаление всех данных YouTube, хранящихся на Платформе, в любое время, отключив интеграцию YouTube в Настройках или связавшись с нами по адресу <a href="mailto:[email protected]" class="text-primary hover:underline">[email protected]</a>.']},{subHeading:"5.2 Patreon",paragraphs:["Patreon подключается как дополнительный инструмент монетизации аудитории. Платформа не является посредником в финансовых отношениях между вами и вашими подписчиками на Patreon."]},{subHeading:"5.3 Stripe",paragraphs:["Stripe используется исключительно для обработки оплаты за подписку на Платформу. Мы не храним данные банковских карт."]}]},{heading:"6. Контент и интеллектуальная собственность",list:["Контент, созданный с помощью вашего ИИ-персонажа, принадлежит вам.","Вы несёте ответственность за соответствие контента законодательству и правилам платформ, на которых он публикуется.","Мы не претендуем на права на ваш контент.","Технология, дизайн и код Платформы являются нашей интеллектуальной собственностью."]},{heading:"7. Ограничения использования",paragraphs:["Вы обязуетесь не использовать Платформу для:"],list:["создания контента, нарушающего законодательство;","распространения ненависти, дискриминации, насилия;","обмана или введения аудитории в заблуждение;","спама, фишинга и мошенничества;","нарушения прав третьих лиц;","попыток несанкционированного доступа к данным других пользователей;","реверс-инжиниринга или копирования Платформы."]},{heading:"8. Ограничение ответственности",list:["Платформа предоставляется «как есть» (as is).","Мы не гарантируем бесперебойную работу и отсутствие ошибок.","Мы не несём ответственности за действия третьих сервисов (YouTube, Patreon, Stripe).","Мы не несём ответственности за финансовые результаты вашей деятельности как создателя контента.","Максимальная ответственность Платформы ограничивается суммой, уплаченной вами за последние 12 месяцев."]},{heading:"9. Прекращение использования",list:["Вы можете прекратить использование Платформы в любое время, удалив аккаунт в настройках.","Мы оставляем за собой право приостановить или заблокировать аккаунт при нарушении Условий.",'При удалении аккаунта ваши данные удаляются в соответствии с <a href="/privacy" class="text-primary hover:underline">Политикой конфиденциальности</a>.']},{heading:"10. Изменения Условий",paragraphs:["Мы оставляем за собой право изменять настоящие Условия. Актуальная версия всегда доступна на этой странице. О существенных изменениях мы уведомим вас заблаговременно."]},{heading:"11. Применимое право",paragraphs:["Настоящие Условия регулируются и толкуются в соответствии с применимым законодательством. Споры разрешаются путём переговоров, а при невозможности — в компетентном суде."]},{heading:"12. Контакты",paragraphs:['По вопросам, связанным с Условиями использования: <a href="mailto:[email protected]" class="text-primary hover:underline">[email protected]</a>']}],Bve={title:zve,effectiveDate:Fve,sections:Uve},Vve="Terms of Service",qve="Effective date: March 30, 2026",Hve=[{heading:"1. Subject of Agreement",paragraphs:['These Terms of Service (hereinafter — "Terms") govern the relationship between the SmartBlogAI platform (hereinafter — "Platform", "we") and an individual or legal entity (hereinafter — "User", "you") using the Platform to create and manage AI personas and related content.',"By registering on the Platform, you confirm that you have read these Terms and accept them in full."]},{heading:"2. Service Description",paragraphs:["SmartBlogAI is a platform for creating and managing AI personas that can:"],list:["create text scripts for videos and Shorts;","run live streams on YouTube;","answer audience questions in real time;","conduct voice consultations;","help monetize your audience through Patreon and other channels."],afterList:"The Platform provides tools but does not guarantee specific financial results from AI persona activities."},{heading:"3. Registration and Account",list:["Login is via Google OAuth. We do not create separate logins and passwords.","You are responsible for the security of your Google account.","One Google account corresponds to one workspace on the Platform.","You agree to provide accurate information."]},{heading:"4. Pricing Plans and Payment",paragraphs:["The Platform offers several pricing plans: Free, Pro, and Business. Payment is processed via Stripe."],list:["Subscriptions auto-renew at the end of each period.","You can cancel your subscription at any time. Access remains until the end of the paid period.","Refunds are handled in accordance with applicable law.","We reserve the right to change prices with 30 days' notice."],afterList:"<strong>Important:</strong> Stripe payments are for Platform usage. This is separate from monetizing your audience via YouTube, Patreon, and other channels."},{heading:"5. Third-Party Integrations",sub:[{subHeading:"5.1 YouTube (Google API)",paragraphs:['YouTube channel connection is via Google OAuth with separate scope requests. You can revoke access at any time via your <a href="https://myaccount.google.com/permissions" target="_blank" rel="noopener noreferrer" class="text-primary hover:underline">Google Account permissions</a> page.','Use of the YouTube API is subject to the <a href="https://www.youtube.com/t/terms" target="_blank" rel="noopener noreferrer" class="text-primary hover:underline">YouTube Terms of Service</a> and <a href="https://policies.google.com/privacy" target="_blank" rel="noopener noreferrer" class="text-primary hover:underline">Google Privacy Policy</a>.',`SmartBlogAI's use and transfer of information received from Google APIs to any other app will adhere to the <a href="https://developers.google.com/terms/api-services-user-data-policy" target="_blank" rel="noopener noreferrer" class="text-primary hover:underline">
1033Google API Services User Data Policy</a>, including the <a href="https://developers.google.com/terms/api-services-user-data-policy#additional_requirements_for_specific_api_scopes" target="_blank" rel="noopener noreferrer" class="text-primary hover:underline">Limited Use requirements</a>.`,"We collect only the YouTube data necessary to provide Platform functionality: channel metadata (name, thumbnail, subscriber count), broadcast/stream management, and live chat interactions. This data is used solely to operate Platform features you have enabled and is not used for advertising, sold to third parties, or used to determine creditworthiness.",'You may request deletion of all YouTube-related data stored by the Platform at any time by disconnecting your YouTube integration in Settings or by contacting us at <a href="mailto:[email protected]" class="text-primary hover:underline">[email protected]</a>.']},{subHeading:"5.2 Patreon",paragraphs:["Patreon is connected as an additional audience monetization tool. The Platform is not an intermediary in financial relationships between you and your Patreon subscribers."]},{subHeading:"5.3 Stripe",paragraphs:["Stripe is used exclusively for processing Platform subscription payments. We do not store bank card data."]}]},{heading:"6. Content and Intellectual Property",list:["Content created with your AI persona belongs to you.","You are responsible for content compliance with laws and platform rules where it is published.","We do not claim rights to your content.","The Platform's technology, design, and code are our intellectual property."]},{heading:"7. Usage Restrictions",paragraphs:["You agree not to use the Platform for:"],list:["creating content that violates the law;","spreading hate, discrimination, or violence;","deceiving or misleading the audience;","spam, phishing, and fraud;","violating third-party rights;","unauthorized access attempts to other users' data;","reverse-engineering or copying the Platform."]},{heading:"8. Limitation of Liability",list:['The Platform is provided "as is".',"We do not guarantee uninterrupted operation or the absence of errors.","We are not responsible for the actions of third-party services (YouTube, Patreon, Stripe).","We are not responsible for the financial results of your activity as a content creator.","Maximum Platform liability is limited to the amount you paid in the last 12 months."]},{heading:"9. Termination",list:["You can stop using the Platform at any time by deleting your account in settings.","We reserve the right to suspend or block an account for Terms violations.",'Upon account deletion, your data is removed in accordance with the <a href="/privacy" class="text-primary hover:underline">Privacy Policy</a>.']},{heading:"10. Changes to Terms",paragraphs:["We reserve the right to modify these Terms. The current version is always available on this page. We will notify you of significant changes in advance."]},{heading:"11. Applicable Law",paragraphs:["These Terms are governed and interpreted in accordance with applicable law. Disputes are resolved through negotiation, and if impossible — in a competent court."]},{heading:"12. Contact",paragraphs:['For questions regarding the Terms of Service: <a href="mailto:[email protected]" class="text-primary hover:underline">[email protected]</a>']}],Wve={title:Vve,effectiveDate:qve,sections:Hve},Gve="Публичная оферта",Yve="Дата вступления в силу: 30 марта 2026 г.",Kve=[{heading:"1. Общие положения",paragraphs:["Настоящий документ является официальным предложением (публичной офертой) платформы SmartBlogAI (далее — «Исполнитель») заключить договор на оказание услуг по предоставлению доступа к Платформе для создания и управления ИИ-персонажами.","Акцептом (принятием) настоящей Оферты является регистрация на Платформе через Google OAuth и/или оплата любого тарифного плана."]},{heading:"2. Предмет Оферты",paragraphs:["Исполнитель предоставляет Заказ
1033чику (Пользователю) доступ к платформе SmartBlogAI для:"],list:["создания и настройки ИИ-персонажей (блогеров, ведущих, консультантов, преподавателей);","генерации контента (скриптов, Shorts);","проведения live-эфиров на YouTube через ИИ-ведущего;","обработки live-чата и генерации AI-ответов;","перепрофилирования контента (из live в Shorts, нарезки, тизеры);","интеграции с YouTube и Patreon для управления каналом и монетизации аудитории;","аналитики и управления контентным конвейером."]},{heading:"3. Порядок оказания услуг",list:["Доступ к Платформе предоставляется на условиях выбранного тарифного плана.","Функциональность зависит от уровня подписки (Free, Pro, Business).","Исполнитель вправе вносить изменения в функциональность Платформы с предварительным уведомлением."]},{heading:"4. Стоимость и порядок оплаты",list:['Актуальные цены указаны на странице <a href="/pricing" class="text-primary hover:underline">тарифов</a>.',"Оплата производится через Stripe в российских рублях или иной валюте, доступной на момент оплаты.","Подписка продлевается автоматически. Отмена возможна в любое время через раздел «Биллинг».","Бесплатный тариф (Free) доступен без оплаты с ограниченной функциональностью."]},{heading:"5. Права и обязанности Исполнителя",paragraphs:["Исполнитель обязуется:"],list:["обеспечивать работоспособность Платформы в пределах разумных технических возможностей;","хранить данные Заказчика в соответствии с Политикой конфиденциальности;","уведомлять о существенных изменениях условий не менее чем за 14 дней;","не передавать персональные данные третьим лицам без согласия Заказчика, кроме случаев, предусмотренных Политикой конфиденциальности."],afterList:"Исполнитель вправе:",list2:["приостановить доступ при нарушении Заказчиком условий использования;","изменять тарифы с предварительным уведомлением;","проводить технические работы с кратковременным ограничением доступа."]},{heading:"6. Права и обязанности Заказчика",paragraphs:["Заказчик обязуется:"],list:["использовать Платформу в соответствии с Условиями использования;","не создавать контент, нарушающий законодательство или права третьих лиц;","обеспечивать безопасность своего аккаунта Google;","своевременно оплачивать выбранный тариф."],afterList:"Заказчик вправе:",list2:["использовать все функции Платформы в рамках выбранного тарифа;","отменить подписку в любое время;","удалить аккаунт и все связанные данные;","обращаться в поддержку по вопросам работы Платформы."]},{heading:"7. Интеллектуальная собственность",list:["Контент, созданный Заказ
1033чиком с помощью ИИ-персонажей, является собственностью Заказчика.","Платформа, её код, дизайн, алгоритмы и технологии являются собственностью Исполнителя.","Исполнитель не приобретает прав на контент Заказчика."]},{heading:"8. Ограничение ответственности",list:["Платформа предоставляется на условиях «как есть» (as is).","Исполнитель не гарантирует конкретных финансовых результатов от использования Платформы.","Исполнитель не несёт ответственности за сбои в работе YouTube, Patreon, Stripe и других внешних сервисов.","Совокупная ответственность Исполнителя ограничивается суммой, уплаченной Заказчиком за последние 12 месяцев."]},{heading:"9. Возврат средств",list:["Возврат средств за неиспользованный период подписки возможен в течение 14 дней с момента оплаты.","После 14 дней возврат не производится, но подписка может быть отменена с сохранением доступа до конца оплаченного периода.",'Запрос на возврат отправляется на <a href="mailto:[email protected]" class="text-primary hover:underline">[email protected]</a>.']},{heading:"10. Срок действия и расторжение",list:["Оферта действует с момента акцепта и до момента удаления аккаунта или расторжения Исполнителем.","Заказчик может расторгнуть договор в одностороннем порядке, удалив аккаунт.","Исполнитель может расторгнуть договор при грубом нарушении Условий с предупреждением за 7 дней."]},{heading:"11. Заключительные положения",list:["Настоящая Оферта регулируется применимым законодательством.","Споры решаются путём переговоров, а при невозможности — в компетентном суде.","Недействительность одного из положений не влечёт недействительность Оферты в целом."]},{heading:"12. Реквизиты и контакты",paragraphs:['SmartBlogAI<br />Email: <a href="mailto:[email protected]" class="text-primary hover:underline">[email protected]</a><br />Сайт: <a href="https://smartblog.lovable.app" class="text-primary hover:underline">smartblog.lovable.app</a>']}],Qve={title:Gve,effectiveDate:Yve,sections:Kve},Jve="Public Offer",Zve="Effective date: March 30, 2026",Xve=[{heading:"1. General Provisions",paragraphs:['This document is an official proposal (public offer) of the SmartBlogAI platform (hereinafter — "Provider") to enter into a service agreement for providing access to the Platform for creating and managing AI personas.',"Acceptance of this Offer is constituted by registration on the Platform via Google OAuth and/or payment for any pricing plan."]},{heading:"2. Subject of the Offer",paragraphs:["The Provider grants the Client (User) access to the SmartBlogAI platform for:"],list:["creating and configuring AI personas (bloggers, hosts, consultants, educators);","content generation (scripts, Shorts);","running live streams on YouTube via an AI host;","processing live chat and generating AI responses;","content repurposing (from live to Shorts, clips, teasers);","integration with YouTube and Patreon for channel management and audience monetization;","analytics and content pipeline management."]},{heading:"3. Service Delivery",list:["Platform access is provided based on the selected pricing plan.","Functionality depends on the subscription level (Free, Pro, Business).","The Provider may modify Platform functionality with prior notice."]},{heading:"4. Pricing and Payment",list:['Current prices are listed on the <a href="/pricing" class="text-primary hover:underline">pricing page</a>.',"Payment is processed via Stripe in the available currency at the time of payment.","Subscriptions auto-renew. Cancellation is available at any time via the Billing section.","The Free plan is available without payment with limited functionality."]},{heading:"5. Provider Rights and Obligations",paragraphs:["The Provider undertakes to:"],list:["ensure Platform operability within reasonable technical capabilities;","store Client data in accordance with the Privacy Policy;","notify of significant condition changes at least 14 days in advance;","not share personal data with third parties without Client consent, except as provided in the Privacy Policy."],afterList:"The Provider is entitled to:",list2:["suspend access if the Client violates the terms of use;","change pricing with prior notice;","perform maintenance with brief access restrictions."]},{heading:"6. Client Rights and Obligations",paragraphs:["The Client undertakes to:"],list:["use the Platform in accordance with the Terms of Service;","not create content that violates the law or third-party rights;","maintain the security of their Google account;","pay for the selected plan on time."],afterList:"The Client is entitled to:",list2:["use all Platform features within the selected plan;","cancel the subscription at any time;","delete the account and all associated data;","contact support regarding Platform issues."]},{heading:"7. Intellectual Property",list:["Content created by the Client using AI personas is the Client's property.","The Platform, its code, design, algorithms, and technology are the Provider's property.","The Provider does not acquire rights to the Client's content."]},{heading:"8. Limitation of Liability",list:['The Platform is provided "as is".',"The Provider does not guarantee specific financial results from Platform use.","The Provider is not responsible for outages of YouTube, Patreon, Stripe, and other external services.","The Provider's total liability is limited to the amount paid by the Client in the last 12 months."]},{heading:"9. Refunds",list:["Refunds for unused subscription periods are available within 14 days of payment.","After 14 days, no refund is issued, but the subscription can be canceled with access retained until the end of the paid period.",'Refund requests are sent to <a href="mailto:[email protected]" class="text-primary hover:underline">[email protected]</a>.']},{heading:"10. Term and Termination",list:["The Offer is effective from acceptance until account deleti
1033on or termination by the Provider.","The Client may terminate the agreement unilaterally by deleting their account.","The Provider may terminate the agreement for gross Terms violations with 7 days' notice."]},{heading:"11. Final Provisions",list:["This Offer is governed by applicable law.","Disputes are resolved through negotiation, and if impossible — in a competent court.","Invalidity of any provision does not invalidate the Offer as a whole."]},{heading:"12. Details and Contact",paragraphs:['SmartBlogAI<br />Email: <a href="mailto:[email protected]" class="text-primary hover:underline">[email protected]</a><br />Website: <a href="https://smartblog.lovable.app" class="text-primary hover:underline">smartblog.lovable.app</a>']}],eye={title:Jve,effectiveDate:Zve,sections:Xve},tye="Политика использования файлов cookie",sye="Дата вступления в силу: 30 марта 2026 г.",nye=[{heading:"1. Что такое cookies",paragraphs:["Cookies (файлы cookie) — это небольшие текстовые файлы, которые сохраняются на вашем устройстве при посещении веб-сайта. Они помогают сайту запоминать ваши настройки и обеспечивать корректную работу."]},{heading:"2. Какие cookies мы используем",sub:[{subHeading:"2.1 Строго необходимые",paragraphs:["Эти cookies необходимы для работы Платформы. Без них вход в аккаунт, навигация и основные функции невозможны."],list:["<strong>Сессия аутентификации</strong> — поддержание входа в аккаунт через Google OAuth.","<strong>CSRF-токен</strong> — защита от межсайтовых подделок запросов.","<strong>Согласие на cookies</strong> — запоминание вашего выбора в баннере cookie."]},{subHeading:"2.2 Функциональные",paragraphs:["Эти cookies запоминают ваши предпочтения для улучшения пользовательского опыта."],list:["<strong>Язык интерфейса</strong> — сохранение выбранного языка.","<strong>Настройки отображения</strong> — тема, состояние сайдбара и другие UI-предпочтения."]},{subHeading:"2.3 Аналитические",paragraphs:["Мы можем использовать аналитические cookies для понимания того, как пользователи взаимодействуют с Платформой, чтобы улучшать продукт. Эти данные анонимизированы."]}]},{heading:"3. Cookies третьих сторон",paragraphs:["Мы не используем рекламные или трекинговые cookies третьих сторон.","Cookies третьих сторон могут устанавливаться только следующими сервисами:"],list:["<strong>Google (OAuth)</strong> — для процесса аутентификации.","<strong>Stripe</strong> — для обработки платежей при оформлении подписки."]},{heading:"4. Управление cookies",paragraphs:["Вы можете управлять cookies следующими способами:"],list:["<strong>Баннер согласия</strong> — при первом посещении вы можете принять или отклонить необязательные cookies.","<strong>Настройки браузера</strong> — вы можете удалить или заблокировать cookies в настройках вашего браузера."],afterList:"Обратите внимание: отключение строго необходимых cookies может привести к некорректной работе Платформы."},{heading:"5. Срок хранения",list:["<strong>Сессионные cookies</strong> — удаляются при закрытии браузера.","<strong>Постоянные cookies</strong> — хранятся до 12 месяцев или до момента их удаления вами."]},{heading:"6. Изменения политики",paragraphs:["Мы оставляем за собой право обновлять данную Политику. Актуальная версия всегда доступна на этой странице."]},{heading:"7. Контакты",paragraphs:['По вопросам, связанным с cookies: <a href="mailto:[email protected]" class="text-primary hover:underline">[email protected]</a>']}],rye={title:tye,effectiveDate:sye,sections:nye},aye="Cookie Policy",iye="Effective date: March 30, 2026",oye=[{heading:"1. What Are Cookies",paragraphs:["Cookies are small text files stored on your device when you visit a website. They help the site remember your preferences and ensure proper operation."]},{heading:"2. Cookies We Use",sub:[{subHeading:"2.1 Strictly Necessary",paragraphs:["These cookies are essential for Platform operation. Without them, login, navigation, and core features are impossible."],list:["<strong>Authentication session</strong> — maintaining login via Google OAuth.","<strong>CSRF token</strong> — protection against cross-site request forgery.","<strong>
1033Cookie consent</strong> — remembering your choice in the cookie banner."]},{subHeading:"2.2 Functional",paragraphs:["These cookies remember your preferences to improve the user experience."],list:["<strong>Interface language</strong> — saving the selected language.","<strong>Display settings</strong> — theme, sidebar state, and other UI preferences."]},{subHeading:"2.3 Analytics",paragraphs:["We may use analytics cookies to understand how users interact with the Platform in order to improve the product. This data is anonymized."]}]},{heading:"3. Third-Party Cookies",paragraphs:["We do not use advertising or tracking cookies from third parties.","Third-party cookies may only be set by the following services:"],list:["<strong>Google (OAuth)</strong> — for the authentication process.","<strong>Stripe</strong> — for payment processing during subscription checkout."]},{heading:"4. Managing Cookies",paragraphs:["You can manage cookies in the following ways:"],list:["<strong>Consent banner</strong> — on your first visit you can accept or decline optional cookies.","<strong>Browser settings</strong> — you can delete or block cookies in your browser settings."],afterList:"Please note: disabling strictly necessary cookies may cause the Platform to malfunction."},{heading:"5. Retention Period",list:["<strong>Session cookies</strong> — deleted when you close the browser.","<strong>Persistent cookies</strong> — stored for up to 12 months or until you delete them."]},{heading:"6. Policy Changes",paragraphs:["We reserve the right to update this Policy. The current version is always available on this page."]},{heading:"7. Contact",paragraphs:['For cookie-related questions: <a href="mailto:[email protected]" class="text-primary hover:underline">[email protected]</a>']}],lye={title:aye,effectiveDate:iye,sections:oye},cye="Откройте следующий уровень",dye="Перейдите на более сильный тариф, чтобы расширить возможности вашего ИИ-блогера, ИИ-ведущего или ИИ-консультанта.",uye="Ежемесячно",hye="Ежегодно",mye="−20%",pye="Лучший выбор",fye="Текущий",gye="/мес",xye="Текущий план",vye="Бесплатный",yye="Перейти на Pro",bye="Выбрать",wye="Сравнить тарифы",jye="Позже",_ye={onePersona:"1 ИИ-персонаж",multiplePersonas:"Несколько ИИ-персонажей",extendedShorts:"Расширенная генерация Shorts",liveCenter:"Центр эфиров",monetization:"Центр монетизации",consultations:"Консультации",analytics:"Расширенная аналитика",teamwork:"Командная работа"},kye={title:cye,subtitle:dye,monthly:uye,yearly:hye,discount:mye,recommended:pye,currentBadge:fye,perMonth:gye,currentPlan:xye,freePlan:vye,upgradePro:yye,select:bye,comparePlans:wye,later:jye,features:_ye},Nye="Unlock the next level",Sye="Upgrade to a stronger plan to expand the capabilities of your AI blogger, host, or consultant.",Cye="Monthly",Tye="Yearly",Pye="−20%",Eye="Best choice",Aye="Current",Rye="/mo",$ye="Current plan",Lye="Free",Iye="Upgrade to Pro",Oye="Select",Dye="Compare plans",Mye="Later",zye={onePersona:"1 AI character",multiplePersonas:"Multiple AI characters",extendedShorts:"Extended Shorts generation",liveCenter:"Live center",monetization:"Monetization center",consultations:"Consultations",analytics:"Advanced analytics",teamwork:"Team collaboration"},Fye={title:Nye,subtitle:Sye,monthly:Cye,yearly:Tye,discount:Pye,recommended:Eye,currentBadge:Aye,perMonth:Rye,currentPlan:$ye,freePlan:Lye,upgradePro:Iye,select:Oye,comparePlans:Dye,later:Mye,features:zye},Uye=["dashboard","content-studio","live-center","persona","settings","billing","upgrade-modal","monetization","analytics","consultations","integrations","onboarding-app","operations","webinars","ads","topic-discovery","trends","news","admin"],Bye=["landing-hero","landing-whatIs","landing-forWhom","landing-capabilities","landing-onboarding","landing-repurpose","landing-roles","landing-liveConsult","landing-monetization","landing-whyBetter","landing-howToEarn","landing-ytp","landing-path","landing-adminPanel","landing-faq","landing-pricing","landing-cta","landing-v2-header","landing-v2-hero","landing-v2-types","landing-v2-capability","landing-v2-advantages","landing-v2-steps","landing-v2-pricing","landing-v2-platforms","landing-v2-slider","landing-v2-formats","landing-v2-plus","landing-v2-faq","landing-v2-personage","landing-v2-footer"],Vye=["login","how-it-works","use-cases","privacy","terms","offer","cookies"];xs.use(IT).use(gM).init({resources:{ru:{common:jV,"landing-hero":eq,"landing-whatIs":yq,"landing-forWhom":Pq,"landing-capabilities":Fq,"landing-onboarding":Zq,"landing-repurpose":c9,"landing-roles":b9,"landing-liveConsult":A9,"landing-monetization":q9,"landing-whyBetter":r7,"landing-howToEarn":y7,"landing-ytp":D7,"landing-path":eH,"landing-adminPanel":hH,"landing-faq":wH,"landing-pricing":FH,"landing-cta":cW,"landing-v2-header":jW,"landing-v2-hero":RW,"landing-v2-types":BW,"landing-v2-capability":XW,"landing-v2-advantages":uG,"landing-v2-steps":jG,"landing-v2-pricing":OG,"landing-v2-platforms":QG,"landing-v2-slider":oY,"landing-v2-formats":yY,"landing-v2-plus":EY,"landing-v2-faq":FY,"landing-v2-personage":QY,"landing-v2-footer":aK,dashboard:GK,"content-studio":HQ,"live-center":CJ,persona:qZ,settings:YX,billing:cee,login:gxe,"how-it-works":lve,"use-cases":_ve,privacy:Lve,terms:Bve,offer:Qve,cookies:rye,"upgrade-modal":kye,monetization:Dee,analytics:Ete,consultations:tne,integrations:Are,"onboarding-app":Lae,operations:coe,webinars:bce,ads:Qde,"topic-discovery":Cue,trends:Lhe,news:Lpe,admin:oge},en:{common:UV,"landing-hero":mq,"landing-whatIs":Nq,"landing-forWhom":$q,"landing-capabilities":Gq,"landing-onboarding":n9,"landing-repurpose":f9,"landing-roles":N9,"landing-liveConsult":D9,"landing-monetization":J9,"landing-whyBetter":u7,"landing-howToEarn":C7,"landing-ytp":G7,"landing-path":oH,"landing-adminPanel":xH,"landing-faq":NH,"landing-pricing":tW,"landing-cta":xW,"landing-v2-header":CW,"landing-v2-hero":DW,"landing-v2-types":GW,"landing-v2-capability":aG,"landing-v2-advantages":xG,"landing-v2-steps":CG,"landing-v2-pricing":HG,"landing-v2-platforms":tY,"landing-v2-slider":mY,"landing-v2-formats":NY,"landing-v2-plus":IY,"landing-v2-faq":HY,"landing-v2-personage":tK,"landing-v2-footer":cK,dashboard:EQ,"content-studio":iJ,"live-center":YJ,persona:FX,settings:see,billing:gee,login:eve,"how-it-works":gve,"use-cases":Eve,privacy:Mve,terms:Wve,offer:eye,cookies:lye,"upgrade-modal":Fye,monetization:rte,analytics:sse,consultations:ere,integrations:lae,"onboarding-app":iie,operations:hle,webinars:Tde,ads:vue,"topic-discovery":Oue,trends:Rme,news:Ofe,admin:Rge}},fallbackLng:"en",defaultNS:"common",ns:["common",...Bye,...Uye,...Vye],interpolation:{escapeValue:!1},detection:{order:["localStorage","navigator"],caches:["localStorage"],lookupLocalStorage:"i18nextLng"}});const qye=["OUTCOME_ENGAGEMENT","OUTCOME_TRAFFIC","OUTCOME_AWARENESS"],W1=()=>({name:"",objective:"OUTCOME_TRAFFIC",budgetUsd:"5",message:"",link:"",countries:"US",ageMin:18,ageMax:65});function Qf(e){const t=e.match(/[\d.]+/);return t?t[0]:""}function nv({open:e,onOpenChange:t,onCreate:s,editing:r,onUpdate:a,prefill:i}){const{t:o}
1033=Oe("ads"),[l,c]=h.useState(!1),[d,u]=h.useState(W1()),m=pa(),p=!!r,f=!p&&!!(i!=null&&i.boostPostId||i!=null&&i.boostIgMediaId),g=(i==null?void 0:i.boostPlatform)??(i!=null&&i.boostPostId?"facebook":i!=null&&i.boostIgMediaId?"instagram":void 0);h.useEffect(()=>{var j;if(e)if(r){const _=r.targeting||{},N=r.creative||{};u({name:r.name||"",objective:r.objective||"OUTCOME_TRAFFIC",budgetUsd:r.daily_budget_cents?(r.daily_budget_cents/100).toFixed(2):"5",message:(N==null?void 0:N.message)||"",link:(N==null?void 0:N.link)||"",countries:Array.isArray((j=_==null?void 0:_.geo_locations)==null?void 0:j.countries)?_.geo_locations.countries.join(", "):"US",ageMin:typeof(_==null?void 0:_.age_min)=="number"?_.age_min:18,ageMax:typeof(_==null?void 0:_.age_max)=="number"?_.age_max:65})}else u({...W1(),name:(i==null?void 0:i.name)??"",objective:(i==null?void 0:i.objective)??"OUTCOME_TRAFFIC",message:(i==null?void 0:i.message)??"",link:(i==null?void 0:i.link)??""})},[e,i,r]);const x=()=>({surface:"Meta (Facebook/Instagram) ads campaign",name:d.name,objective:d.objective,message:d.message,link:d.link,countries:d.countries,age_min:String(d.ageMin),age_max:String(d.ageMax),daily_budget_usd:d.budgetUsd}),b=async(j,_,N)=>m.fill({fieldName:j,fieldLabel:_,currentValue:N,pageContext:x(),language:xs.language||"ru"}),v=async j=>{j.preventDefault(),c(!0);try{const _=d.countries.split(",").map(k=>k.trim().toUpperCase()).filter(Boolean),N=Math.max(100,Math.round(parseFloat(d.budgetUsd||"0")*100));p&&r&&a?await a(r.id,{name:d.name.trim(),dailyBudgetCents:N,countries:_,ageMin:d.ageMin,ageMax:d.ageMax,message:d.message.trim()||void 0}):s&&await s({name:d.name.trim(),objective:d.objective,dailyBudgetCents:N,message:f?void 0:d.message.trim(),countries:_,ageMin:d.ageMin,ageMax:d.ageMax,liveClipId:i==null?void 0:i.liveClipId,boostPostId:i==null?void 0:i.boostPostId,boostIgMediaId:i==null?void 0:i.boostIgMediaId,boostPlatform:g})}finally{c(!1)}},y=d.message.length,w=y>125;return n.jsx(ns,{open:e,onOpenChange:t,children:n.jsxs(Zt,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[n.jsxs(Xt,{children:[n.jsx(es,{children:p?o("modal.editTitle",{defaultValue:"Редактирование кампании"}):o("modal.title")}),n.jsxs(us,{children:[o("modal.subtitle"),(i==null?void 0:i.pageName)&&n.jsxs(n.Fragment,{children:[" · ",n.jsx("span",{className:"text-foreground font-medium",children:i.pageName})]})]})]}),n.jsxs("div",{className:"grid md:grid-cols-[1fr_240px] gap-5",children:[n.jsxs("form",{onSubmit:v,className:"space-y-4",children:[n.jsxs("div",{className:"space-y-1.5",children:[n.jsx(Jt,{children:o("modal.name")}),n.jsx(Ot,{required:!0,value:d.name,onChange:j=>u({...d,name:j.target.value}),placeholder:o("modal.namePh"),aiLoading:m.isLoading("m_name"),onAiFill:async()=>{const j=await b("m_name","Короткое название кампании Meta (Facebook/Instagram)",d.name);j&&u(_=>({..._,name:j}))}})]}),n.jsxs("div",{className:"space-y-1.5",children:[n.jsx(Jt,{children:o("modal.objective")}),n.jsx("div",{className:"grid grid-cols-3 gap-2",children:qye.map(j=>n.jsx("button",{type:"button",disabled:p,onClick:()=>u({...d,objective:j}),className:`text-xs px-3 py-2 rounded-lg border transition-colors ${d.objective===j?"bg-primary/10 border-primary text-primary font-medium":"border-border/50 text-muted-foreground hover:border-border"} ${p?"opacity-60 cursor-not-allowed":""}`,children:o(`objective.${j}`)},j))})]}),n.jsxs("div",{className:"space-y-1.5",children:[n.jsx(Jt,{children:o("modal.budget")}),n.jsx(Ot,{required:!0,type:"number",min:"1",step:"0.5",value:d.budgetUsd,onChange:j=>u({...d,budgetUsd:j.target.value}),aiLoading:m.isLoading("m_budget"),onAiFill:async()=>{const j=await b("m_budget","Рекомендуемый дневной бюджет в USD (только число, например 5 или 15)",d.budgetUsd),_=Qf(j||"");_&&u(N=>({...N,budgetUsd:_}))}}),n.jsx("p",{className:"text-[11px] text-muted-foreground",children:o("modal.budgetHint")})]}),f?n.jsxs("div",{className:"rounded-lg border border-border/60 bg-muted/30 p-3 space-y-2",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:`text-[10px] font-semibold uppercase tracking-wide px-2 py-0.5 rounded ${g==="instagram"?"bg-pink-500/15 text-pink-600":"bg-blue-500/15 text-blue-600"}`,children:g==="instagram"?"Instagram":"Facebook"}),n.jsx("span",{className:"text-xs font-medium text-foreground",children:o("modal.boostAuto",{defaultValue:"Продвигаем уже опубликованный пост"})})]}),n.jsx("p",{className:"text-[11px] text-muted-foreground leading-snug",children:g==="instagram"?o("modal.boostHintIg",{defaultValue:"Реклама будет показана только в Instagram (Feed / Reels / Stories) как ваш существующий пост. Лайки и просмотры с органики усиливают рекламу."}):o("modal.boostHintFb",{defaultValue:"Реклама будет показана только в Facebook (Feed / Reels / Stories / In-Stream) как ваш существующий пост. Лайки и просмотры с органики усиливают рекламу."})}),(i==null?void 0:i.boostPostUrl)&&n.jsxs("a",{href:i.boostPostUrl,target:"_blank",rel:"noopener noreferrer",className:"text-[11px] text-primary inline-flex items-center gap-1 hover:underline",children:[n.jsx(Rs,{size:10})," ",o("modal.boostOpenPost",{defaultValue:"Открыть пост"})]})]}):n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"space-y-1.5",children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsx(Jt,{children:o("modal.message")}),n.jsxs("span",{className:`text-[10px] ${w?"text-amber-600":"text-muted-foreground"}`,children:[y,"/125"]})]}),n.jsx(os,{required:!p,rows:3,value:d.message,onChange:j=>u({...d,message:j.target.value}),placeholder:o("modal.messagePh"),aiLoading:m.isLoading("m_message"),onAiFill:async()=>
1033{const j=await b("m_message","Цепляющий рекламный текст для поста Meta (≤125 символов), естественный, без хэштегов и эмодзи в конце",d.message);j&&u(_=>({..._,message:j.slice(0,125)}))}})]}),n.jsx("p",{className:"text-[11px] text-muted-foreground",children:o("modal.linkAuto",{defaultValue:"Реклама автоматически ведёт на вашу Facebook-страницу — так аудитория остаётся в FB/Instagram и подписывается на ваш аккаунт."})})]}),n.jsxs("div",{className:"space-y-1.5",children:[n.jsx(Jt,{children:o("modal.countries")}),n.jsx(Ot,{value:d.countries,onChange:j=>u({...d,countries:j.target.value}),placeholder:o("modal.countriesPh"),aiLoading:m.isLoading("m_countries"),onAiFill:async()=>{const j=await b("m_countries","Список 2-5 стран таргета (двухбуквенные ISO коды через запятую, например: US, GB, DE)",d.countries);j&&u(_=>({..._,countries:j.replace(/[^A-Za-z,\s]/g,"").trim()}))}})]}),n.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[n.jsxs("div",{className:"space-y-1.5",children:[n.jsx(Jt,{children:o("modal.ageMin")}),n.jsx(Ot,{type:"number",min:"13",max:"65",value:d.ageMin,onChange:j=>u({...d,ageMin:parseInt(j.target.value)||18}),aiLoading:m.isLoading("m_age_min"),onAiFill:async()=>{const j=await b("m_age_min","Минимальный возраст целевой аудитории (число от 13 до 65). Верни только число.",String(d.ageMin)),_=parseInt(Qf(j||"")||"");_>=13&&_<=65&&u(N=>({...N,ageMin:_}))}})]}),n.jsxs("div",{className:"space-y-1.5",children:[n.jsx(Jt,{children:o("modal.ageMax")}),n.jsx(Ot,{type:"number",min:"13",max:"65",value:d.ageMax,onChange:j=>u({...d,ageMax:parseInt(j.target.value)||65}),aiLoading:m.isLoading("m_age_max"),onAiFill:async()=>{const j=await b("m_age_max","Максимальный возраст целевой аудитории (число от 13 до 65, больше или равно min). Верни только число.",String(d.ageMax)),_=parseInt(Qf(j||"")||"");_>=13&&_<=65&&u(N=>({...N,ageMax:_}))}})]})]}),n.jsxs(Hl,{children:[n.jsx(L,{type:"button",variant:"ghost",onClick:()=>t(!1),disabled:l,children:o("modal.cancel")}),n.jsxs(L,{type:"submit",variant:"hero",disabled:l,className:"gap-2",children:[l&&n.jsx(xe,{size:14,className:"animate-spin"}),l?o("modal.submitting"):p?o("modal.save",{defaultValue:"Сохранить"}):o("modal.submit")]})]})]}),n.jsxs("aside",{className:"space-y-2",children:[n.jsx(Jt,{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:o("modal.preview")}),n.jsxs("div",{className:"rounded-xl border border-border/60 bg-surface-elevated overflow-hidden text-xs",children:[n.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 border-b border-border/40",children:[n.jsx("div",{className:"w-7 h-7 rounded-full bg-blue-100 flex items-center justify-center text-blue-600 font-bold text-[10px]",children:((i==null?void 0:i.pageName)||"FB").slice(0,2).toUpperCase()}),n.jsxs("div",{className:"min-w-0",children:[n.jsx("p",{className:"text-[11px] font-semibold text-foreground truncate",children:(i==null?void 0:i.pageName)||"Your Page"}),n.jsx("p",{className:"text-[9px] text-muted-foreground",children:o("modal.sponsored")})]})]}),n.jsx("p",{className:"px-3 py-2 text-[11px] text-foreground whitespace-pre-wrap break-words leading-snug",children:d.message||o("modal.previewMessagePlaceholder")}),n.jsx("div",{className:"w-full aspect-video bg-muted/50 flex items-center justify-center text-[10px] text-muted-foreground",children:f?o("modal.previewBoostMedia",{defaultValue:"Видео из вашего поста"}):o("modal.previewNoImage")}),n.jsxs("div",{className:"px-3 py-2 border-t border-border/40 flex items-center justify-between gap-2",children:[n.jsx("p",{className:"text-[10px] text-muted-foreground truncate",children:d.link?(()=>{try{return new URL(d.link.startsWith("http")?d.link:`https://${d.link}`).host}catch{return d.link}})():"your-site.com"}),n.jsxs("button",{type:"button",className:"text-[10px] font-semibold text-primary inline-flex items-center gap-1 shrink-0",children:[o("modal.previewCta")," ",n.jsx(Rs,{size:9})]})]})]}
1033),n.jsx("p",{className:"text-[10px] text-muted-foreground/80 leading-relaxed",children:o("modal.previewHint")})]})]})]})})}function tb(){const{session:e,profile:t}=st(),s=t==null?void 0:t.workspace_id,[r,a]=h.useState("not_connected"),[i,o]=h.useState(null),[l,c]=h.useState([]),[d,u]=h.useState(!0),[m,p]=h.useState(null),f=h.useCallback(async()=>{if(!s){u(!1);return}try{const{data:v}=await I.from("google_ads_accounts").select("*").eq("workspace_id",s).maybeSingle();if(!v)a("not_connected"),o(null),c([]);else{o({googleUserId:v.google_user_id,googleEmail:v.google_email,customerId:v.customer_id,customerDescriptiveName:v.customer_descriptive_name,customerCurrencyCode:v.customer_currency_code,loginCustomerId:v.login_customer_id,tokenExpiresAt:v.token_expires_at}),c(v.available_customers||[]);const y=v.token_expires_at&&new Date(v.token_expires_at).getTime()-Date.now()<5*60*1e3;a(v.status||(y?"expired":"connected"))}}catch(v){console.error("Google Ads fetch failed",v)}finally{u(!1)}},[s]);h.useEffect(()=>{f()},[f]),h.useEffect(()=>{const v=new URL(window.location.href),y=v.searchParams.get("gads");if(!y)return;const w=v.searchParams.get("msg");v.searchParams.delete("gads"),v.searchParams.delete("msg"),window.history.replaceState({},"",v.pathname+(v.search?`?${v.searchParams}`:"")),y==="connected"?(a("connected"),p(null),f()):(a("error"),p(w||"Connection failed"))},[f]);const g=h.useCallback(async()=>{if(!(e!=null&&e.access_token))return;a("connecting"),p(null);const{data:v,error:y}=await I.functions.invoke("google-ads-auth-url",{headers:{Authorization:`Bearer ${e.access_token}`}});if(y||v!=null&&v.error){a("error"),p((v==null?void 0:v.error)||(y==null?void 0:y.message)||"Failed to get auth URL");return}v!=null&&v.url&&(window.location.href=v.url)},[e==null?void 0:e.access_token]),x=h.useCallback(async()=>{s&&(await I.from("google_ads_accounts").delete().eq("workspace_id",s),a("not_connected"),o(null),c([]))},[s]),b=h.useCallback(async v=>{if(!s||!(e!=null&&e.access_token))throw new Error("Not ready");const{data:y,error:w}=await I.functions.invoke("google-ads-update-selection",{body:{workspaceId:s,...v},headers:{Authorization:`Bearer ${e.access_token}`}});if(w||y!=null&&y.error)throw new Error((y==null?void 0:y.error)||(w==null?void 0:w.message)||"Failed");await f()},[s,e==null?void 0:e.access_token,f]);return{status:r,account:i,loading:d,error:m,availableCustomers:l,startConnect:g,disconnect:x,refresh:f,updateSelection:b}}function OT(){const{session:e,profile:t}=st(),s=t==null?void 0:t.workspace_id,[r,a]=h.useState([]),[i,o]=h.useState(!0),[l,c]=h.useState(null),d=h.useCallback(async()=>{if(!s){o(!1);return}const{data:f,error:g}=await I.from("google_ad_campaigns").select("*").eq("workspace_id",s).order("created_at",{ascending:!1});g?c(g.message):a(f||[]),o(!1)},[s]);h.useEffect(()=>{d()},[d]),h.useEffect(()=>{if(!s)return;const f=I.channel(`google_ad_campaigns:${s}:${Math.random().toString(36).slice(2)}`).on("postgres_changes",{event:"*",schema:"public",table:"google_ad_campaigns",filter:`workspace_id=eq.${s}`},()=>d()).subscribe();return()=>{I.removeChannel(f)}},[s,d]);const u=h.useCallback(async f=>{if(!s||!(e!=null&&e.access_token))throw new Error("Not ready");c(null);const{data:g,error:x}=await I.functions.invoke("google-ads-create-campaign",{body:{workspaceId:s,...f},headers:{Authorization:`Bearer ${e.access_token}`}});if(x||g!=null&&g.error){const b=(g==null?void 0:g.error)||(x==null?void 0:x.message)||"Failed";throw c(b),new Error(b)}return await d(),g},[s,e==null?void 0:e.access_token,d]),m=h.useCallback(async(f,g)=>{if(!(e!=null&&e.access_token))return;c(null);const{data:x,error:b}=await I.functions.invoke("google-ads-update-campaign-status",{body:{campaignId:f,action:g},headers:{Authorization:`Bearer ${e.access_token}`}});if(b||x!=null&&x.error){const v=(x==null?void 0:x.error)||(b==null?void 0:b.message)||"Failed";throw c(v),new Error(v)}await d()},[e==null?void 0:e.access_token,d]),p=h.useCallback(async(f,g)=>{if(!(e!=null&&e.access_token))throw new Error("Not ready");c(null);const{data:x,error:b}=await I.functions.invoke("google-ads-update-campaign",{body:{campaignId:f,...g},headers:{Authorization:`Bearer ${e.access_token}`}});if(b||x!=null&&x.error){const v=(x==null?void 0:x.error)||(b==null?void 0:b.message)||"Failed";throw c(v),new Error(v)}await d()},[e==null?void 0:e.access_token,d]);return{campaigns:r,loading:i,error:l,refresh:d,create:u,updateStatus:m,update:p}}function Hye(e){const{profile:t}=st(),s=t==null?void 0:t.workspace_id,[r,a]=h.useState({}),i=e.slice().sort().join(","),o=h.useCallback(async()=>
1033{if(!s||e.length===0){a({});return}const{data:l}=await I.from("google_ad_campaigns").select("*").eq("workspace_id",s).in("live_clip_id",e).order("created_at",{ascending:!1}),c={};for(const d of l||[])d.live_clip_id&&!c[d.live_clip_id]&&(c[d.live_clip_id]=d);a(c)},[s,i]);return h.useEffect(()=>{o()},[o]),h.useEffect(()=>{if(!s)return;const l=I.channel(`google_ad_campaigns_byclip:${s}:${Math.random().toString(36).slice(2)}`).on("postgres_changes",{event:"*",schema:"public",table:"google_ad_campaigns",filter:`workspace_id=eq.${s}`},()=>o()).subscribe();return()=>{I.removeChannel(l)}},[s,o]),{byClip:r,refresh:o}}const G1=()=>({name:"",youtubeVideoId:"",budgetUsd:"5",finalUrl:"",countries:"US",languages:"en"});function Wye(e){const t=e.trim();if(!t)return"";if(/^[A-Za-z0-9_-]{6,15}$/.test(t))return t;const s=t.match(/(?:v=|youtu\.be\/|shorts\/|embed\/)([A-Za-z0-9_-]{6,15})/);return(s==null?void 0:s[1])||t}function Gye(e){const t=e.match(/[\d.]+/);return t?t[0]:""}function rv({open:e,onOpenChange:t,onCreate:s,editing:r,onUpdate:a,prefill:i}){const{t:o}=Oe("ads"),[l,c]=h.useState(!1),[d,u]=h.useState(G1()),m=pa(),p=!!r;h.useEffect(()=>{var y,w;if(e)if(r){const j=((y=r.creative)==null?void 0:y.youtube_video_id)||"",_=((w=r.creative)==null?void 0:w.final_url)||(j?`https://www.youtube.com/watch?v=${j}`:""),N=r.targeting||{};u({name:r.name||"",youtubeVideoId:j,budgetUsd:r.daily_budget_micros?(r.daily_budget_micros/1e6).toFixed(2):"5",finalUrl:_,countries:Array.isArray(N==null?void 0:N.countries)?N.countries.join(", "):"US",languages:Array.isArray(N==null?void 0:N.languages)?
1033N.languages.join(", "):"en"})}else u({...G1(),name:(i==null?void 0:i.name)??"",youtubeVideoId:(i==null?void 0:i.youtubeVideoId)??"",finalUrl:(i==null?void 0:i.finalUrl)??(i!=null&&i.youtubeVideoId?`https://www.youtube.com/watch?v=${i.youtubeVideoId}`:"")})},[e,i,r]);const f=Wye(d.youtubeVideoId),g=f?`https://i.ytimg.com/vi/${f}/hqdefault.jpg`:"",x=()=>({surface:"Google Ads YouTube campaign",name:d.name,youtube_video_id:f,final_url:d.finalUrl,countries:d.countries,languages:d.languages,daily_budget_usd:d.budgetUsd}),b=async(y,w,j)=>m.fill({fieldName:y,fieldLabel:w,currentValue:j,pageContext:x(),language:xs.language||"ru"}),v=async y=>{y.preventDefault(),c(!0);try{const w=f?`https://www.youtube.com/watch?v=${f}`:d.finalUrl.trim(),j=d.countries.split(",").map(k=>k.trim().toUpperCase()).filter(Boolean),_=d.languages.split(",").map(k=>k.trim().toLowerCase()).filter(Boolean),N=Math.max(1e6,Math.round(parseFloat(d.budgetUsd||"0")*1e6));p&&r&&a?await a(r.id,{name:d.name.trim(),dailyBudgetMicros:N,finalUrl:w,countries:j,languages:_}):s&&await s({name:d.name.trim(),youtubeVideoId:f,dailyBudgetMicros:N,finalUrl:w,countries:j,languages:_,liveClipId:i==null?void 0:i.liveClipId,contentItemId:i==null?void 0:i.contentItemId})}finally{c(!1)}};return n.jsx(ns,{open:e,onOpenChange:t,children:n.jsxs(Zt,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[n.jsxs(Xt,{children:[n.jsxs(es,{className:"flex items-center gap-2",children:[n.jsx(Ls,{className:"text-red-600",size:18})," ",p?o("googleModal.editTitle",{defaultValue:"Редактирование YouTube-кампании"}):o("googleModal.title")]}),n.jsx(us,{children:o("googleModal.subtitle")})]}),n.jsxs("div",{className:"grid md:grid-cols-[1fr_240px] gap-5",children:[n.jsxs("form",{onSubmit:v,className:"space-y-4",children:[n.jsxs("div",{className:"space-y-1.5",children:[n.jsx(Jt,{children:o("modal.name")}),n.jsx(Ot,{required:!0,value:d.name,onChange:y=>u({...d,name:y.target.value}),placeholder:o("modal.namePh"),aiLoading:m.isLoading("g_name"),onAiFill:async()=>{const y=await b("g_name","Короткое название кампании YouTube (для отчётности)",d.name);y&&u(w=>({...w,name:y}))}})]}),n.jsxs("div",{className:"space-y-1.5",children:[n.jsx(Jt,{children:o("googleModal.video")}),n.jsx(Ot,{required:!0,value:d.youtubeVideoId,onChange:y=>u({...d,youtubeVideoId:y.target.value}),placeholder:"https://youtube.com/watch?v=…  или ID",hideAi:!0,disabled:p}),n.jsx("p",{className:"text-[11px] text-muted-foreground",children:o("googleModal.videoHint")})]}),n.jsxs("div",{className:"space-y-1.5",children:[n.jsx(Jt,{children:o("modal.budget")}),n.jsx(Ot,{required:!0,type:"number",min:"1",step:"0.5",value:d.budgetUsd,onChange:y=>u({...d,budgetUsd:y.target.value}),aiLoading:m.isLoading("g_budget"),onAiFill:async()=>{const y=await b("g_budget","Рекомендуемый дневной бюджет в USD (только число, например 5 или 15)",d.budgetUsd),w=Gye(y||"");w&&u(j=>({...j,budgetUsd:w}))}}),n.jsx("p",{className:"text-[11px] text-muted-foreground",children:o("googleModal.budgetHint")})]}),f&&n.jsx("p",{className:"text-[11px] text-muted-foreground",children:o("googleModal.finalUrlAuto",{defaultValue:"Реклама ведёт на это YouTube-видео — так зрители остаются на YouTube, что усиливает органический рост канала."})}),n.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[n.jsxs("div",{className:"space-y-1.5",children:[n.jsx(Jt,{children:o("modal.countries")}),n.jsx(Ot,{value:d.countries,onChange:y=>u({...d,countries:y.target.value}),placeholder:o("modal.countriesPh"),aiLoading:m.isLoading("g_countries"),onAiFill:async()=>{const y=await b("g_countries","Список 2-5 наиболее подходящих стран таргета (двухбуквенные ISO коды через запятую, например: US, GB, DE)",d.countries);y&&u(w=>({...w,countries:y.replace(/[^A-Za-z,\s]/g,"").trim()}))}})]}),n.jsxs("div",{className:"space-y-1.5",children:[n.jsx(Jt,{children:o("googleModal.languages")}),n.jsx(Ot,{value:d.languages,onChange:y=>u({...d,languages:y.target.value}),placeholder:"en, ru",aiLoading:m.isLoading("g_langs"),onAiFill:async()=>{const y=await b("g_langs","Список языков для таргета (двухбуквенные коды через запятую, например: en, ru, es). 1-3 кода.",d.languages);y&&u(w=>({...w,languages:y.replace(/[^A-Za-z,\s]/g,"").trim().toLowerCase()}))}})]})]}),n.jsxs(Hl,{children:[n.jsx(L,{type:"button",variant:"ghost",onClick:()=>t(!1),disabled:l,children:o("modal.cancel")}),n.jsxs(L,{type:"submit",variant:"hero",disabled:l||!f,className:"gap-2",children:[l&&n.jsx(xe,{size:14,className:"animate-spin"}),l?o("modal.submitting"):p?o("modal.save",{defaultValue:"Сохранить"}):o("modal.submit")]})]})]}),n.jsxs("aside",{className:"space-y-2",children:[n.jsx(Jt,{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:o("modal.preview")}),n.jsxs("div",{className:"rounded-xl border border-border/60 bg-surface-elevated overflow-hidden text-xs",children:[g?n.jsx("img",{src:g,alt:"",className:"w-full aspect-video object-cover bg-muted"}):n.jsx("div",{className:"w-full aspect-video bg-muted/50 flex items-center justify-center text-[10px] text-muted-foreground",children:o("googleModal.previewNoVideo")}),n.jsxs("div",{className:"px-3 py-2 border-t border-border/40",children:[n.jsx("p",{className:"text-[11px] font-semibold text-foreground truncate",children:d.name||o("googleModal.previewNamePlaceholder")}),n.jsxs("p",{className:"text-[10px] text-muted-foreground mt-0.5",children:["YouTube · ",o("modal.sponsored")]})]})]}
1033),n.jsx("p",{className:"text-[10px] text-muted-foreground/80 leading-relaxed",children:o("googleModal.previewHint")})]})]})]})})}const Yye=new Intl.NumberFormat(void 0,{notation:"compact",maximumFractionDigits:1}),Kye=5*60*1e3;function Qye(e){if(e==null)return"—";const t=Math.round(e),s=Math.floor(t/60),r=t%60;return s>0?`${s}:${r.toString().padStart(2,"0")}`:`${r}s`}function DT({liveSessionId:e}){const{t}=Oe("webinars"),{t:s}=Oe("ads"),{clips:r,loading:a,publish:i,unpublish:o,refreshAnalytics:l,getSignedUrl:c,analyzeTopClips:d}=EU(e),u=Tp(),{status:m,account:p}=eb(),{create:f}=ET(),{status:g,account:x}=tb(),{create:b}=OT(),v=r.map(K=>K.id),{byClip:y}=FB(v),{byClip:w}=Hye(v),[j,_]=h.useState(null),[N,k]=h.useState(null),[S,T]=h.useState(null),[C,B]=h.useState(null),[E,H]=h.useState({}),[z,ne]=h.useState(!1),[V,te]=h.useState({}),[R,F]=h.useState(null),[$,J]=h.useState(null),[Y,re]=h.useState(null),[G,O]=h.useState(null),{enabled:Z,hours:A,setEnabled:oe,setHours:ue}=Hy(),je=m==="connected"&&!!(p!=null&&p.adAccountId)&&!!(p!=null&&p.pageId),ae=g==="connected"&&!!(x!=null&&x.customerId),ie=async K=>{var M,se;const ye=(M=K.published_targets)==null?void 0:M.facebook,De=(se=K.published_targets)==null?void 0:se.instagram,pt=!!(ye!=null&&ye.ok&&(ye!=null&&ye.id)),kt=!!(De!=null&&De.ok&&(De!=null&&De.id)),X=pt?"facebook":kt?"instagram":null;_({name:K.title||`Webinar clip #${K.block_index+1}`,objective:"OUTCOME_ENGAGEMENT",liveClipId:K.id,pageName:(p==null?void 0:p.pageName)||void 0,boostPlatform:X||void 0,boostPostId:X==="facebook"?String(ye.id):void 0,boostIgMediaId:X==="instagram"?String(De.id):void 0,boostPostUrl:X==="facebook"?ye==null?void 0:ye.url:De==null?void 0:De.url})},we=K=>{const ye=K.trim();if(!ye)return"";if(/^[A-Za-z0-9_-]{6,15}$/.test(ye))return ye;const De=ye.match(/(?:v=|youtu\.be\/|shorts\/|embed\/)([A-Za-z0-9_-]{6,15})/);return(De==null?void 0:De[1])||""},Ae=K=>{var pt,kt;const ye=((kt=(pt=K.published_targets)==null?void 0:pt.youtube)==null?void 0:kt.url)||(K.published_url??null),De=we(ye||"");k({name:K.title||`Webinar clip #${K.block_index+1}`,youtubeVideoId:De,finalUrl:ye||(De?`https://www.youtube.com/watch?v=${De}`:""),liveClipId:K.id})},nt=h.useRef(0),Qe=h.useRef(!1);if(h.useEffect(()=>{!r.some(ye=>ye.status==="ready"&&(ye.spoken_text||"").trim().length>0&&!ye.title)||Qe.current||Date.now()-nt.current<2e4||(Qe.current=!0,nt.current=Date.now(),I.functions.invoke("generate-clip-metadata",{body:{live_session_id:e}}).catch(ye=>console.error("[clips] generate-clip-metadata failed",ye)).finally(()=>{Qe.current=!1}))},[r,e]),a&&r.length===0)return n.jsxs("div",{className:"mt-3 pt-3 border-t border-border/40 flex items-center gap-2 text-xs text-muted-foreground",children:[n.jsx(xe,{size:12,className:"animate-spin"}),t("clips.loading",{defaultValue:"Loading clips…"})]});if(r.length===0)return n.jsxs("div",{className:"mt-3 pt-3 border-t border-border/40 rounded-lg",children:[n.jsxs("div",{className:"flex items-center gap-2 text-xs font-semibold text-foreground mb-2",children:[n.jsx(pm,{size:12,className:"text-primary"}),t("clips.title",{defaultValue:"Auto-clips"}),n.jsx(fe,{variant:"outline",className:"text-[10px] px-1.5",children:"0"})]}),n.jsx("p",{className:"text-xs text-muted-foreground",children:t("clips.emptyDesc",{defaultValue:"No clips have been generated for this stream yet."})})]});const P=r.filter(K=>K.status==="ready").length,U=async(K,ye,De)=>{var X,M;if(K.status!=="ready"||Sm(K)||S===K.id)return;let pt=u.linkedPlatforms;if(u.status==="connected"&&pt.length===0&&(pt=await u.refreshStatus()),u.status!=="connected"||pt.length===0){Le.error(t("clips.noSocialLinked",{defaultValue:"Привяжите соцсети в разделе Интеграции → Социальный хаб"}));return}const kt=ye&&ye.length>0?Array.from(new Set(ye.map(js).filter(se=>pt.map(js).includes(se)))):$2(K,pt);if(kt.length===0){Le.info(t("clips.toastNothingToDo",{defaultValue:"Уже опубликовано во все подключённые сети"}));return}T(K.id);try{const se=De??(Z?{scheduleHoursOffset:A}:void 0),he=await i(K.id,kt,se),Ce=(he==null?void 0:he.results_now)||(he==null?void 0:he.results)||{},Ve=Object.entries(Ce).filter(([,ee])=>ee==null?void 0:ee.ok),me=Object.entries(Ce).filter(([,ee])=>!(ee!=null&&ee.ok));if(he!=null&&he.nothing_to_do){Le.info(t("clips.toastNothingToDo",{defaultValue:"Уже опубликовано во все подключённые сети"}));return}const Ge=Ve.map(([ee])=>Br[js(ee)]||ee),Ye=me.map(([ee])=>Br[js(ee)]||ee);if(Ve.length>0&&me.length===0)Le.success(t("clips.toastPublishedTo",{list:Ge.join(", "),defaultValue:`Опубликовано: ${Ge.join(", ")}`}));else if(Ve.length>0&&me.length>0){const ee=((X=me[0][1])==null?void 0:X.error)||"failed";
1033Le.warning(t("clips.toastPartial",{ok:Ge.join(", "),fail:Ye.join(", "),defaultValue:`Опубликовано: ${Ge.join(", ")}. Ошибки: ${Ye.join(", ")} — ${ee}`}))}else if(me.length>0){const ee=((M=me[0][1])==null?void 0:M.error)||"failed";Le.error(`${Ye.join(", ")}: ${ee}`)}}catch(se){Le.error((se==null?void 0:se.message)||t("clips.publishFailed",{defaultValue:"Publish failed"}))}finally{T(null)}},Q=async K=>{const ye=await c(K);if(!ye){Le.error(t("clips.previewUnavailable",{defaultValue:"Preview unavailable"}));return}B({clipId:K.id,url:ye})},ve=async K=>{const ye=await c(K);if(!ye){Le.error(t("clips.previewUnavailable",{defaultValue:"Preview unavailable"}));return}const De=`clip-${K.block_index+1}.mp4`;try{await Gy(ye,De,{mimeFallback:"video/mp4"})}catch{}},We=r.filter(K=>K.status==="ready"&&(K.spoken_text||"").trim().length>0),Ze=r.some(K=>K.highlight_analyzed_at),Je=async()=>{if(!(z||We.length===0)){ne(!0);try{await d(3),Le.success(t("clips.analyzeDone",{defaultValue:"Top-3 клипа определены"}))}catch(K){Le.error((K==null?void 0:K.message)||t("clips.analyzeFailed",{defaultValue:"Не удалось проанализировать"}))}finally{ne(!1)}}},xt=async()=>{if(!$)return;const K=`${$.clipId}:${$.platform}`;re(K);try{await o($.clipId,$.platform),Le.success(t("clips.unpublished",{name:$.label,defaultValue:`Удалено из ${$.label}`})),J(null)}catch(ye){Le.error((ye==null?void 0:ye.message)||t("clips.unpublishFailed",{defaultValue:"Не удалось удалить публикацию"}))}finally{re(null)}},Pt=async K=>{if(G!==K.id){O(K.id);try{const ye=await l(K.id);ye!=null&&ye.errors?Le.warning(t("clips.analyticsPartial",{defaultValue:"Часть статистики не удалось обновить"})):ye!=null&&ye.nothing_to_do?Le.info(t("clips.analyticsNothing",{defaultValue:"Нечего обновлять"})):Le.success(t("clips.analyticsUpdated",{defaultValue:"Статистика обновлена"}))}catch(ye){Le.error((ye==null?void 0:ye.message)||t("clips.analyticsFailed",{defaultValue:"Не удалось обновить статистику"}))}finally{O(null)}}};return n.jsxs("div",{className:"mt-3 pt-3 border-t border-border/40",children:[n.jsxs("div",{className:"flex items-center justify-between mb-2 gap-2 flex-wrap",children:[n.jsxs("div",{className:"flex items-center gap-2 text-xs font-semibold text-foreground",children:[n.jsx(pm,{size:12,className:"text-primary"}),t("clips.title",{defaultValue:"Auto-clips"}),n.jsx(fe,{variant:"outline",className:"text-[10px] px-1.5",children:r.length}),P>0&&n.jsxs("span",{className:"text-muted-foreground font-normal",children:["· ",t("clips.readyCount",{count:P,defaultValue:`${P} ready`})]})]}),We.length>=2&&n.jsxs(L,{size:"sm",variant:Ze?"outline":"hero",className:"h-7 gap-1 text-[11px] px-2",onClick:Je,disabled:z,title:t("clips.analyzeHint",{defaultValue:"ИИ оценит транскрипты и отметит 3 самых медийных"}),children:[z?n.jsx(xe,{size:11,className:"animate-spin"}):n.jsx(tt,{size:11}),z?t("clips.analyzing",{defaultValue:"Анализ…"}):Ze?t("clips.reanalyze",{defaultValue:"Переанализировать"}):t("clips.findTop3",{defaultValue:"Найти топ-3 клипа"})]})]}),n.jsx("div",{className:"space-y-1.5",children:r.map(K=>{var X;const ye=K.status==="ready",De=K.status==="failed",pt=K.status==="pending",kt=K.status==="uploading";return n.jsxs("div",{className:`flex items-center gap-2 p-2 rounded-lg border text-xs transition-colors ${K.is_top_pick?"bg-amber-50 dark:bg-amber-500/10 border-amber-300/60 dark:border-amber-500/30":"bg-muted/20 border-border/30"}`,children:[K.status==="ready"&&K.title&&n.jsx(Jy,{entityType:"live_clip",entityId:K.id,initialUrl:K.thumbnail_path,autoGenerate:!0,aspect:"16:9",compact:!0}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsxs("div",{className:"flex items-center gap-2 text-foreground flex-wrap",children:[n.jsxs("span",{className:"text-[10px] font-mono text-muted-foreground shrink-0",children:["#",K.block_index+1]}),K.title?n.jsx("span",{className:"font-semibold text-foreground text-[12px] leading-snug min-w-0 break-words",children:K.title}):n.jsx("span",{className:"text-muted-foreground italic text-[11px]",children:t("clips.titlePending",{defaultValue:"Генерируем наÐ
1033·Ð²Ð°Ð½Ð¸Ðµâ€¦"})}),n.jsxs("span",{className:"text-muted-foreground inline-flex items-center gap-1 ml-auto shrink-0",children:[n.jsx(ls,{size:10}),Qye(K.duration_seconds)]}),((X=K.comments_json)==null?void 0:X.length)>0&&n.jsxs("span",{className:"text-muted-foreground",children:["· ",t("clips.commentsCount",{count:K.comments_json.length,defaultValue:`${K.comments_json.length} cmt`})]}),K.is_top_pick&&n.jsxs(fe,{className:"text-[10px] px-1.5 py-0 gap-1 bg-amber-500 hover:bg-amber-500 text-white border-0",children:[n.jsx(gS,{size:10,className:"fill-current"}),t("clips.topPick",{defaultValue:"ТОП-3"})]}),typeof K.highlight_score=="number"&&n.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["· ",t("clips.score",{defaultValue:"оценка"}),": ",Math.round(K.highlight_score)]})]}),K.description&&n.jsx("p",{className:"text-[11px] text-foreground/80 mt-0.5 leading-snug break-words",children:K.description}),K.seo_tags&&K.seo_tags.length>0&&n.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:K.seo_tags.slice(0,6).map(M=>n.jsxs("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-primary/10 text-primary",children:["#",M]},M))}),K.is_top_pick&&K.highlight_reason&&n.jsx("p",{className:"text-[11px] text-amber-700 dark:text-amber-300 mt-0.5 italic",children:K.highlight_reason}),K.spoken_text&&n.jsxs(n.Fragment,{children:[n.jsx("p",{className:`text-[11px] text-muted-foreground mt-0.5 whitespace-pre-wrap break-words ${E[K.id]?"":"line-clamp-2"}`,children:K.spoken_text}),n.jsx("button",{type:"button",onClick:()=>H(M=>({...M,[K.id]:!M[K.id]})),className:"text-[10px] text-primary hover:underline mt-0.5",children:E[K.id]?t("clips.collapse",{defaultValue:"Свернуть"}):t("clips.expand",{defaultValue:"Показать весь текст"})})]}),De&&K.error_text&&n.jsxs("p",{className:"text-[11px] text-destructive truncate mt-0.5 inline-flex items-center gap-1",children:[n.jsx(Ad,{size:10})," ",K.error_text]}),ye&&(()=>{const M=u.linkedPlatforms.map(js),se=K.published_targets||{},he=Array.from(new Set([...M,...Object.keys(se).map(js)]));if(he.length===0)return null;const Ce=he.some(me=>{var Ye;const Ge=Object.keys(se).find(ee=>js(ee)===me);return Ge?(Ye=se[Ge])==null?void 0:Ye.ok:!1}),Ve=he.some(me=>{var Ye;const Ge=Object.keys(se).find(ee=>js(ee)===me);return Ge?(Ye=se[Ge])==null?void 0:Ye.analytics:!1});return n.jsxs("div",{className:"mt-1.5",children:[n.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[he.map(me=>{const Ge=Object.keys(se).find(ge=>js(ge)===me),Ye=Ge?se[Ge]:void 0,ee=Br[me]||me,W=`${K.id}:${me}`;if(Ye!=null&&Ye.ok){const ge=t("clips.platformChipTooltipOk",{name:ee,defaultValue:`Опубликовано в ${ee}`});return n.jsxs("span",{className:"group relative inline-flex",children:[Ye.url?n.jsx("a",{href:Ye.url,target:"_blank",rel:"noopener noreferrer",className:"hover:opacity-80",title:ge,children:n.jsxs(fe,{variant:"outline",className:"text-[10px] gap-1 px-1.5 py-0 pr-5 border-emerald-300/60 text-emerald-700 dark:text-emerald-300 bg-emerald-50/60 dark:bg-emerald-500/10",children:[n.jsx(ms,{size:9})," ",ee]})}):n.jsxs(fe,{variant:"outline",className:"text-[10px] gap-1 px-1.5 py-0 pr-5 border-emerald-300/60 text-emerald-700 dark:text-emerald-300 bg-emerald-50/60 dark:bg-emerald-500/10",title:ge,children:[n.jsx(ms,{size:9})," ",ee]}),n.jsx("button",{type:"button",onClick:Ne=>{Ne.preventDefault(),Ne.stopPropagation(),J({clipId:K.id,platform:me,label:ee})},disabled:Y===W,className:"absolute right-0.5 top-1/2 -translate-y-1/2 p-0.5 rounded text-emerald-700/70 dark:text-emerald-300/70 hover:text-destructive hover:bg-destructive/10 disabled:opacity-50",title:t("clips.unpublishBtn",{name:ee,defaultValue:`Снять публикацию из ${ee}`}),children:Y===W?n.jsx(xe,{size:9,className:"animate-spin"}):n.jsx(Qn,{size:9})})]},me)}return Ye&&!Ye.ok?n.jsxs(fe,{variant:"outline",className:"text-[10px] gap-1 px-1.5 py-0 border-destructive/40 text-destructive bg-destructive/5",title:t("clips.platformChipTooltipError",{name:ee,error:Ye.error||"failed",defaultValue:`${ee}: ${Ye.error||"ошибка"}`}),children:[n.jsx(Ad,{size:9})," ",ee]},me):n.jsx(fe,{variant:"outline",className:"text-[10px] gap-1 px-1.5 py-0 border-muted-foreground
1033/30 text-muted-foreground",title:t("clips.platformChipTooltipPending",{name:ee,defaultValue:`${ee} — ещё не публиковали`}),children:ee},me)}),Ce&&(()=>{var Ye,ee;let me=0;for(const W of he){const ge=Object.keys(se).find(rt=>js(rt)===W),Ne=ge?(ee=(Ye=se[ge])==null?void 0:Ye.analytics)==null?void 0:ee.fetched_at:void 0;Ne&&(me=Math.max(me,new Date(Ne).getTime()))}const Ge=me>0&&Date.now()-me<Kye;return n.jsx("button",{type:"button",onClick:()=>Pt(K),disabled:G===K.id,className:`inline-flex items-center justify-center h-5 w-5 rounded text-muted-foreground hover:text-foreground hover:bg-muted/40 disabled:opacity-50 ${Ge?"opacity-60":""}`,title:t("clips.analyticsRefresh",{defaultValue:"Обновить статистику"}),children:G===K.id?n.jsx(xe,{size:10,className:"animate-spin"}):n.jsx(ss,{size:10})})})()]}),Ve&&n.jsx("div",{className:"mt-1 flex flex-wrap gap-x-3 gap-y-0.5",children:he.map(me=>{var ge;const Ge=Object.keys(se).find(Ne=>js(Ne)===me),Ye=Ge?(ge=se[Ge])==null?void 0:ge.analytics:void 0;if(!Ye)return null;const ee=Br[me]||me,W=Ne=>typeof Ne=="number"?Yye.format(Ne):null;return n.jsxs("span",{className:"inline-flex items-center gap-1.5 text-[10px] text-muted-foreground",children:[n.jsxs("span",{className:"font-medium text-foreground/80",children:[ee,":"]}),W(Ye.views)&&n.jsxs("span",{className:"inline-flex items-center gap-0.5",children:[n.jsx(oi,{size:9}),W(Ye.views)]}),W(Ye.likes)&&n.jsxs("span",{className:"inline-flex items-center gap-0.5",children:[n.jsx(co,{size:9}),W(Ye.likes)]}),W(Ye.comments)&&n.jsxs("span",{className:"inline-flex items-center gap-0.5",children:[n.jsx(lu,{size:9}),W(Ye.comments)]})]},me)})})]})})()]}),n.jsx(fe,{variant:"outline",className:`text-[10px] uppercase tracking-wider ${ye?"border-primary/40 text-primary":De?"border-destructive/40 text-destructive":"border-muted-foreground/30 text-muted-foreground"}`,children:ye?t("clips.statusReady",{defaultValue:"ready"}):kt?t("clips.statusUploading",{defaultValue:"uploading"}):De?t("clips.statusFailed",{defaultValue:"failed"}):t("clips.statusPending",{defaultValue:"pending"})}),n.jsxs("div",{className:"flex items-center gap-1",children:[ye&&n.jsxs(n.Fragment,{children:[n.jsx(L,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0",onClick:()=>Q(K),title:t("clips.preview",{defaultValue:"Preview"}),children:n.jsx(Rs,{size:12})}),n.jsx(L,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0",onClick:()=>ve(K),title:t("clips.download",{defaultValue:"Download"}),children:n.jsx(Ny,{size:12})}),(()=>{var Ve,me,Ge,Ye;const M=y[K.id],se=((me=(Ve=K.published_targets)==null?void 0:Ve.facebook)==null?void 0:me.url)||((Ye=(Ge=K.published_targets)==null?void 0:Ge.instagram)==null?void 0:Ye.url);if(M)return n.jsx(L,{asChild:!0,size:"sm",variant:"outline",className:"h-7 gap-1 text-[11px] px-2 border-blue-300/60 text-blue-700 dark:text-blue-300 bg-blue-50/60 dark:bg-blue-500/10",children:n.jsxs(zt,{to:"/app/ads",title:s("clip.openAds"),children:[n.jsx(za,{size:11})," ",s("clip.campaignBadge",{status:s(`status.${M.status}`)})]})});const he=!je||!se,Ce=s(je?se?"clip.btnTooltip":"clip.needFacebookOrInstagram":"clip.needMeta");return n.jsxs(L,{size:"sm",variant:"ghost",className:"h-7 gap-1 text-[11px] px-2",disabled:he,onClick:()=>ie(K),title:Ce,children:[n.jsx(za,{size:11})," ",s("clip.btn")]})})(),(()=>{var me,Ge;const M=w[K.id],se=((Ge=(me=K.published_targets)==null?void 0:me.youtube)==null?void 0:Ge.url)||K.published_url,he=!!we(se||"");if(M)return n.jsx(L,{asChild:!0,size:"sm",variant:"outline",className:"h-7 gap-1 text-[11px] px-2 border-red-300/60 text-red-700 dark:text-red-300 bg-red-50/60 dark:bg-red-500/10",children:n.jsxs(zt,{to:"/app/ads",title:s("clip.openAds"),children:[n.jsx(Ls,{size:11})," ",s("clip.googleCampaignBadge",{status:s(`status.${M.status}`)})]})});const Ce=!ae||!he,Ve=s(ae?he?"clip.googleBtnTooltip":"clip.needYoutube":"clip.needGoogle");return n.jsxs(L,{size:"sm",variant:"ghost",className:"h-7 gap-1 text-[11px] px-2",disabled:Ce,onClick:()=>Ae(K),title:Ve,children:[n.jsx(Ls,{size:11,className:"text-red-600"})," ",s("clip.googleBtn")]})})(),(()=>{const M=S===K.id||Sm(K),se=Wy(K),he=u.linkedPlatforms.map(js),Ce=he.filter(Ne=>!se.has(Ne)),Ve=u.status!=="connected"||he.length===0,me=!Ve&&Ce.length===0,Ge=!Ve&&se.size>0&&Ce.length>0;if(Ve&&se.size===0)return n.jsx(L,{asChild:!0,size:"sm",variant:"outline",className:"h-7 gap-1 text-[11px] px-2",children:n.jsxs(zt,{to:"/app/integrations",title:t("clips.connectSocialsCta",{defaultValue:"Подключите соцсети"}),children:[n.jsx(Pr,{size:11}),t("clips.connectSocialsCta",{defaultValue:"Подключите соцсети"})]})});
1033const Ye=M?t("clips.publishingBtn",{defaultValue:"Публикуется…"}):me?t("clips.publishedEverywhere",{defaultValue:"Опубликовано везде"}):Ge?t("clips.publishMoreBtn",{count:Ce.length,defaultValue:`Опубликовать ещё в ${Ce.length}`}):t("clips.publishBtn",{defaultValue:"Опубликовать"}),ee=new Set(Ce),W=V[K.id]??ee,ge=Array.from(W).filter(Ne=>Ce.includes(Ne));return n.jsxs("div",{className:"inline-flex items-stretch",children:[n.jsxs(L,{size:"sm",variant:me?"outline":"hero",className:"h-7 gap-1 text-[11px] px-2 rounded-r-none",onClick:()=>{me||U(K)},disabled:M||me,title:me?he.map(Ne=>Br[Ne]||Ne).join(", "):void 0,children:[M?n.jsx(xe,{size:11,className:"animate-spin"}):me?n.jsx(ms,{size:11}):n.jsx(Za,{size:11}),Ye]}),!me&&n.jsxs(MB,{open:R===K.id,onOpenChange:Ne=>{F(Ne?K.id:null),Ne&&!V[K.id]&&te(rt=>({...rt,[K.id]:ee}))},children:[n.jsx(zB,{asChild:!0,children:n.jsx(L,{size:"sm",variant:me?"outline":"hero",className:"h-7 px-1 rounded-l-none border-l border-l-background/30",disabled:M,title:t("clips.publishTargetsTitle",{defaultValue:"Выбрать платформы"}),children:n.jsx(ps,{size:11})})}),n.jsxs(PT,{align:"end",className:"w-60 p-2",children:[n.jsx("div",{className:"text-xs font-semibold mb-1.5",children:t("clips.publishTargetsTitle",{defaultValue:"Куда опубликовать"})}),n.jsx("div",{className:"space-y-1",children:he.map(Ne=>{const rt=se.has(Ne),Re=Br[Ne]||Ne,lt=rt?!1:W.has(Ne);return n.jsxs("label",{className:`flex items-center gap-2 text-xs px-1.5 py-1 rounded ${rt?"opacity-60":"hover:bg-muted/40 cursor-pointer"}`,children:[n.jsx(Wl,{checked:lt,disabled:rt,onCheckedChange:at=>{te(vs=>{const Ht=new Set(vs[K.id]??ee);return at?Ht.add(Ne):Ht.delete(Ne),{...vs,[K.id]:Ht}})}}),n.jsx("span",{className:"flex-1",children:Re}),rt&&n.jsx("span",{className:"text-[10px] text-emerald-600 dark:text-emerald-400",children:t("clips.platformAlreadyPublished",{defaultValue:"уже опубликовано"})})]},Ne)})}),n.jsxs("div",{className:"flex items-center gap-2 mt-2 pt-2 border-t",children:[n.jsx(Wl,{id:`clip-sched-${K.id}`,checked:Z,onCheckedChange:Ne=>oe(!!Ne)}),n.jsx("label",{htmlFor:`clip-sched-${K.id}`,className:"text-[11px] cursor-pointer",children:t("clips.scheduleLabel",{defaultValue:"Отложить"})}),Z&&n.jsxs("div",{className:"flex items-center gap-1",children:[n.jsx("span",{className:"text-[11px] text-muted-foreground",children:"+"}),n.jsx("input",{type:"number",min:1,max:720,value:A,onChange:Ne=>{const rt=Math.max(1,Math.min(720,parseInt(Ne.target.value||"1",10)||1));ue(rt)},className:"h-6 w-14 text-[11px] rounded border bg-background px-1"}),n.jsx("span",{className:"text-[11px] text-muted-foreground",children:t("clips.scheduleHours",{defaultValue:"ч после последнего"})})]})]}),n.jsxs(L,{size:"sm",variant:"hero",className:"w-full mt-2 h-7 text-[11px]",disabled:ge.length===0||M,onClick:()=>{F(null);const Ne=Z?A:void 0;U(K,ge,Ne?{scheduleHoursOffset:Ne}:void 0)},children:[n.jsx(Za,{size:11,className:"mr-1"}),t("clips.publishSelected",{count:ge.length,defaultValue:`Опубликовать в выбранные (${ge.length})`})]})]})]})]})})()]}),(pt||kt)&&n.jsx(xe,{size:12,className:"animate-spin text-muted-foreground"})]})]},K.id)})}),C&&n.jsx("div",{className:"fixed inset-0 z-50 bg-black/70 flex items-center justify-center p-4",onClick:()=>B(null),children:n.jsxs("div",{className:"bg-background rounded-xl p-3 max-w-2xl w-full",onClick:K=>K.stopPropagation(),children:[n.jsx("video",{src:C.url,controls:!0,autoPlay:!0,className:"w-full rounded-lg"}),n.jsx("div",{className:"flex justify-end mt-2",children:n.jsx(L,{size:"sm",variant:"outline",onClick:()=>B(null),children:"Close"})})]})}),n.jsx(bi,{open:!!$,onOpenChange:K=>{K||J(null)}
1033,children:n.jsxs(oa,{children:[n.jsxs(la,{children:[n.jsx(da,{children:t("clips.unpublishConfirmTitle",{name:($==null?void 0:$.label)||"",defaultValue:`Удалить пост из ${($==null?void 0:$.label)||""}?`})}),n.jsx(ua,{children:t("clips.unpublishConfirmDesc",{defaultValue:"Пост будет удалён в соцсети, и чип станет серым. Действие необратимо."})})]}),n.jsxs(ca,{children:[n.jsx(ma,{children:t("clips.cancel",{defaultValue:"Отмена"})}),n.jsxs(ha,{onClick:K=>{K.preventDefault(),xt()},disabled:!!Y,children:[Y?n.jsx(xe,{size:12,className:"animate-spin mr-1"}):null,t("clips.unpublishBtn",{name:($==null?void 0:$.label)||"",defaultValue:"Удалить"})]})]})]})}),n.jsx(nv,{open:!!j,onOpenChange:K=>{K||_(null)},prefill:j??void 0,onCreate:async K=>{try{await f(K),Le.success(s("createCampaign")),_(null)}catch(ye){Le.error(ye.message||s("errors.createFailed"))}}}),n.jsx(rv,{open:!!N,onOpenChange:K=>{K||k(null)},prefill:N??void 0,onCreate:async K=>{try{await b(K),Le.success(s("googleModal.created",{defaultValue:"YouTube кампания создана (на паузе)"})),k(null)}catch(ye){Le.error(ye.message||s("errors.createFailed"))}}})]})}function Jye(e){if(!e||e<=0)return"—";const t=Math.round(e),s=Math.floor(t/3600),r=Math.floor(t%3600/60),a=t%60;return s>0?`${s}h ${r}m`:r>0?`${r}m ${a}s`:`${a}s`}function Zye({sessions:e,loading:t,onContinue:s,continuingId:r}){const{formatDate:a}=or(),{t:i}=Oe("live-center"),[o,l]=h.useState(null),c=u=>l(m=>m===u?null:u);if(t)return n.jsx(de.div,{...Te(.25),className:"rounded-2xl bg-surface-elevated border border-border/50 shadow-premium-sm p-6 flex items-center justify-center min-h-[120px]",children:n.jsx(xe,{size:20,className:"animate-spin text-primary"})});const d=u=>{const m=u.metadata_json??{},p=m.youtube_watch_url||m.youtube_url||m.watch_url,f=!!s&&["ended","failed","canceled"].includes(u.status),g=r===u.id;return n.jsxs("div",{className:"px-4 py-4 bg-muted/10 border-t border-border/30 space-y-3",children:[n.jsxs("div",{className:"flex flex-wrap gap-2 text-[11px]",children:[u.started_at&&n.jsxs(fe,{variant:"secondary",className:"gap-1",children:[n.jsx(St,{size:9})," ",a(u.started_at)]}),n.jsxs(fe,{variant:"secondary",className:"gap-1",children:[n.jsx(ls,{size:9})," ",Jye(u.duration_seconds)]}),u.live_mode&&n.jsx(fe,{variant:"outline",children:i(`modes.${u.live_mode}`,u.live_mode)}),u.platform&&n.jsx(fe,{variant:"outline",children:u.platform}),p&&n.jsx("a",{href:p,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 rounded-md border border-primary/30 text-primary px-2 py-0.5 text-[11px] hover:bg-primary/5",children:i("history.openYoutube","Open on YouTube")})]}),f&&n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsxs(L,{size:"sm",variant:"outline",disabled:g,onClick:x=>{x.stopPropagation(),s(u)},className:"gap-1.5",children:[g?n.jsx(xe,{size:13,className:"animate-spin"}):n.jsx(o4,{size:13}),"Продолжить с того же места"]}),n.jsx("span",{className:"text-[10px] text-muted-foreground",children:"Создаст новый эфир и продолжит план с того блока, где остановились"})]}),n.jsx(DT,{liveSessionId:u.id})]})};return n.jsxs(de.div,{...Te(.25),className:"rounded-2xl bg-surface-elevated border border-border/50 shadow-premium-sm p-6 space-y-4",children:[n.jsxs("h2",{className:"font-heading font-semibold text-lg text-foreground flex items-center gap-2",children:[n.jsx(ii,{size:18,className:"text-primary"})," ",i("history.title")]}),e.length===0?n.jsx(Er,{icon:ii,title:i("history.emptyTitle"),description:i("history.emptyDesc")}):n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"hidden md:block rounded-xl border border-border/40 overflow-hidden",children:n.jsxs("table",{className:"w-full text-sm",children:[n.jsx("thead",{children:n.jsxs("tr",{className:"bg-muted/30 text-muted-foreground text-[11px] uppercase tracking-wider",children:[n.jsx("th",{className:"text-left px-4 py-2.5 font-semibold",children:i("history.colName")}),n.jsx("th",{className:"text-left px-4 py-2.5 font-semibold",children:i("history.colDate")}),n.jsx("th",{className:"text-left px-4 py-2.5 font-semibold",children:i("history.colFormat")}),n.jsx("th",{className:"text-left px-4 py-2.5 font-semibold",children:i("history.colStatus")}),n.jsx("th",{className:"px-4 py-2.5"})]})}),n.jsx("tbody",{children:e.map(u=>{const m=o===u.id;return n.jsxs(h.Fragment,{children:[n.jsxs("tr",{onClick:()=>
1033c(u.id),className:`border-t border-border/30 cursor-pointer transition-colors ${m?"bg-muted/20":"hover:bg-muted/10"}`,children:[n.jsx("td",{className:"px-4 py-3 font-semibold text-foreground text-xs",children:u.title}),n.jsx("td",{className:"px-4 py-3 text-muted-foreground text-xs",children:u.ended_at?a(u.ended_at):"—"}),n.jsx("td",{className:"px-4 py-3",children:n.jsx(fe,{variant:"secondary",className:"text-[10px]",children:i(`modes.${u.live_mode}`,u.live_mode??"")})}),n.jsx("td",{className:"px-4 py-3",children:n.jsx(yr,{status:u.status})}),n.jsx("td",{className:"px-4 py-3 text-right",children:n.jsx(yn,{size:14,className:`text-muted-foreground transition-transform ${m?"rotate-90 text-primary":""}`})})]}),m&&n.jsx("tr",{children:n.jsx("td",{colSpan:5,className:"p-0",children:n.jsx(de.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},transition:{duration:.18},className:"overflow-hidden",children:d(u)})})})]},u.id)})})]})}),n.jsx("div",{className:"md:hidden space-y-2.5",children:e.map(u=>{const m=o===u.id;return n.jsxs("div",{className:"rounded-xl border border-border/40 bg-muted/10 overflow-hidden",children:[n.jsxs("button",{onClick:()=>c(u.id),className:"w-full text-left p-4 space-y-2",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsx("p",{className:"font-heading font-semibold text-sm text-foreground",children:u.title}),n.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[n.jsx(yr,{status:u.status}),n.jsx(yn,{size:14,className:`text-muted-foreground transition-transform ${m?"rotate-90 text-primary":""}`})]})]}),n.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[n.jsxs(fe,{variant:"secondary",className:"text-[10px] gap-1",children:[n.jsx(yy,{size:9}),u.ended_at?a(u.ended_at):"—"]}),n.jsx(fe,{variant:"secondary",className:"text-[10px]",children:i(`modes.${u.live_mode}`,u.live_mode??"")})]})]}),n.jsx(xn,{initial:!1,children:m&&n.jsx(de.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.18},className:"overflow-hidden",children:d(u)})})]},u.id)})})]})]})}function Xye(e){const[t,s]=h.useState([]),[r,a]=h.useState([]),[i,o]=h.useState(null),[l,c]=h.useState(null),[d,u]=h.useState([]),[m,p]=h.useState([]),[f,g]=h.useState([]),[x,b]=h.useState(null),[v,y]=h.useState(!1),[w,j]=h.useState(null),_=h.useRef(null),N=h.useCallback(async S=>{y(!0),j(null);try{const[T,C,B,E,H,z,ne,V]=await Promise.all([I.from("live_turns").select("id, kind, state, text, tts_text, subtitle_text, selection_reason, selection_score, is_terminal, end_after_playback, source, created_at, played_at, committed_at, error_text").eq("live_session_id",S).order("created_at",{ascending:!1}).limit(20),I.from("live_comments_inbox").select("id, author_id, author_name, raw_text, safe_text, source, moderation_status, moderation_reason, selected_into_turn_id, received_at").eq("live_session_id",S).order("received_at",{ascending:!1}).limit(30),I.from("live_session_runtime").select("duration_final_requested, terminal_reserved, next_should_be_terminal, last_pick_kind, last_pick_at, reserved_turn_id, webinar_block_index, covered_block_ids, last_topic_id, return_to_block_id, updated_at").eq("live_session_id",S).maybeSingle(),I.from("live_memory_summary").select("summary_text, events_since_last_update, updated_at").eq("live_session_id",S).maybeSingle(),I.from("live_facts").select("id, fact_text, kind, created_at").eq("live_session_id",S).order("created_at",{ascending:!1}).limit(5),I.from("live_dialog_events").select("id, role, participant_id, participant_name, input_kind, text, safe_text, turn_id, created_at").eq("live_session_id",S).order("created_at",{ascending:!1}).limit(20),I.from("live_topic_thread").select("id, title, thesis, source_kind, source_turn_id, created_at").eq("live_session_id",S).order("created_at",{ascending:!1}).limit(10),I.from("live_sessions").select("live_mode, webinar_plan_json, started_at").eq("id",S).maybeSingle()]);T.data&&s(T.data),C.data&&a(C.data),o(B.data??null),c(E.data??null),H.data&&u(H.data),z.data&&p(z.data),ne.data&&g(ne.data),b(V.data??null)}catch(T){console.error("[useLiveMonitor] fetch error",T),j(T.message||"Failed to load monitor data")}finally{y(!1)}},[]);h.useEffect(()=>{if(_.current=e,!e){s([]),a([]),o(null),c(null),u([]),p([]),g([]),b(null);return}N(e);const S=I.channel(`live_monitor_${e}`).on("postgres_changes",{event:"*",schema:"public",table:"live_turns",filter:`live_session_id=eq.${e}`},()=>{_.current===e&&N(e)}).on("postgres_changes",{event:"*",schema:"public",table:"live_comments_inbox",filter:`live_session_id=eq.${e}`},()=>{_.current===e&&N(e)}).on("postgres_changes",{event:"*",schema:"public",table:"live_session_runtime",filter:`live_session_id=eq.${e}`},()=>{_.current===e&&N(e)}).on("postgres_changes",{event:"*",schema:"public",table:"live_memory_summary",filter:`live_session_id=eq.${e}`},()=>{_.current===e&&N(e)}).subscribe();return()=>{I.removeChannel(S)}},[e,N]);const k=h.useCallback(async()=>{_.current&&await N(_.current)},[N]);return{turns:t,comments:r,runtime:i,memory:l,facts:d,events:m,topics:f,session:x,loading:v,error:w,refresh:k}}const ebe={preparing:"bg-amber-100 text-amber-800 border-amber-200",ready:"bg-blue-100 text-blue-800 border-blue-200",playing:"bg-emerald-100 text-emerald-800 border-emerald-200",played:"bg-muted text-muted-foreground border-border",failed:"bg-destructive/10 text-destructive border-destructive/30",cancelled:"bg-muted text-muted-foreground border-border"};function tbe(e,t){return e?e.length>t?e.slice(0,t)+"…":e:"—"}function sbe(e){try{return new Date(e).toLocaleTimeString()}catch{return e}}function nbe({turns:e,highlightTurnId:t}){const[s,r]=h.useState(null);return e.length?n.jsx("div",{className:"space-y-1.5",children:e.map(a=>{const i=s===a.id,o=t===a.id;return n.jsxs("div",{id:`turn-${a.id}`,className:`rounded-lg border ${o?"border-primary/60 bg-primary/5":"border-border/60 bg-background"} text-xs transition-colors`,children:[n.jsxs("button",{onClick:()=>r(i?null:a.id),className:"w-full px-3 py-2 flex items-center gap-2 text-left hover:bg-muted/50 rounded-lg",children:[i?n.jsx(ps,{size:12,className:"text-muted-foreground shrink-0"}):n.jsx(yn,{size:12,className:"text-muted-foreground shrink-0"}),n.jsx("span",{className:"font-mono text-[10px] text-muted-foreground w-16 shrink-0",children:sbe(a.created_at)}),n.jsx(fe,{variant:"outline",className:"text-[10px] font-normal shrink-0",children:a.kind}),n.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded border shrink-0 ${ebe[a.state]||"bg-muted text-foreground border-border"}`,children:a.state}),a.is_terminal&&n.jsx(fe,{className:"text-[10px] bg-destructive/10 text-destructive border-destructive/30 shrink-0",children:"terminal"}),typeof a.selection_score=="number"&&n.jsx("span",{className:"text-[10px] text-muted-foreground shrink-0 font-mono",children:a.selection_score.toFixed(2)}
1033),n.jsx("span",{className:"text-foreground/80 truncate flex-1 min-w-0",children:tbe(a.text,80)})]}),i&&n.jsxs("div",{className:"px-3 pb-3 pt-1 space-y-2 border-t border-border/40",children:[a.selection_reason&&n.jsxs("div",{children:[n.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted-foreground mb-0.5",children:"Reason"}),n.jsx("p",{className:"text-xs text-foreground/90",children:a.selection_reason})]}),n.jsxs("div",{children:[n.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted-foreground mb-0.5",children:"Text"}),n.jsx("p",{className:"text-xs whitespace-pre-wrap text-foreground/90",children:a.text||"—"})]}),a.tts_text&&a.tts_text!==a.text&&n.jsxs("div",{children:[n.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted-foreground mb-0.5",children:"TTS text"}),n.jsx("p",{className:"text-xs whitespace-pre-wrap text-foreground/70 font-mono",children:a.tts_text})]}),a.subtitle_text&&a.subtitle_text!==a.text&&n.jsxs("div",{children:[n.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted-foreground mb-0.5",children:"Subtitles"}),n.jsx("p",{className:"text-xs whitespace-pre-wrap text-foreground/70",children:a.subtitle_text})]}),a.error_text&&n.jsxs("div",{children:[n.jsx("p",{className:"text-[10px] uppercase tracking-wide text-destructive mb-0.5",children:"Error"}),n.jsx("p",{className:"text-xs text-destructive whitespace-pre-wrap",children:a.error_text})]}),a.source&&Object.keys(a.source).length>0&&n.jsxs("div",{children:[n.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted-foreground mb-0.5",children:"Source"}),n.jsx("pre",{className:"text-[10px] text-muted-foreground font-mono overflow-x-auto",children:JSON.stringify(a.source,null,2)})]})]})]},a.id)})}):n.jsx("p",{className:"text-sm text-muted-foreground italic",children:"No turns yet."})}function rbe(e){if(!e)return"—";try{return new Date(e).toLocaleTimeString()}catch{return e}}function abe({memory:e,facts:t}){var r;const s=((r=e==null?void 0:e.summary_text)==null?void 0:r.length)??0;return n.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[n.jsxs("div",{className:"rounded-lg border border-border/60 bg-background p-3",children:[n.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[n.jsx(vy,{size:14,className:"text-primary"}),n.jsx("span",{className:"text-xs font-medium text-foreground",children:"Summary"})]}),n.jsxs("div",{className:"text-xs text-muted-foreground space-y-1",children:[n.jsxs("p",{children:[n.jsx("span",{className:"font-mono text-foreground",children:s})," chars"]}),n.jsxs("p",{children:["Pending events: ",n.jsx("span",{className:"font-mono text-foreground",children:(e==null?void 0:e.events_since_last_update)??0})]}),n.jsxs("p",{children:["Updated: ",n.jsx("span",{className:"font-mono text-foreground",children:rbe(e==null?void 0:e.updated_at)})]})]})]}),n.jsxs("div",{className:"rounded-lg border border-border/60 bg-background p-3",children:[n.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[n.jsx(tt,{size:14,className:"text-primary"}),n.jsx("span",{className:"text-xs font-medium text-foreground",children:"Recent facts"}),n.jsx("span",{className:"text-[10px] text-muted-foreground ml-auto",children:t.length})]}),t.length===0?n.jsx("p",{className:"text-xs text-muted-foreground italic",children:"No facts extracted yet."}):n.jsx("ul",{className:"space-y-1",children:t.map(a=>n.jsxs("li",{className:"text-xs text-foreground/85 leading-snug",children:[n.jsx("span",{className:"text-muted-foreground font-mono text-[10px] mr-1",children:a.kind||"fact"}),a.fact_text]},a.id))})]})]})}const Y1={pending:"bg-amber-100 text-amber-800 border-amber-200",approved:"bg-emerald-100 text-emerald-800 border-emerald-200",safe_note:"bg-blue-100 text-blue-800 border-blue-200",rejected:"bg-destructive/10 text-destructive border-destructive/30"},ibe=40,obe=9e4;function K1(e,t){return e.length>t?e.slice(0,t)+"…":e}function lbe(e){try{return new Date(e).toLocaleTimeString()}catch{return e}}function cbe(e){const t=[];for(const s of e){const a=(s.safe_text||s.raw_text||"").length<=ibe,i=t[t.length-1],o=i?new Date(i.items[i.items.length-1].received_at).getTime():0,l=new Date(s.received_at).getTime(),c=i&&Math.abs(o-l)<=obe;if(i&&c&&i.authorId===s.author_id){i.items.push(s);continue}if(i&&c&&i.kind==="shorts"&&a){i.items.push(s);continue}t.push({key:s.id,authorId:s.author_id,authorName:s.author_name,source:s.source,items:[s],kind:a&&(!i||i.authorId!==s.author_id)?"shorts":"author"})}return t}function dbe({comments:e,onScrollToTurn:t}){const s=e.reduce((a,i)=>(a[i.moderation_status]=(a[i.moderation_status]||0)+1,a),{}),r=cbe(e.slice(0,30));return n.jsxs("div",{className:"space-y-3",children:[n.jsx("div",{className:"flex flex-wrap gap-2",children:["pending","approved","safe_note","rejected"].map(a=>n.jsxs("span",{className:`text-[10px] px-2 py-1 rounded border font-mono ${Y1[a]}`,children:[a,": ",s[a]||0]},a))}),e.length===0?n.jsx("p",{className:"text-sm text-muted-foreground italic",children:"No comments yet."}):n.jsx("ul",{className:"space-y-1.5 max-h-80 overflow-y-auto",children:r.slice(0,12).map(a=>{const i=a.items[0],o=a.items.length>1,l=a.kind==="shorts"&&o;return n.jsxs("li",{className:"rounded-lg border border-border/60 bg-background px-3 py-2 text-xs",children:[n.jsxs("div",{className:"flex items-center gap-2 mb-1 flex-wrap",children:[n.jsx("span",{className:"font-mono text-[10px] text-muted-foreground",children:lbe(i.received_at)}),n.jsx(fe,{variant:"outline",className:"text-[10px] font-normal",children:a.source}),n.jsx("span",{className:"font-medium text-foreground truncate",children:l?`${a.items.length} коротких`:a.authorName||a.authorId}),o&&n.jsxs(fe,{variant:"outline",className:"text-[10px] font-normal",children:["×",a.items.length]}),n.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded border ${Y1[i.moderation_status]||"bg-muted text-foreground border-border"} ml-auto`,children:i.moderation_status})]}),o?n.jsx("ul",{className:"space-y-1 pl-2 border-l border-border/40",children:a.items.map(c=>n.jsxs("li",{className:"flex items-start gap-2",children:[l&&n.jsxs("span",{className:"font-medium text-foreground
1033/70 text-[10px] shrink-0 truncate max-w-[80px]",children:[c.author_name||c.author_id,":"]}),n.jsx("span",{className:"text-foreground/85 flex-1",children:K1(c.safe_text||c.raw_text,200)}),c.selected_into_turn_id&&t&&n.jsx("button",{onClick:()=>t(c.selected_into_turn_id),className:"text-[10px] text-primary hover:underline shrink-0",children:"→ turn"})]},c.id))}):n.jsxs(n.Fragment,{children:[n.jsx("p",{className:"text-foreground/85",children:K1(i.safe_text||i.raw_text,200)}),i.moderation_reason&&n.jsx("p",{className:"text-[10px] text-muted-foreground mt-1 italic",children:i.moderation_reason}),i.selected_into_turn_id&&t&&n.jsx("button",{onClick:()=>t(i.selected_into_turn_id),className:"text-[10px] text-primary hover:underline mt-1",children:"→ turn"})]})]},a.key)})})]})}const ube={user:"bg-blue-100 text-blue-800 border-blue-200",assistant:"bg-emerald-100 text-emerald-800 border-emerald-200",system:"bg-muted text-muted-foreground border-border"};function hbe(e,t){return e?e.length>t?e.slice(0,t)+"…":e:"—"}function mbe(e){try{return new Date(e).toLocaleTimeString()}catch{return e}}function pbe({events:e,onScrollToTurn:t}){return e.length?n.jsx("ul",{className:"space-y-1.5 max-h-80 overflow-y-auto",children:e.map(s=>n.jsxs("li",{className:"rounded-lg border border-border/60 bg-background px-3 py-2 text-xs",children:[n.jsxs("div",{className:"flex items-center gap-2 mb-1 flex-wrap",children:[n.jsx("span",{className:"font-mono text-[10px] text-muted-foreground",children:mbe(s.created_at)}),n.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded border ${ube[s.role]||"bg-muted text-foreground border-border"}`,children:s.role}),s.input_kind&&n.jsx(fe,{variant:"outline",className:"text-[10px] font-normal",children:s.input_kind}),s.participant_name&&n.jsx("span",{className:"font-medium text-foreground truncate",children:s.participant_name}),s.turn_id&&t&&n.jsx("button",{onClick:()=>t(s.turn_id),className:"text-[10px] text-primary hover:underline ml-auto",children:"→ turn"})]}),n.jsx("p",{className:"text-foreground/85 whitespace-pre-wrap",children:hbe(s.safe_text||s.text,240)})]},s.id))}):n.jsx("p",{className:"text-sm text-muted-foreground italic",children:"No dialog events yet."})}function fbe(e){try{return new Date(e).toLocaleTimeString()}catch{return e}}function gbe({topics:e,onScrollToTurn:t}){return e.length?n.jsx("ul",{className:"space-y-1.5",children:e.map(s=>n.jsxs("li",{className:"rounded-lg border border-border/60 bg-background px-3 py-2 text-xs",children:[n.jsxs("div",{className:"flex items-center gap-2 mb-1 flex-wrap",children:[n.jsx("span",{className:"font-mono text-[10px] text-muted-foreground",children:fbe(s.created_at)}),s.source_kind&&n.jsx(fe,{variant:"outline",className:"text-[10px] font-normal",children:s.source_kind}),n.jsx("span",{className:"font-medium text-foreground truncate flex-1 min-w-0",children:s.title}),s.source_turn_id&&t&&n.jsx("button",{onClick:()=>t(s.source_turn_id),className:"text-[10px] text-primary hover:underline shrink-0",children:"→ turn"})]}),s.thesis&&n.jsx("p",{className:"text-foreground/75 whitespace-pre-wrap",children:s.thesis})]},s.id))}):n.jsx("p",{className:"text-sm text-muted-foreground italic",children:"No topics covered yet."})}function xbe(e){return Array.isArray(e)?e:e&&Array.isArray(e.blocks)?e.blocks:[]}function vbe(e){if(!e)return"—";const t=Math.max(0,Math.floor((Date.now()-new Date(e).getTime())/1e3));return t<60?`${t}s ago`:t<3600?`${Math.floor(t/60)}m ago`:`${Math.floor(t/3600)}h ago`}function ybe({session:e,runtime:t,topics:s,comments:r}){var o,l;const a=(e==null?void 0:e.live_mode)??"free_live";if(a==="webinar"){const c=xbe(e==null?void 0:e.webinar_plan_json),d=(t==null?void 0:t.webinar_block_index)??0,u=c[d],m=c[d+1],p=c.length;return n.jsxs("div",{className:"rounded-xl bg-gradient-to-r from-primary/10 to-accent/5 border border-primary/20 px-4 py-3",children:[n.jsxs("div",{className:"flex items-center gap-2 text-[10px] uppercase tracking-wider text-primary font-semibold mb-1.5",children:[n.jsx(dp,{size:12})," Webinar · block ",Math.min(d+1,Math.max(p,1))," / ",p||"?"]}),n.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[n.jsx("span",{className:"text-sm font-medium text-foreground truncate",children:(u==null?void 0:u.title)??(p===0?"No plan loaded":"Plan complete")}
1033),m&&n.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-muted-foreground",children:[n.jsx(yn,{size:12})," next: ",n.jsx("span",{className:"truncate max-w-[200px]",children:m.title})]})]}),p>0&&n.jsx("div",{className:"mt-2 h-1 rounded-full bg-muted/40 overflow-hidden",children:n.jsx("div",{className:"h-full bg-primary transition-all",style:{width:`${Math.min(100,(((o=t==null?void 0:t.covered_block_ids)==null?void 0:o.length)??0)/p*100)}%`}})})]})}if(a==="nonstop_trends"){const c=s[0];return n.jsxs("div",{className:"rounded-xl bg-gradient-to-r from-amber-500/10 to-orange-500/5 border border-amber-500/20 px-4 py-3",children:[n.jsxs("div",{className:"flex items-center gap-2 text-[10px] uppercase tracking-wider text-amber-700 font-semibold mb-1.5",children:[n.jsx(Ol,{size:12})," Trends"]}),n.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[n.jsx("span",{className:"text-sm font-medium text-foreground truncate",children:(c==null?void 0:c.title)??"Waiting for first topic…"}),n.jsxs("span",{className:"text-xs text-muted-foreground",children:["· covered: ",s.length]})]})]})}const i=((l=r[0])==null?void 0:l.received_at)??null;return n.jsxs("div",{className:"rounded-xl bg-gradient-to-r from-emerald-500/10 to-teal-500/5 border border-emerald-500/20 px-4 py-3",children:[n.jsxs("div",{className:"flex items-center gap-2 text-[10px] uppercase tracking-wider text-emerald-700 font-semibold mb-1.5",children:[n.jsx(St,{size:12})," Free live"]}),n.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[n.jsx("span",{className:"text-sm font-medium text-foreground",children:"Free chat with viewers"}),n.jsxs("span",{className:"text-xs text-muted-foreground",children:["· last comment: ",vbe(i)]})]})]})}function bbe(e){if(!e)return"—";const t=new Date(e).getTime();if(Number.isNaN(t))return"—";const s=Math.max(0,Math.floor((Date.now()-t)/1e3)),r=Math.floor(s/3600),a=Math.floor(s%3600/60),i=s%60;return r>0?`${r}h ${a}m`:`${a}m ${i}s`}function MT({liveSessionId:e,workspaceId:t,startedAt:s,personaName:r}){const{turns:a,comments:i,runtime:o,memory:l,facts:c,events:d,topics:u,session:m,loading:p,error:f}=Xye(e),[g,x]=h.useState(!1),[b,v]=h.useState(null),[y,w]=h.useState(null),j=(o==null?void 0:o.duration_final_requested)??!1,_=async()=>{if(confirm("Request a graceful end? The next turn will be a closing summary.")){x(!0),v(null);try{const{error:k,data:S}=await I.functions.invoke("worker-api",{body:{action:"live_turn_request_final",live_session_id:e,workspace_id:t}});if(k||S!=null&&S.error)throw new Error((S==null?void 0:S.error)||(k==null?void 0:k.message)||"Failed")}catch(k){console.error("[LiveMonitor] request_final failed",k),v(k.message||"Failed")}finally{x(!1)}}},N=k=>{w(k);const S=document.getElementById(`turn-${k}`);S&&S.scrollIntoView({behavior:"smooth",block:"center"}),setTimeout(()=>w(null),2500)};return n.jsxs(de.div,{...Te(.05),className:"rounded-2xl bg-surface-elevated border border-border/50 shadow-premium-sm p-6 space-y-5",children:[n.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Ed,{size:18,className:"text-primary"}),n.jsx("h2",{className:"font-heading font-semibold text-lg text-foreground",children:"Стрим в реальном времени"}),p&&n.jsx(xe,{size:14,className:"animate-spin text-muted-foreground"})]}),n.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground flex-wrap",children:[r&&n.jsx(fe,{variant:"outline",className:"text-[10px]",children:r}),n.jsx("span",{className:"font-mono",children:bbe(s)}),typeof(o==null?void 0:o.webinar_block_index)=="number"&&n.jsxs(fe,{variant:"outline",className:"text-[10px]",children:["block ",o.webinar_block_index+1,Array.isArray(o.covered_block_ids)&&o.covered_block_ids.length>0?` · ${o.covered_block_ids.length} done`:""]}),(o==null?void 0:o.last_topic_id)&&n.jsxs(fe,{variant:"outline",className:"text-[10px]",children:["topic ",o.last_topic_id.slice(0,6)]}),j&&n.jsx(fe,{className:"text-[10px] bg-amber-100 text-amber-800 border-amber-200",children:"final requested"}),(o==null?void 0:o.terminal_reserved)&&n.jsx(fe,{className:"text-[10px] bg-destructive/10 text-destructive border-destructive/30",children:"terminal reserved"}),n.jsx("span",{className:"text-[10px] font-mono opacity-60",children:e.slice(0,8)})]})]}),f&&n.jsxs("div",{className:"rounded-lg border border-destructive/30 bg-destructive/10 p-3 flex items-start gap-2",children:[n.jsx(ft,{size:14,className:"text-destructive mt-0.5 shrink-0"}),n.jsx("p",{className:"text-xs text-destructive",children:f})]}),(()=>{const k=a.find(T=>T.state==="playing"),S=a.find(T=>["preparing","ready"].includes(T.state));return!k&&!S?null:n.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[k&&n.jsxs("div",{className:"rounded-xl border border-emerald-500/30 bg-emerald-500/5 px-3 py-2.5",children:[n.jsxs("div",{className:"flex items-center gap-1.5 text-[10px] uppercase tracking-wider text-emerald-700 font-semibold mb-1",children:[n.jsxs("span",{className:"relative flex h-2 w-2",children:[n.jsx("span",{className:"absolute inline-flex h-full w-full animate-ping rounded-full bg-emerald-500 opacity-60"}),n.jsx("span",{className:"relative inline-flex h-2 w-2 rounded-full bg-emerald-500"})]}),"Сейчас говорит · ",k.kind]}
1033),n.jsx("p",{className:"text-xs text-foreground/90 line-clamp-2",children:k.text||"—"})]}),S&&n.jsxs("div",{className:"rounded-xl border border-border/60 bg-muted/30 px-3 py-2.5",children:[n.jsxs("div",{className:"flex items-center gap-1.5 text-[10px] uppercase tracking-wider text-muted-foreground font-semibold mb-1",children:["Дальше · ",S.kind," · ",S.state]}),n.jsx("p",{className:"text-xs text-foreground/80 line-clamp-2",children:S.text||"—"})]})]})})(),n.jsxs("section",{children:[n.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[n.jsx(w4,{size:14,className:"text-muted-foreground"}),n.jsx("h3",{className:"text-sm font-medium text-foreground",children:"Turns"}),n.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["last ",a.length]})]}),n.jsx(nbe,{turns:a,highlightTurnId:y})]}),n.jsx(ybe,{session:m,runtime:o,topics:u,comments:i}),n.jsxs("section",{children:[n.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[n.jsx(a4,{size:14,className:"text-muted-foreground"}),n.jsx("h3",{className:"text-sm font-medium text-foreground",children:"Memory"})]}),n.jsx(abe,{memory:l,facts:c})]}),n.jsxs("section",{children:[n.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[n.jsx(f4,{size:14,className:"text-muted-foreground"}),n.jsx("h3",{className:"text-sm font-medium text-foreground",children:"Topics covered"}),n.jsx("span",{className:"text-[10px] text-muted-foreground",children:u.length})]}),n.jsx(gbe,{topics:u,onScrollToTurn:N})]}),n.jsxs("section",{children:[n.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[n.jsx(N4,{size:14,className:"text-muted-foreground"}),n.jsx("h3",{className:"text-sm font-medium text-foreground",children:"Dialog events"}),n.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["last ",d.length]})]}),n.jsx(pbe,{events:d,onScrollToTurn:N})]}),n.jsxs("section",{children:[n.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[n.jsx(up,{size:14,className:"text-muted-foreground"}),n.jsx("h3",{className:"text-sm font-medium text-foreground",children:"Comments inbox"})]}),n.jsx(dbe,{comments:i,onScrollToTurn:N})]}),n.jsxs("div",{className:"pt-2 border-t border-border/40 flex items-center justify-between gap-3 flex-wrap",children:[b&&n.jsxs("p",{className:"text-xs text-destructive flex items-center gap-1.5",children:[n.jsx(ft,{size:12})," ",b]}),n.jsx("div",{className:"ml-auto",children:n.jsxs(L,{variant:"outline",size:"sm",onClick:_,disabled:g||j,className:"gap-2",children:[g?n.jsx(xe,{size:14,className:"animate-spin"}):n.jsx(S4,{size:14}),j?"Final already requested":"Request graceful end"]})})]})]})}function zT({liveSessionId:e,title:t="Промпты этого эфира",subtitle:s="Точечные правки системных промптов только для этой сессии. Перебивают значения из персоны и глобальные."}){const[r,a]=h.useState({}),[i,o]=h.useState(""),[l,c]=h.useState(""),[d,u]=h.useState(!1),[m,p]=h.useState(!1),[f,g]=h.useState(!1);h.useEffect(()=>{let w=!1;if(e)return I.from("live_sessions").select("metadata_json").eq("id",e).maybeSingle().then(({data:j})=>{if(w)return;const _=(j==null?void 0:j.metadata_json)||{};a(_.prompt_overrides||{});const N=typeof _.live_addendum=="string"?_.live_addendum:"";o(N),c(N),u(!0)}),()=>{w=!0}},[e]);const x=h.useCallback(async w=>{a(w);const{data:j}=await I.from("live_sessions").select("metadata_json").eq("id",e).maybeSingle(),N={...(j==null?void 0:j.metadata_json)||{},prompt_overrides:w};await I.from("live_sessions").update({metadata_json:N}).eq("id",e)},[e]),b=h.useCallback(async()=>{p(!0);try{const{data:w}=await I.from("live_sessions").select("metadata_json").eq("id",e).maybeSingle(),_={...(w==null?void 0:w.metadata_json)||{},live_addendum:i.trim()||null,live_addendum_updated_at:new Date().toISOString()};await I.from("live_sessions").update({metadata_json:_}).eq("id",e),c(i)}finally{p(!1)}},[e,i]),v=h.useCallback(async()=>{g(!0);try{const{data:w,error:j}=await I.from("live_sessions").select("persona_id, title, description, live_mode").eq("id",e).maybeSingle();if(j||!w)throw j||new Error("session_not_found");
1033if(!w.persona_id){Le.error("У эфира нет персоны");return}const{data:_}=await I.from("personas").select("name, language").eq("id",w.persona_id).maybeSingle(),{data:N,error:k}=await I.functions.invoke("generate-auto-messages",{body:{persona_name:(_==null?void 0:_.name)||"Host",persona_id:w.persona_id,language:(_==null?void 0:_.language)||"ru",title:w.title||"",description:w.description||"",session_type:w.live_mode==="webinar"?"webinar":"stream"}});if(k)throw k;if(!(N!=null&&N.greeting))throw new Error("empty_greeting");const S={greeting_text:N.greeting,continue_text:N.continue_talking??null};N.summary&&(S.summary_text=N.summary);const{error:T}=await I.from("live_sessions").update(S).eq("id",e);if(T)throw T;Le.success("Промпт пересобран из персоны — применится к следующим репликам")}catch(w){Le.error(`Не удалось пересоздать: ${(w==null?void 0:w.message)||"ошибка"}`)}finally{g(!1)}},[e]);if(!d)return null;const y=i!==l;return n.jsxs("div",{className:"space-y-4",children:[n.jsxs("div",{className:"rounded-lg border border-primary/30 bg-primary/5 p-4 space-y-3",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(tt,{className:"w-4 h-4 text-primary"}),n.jsxs("div",{children:[n.jsx("div",{className:"font-medium text-sm",children:"Дополнение к промпту (live)"}),n.jsx("div",{className:"text-xs text-muted-foreground",children:"Этот текст добавляется ко всем системным промптам этой сессии при каждом запросе. Используйте для быстрых правок на лету — например «отвечай короче», «не упоминай X», «делай акцент на Y». Применяется сразу к следующим репликам ведущего."})]})]}),n.jsx(Fs,{value:i,onChange:w=>o(w.target.value),rows:4,placeholder:"Например: говори более энергично, упоминай оффер каждые 5 минут, избегай темы политики…"}),n.jsx("div",{className:"flex justify-end",children:n.jsx(L,{size:"sm",onClick:b,disabled:!y||m,children:m?"Сохранение…":y?"Применить к эфиру":"Сохранено"})})]}),n.jsx("div",{className:"rounded-lg border border-border bg-card p-4 space-y-3",children:n.jsxs("div",{className:"flex items-start justify-between gap-3",children:[n.jsxs("div",{children:[n.jsx("div",{className:"font-medium text-sm",children:"Промпт эфира из персоны"}),n.jsx("div",{className:"text-xs text-muted-foreground",children:"Greeting / continue / summary эфира были сгенерированы при создании. Если вы поменяли персону или её промпты — пересоберите их по текущей персоне. Эфир не прерывается, новые тексты применятся к следующим репликам."})]}),n.jsxs(L,{size:"sm",variant:"outline",onClick:v,disabled:f,className:"shrink-0",children:[n.jsx(ss,{className:`w-4 h-4 mr-2 ${f?"animate-spin":""}`}),f?"Пересоздаём…":"Пересоздать из персоны"]})]})}),n.jsx(sT,{overrides:r,onOverridesChange:x,slotFilter:w=>w.startsWith("live.")||w.startsWith("content.")||w.startsWith("webinar."),title:t,subtitle:s})]})}function wbe({session:e,personaName:t,onApprove:s,onReturnToDraft:r,onLaunch:a,acting:i}){const{formatDateShort:o}=or(),{t:l}=Oe("live-center"),c=e.status==="review",d=e.status==="approved",u=e.metadata_json;return n.jsx(de.div,{initial:{opacity:0,y:8},animate:{opacity:1,y:0},className:`rounded-xl border shadow-premium-sm overflow-hidden ${c?"border-amber-200/60 bg-amber-50/5":d?"border-emerald-200/60 bg-emerald-50/5":"border-border/50 bg-surface-elevated"}`,children:n.jsxs("div",{className:"p-4 space-y-3",children:[n.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[n.jsx(yr,{status:e.status}),c&&n.jsxs(fe,{variant:"outline",className:"text-[9px] border-amber-300/50 text-amber-700 gap-1",children:[n.jsx(oi,{size:8})," ",l("review.awaitingReview")]}),d&&n.jsxs(fe,{variant:"outline",className:"text-[9px] border-emerald-300/50 text-emerald-700 gap-1",children:[n.jsx(Od,{size:8})," ",l("review.approvedForLaunch")]})]}),n.jsx("h3",{className:"font-heading font-semibold text-base text-foreground",children:e.title}),e.description&&n.jsx("p",{className:"text-xs text-muted-foreground",children:e.description}),n.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2",children:[n.jsx(To,{icon:Xs,label:l("review.persona"),value:t||l("review.notAssigned")}),n.jsx(To,{icon:St,label:l("review.mode"),value:l(`modesFull.${e.live_mode}`,e.live_mode??"—")}),n.jsx(To,{icon:lu,label:"Q&A",value:l(`chatLabels.${e.chat_reply_mode}`,e.chat_reply_mode??"—")}),n.jsx(To,{icon:Ls,label:l("review.platform"),value:(u==null?void 0:u.stream_source)==="custom_rtmp"?"Custom RTMP":e.platform??"YouTube"}),e.scheduled_at&&n.jsx(To,{icon:ls,label:l("review.scheduled"),value:o(e.scheduled_at)}),(u==null?void 0:u.planned_duration_min)&&n.jsx(To,{icon:ls,label:l("review.duration"),value:l("review.durationMin",{min:u.planned_duration_min})})]}),(c||d)&&n.jsxs("div",{className:"flex flex-wrap gap-2 pt-1",children:[c&&n.jsxs(n.Fragment,{children:[n.jsxs(L,{size:"sm",className:"gap-1.5 text-xs h-8",onClick:()=>s(e.id),disabled:i,children:[n.jsx(wt,{size:12})," ",l("review.approve")]}),n.jsxs(L,{size:"sm",variant:"outline",className:"gap-1.5 text-xs h-8",onClick:()=>r(e.id),disabled:i,children:[n.jsx(Hi,{size:12})," ",l("review.returnToDraft")]})]}),d&&n.jsxs(n.Fragment,{children:[n.jsxs(L,{size:"sm",variant:"hero",className:"gap-1.5 text-xs h-8",onClick:()=>a(e.id),disabled:i,children:[n.jsx(Ld,{size:12})," ",l("review.launch")]}),n.jsxs(L,{size:"sm",variant:"outline",className:"gap-1.5 text-xs h-8",onClick:()=>r(e.id),disabled:i,children:[n.jsx(Hi,{size:12})," ",l("review.returnToDraft")]})]})]})]})})}function To({icon:e,label:t,value:s}){return n.jsxs("div",{className:"rounded-lg bg-muted/20 p-2.5",children:[n.jsxs("div",{className:"flex items-center gap-1 text-[9px] text-muted-foreground font-semibold uppercase tracking-wider mb-0.5",children:[n.jsx(e,{size:9})," ",t]}),n.jsx("p",{className:"text-xs font-medium text-foreground truncate",children:s})]})}const jbe="production",_be=()=>jbe==="test";function kbe(){return Oe("common"),null}function Nbe({compact:e=!1}){return Oe("common"),null}const Jf="simulator.activeSessionId";function Sbe(){const{t:e}=Oe("common"),{profile:t}=st(),{personas:s,loading:r}=wi(),[a,i]=h.useState(""),[o,l]=h.useState("free_live"),[c,d]=h.useState(""),[u,m]=h.useState(""),[p,f]=h.useState(!1),[g,x]=h.useState(null),[b,v]=h.useState(null),[y,w]=h.useState(!1),[j,_]=h.useState(null),[N,k]=h.useState(""),[S,T]=h.useState("Viewer"),[C,B]=h.useState(!1),E=h.useRef(null),H=h.useRef(null);h.useEffect(()=>{const $=localStorage.getItem(Jf);$&&x($)},[]),h.useEffect(()=>{g?localStorage.setItem(Jf,g):localStorage.removeItem(Jf)},[g]),h.useEffect(()=>{I.auth.getSession().then(({data:J})=>{var Y;H.current=((Y=J.session)==null?void 0:Y.access_token)??null});const{data:$}=I.auth.onAuthStateChange((J,Y)=>{H.current=(Y==null?void 0:Y.access_token)??null});return()=>$.subscription.unsubscribe()},[]),h.useEffect(()=>{if(!g)return;const $=()=>{fetch("https://nfqxajdgklseicehjolk.supabase.co/functions/v1/simulator",{method:"POST",keepalive:!0,headers:{"Content-Type":"application/json",...H.current?{Authorization:`Bearer ${H.current}`}:{}},body:JSON.stringify({action:"end",live_session_id:g})}).catch(()=>{})};return window.addEventListener("beforeunload",$),()=>window.removeEventListener("beforeunload",$)},[g]),h.useEffect(()=>{if(!C||!g)return;const $=async()=>{await z("tick",{live_session_id:g}).catch(()=>{})};return E.current=window.setInterval($,12e3),()=>{E.current&&window.clearInterval(E.current)}},[C,g]);async function z($,J={}){const{data:Y,error:re}=await I.functions.invoke("simulator",{body:{action:$,...J}});if(re||Y!=null&&Y.error)throw new Error((Y==null?void 0:Y.error)||(re==null?void 0:re.message)||"Simulator error");return Y}const ne=async()=>
1033{if(a){_(null),w(!0);try{let $=null;if(o==="webinar"&&c.trim()){f(!0);try{const{data:Y,error:re}=await I.functions.invoke("parse-webinar-plan",{body:{plan_text:c}});if(re||Y!=null&&Y.error)throw new Error((Y==null?void 0:Y.error)||(re==null?void 0:re.message));$=(Y==null?void 0:Y.blocks)||null}finally{f(!1)}}const J=await z("start",{persona_id:a,live_mode:o,webinar_plan:o==="webinar"?c:null,webinar_plan_json:$,topic_query:o==="nonstop_trends"?u:null});x(J.live_session_id),v(new Date().toISOString())}catch($){_($.message)}finally{w(!1)}}},V=async()=>{if(g){w(!0),_(null);try{await z("tick",{live_session_id:g})}catch($){const J=$.message||"Simulator error";_(J),J.includes("session_not_found")&&(x(null),v(null),B(!1))}finally{w(!1)}}},te=async()=>{if(!(!g||!N.trim())){w(!0),_(null);try{await z("inject_comment",{live_session_id:g,text:N.trim(),author_name:S.trim()||"Viewer"}),k("")}catch($){_($.message)}finally{w(!1)}}},R=async()=>{if(g&&confirm("End simulation and wipe all data?")){w(!0),_(null);try{await z("end",{live_session_id:g}),x(null),v(null),B(!1)}catch($){const J=$.message||"Simulator error";J.includes("session_not_found")?(x(null),v(null),B(!1)):_(J)}finally{w(!1)}}},F=s.find($=>$.id===a);return n.jsxs("div",{className:"space-y-6",children:[n.jsx("p",{className:"text-sm text-muted-foreground",children:e("simulator.subtitle","Test how your persona behaves in a live broadcast. Inject comments, ask for continuations, observe memory and topic threading. Everything is wiped on End.")}),j&&n.jsxs(de.div,{...Te(.02),className:"rounded-xl border border-destructive/30 bg-destructive/10 p-4 flex items-start gap-3",children:[n.jsx(ft,{size:18,className:"text-destructive mt-0.5 shrink-0"}),n.jsx("div",{className:"flex-1",children:n.jsx("p",{className:"text-sm font-medium text-destructive",children:j})}),n.jsx("button",{onClick:()=>_(null),className:"text-xs text-muted-foreground hover:text-foreground",children:"×"})]}),n.jsxs(de.div,{...Te(.04),className:"rounded-2xl bg-surface-elevated border border-border/50 shadow-premium-sm p-6 space-y-4",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(fe,{variant:g?"default":"outline",className:"text-[10px]",children:g?e("simulator.running","Running"):e("simulator.idle","Idle")}),g&&n.jsx("span",{className:"text-[10px] font-mono opacity-60",children:g.slice(0,8)})]}),g?n.jsxs("div",{className:"space-y-4",children:[n.jsxs("div",{className:"flex flex-wrap gap-2",children:[n.jsxs(L,{onClick:V,disabled:y,variant:"default",className:"gap-2",children:[y?n.jsx(xe,{size:16,className:"animate-spin"}):n.jsx(ss,{size:16}),e("simulator.continue","Continue (next turn)")]}),n.jsx(L,{onClick:()=>B($=>!$),disabled:y,variant:C?"secondary":"outline",children:C?e("simulator.autoOn","Auto: ON (12s)"):e("simulator.autoOff","Auto: OFF")}),n.jsxs(L,{onClick:R,disabled:y,variant:"destructive",className:"gap-2 ml-auto",children:[n.jsx(du,{size:16}),e("simulator.end","End & wipe")]})]}),n.jsxs("div",{className:"rounded-xl border border-border/40 bg-background p-4 space-y-3",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(_4,{size:16,className:"text-muted-foreground"}),n.jsx("h3",{className:"text-sm font-medium",children:e("simulator.injectComment","Inject viewer comment")})]}),n.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-[160px_1fr_auto] gap-2",children:[n.jsx(gt,{value:S,onChange:$=>T($.target.value),placeholder:"Author name",className:"text-sm"}),n.jsx(Fs,{value:N,onChange:$=>k($.target.value),placeholder:"What does the viewer say?",className:"min-h-[44px] text-sm resize-none",rows:1,onKeyDown:$=>{$.key==="Enter"&&!$.shiftKey&&($.preventDefault(),te())}}),n.jsx(L,{onClick:te,disabled:y||!N.trim(),className:"gap-2",children:n.jsx(Za,{size:14})})]}),n.jsx("p",{className:"text-[10px] text-muted-foreground",children:e("simulator.commentHint","Comments queue up. On the next 'Continue' the director will pick them and reply.")})]})]}):n.jsxs("div",{className:"space-y-4",children:[n.jsxs("div",{className:"space-y-2",children:[n.jsx(Jt,{children:"Mode"}),n.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-2",children:[{id:"free_live",icon:St,title:"Free live",desc:"Болтает со зрителями"},{id:"nonstop_trends",icon:Ol,title:"Trends",desc:"Сама берёт горячие темы"},{id:"webinar",icon:dp,title:"Webinar",desc:"Идёт по твоему плану"}].map(({id:$,icon:J,title:Y,desc:re})=>{const G=o===$;return n.jsxs("button",{type:"button",onClick:()=>l($),className:`text-left rounded-xl border p-3 transition-all ${G?"border-primary bg-primary/5 shadow-premium-sm":"border-border/50 bg-muted/20 hover:border-border"}`,children:[n.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[n.jsx(J,{size:16,className:G?"text-primary":"text-muted-foreground"}),n.jsx("div",{className:"text-sm font-medium text-foreground",children:Y})]}),n.jsx("div",{className:"text-[11px] text-muted-foreground leading-snug",children:re})]},$)})})]}),n.jsxs("div",{className:"space-y-2",children:[n.jsx(Jt,{children:e("simulator.persona","Persona")}),n.jsxs(ut,{value:a,onValueChange:i,children:[n.jsx(ct,{children:n.jsx(ht,{placeholder:r?"Loading...":"Select persona"})}),n.jsx(dt,{children:s.map($=>n.jsxs(ce,{value:$.id,children:[$.name," ",$.language?`(${$.language})`:""]},$.id))})]})]}),o==="webinar"&&n.jsxs("div",{className:"space-y-2",children:[n.jsx(Jt,{children:"План вебинара (свободный текст — распарсится в блоки)"}),n.jsx(Fs,{value:c,onChange:$=>d($.target.value),placeholder:"Например: 1. Введение — кто я и о чём поговорим. 2. Главный кейс — пошагово. 3. Q&A.",className:"min-h-[120px] text-sm"})]}),o==="nonstop_trends"&&n.jsxs("div",{className:"space-y-2",children:[n.jsx(Jt,{children:"Тематика трендов (опционально)"}),n.jsx(gt,{value:u,onChange:$=>m($.target.value),placeholder:"например: AI, fitness, crypto"})]}),n.jsxs(L,{onClick:ne,disabled:!a||y||p,className:"gap-2",children:[y||p?n.jsx(xe,{size:16,className:"animate-spin"}):n.jsx(en,{size:16}),p?"Парсим план...":e("simulator.start","Start simulation")]})]})]}),g&&(t==null?void 0:t.workspace_id)&&n.jsx(MT,{liveSessionId:g,workspaceId:t.
1033workspace_id,startedAt:b,personaName:F==null?void 0:F.name})]})}const Cbe=()=>{const{t:e}=Oe("live-center"),[t,s]=tu(),r=t.get("mode")==="sim"?"sim":"live",a=ie=>{const we=new URLSearchParams(t);ie==="sim"?we.set("mode","sim"):we.delete("mode"),s(we,{replace:!0})},{profile:i}=st(),{sessions:o,upcoming:l,active:c,history:d,loading:u,refresh:m,create:p,updateStatus:f,patchSession:g}=uo(),{status:x,error:b,startConnect:v}=lo(),{active:y,jobsForEntity:w,create:j}=ho(),{planKey:_}=ar(),{personas:N}=wi(),[k,S]=h.useState(!1),[T,C]=h.useState(!1),[B,E]=h.useState(null),[H,z]=h.useState(null),[ne,V]=h.useState(null),te=o.filter(ie=>ie.status==="failed"),{t:R}=Oe("common"),F=kp({t:R,ytStatus:x,ytError:b,onYtReconnect:v,failedLiveSessions:te}),$=async ie=>{S(!0);const we=await p(ie);return S(!1),we},J=o.filter(ie=>ie.status==="review"),Y=o.filter(ie=>ie.status==="approved"),re=c??l,G=ie=>{var we;return(we=N.find(Ae=>Ae.id===ie))==null?void 0:we.name},O=async ie=>{C(!0),await f(ie,"review"),C(!1)},Z=async ie=>{C(!0),await f(ie,"approved"),C(!1)},A=async ie=>{C(!0),await f(ie,"draft"),C(!1)},oe=async(ie,we)=>{var U,Q,ve,We,Ze;C(!0),E(null),z(null);const Ae=we??o.find(Je=>Je.id===ie);if(!(Ae!=null&&Ae.persona_id)){E("Persona is required to launch a live session."),C(!1);return}const Qe=(Ae.metadata_json||{}).stream_source||(Ae.platform==="restream"?"restream":"youtube"),P=Qe==="custom_rtmp"||Qe==="restream";try{if(P)console.log(`[LiveCenter] ${Qe} flow — skipping YouTube broadcast creation`);else{try{await I.functions.invoke("sync-live-meta",{body:{live_session_id:ie}})}catch(he){console.warn("[LiveCenter] sync-live-meta pre-launch failed:",he)}const se=await I.functions.invoke("youtube-live",{body:{action:"create_live",live_session_id:ie}});if((U=se.data)!=null&&U.active_session_id){z(se.data.active_session_id),E(e("conflictError")),C(!1);return}if((Q=se.data)!=null&&Q.quota_exceeded){E(e("quotaExceeded")),C(!1);return}if(se.error||(ve=se.data)!=null&&ve.error)throw new Error(((We=se.data)==null?void 0:We.error)||((Ze=se.error)==null?void 0:Ze.message)||"YouTube broadcast creation failed");console.log("[LiveCenter] YouTube broadcast created:",se.data)}const Je=new Date().toISOString(),{error:xt}=await I.from("live_sessions").update({status:"live",started_at:Je}).eq("id",ie).in("status",["draft","scheduled","ready","review","approved"]);if(xt){console.error("[LiveCenter] mark live failed:",xt),E(xt.message),C(!1);return}g(ie,{status:"live",started_at:Je});const Pt=Ae!=null&&Ae.persona_id?N.find(se=>se.id===Ae.persona_id):null,K=(Pt==null?void 0:Pt.prompt_config)||{},ye={background_restore:K.background_restore??.5,face_restore:K.face_restore??.5},{data:De}=await I.from("jobs").select("id, status, payload_json").eq("workspace_id",(i==null?void 0:i.workspace_id)||"").eq("job_type",ql.CONDUCT_LIVE_SESSION).in("status",["queued","running"]),pt=(De||[]).find(se=>{var he;return((he=se.payload_json)==null?void 0:he.live_session_id)===ie});if(pt){console.warn("[LiveCenter] Duplicate launch suppressed — job already exists:",pt.id),m(),C(!1);return}const kt=(Ae==null?void 0:Ae.metadata_json)||{},X=kt.live_subtitles!==!1,M=typeof kt.watermark_text=="string"?kt.watermark_text.trim().slice(0,120):"";await j({job_type:ql.CONDUCT_LIVE_SESSION,persona_id:(Ae==null?void 0:Ae.persona_id)||null,payload_json:{live_session_id:ie,plan_key:_||"free",filters:ye,live_subtitles:X,...M?{watermark_text:M}:{}}}),m()}catch(Je){console.error("[LiveCenter] Launch failed:",Je),E(Je.message||"Launch failed"),await f(ie,"approved")}C(!1)},ue=async ie=>{var P,U,Q;C(!0);const we=o.find(ve=>ve.id===ie),nt=((we==null?void 0:we.metadata_json)||{}).stream_source||((we==null?void 0:we.platform)==="restream"?"restream":"youtube"),Qe=nt==="custom_rtmp"||nt==="restream";try{if(Qe)await f(ie,"ended");else{const ve=await I.functions.invoke("youtube-live",{body:{action:"end_live",live_session_id:ie}});if(ve.error||(P=ve.data)!=null&&P.error)throw new Error(((U=ve.data)==null?void 0:U.error)||((Q=ve.error)==null?void 0:Q.message)||"Failed to end stream");console.log("[LiveCenter] Stream ended:",ve.data)}await m()}catch(ve){console.error("[LiveCenter] End stream failed:",ve),E(ve.message||"Failed to end stream")}C(!1)},je=async ie=>{if(ie!=null&&ie.id){V(ie.id),E(null);try{const{data:we,error:Ae}=await I.functions.invoke("live-session-continue",{body:{live_session_id:ie.id}});if(Ae||we!=null&&we.error||!(we!=null&&we.new_session_id))throw new Error((we==null?void 0:we.error)||(Ae==null?void 0:Ae.message)||"Continue failed");await m(),await oe(we.new_session_id,we.session)}catch(we){console.error("[LiveCenter] Continue failed:",we),E(we.message||"Continue failed")}finally{V(null)}}};if(u)return n.jsx("div",{className:"flex items-center justify-center min-h-[400px]",children:n.jsx(xe,{className:"w-6 h-6 animate-spin text-primary"})});const ae=n.jsxs("div",{className:"inline-flex items-center rounded-xl border border-border/60 bg-surface-elevated p-1 shadow-premium-sm",children:[n.jsxs("button",{type:"button",onClick:()=>a("live"),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium transition-all ${r==="live"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[n.jsx(St,{size:13})," В эфир"]}),n.jsxs("button",{type:"button",onClick:()=>a("sim"),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium transition-all ${r==="sim"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[n.jsx(Rx,{size:13})," Симуляция"]}
1033)]});return n.jsxs("div",{className:"max-w-6xl mx-auto space-y-8",children:[n.jsxs(de.div,{...Te(),className:"flex items-center justify-between gap-3 flex-wrap",children:[n.jsxs("h1",{className:"font-heading font-bold text-2xl md:text-3xl text-foreground flex items-center gap-2",children:[r==="sim"?n.jsx(Rx,{className:"text-primary",size:24}):n.jsx(St,{className:"text-primary",size:24}),r==="sim"?"Симулятор персоны":e("pageTitle")]}),ae]}),r==="sim"?n.jsx(Sbe,{}):n.jsx(Tbe,{launchError:B,conflictSessionId:H,acting:T,setActing:C,setLaunchError:E,setConflictSessionId:z,handleEndLive:ue,liveAlerts:F,heroSession:re,handleSendToReview:O,reviewSessions:J,approvedSessions:Y,handleApprove:Z,handleReturnToDraft:A,handleLaunch:oe,active:c,profile:i,getPersonaName:G,handleCreate:$,saving:k,history:d,loading:u,handleContinue:je,continuingId:ne,t:e})]})};function Tbe(e){const{launchError:t,conflictSessionId:s,acting:r,setActing:a,setLaunchError:i,setConflictSessionId:o,handleEndLive:l,liveAlerts:c,heroSession:d,handleSendToReview:u,reviewSessions:m,approvedSessions:p,handleApprove:f,handleReturnToDraft:g,handleLaunch:x,active:b,profile:v,getPersonaName:y,handleCreate:w,saving:j,history:_,loading:N,handleContinue:k,continuingId:S,t:T}=e;return n.jsxs(n.Fragment,{children:[t&&n.jsxs(de.div,{...Te(.02),className:"rounded-xl border border-destructive/30 bg-destructive/10 p-4 flex items-start gap-3",children:[n.jsx(ft,{size:18,className:"text-destructive mt-0.5 shrink-0"}),n.jsxs("div",{className:"flex-1",children:[n.jsx("p",{className:"text-sm font-medium text-destructive",children:T("launchError")}),n.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:t})]}),s&&n.jsx("button",{onClick:async()=>{a(!0),await l(s),i(null),o(null),a(!1)},disabled:r,className:"shrink-0 rounded-lg bg-destructive text-destructive-foreground px-3 py-1.5 text-xs font-medium hover:bg-destructive/90 disabled:opacity-50 transition-colors",children:T(r?"hero.endingStream":"conflictEndBtn")})]}),n.jsx(Nbe,{compact:!0}),n.jsx(_p,{alerts:c,title:T("errorsTitle")}),n.jsx(E2,{session:d,onCreateClick:()=>{},onSendToReview:d&&["scheduled","ready"].includes(d.status)?()=>u(d.id):void 0,onLaunch:d&&["approved","ready"].includes(d.status)?()=>x(d.id):void 0,onEndLive:(d==null?void 0:d.status)==="live"?()=>l(d.id):void 0,acting:r}),d&&["scheduled","ready","review","approved","live"].includes(d.status)&&n.jsx(de.div,{...Te(.06),className:"rounded-2xl bg-surface-elevated border border-border/50 shadow-premium-sm p-5",children:n.jsx(x6,{sessionStatus:d.status})}),d&&n.jsx(zT,{liveSessionId:d.id}),b&&(v==null?void 0:v.workspace_id)&&n.jsx(MT,{liveSessionId:b.id,workspaceId:v.workspace_id,startedAt:b.started_at,personaName:y(b.persona_id)}),n.jsx(kB,{}),(m.length>0||p.length>0)&&n.jsxs(de.div,{...Te(.08),className:"rounded-2xl bg-surface-elevated border border-amber-200/40 shadow-premium-sm p-6 space-y-4",children:[n.jsxs("h2",{className:"font-heading font-semibold text-lg text-foreground flex items-center gap-2",children:[n.jsx(oi,{size:18,className:"text-amber-500"})," ",T("reviewTitle"),n.jsx(fe,{variant:"outline",className:"text-[10px] ml-1",children:m.length+p.length})]}),n.jsx("div",{className:"space-y-3",children:[...m,...p].map(C=>n.jsx(wbe,{session:C,personaName:y(C.persona_id),onApprove:f,onReturnToDraft:g,onLaunch:x,acting:r},C.id))})]}),n.jsx(_B,{onCreate:w,saving:j}),n.jsx(Zye,{sessions:_,loading:N,onContinue:k,continuingId:S})]})}const Pbe=[{key:"ytGrowth",icon:Ls,status:"active",link:"/app/integrations"},{key:"memberLayer",icon:eo,status:"soon",link:""},{key:"patreonSubs",icon:co,status:"setup",link:"/app/integrations"},{key:"paidLive",icon:St,status:"setup",link:"/app/webinars"},{key:"webinars",icon:Ja,status:"setup",link:"/app/webinars"},{key:"consultations",icon:Zs,status:"setup",link:"/app/consultations"},{key:"archive",icon:ii,status:"soon",link:""},{key:"courses",icon:Cy,status:"soon",link:""}],Zf=[{key:"shorts",icon:Ns},{key:"freeLive",icon:St},{key:"clips",icon:ii},{key:"repeatViewers",icon:eo},{key:"patreon",icon:co},{key:"webinars",icon:Ja},{key:"consultations",icon:Zs}],Ebe=()=>{const{t:e}=Oe("monetization"),{status:t}=lo(),{status:s}=Cp(),{items:r,loading:a}=nT(),{sessions:i,loading:o}=uo();if(a||o)return n.jsx(Ln,{message:e("loading")});const l=t==="connected",c=s==="connected",d=r.some(g=>g.content_type==="short"),u=i.length>0,m=[{label:e("readiness.channelCreated"),done:l},{label:e("readiness.shortsPublished"),done:d},{label:e("readiness.liveRunning"),done:u},{label:e("readiness.audienceForming"),done:d&&u},{label:e("readiness.patreonConnected"),done:c},{label:e("readiness.premiumLaunched"),done:!1}],p=m.filter(g=>g.done).length,f={active:{label:e("statusActive"),cls:"bg-emerald-50 text-emerald-600"},setup:{label:e("statusSetup"),cls:""},soon:{label:e("statusSoon"),cls:"bg-muted/50 text-muted-foreground"}};
1033return n.jsxs("div",{className:"max-w-6xl mx-auto space-y-8",children:[n.jsx(de.div,{...Te(),children:n.jsxs("h1",{className:"font-heading font-bold text-2xl md:text-3xl text-foreground flex items-center gap-2",children:[n.jsx(ky,{className:"text-primary",size:24}),e("pageTitle")]})}),n.jsxs(de.div,{...Te(.05),className:"rounded-2xl bg-surface-elevated border border-border/50 shadow-premium-sm p-6 space-y-5",children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("h2",{className:"font-heading font-semibold text-lg text-foreground flex items-center gap-2",children:[n.jsx(uu,{size:18,className:"text-primary"})," ",e("readinessTitle")]}),n.jsxs("span",{className:"text-xs font-semibold text-muted-foreground",children:[p,"/",m.length]})]}),n.jsx("div",{className:"h-2 rounded-full bg-muted/50 overflow-hidden",children:n.jsx(de.div,{initial:{width:0},animate:{width:`${p/m.length*100}%`},transition:{duration:.8,delay:.2},className:"h-full rounded-full bg-gradient-primary"})}),n.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-3 gap-x-6 gap-y-2",children:m.map((g,x)=>n.jsxs("div",{className:"flex items-center gap-2",children:[g.done?n.jsx(wt,{size:16,className:"text-primary"}):n.jsx(Ll,{size:16,className:"text-muted-foreground/40"}),n.jsx("span",{className:`text-sm ${g.done?"text-foreground font-medium":"text-muted-foreground"}`,children:g.label})]},x))})]}),n.jsxs(de.div,{...Te(.1),className:"space-y-4",children:[n.jsxs("h2",{className:"font-heading font-semibold text-lg text-foreground flex items-center gap-2",children:[n.jsx(tt,{size:18,className:"text-primary"})," ",e("cardsTitle")]}),n.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-4 gap-3",children:Pbe.map(g=>{const x=f[g.status];return n.jsxs("div",{className:"group rounded-2xl border border-border/50 bg-surface-elevated shadow-premium-sm p-5 flex flex-col hover:shadow-premium-md hover:border-primary/20 transition-all duration-200",children:[n.jsx("div",{className:"w-10 h-10 rounded-xl bg-primary/10 flex items-center justify-center text-primary mb-3 group-hover:bg-primary/15 transition-colors",children:n.jsx(g.icon,{size:20})}),n.jsx("h3",{className:"font-heading font-semibold text-sm text-foreground",children:e(`cards.${g.key}.title`)}),n.jsx("p",{className:"text-[11px] text-muted-foreground mt-1 leading-relaxed flex-1",children:e(`cards.${g.key}.desc`)}),n.jsx("div",{className:"mt-3",children:g.status==="setup"&&g.link?n.jsx(L,{variant:"hero-outline",size:"sm",className:"h-7 text-[11px] gap-1 w-full",asChild:!0,children:n.jsxs(zt,{to:g.link,children:[e("statusSetup")," ",n.jsx(yn,{size:12})]})}):n.jsx("span",{className:`inline-block text-[10px] font-semibold px-2.5 py-0.5 rounded-full ${x.cls}`,children:x.label})})]},g.key)})})]}),n.jsxs(de.div,{...Te(.15),className:"rounded-2xl bg-surface-elevated border border-border/50 shadow-premium-sm p-6 space-y-5",children:[n.jsx("h2",{className:"font-heading font-semibold text-lg text-foreground",children:e("launchTitle")}),n.jsx("div",{className:"hidden md:flex items-center justify-between gap-1",children:Zf.map((g,x)=>n.jsxs("div",{className:"flex items-center gap-1 flex-1",children:[n.jsxs("div",{className:"flex flex-col items-center text-center flex-1",children:[n.jsx("div",{className:`w-11 h-11 rounded-xl flex items-center justify-center mb-2 ${x<2?"bg-primary/10 text-primary":"bg-muted/40 text-muted-foreground"}`,children:n.jsx(g.icon,{size:20})}),n.jsx("span",{className:`text-[11px] font-semibold leading-tight ${x<2?"text-foreground":"text-muted-foreground"}`,children:e(`launchSteps.${g.key}`)}),n.jsx("span",{className:"text-[9px] text-muted-foreground/60 mt-0.5",children:e("step",{n:x+1})})]}),x<Zf.length-1&&n.jsx(Tr,{size:14,className:"text-border shrink-0 mb-6"})]},g.key))}),n.jsx("div",{className:"md:hidden space-y-2",children:Zf.map((g,x)=>n.jsxs("div",{className:`flex items-center gap-3 rounded-xl border px-4 py-3 ${x<2?"border-primary/20 bg-primary/[0.03]":"border-border/40 bg-muted/10"}`,children:[n.jsx("span",{className:"text-[10px] font-bold text-muted-foreground w-5",children:x+1}),n.jsx(g.icon,{size:16,className:x<2?"text-primary":"text-muted-foreground"}),n.jsx("span",{className:`text-sm font-medium ${x<2?"text-foreground":"text-muted-foreground"}`,children:e(`launchSteps.${g.key}`)})]},g.key))})]})]})},kc="content.youtube_comment_reply";function Abe(){const{profile:e,user:t}=st(),s=e==null?void 0:e.workspace_id,[r,a]=h.useState(""),[i,o]=h.useState([]),[l,c]=h.useState(""),[d,u]=h.useState(!1),[m,p]=h.useState(!0),[f,g]=h.useState(!1),[x,b]=h.useState(null);h.useEffect(()=>{if(!s)return;let w=!1;return p(!0),(async()=>{const[{data:j},{data:_}]=await Promise.all([I.from("prompt_templates").select("body, variables").eq("slot_key",kc).maybeSingle(),I.from("workspace_prompt_overrides").select("body").eq("workspace_id",s).eq("slot_key",kc).maybeSingle()]);w||(a((j==null?void 0:j.body)||""),o(Array.isArray(j==null?void 0:j.variables)?j.variables:[]),_!=null&&_.body&&_.body.trim()?(c(_.body),u(!0)):(c((j==null?void 0:j.body)||""),u(!1)),p(!1))})(),()=>{w=!0}},[s]);const v=async()=>
1033{if(!s||!t)return;g(!0);const w=l.trim();!w||w===r.trim()?(await I.from("workspace_prompt_overrides").delete().eq("workspace_id",s).eq("slot_key",kc),u(!1),c(r)):(await I.from("workspace_prompt_overrides").upsert({workspace_id:s,slot_key:kc,body:w,updated_by:t.id},{onConflict:"workspace_id,slot_key"}),u(!0)),g(!1),b(Date.now()),setTimeout(()=>b(null),2500)},y=async()=>{s&&(g(!0),await I.from("workspace_prompt_overrides").delete().eq("workspace_id",s).eq("slot_key",kc),u(!1),c(r),g(!1),b(Date.now()),setTimeout(()=>b(null),2500))};return n.jsx(de.div,{...Te(.08),className:"rounded-2xl bg-surface-elevated border border-border/50 shadow-premium-sm overflow-hidden md:col-span-2",children:n.jsxs("div",{className:"p-6 space-y-4",children:[n.jsxs("div",{className:"flex items-start justify-between gap-4",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("div",{className:"w-12 h-12 rounded-xl bg-red-50 flex items-center justify-center",children:n.jsx(up,{size:22,className:"text-red-500"})}),n.jsxs("div",{children:[n.jsx("h2",{className:"font-heading font-bold text-lg text-foreground",children:"Авто-ответы на комменты YouTube"}),n.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Один промпт на весь аккаунт. От лица владельца канала, не персон."})]})]}),d?n.jsx("span",{className:"text-[10px] uppercase tracking-wider rounded-full bg-primary/10 text-primary px-2 py-0.5 font-medium shrink-0",children:"свой промпт"}):n.jsx("span",{className:"text-[10px] uppercase tracking-wider rounded-full bg-muted text-muted-foreground px-2 py-0.5 font-medium shrink-0",children:"дефолтный"})]}),n.jsx("p",{className:"text-sm text-muted-foreground leading-relaxed",children:"Этот промпт используется для автоматических ответов на комментарии под всеми твоими Shorts и видео. Отвечает от имени канала — единый стиль для всех персон."}),m?n.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground py-4",children:[n.jsx(xe,{size:14,className:"animate-spin"})," Загружаю…"]}):n.jsxs(n.Fragment,{children:[n.jsx(Fs,{value:l,onChange:w=>c(w.target.value),placeholder:r,className:"bg-muted/20 min-h-[280px] text-xs font-mono resize-y"}),i.length>0&&n.jsxs("div",{className:"flex flex-wrap gap-1",children:[n.jsx("span",{className:"text-[10px] text-muted-foreground mr-1",children:"Доступные переменные:"}),i.map(w=>n.jsx("code",{className:"text-[10px] bg-muted px-1.5 py-0.5 rounded font-mono",children:`{{${w}}}`},w))]}),n.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 pt-2",children:[n.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-muted-foreground",children:[n.jsx(tt,{size:12,className:"text-primary"}),"gemini-3-flash · ~280 символов · человеческий стиль"]}),n.jsxs("div",{className:"flex items-center gap-2",children:[x&&n.jsx("span",{className:"text-[11px] text-emerald-600",children:"сохранено"}),d&&n.jsxs(L,{size:"sm",variant:"ghost",className:"gap-1.5 text-xs",onClick:y,disabled:f,children:[n.jsx(hp,{size:13})," К дефолтному"]}),n.jsxs(L,{size:"sm",variant:"hero",className:"gap-1.5",onClick:v,disabled:f||m,children:[f?n.jsx(xe,{size:13,className:"animate-spin"}):n.jsx(Id,{size:13}),"Сохранить"]})]})]})]})]})})}const Rbe=()=>{const{t:e}=Oe("integrations"),{formatNumber:t}=or();st();const{status:s,channel:r,loading:a,error:i,startConnect:o,disconnect:l}=lo(),{status:c,creator:d,loading:u,error:m,startConnect:p,disconnect:f}=Cp(),{status:g,account:x,loading:b,error:v,startConnect:y,disconnect:w}=nS(),{status:j,account:_,loading:N,error:k,startConnect:S,disconnect:T,availableAdAccounts:C,availablePages:B,updateSelection:E}=eb(),[H,z]=h.useState(null),{status:ne,account:V,loading:te,error:R,startConnect:F,disconnect:$,availableCustomers:J,updateSelection:Y}=tb(),[re,G]=h.useState(!1),O=Tp(),Z=s==="connected",A=s==="connecting",oe=s==="expired",ue=s==="error",je=(ae,ie)=>ie?e("statusLoading"):{connected:e("statusConnected"),connecting:e("statusConnecting"),expired:e("statusExpired"),error:e("statusError")}[ae]||e("statusNotConnected");
1033return n.jsxs("div",{className:"max-w-5xl mx-auto space-y-8",children:[n.jsx(de.div,{...Te(),children:n.jsxs("h1",{className:"font-heading font-bold text-2xl md:text-3xl text-foreground flex items-center gap-2",children:[n.jsx(Pr,{className:"text-primary",size:24}),e("pageTitle")]})}),n.jsxs("div",{className:"grid md:grid-cols-2 gap-5",children:[n.jsx(de.div,{...Te(.05),className:"rounded-2xl bg-surface-elevated border border-border/50 shadow-premium-sm overflow-hidden",children:n.jsxs("div",{className:"p-6 space-y-4",children:[n.jsxs("div",{className:"flex items-start justify-between",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("div",{className:"w-12 h-12 rounded-xl bg-red-50 flex items-center justify-center",children:n.jsx(Ls,{size:24,className:"text-red-500"})}),n.jsxs("div",{children:[n.jsx("h2",{className:"font-heading font-bold text-lg text-foreground",children:"YouTube"}),n.jsx("p",{className:"text-[11px] text-muted-foreground",children:e("publicPlatform")})]})]}),n.jsx(fe,{variant:Z?"default":ue||oe?"destructive":"secondary",className:"text-[10px]",children:je(s,a)})]}),Z&&r&&n.jsxs("div",{className:"flex items-center gap-3 rounded-xl border border-emerald-200/50 bg-emerald-50/30 px-4 py-3",children:[r.thumbnail&&n.jsx("img",{src:r.thumbnail,alt:"",className:"w-10 h-10 rounded-full object-cover"}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("p",{className:"text-sm font-semibold text-foreground truncate",children:r.title}),n.jsxs("p",{className:"text-[11px] text-muted-foreground",children:[r.handle?`@${r.handle}`:r.id,r.subscriberCount&&` · ${t(Number(r.subscriberCount))}`]})]}),n.jsx(wt,{size:18,className:"text-emerald-500 shrink-0"})]}),(ue||oe)&&n.jsxs("div",{className:"flex items-center gap-3 rounded-xl border border-amber-200/50 bg-amber-50/30 px-4 py-3",children:[n.jsx(ft,{size:18,className:"text-amber-500 shrink-0"}),n.jsxs("div",{className:"flex-1",children:[n.jsx("p",{className:"text-sm font-semibold text-foreground",children:e(oe?"tokenExpired":"connectionError")}),n.jsx("p",{className:"text-[11px] text-muted-foreground",children:i||e("reconnectNote")})]})]}),n.jsx("p",{className:"text-sm text-muted-foreground leading-relaxed",children:e(Z?"yt.connectedDesc":"yt.disconnectedDesc")}),n.jsx("div",{className:"grid grid-cols-2 gap-2",children:e("yt.features",{returnObjects:!0}).map(ae=>n.jsxs("div",{className:"flex items-center gap-2 rounded-lg bg-muted/20 px-3 py-2",children:[n.jsx(Ns,{size:13,className:"text-red-400 shrink-0"}),n.jsx("span",{className:"text-[11px] text-foreground font-medium leading-tight",children:ae})]},ae))}),n.jsx("div",{className:"flex gap-2",children:Z?n.jsxs(n.Fragment,{children:[n.jsxs(L,{variant:"secondary",className:"flex-1 gap-2",disabled:!0,children:[n.jsx(wt,{size:15})," ",e("yt.connected")]}),n.jsxs(L,{variant:"ghost",size:"sm",className:"gap-1.5 text-xs text-muted-foreground",onClick:l,children:[n.jsx(jo,{size:13})," ",e("yt.disconnect")]})]}):A||a?n.jsxs(L,{variant:"hero",className:"w-full gap-2",disabled:!0,children:[n.jsx(xe,{size:15,className:"animate-spin"})," ",e("statusConnecting")]}):oe||ue?n.jsxs(L,{variant:"hero",className:"w-full gap-2",onClick:o,children:[n.jsx(ss,{size:15})," ",e("yt.reconnect")]}):n.jsxs(L,{variant:"hero",className:"w-full gap-2",onClick:o,children:[n.jsx(Rs,{size:15})," ",e("yt.connect")]})}),n.jsx("p",{className:"text-[10px] text-muted-foreground/70 leading-relaxed",children:e("yt.note")})]})}),n.jsx(Abe,{}),n.jsx(de.div,{...Te(.1),className:"rounded-2xl bg-surface-elevated border border-border/50 shadow-premium-sm overflow-hidden",children:n.jsxs("div",{className:"p-6 space-y-4",children:[n.jsxs("div",{className:"flex items-start justify-between",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("div",{className:"w-12 h-12 rounded-xl bg-orange-50 flex items-center justify-center",children:n.jsx(co,{size:24,className:"text-orange-500"})}),n.jsxs("div",{children:[n.jsx("h2",{className:"font-heading font-bold text-lg text-foreground",children:"Patreon"}),n.jsx("p",{className:"text-[11px] text-muted-foreground",children:e("paidLayer")})]})]}),n.jsx(fe,{variant:c==="connected"?"default":c==="error"||c==="expired"?"destructive":"secondary",className:"text-[10px]",children:je(c,u)})]}),c==="connected"&&d&&n.jsxs("div",{className:"flex items-center gap-3 rounded-xl border border-emerald-200/50 bg-emerald-50/30 px-4 py-3",children:[d.imageUrl&&n.jsx("img",{src:d.imageUrl,alt:"",className:"w-10 h-10 rounded-full object-cover"}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("p",{className:"text-sm font-semibold text-foreground truncate",children:d.name}),n.jsxs("p",{className:"text-[11px] text-muted-foreground",children:[d.campaignTitle||"Patreon Creator",d.patronCount>0&&` · ${d.patronCount} ${e("patreon.patrons")}`]})]}),n.jsx(wt,{size:18,className:"text-emerald-500 shrink-0"})]}),(c==="error"||c==="expired")&&n.jsxs("div",{className:"flex items-center gap-3 rounded-xl border border-amber-200/50 bg-amber-50/30 px-4 py-3",children:[n.jsx(ft,{size:18,className:"text-amber-500 shrink-0"}),n.jsxs("div",{className:"flex-1",children:[n.jsx("p",{className:"text-sm font-semibold text-foreground",children:e(c==="expired"?"tokenExpired":"connectionError")}),n.jsx("p",{className:"text-[11px] text-muted-foreground",children:m||e("reconnectNote")})]})]}),n.jsx("p",{className:"text-sm text-muted-foreground leading-relaxed",children:e(c==="connected"?"patreon.connectedDesc":Z?"patreon.readyDesc":"patreon.notReadyDesc")}),n.jsx("div",{className:"grid grid-cols-2 gap-2",children:e("patreon.features",{returnObjects:!0}).map(ae=>n.jsxs("div",{className:"flex items-center gap-2 rounded-lg bg-muted/20 px-3 py-2",children:[n.jsx(p4,{size:13,className:"text-orange-400 shrink-0"}),n.jsx("span",{className:"text-[11px] text-foreground font-medium leading-tight",children:ae})]},ae))}),!Z&&c==="not_connected"&&n.jsxs("div",{className:"flex items-center gap-3 rounded-xl border border-amber-200/50 bg-amber-50/30 px-4 py-3",children:[n.jsx(ft,{size:16,className:"text-amber-500 shrink-0"}),n.jsx("p",{className:"text-[11px] text-muted-foreground leading-relaxed",children:e("patreon.ytFirstWarning")})]}),n.jsx("div",{className:"flex gap-2",children:c==="connected"?n.jsxs(n.Fragment,{children:[n.jsxs(L,{variant:"secondary",className:"flex-1 gap-2",disabled:!0,children:[n.jsx(wt,{size:15})," ",e("patreon.connected")]}),n.jsxs(L,{variant:"ghost",size:"sm",className:"gap-1.5 text-xs text-muted-foreground",onClick:f,children:[n.jsx(jo,{size:13})," ",e("patreon.disconnect")]})]}):c==="connecting"||u?n.jsxs(L,{variant:"hero",className:"w-full gap-2",disabled:!0,children:[n.jsx(xe,{size:15,className:"animate-spin"})," ",e("statusConnecting")]}):c==="expired"||c==="error"?n.jsxs(L,{variant:"hero",className:"w-full gap-2",onClick:p,children:[n.jsx(ss,{size:15})," ",e("patreon.reconnect")]}):n.jsxs(L,{variant:Z?"hero":"hero-outline",className:"w-full gap-2",onClick:p,disabled:!Z,children:[n.jsx(Rs,{size:15}),e(Z?"patreon.connect":"patreon.connectYtFirst")]})}
1033),n.jsx("p",{className:"text-[10px] text-muted-foreground/70 leading-relaxed",children:e("patreon.note")})]})}),n.jsx(de.div,{...Te(.12),className:"rounded-2xl bg-surface-elevated border border-border/50 shadow-premium-sm overflow-hidden md:col-span-2",children:n.jsxs("div",{className:"p-6 space-y-4",children:[n.jsxs("div",{className:"flex items-start justify-between",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("div",{className:"w-12 h-12 rounded-xl bg-primary/10 flex items-center justify-center",children:n.jsx(fm,{size:24,className:"text-primary"})}),n.jsxs("div",{children:[n.jsx("h2",{className:"font-heading font-bold text-lg text-foreground",children:e("ayrshare.title")}),n.jsx("p",{className:"text-[11px] text-muted-foreground",children:e("ayrshare.subtitle")})]})]}),n.jsx(fe,{variant:O.status==="connected"?"default":"secondary",className:"text-[10px]",children:O.loading?e("statusLoading"):O.status==="connected"?e("statusConnected"):e("statusNotConnected")})]}),n.jsx("p",{className:"text-sm text-muted-foreground leading-relaxed",children:e("ayrshare.longDesc")}),O.status==="connected"&&n.jsxs("div",{className:"space-y-2",children:[n.jsx("div",{className:"text-xs font-semibold text-foreground",children:e("ayrshare.linkedTitle")}),O.linkedPlatforms.length===0?n.jsxs("div",{className:"flex items-center gap-2 rounded-xl border border-amber-200/50 bg-amber-50/30 px-4 py-3",children:[n.jsx(ft,{size:16,className:"text-amber-500 shrink-0"}),n.jsx("p",{className:"text-[11px] text-muted-foreground",children:e("ayrshare.noneLinked")})]}):n.jsx("div",{className:"flex flex-wrap gap-2",children:O.linkedPlatforms.map(ae=>{const ie=e(`ayrshare.platforms.${ae}`,{defaultValue:ae}),we=O.displayNames[ae];return n.jsxs("div",{className:"flex items-center gap-2 rounded-lg bg-emerald-50/40 border border-emerald-200/50 px-3 py-1.5",children:[n.jsx(wt,{size:13,className:"text-emerald-500"}),n.jsx("span",{className:"text-[12px] font-medium text-foreground",children:ie}),we&&n.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["· ",we]})]},ae)})})]}),O.error&&n.jsxs("div",{className:"flex items-center gap-2 rounded-xl border border-destructive/30 bg-destructive/5 px-4 py-2",children:[n.jsx(ft,{size:14,className:"text-destructive shrink-0"}),n.jsx("p",{className:"text-[11px] text-destructive",children:O.error})]}),n.jsx("div",{className:"flex flex-wrap gap-2",children:O.status!=="connected"?n.jsxs(L,{variant:"hero",className:"gap-2",onClick:()=>void O.createProfile().catch(()=>{}),disabled:O.loading,children:[O.loading?n.jsx(xe,{size:15,className:"animate-spin"}):n.jsx(tt,{size:15}),O.loading?e("ayrshare.creating"):e("ayrshare.createProfile")]}):n.jsxs(n.Fragment,{children:[n.jsxs(L,{variant:"hero",className:"gap-2",onClick:()=>void O.openLinkPage().catch(()=>{}),disabled:O.loading,children:[n.jsx(Rs,{size:15})," ",e("ayrshare.openLinkPage")]}),n.jsxs(L,{variant:"outline",className:"gap-2",onClick:()=>void O.refreshStatus().catch(()=>{}),disabled:O.loading,children:[O.loading?n.jsx(xe,{size:14,className:"animate-spin"}):n.jsx(ss,{size:14}),e("ayrshare.refresh")]}),n.jsxs(L,{variant:"ghost",size:"sm",className:"gap-1.5 text-xs text-muted-foreground",onClick:()=>void O.disconnect().catch(()=>{}),children:[n.jsx(jo,{size:13})," ",e("ayrshare.disconnect")]})]})}),n.jsx("p",{className:"text-[10px] text-muted-foreground/70 leading-relaxed",children:e("ayrshare.note")})]})}),n.jsx(de.div,{...Te(.11),className:"rounded-2xl bg-surface-elevated border border-border/50 shadow-premium-sm overflow-hidden md:col-span-2",children:n.jsxs("div",{className:"p-6 space-y-4",children:[n.jsxs("div",{className:"flex items-start justify-between",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("div",{className:"w-12 h-12 rounded-xl bg-violet-50 flex items-center justify-center",children:n.jsx(St,{size:24,className:"text-violet-500"})}),n.jsxs("div",{children:[n.jsx("h2",{className:"font-heading font-bold text-lg text-foreground",children:"Restream"}),n.jsx("p",{className:"text-[11px] text-muted-foreground",children:e("restream.subtitle")})]})]}),n.jsx(fe,{variant:g==="connected"?"default":g==="error"||g==="expired"?"destructive":"secondary",className:"text-[10px]",children:je(g,b)})]}),g==="connected"&&x&&n.jsxs("div",{className:"flex items-center gap-3 rounded-xl border border-emerald-200/50 bg-emerald-50/30 px-4 py-3",children:[n.jsx("div",{className:"w-10 h-10 rounded-full bg-violet-100 flex items-center justify-center text-violet-600 font-semibold text-sm",children:(x.username||"R").slice(0,2).toUpperCase()}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("p",{className:"text-sm font-semibold text-foreground truncate",children:x.username||"Restream user"}),n.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["ID: ",x.providerAccountId||"—"]}
1033)]}),n.jsx(wt,{size:18,className:"text-emerald-500 shrink-0"})]}),(g==="error"||g==="expired")&&n.jsxs("div",{className:"flex items-center gap-3 rounded-xl border border-amber-200/50 bg-amber-50/30 px-4 py-3",children:[n.jsx(ft,{size:18,className:"text-amber-500 shrink-0"}),n.jsxs("div",{className:"flex-1",children:[n.jsx("p",{className:"text-sm font-semibold text-foreground",children:e(g==="expired"?"tokenExpired":"connectionError")}),n.jsx("p",{className:"text-[11px] text-muted-foreground",children:v||e("reconnectNote")})]})]}),n.jsx("p",{className:"text-sm text-muted-foreground leading-relaxed",children:e("restream.longDesc")}),n.jsx("div",{className:"flex gap-2",children:g==="connected"?n.jsxs(n.Fragment,{children:[n.jsxs(L,{variant:"secondary",className:"flex-1 gap-2",disabled:!0,children:[n.jsx(wt,{size:15})," ",e("restream.connected")]}),n.jsxs(L,{variant:"ghost",size:"sm",className:"gap-1.5 text-xs text-muted-foreground",onClick:w,children:[n.jsx(jo,{size:13})," ",e("restream.disconnect")]})]}):g==="connecting"||b?n.jsxs(L,{variant:"hero",className:"w-full gap-2",disabled:!0,children:[n.jsx(xe,{size:15,className:"animate-spin"})," ",e("statusConnecting")]}):g==="expired"||g==="error"?n.jsxs(L,{variant:"hero",className:"w-full gap-2",onClick:y,children:[n.jsx(ss,{size:15})," ",e("restream.reconnect")]}):n.jsxs(L,{variant:"hero",className:"w-full gap-2",onClick:y,children:[n.jsx(Rs,{size:15})," ",e("restream.connect")]})}),n.jsx("p",{className:"text-[10px] text-muted-foreground/70 leading-relaxed",children:e("restream.note")})]})}),n.jsx(de.div,{...Te(.13),className:"rounded-2xl bg-surface-elevated border border-border/50 shadow-premium-sm overflow-hidden md:col-span-2",children:n.jsxs("div",{className:"p-6 space-y-4",children:[n.jsxs("div",{className:"flex items-start justify-between",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("div",{className:"w-12 h-12 rounded-xl bg-blue-50 flex items-center justify-center",children:n.jsx(za,{size:24,className:"text-blue-600"})}),n.jsxs("div",{children:[n.jsx("h2",{className:"font-heading font-bold text-lg text-foreground",children:e("meta.title")}),n.jsx("p",{className:"text-[11px] text-muted-foreground",children:e("meta.subtitle")})]})]}),n.jsx(fe,{variant:j==="connected"?"default":j==="error"||j==="expired"?"destructive":"secondary",className:"text-[10px]",children:je(j,N)})]}),j==="connected"&&_&&n.jsxs("div",{className:"space-y-2",children:[_.adAccountName&&n.jsxs("div",{className:"flex items-center gap-3 rounded-xl border border-emerald-200/50 bg-emerald-50/30 px-4 py-2.5",children:[n.jsx(wt,{size:16,className:"text-emerald-500 shrink-0"}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("p",{className:"text-[11px] text-muted-foreground",children:e("meta.adAccountLabel")}),n.jsx("p",{className:"text-sm font-semibold text-foreground truncate",children:_.adAccountName})]})]}),_.pageName&&n.jsxs("div",{className:"flex items-center gap-3 rounded-xl border border-blue-200/40 bg-blue-50/20 px-4 py-2.5",children:[n.jsx(eo,{size:16,className:"text-blue-500 shrink-0"}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("p",{className:"text-[11px] text-muted-foreground",children:e("meta.pageLabel")}),n.jsx("p",{className:"text-sm font-semibold text-foreground truncate",children:_.pageName})]})]}),_.instagramUsername&&n.jsxs("div",{className:"flex items-center gap-3 rounded-xl border border-pink-200/40 bg-pink-50/20 px-4 py-2.5",children:[n.jsx(tt,{size:16,className:"text-pink-500 shrink-0"}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("p",{className:"text-[11px] text-muted-foreground",children:e("meta.instagramLabel")}),n.jsxs("p",{className:"text-sm font-semibold text-foreground truncate",children:["@",_.instagramUsername]})]})]}),!_.adAccountId&&n.jsxs("div",{className:"flex items-center gap-2 rounded-xl border border-amber-200/50 bg-amber-50/30 px-4 py-2.5",children:[n.jsx(ft,{size:14,className:"text-amber-500 shrink-0"}),n.jsx("p",{className:"text-[11px] text-muted-foreground leading-relaxed",children:e("meta.missingAdAccount")}
1033)]}),(C.length>1||B.length>1)&&n.jsxs("div",{className:"grid sm:grid-cols-2 gap-2 pt-1",children:[C.length>1&&n.jsxs("div",{className:"space-y-1",children:[n.jsx("label",{className:"text-[10px] uppercase tracking-wide text-muted-foreground",children:e("meta.selectAdAccount")}),n.jsx("select",{className:"w-full text-xs rounded-lg border border-border/60 bg-background px-2.5 py-1.5 disabled:opacity-60",value:_.adAccountId||"",disabled:H==="adAccount",onChange:async ae=>{z("adAccount");try{await E({adAccountId:ae.target.value})}finally{z(null)}},children:C.map(ae=>n.jsxs("option",{value:ae.id,children:[ae.name,ae.currency?` · ${ae.currency}`:"",ae.status!==1?" (paused)":""]},ae.id))})]}),B.length>1&&n.jsxs("div",{className:"space-y-1",children:[n.jsx("label",{className:"text-[10px] uppercase tracking-wide text-muted-foreground",children:e("meta.selectPage")}),n.jsx("select",{className:"w-full text-xs rounded-lg border border-border/60 bg-background px-2.5 py-1.5 disabled:opacity-60",value:_.pageId||"",disabled:H==="page",onChange:async ae=>{z("page");try{await E({pageId:ae.target.value})}finally{z(null)}},children:B.map(ae=>n.jsxs("option",{value:ae.id,children:[ae.name,ae.instagram_username?` · @${ae.instagram_username}`:""]},ae.id))})]}),n.jsx("p",{className:"sm:col-span-2 text-[10px] text-muted-foreground/80",children:e("meta.selectHint")})]})]}),(j==="error"||j==="expired")&&n.jsxs("div",{className:"flex items-center gap-3 rounded-xl border border-amber-200/50 bg-amber-50/30 px-4 py-3",children:[n.jsx(ft,{size:18,className:"text-amber-500 shrink-0"}),n.jsxs("div",{className:"flex-1",children:[n.jsx("p",{className:"text-sm font-semibold text-foreground",children:e(j==="expired"?"tokenExpired":"connectionError")}),n.jsx("p",{className:"text-[11px] text-muted-foreground",children:k||e("reconnectNote")})]})]}),n.jsx("p",{className:"text-sm text-muted-foreground leading-relaxed",children:e(j==="connected"?"meta.connectedDesc":"meta.disconnectedDesc")}),n.jsx("div",{className:"grid grid-cols-2 gap-2",children:e("meta.features",{returnObjects:!0}).map(ae=>n.jsxs("div",{className:"flex items-center gap-2 rounded-lg bg-muted/20 px-3 py-2",children:[n.jsx(za,{size:13,className:"text-blue-400 shrink-0"}),n.jsx("span",{className:"text-[11px] text-foreground font-medium leading-tight",children:ae})]},ae))}),n.jsx("div",{className:"flex gap-2",children:j==="connected"?n.jsxs(n.Fragment,{children:[n.jsxs(L,{variant:"secondary",className:"flex-1 gap-2",disabled:!0,children:[n.jsx(wt,{size:15})," ",e("meta.connected")]}),n.jsxs(L,{variant:"ghost",size:"sm",className:"gap-1.5 text-xs text-muted-foreground",onClick:T,children:[n.jsx(jo,{size:13})," ",e("meta.disconnect")]})]}):j==="connecting"||N?n.jsxs(L,{variant:"hero",className:"w-full gap-2",disabled:!0,children:[n.jsx(xe,{size:15,className:"animate-spin"})," ",e("statusConnecting")]}):j==="expired"||j==="error"?n.jsxs(L,{variant:"hero",className:"w-full gap-2",onClick:S,children:[n.jsx(ss,{size:15})," ",e("meta.reconnect")]}):n.jsxs(L,{variant:"hero",className:"w-full gap-2",onClick:S,children:[n.jsx(Rs,{size:15})," ",e("meta.connect")]})}),n.jsx("p",{className:"text-[10px] text-muted-foreground/70 leading-relaxed",children:e("meta.note")})]})}),n.jsx(de.div,{...Te(.15),className:"rounded-2xl bg-surface-elevated border border-border/50 shadow-premium-sm overflow-hidden md:col-span-2",children:n.jsxs("div",{className:"p-6 space-y-4",children:[n.jsxs("div",{className:"flex items-start justify-between",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("div",{className:"w-12 h-12 rounded-xl bg-red-50 flex items-center justify-center",children:n.jsx(za,{size:24,className:"text-red-600"})}),n.jsxs("div",{children:[n.jsx("h2",{className:"font-heading font-bold text-lg text-foreground",children:e("googleAds.title")}),n.jsx("p",{className:"text-[11px] text-muted-foreground",children:e("googleAds.subtitle")})]})]}),n.jsx(fe,{variant:ne==="connected"?"default":ne==="error"||ne==="expired"?"destructive":"secondary",className:"text-[10px]",children:je(ne,te)})]}),ne==="connected"&&V&&n.jsxs("div",{className:"space-y-2",children:[V.customerDescriptiveName&&n.jsxs("div",{className:"flex items-center gap-3 rounded-xl border border-emerald-200/50 bg-emerald-50/30 px-4 py-2.5",children:[n.jsx(wt,{size:16,className:"text-emerald-500 shrink-0"}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("p",{className:"text-[11px] text-muted-foreground",children:e("googleAds.customerLabel")}),n.jsxs("p",{className:"text-sm font-semibold text-foreground truncate",children:[V.customerDescriptiveName,V.customerCurrencyCode?` · ${V.customerCurrencyCode}`:"",V.customerId?` · ${V.customerId}`:""]})]})]}),!V.customerId&&n.jsxs("div",{className:"flex items-center gap-2 rounded-xl border border-amber-200/50 bg-amber-50/30 px-4 py-2.5",children:[n.jsx(ft,{size:14,className:"text-amber-500 shrink-0"}),n.jsx("p",{className:"text-[11px] text-muted-foreground leading-relaxed",children:e("googleAds.missingCustomer")})]}),J.length>1&&n.jsxs("div",{className:"space-y-1 pt-1",children:[n.jsx("label",{className:"text-[10px] uppercase tracking-wide text-muted-foreground",children:e("googleAds.selectCustomer")}),n.jsx("select",{className:"w-full text-xs rounded-lg border border-border/60 bg-background px-2.5 py-1.5 disabled:opacity-60",value:V.customerId||"",disabled:re,onChange:async ae=>{G(!0);try{await Y({customerId:ae.target.value})}finally{G(!1)}},children:J.map(ae=>n.jsxs("option",{value:ae.id,children:[ae.descriptive_name||`Account ${ae.id}`,ae.currency_code?` · ${ae.currency_code}`:"",ae.manager?" (MCC)":"",ae.test_account?" (test)":""]},ae.id))}
1033),n.jsx("p",{className:"text-[10px] text-muted-foreground/80",children:e("googleAds.selectHint")})]})]}),(ne==="error"||ne==="expired")&&n.jsxs("div",{className:"flex items-center gap-3 rounded-xl border border-amber-200/50 bg-amber-50/30 px-4 py-3",children:[n.jsx(ft,{size:18,className:"text-amber-500 shrink-0"}),n.jsxs("div",{className:"flex-1",children:[n.jsx("p",{className:"text-sm font-semibold text-foreground",children:e(ne==="expired"?"tokenExpired":"connectionError")}),n.jsx("p",{className:"text-[11px] text-muted-foreground",children:R||e("reconnectNote")})]})]}),n.jsx("p",{className:"text-sm text-muted-foreground leading-relaxed",children:e(ne==="connected"?"googleAds.connectedDesc":"googleAds.disconnectedDesc")}),n.jsx("div",{className:"grid grid-cols-2 gap-2",children:e("googleAds.features",{returnObjects:!0}).map(ae=>n.jsxs("div",{className:"flex items-center gap-2 rounded-lg bg-muted/20 px-3 py-2",children:[n.jsx(za,{size:13,className:"text-red-400 shrink-0"}),n.jsx("span",{className:"text-[11px] text-foreground font-medium leading-tight",children:ae})]},ae))}),n.jsx("div",{className:"flex gap-2",children:ne==="connected"?n.jsxs(n.Fragment,{children:[n.jsxs(L,{variant:"secondary",className:"flex-1 gap-2",disabled:!0,children:[n.jsx(wt,{size:15})," ",e("googleAds.connected")]}),n.jsxs(L,{variant:"ghost",size:"sm",className:"gap-1.5 text-xs text-muted-foreground",onClick:$,children:[n.jsx(jo,{size:13})," ",e("googleAds.disconnect")]})]}):ne==="connecting"||te?n.jsxs(L,{variant:"hero",className:"w-full gap-2",disabled:!0,children:[n.jsx(xe,{size:15,className:"animate-spin"})," ",e("statusConnecting")]}):ne==="expired"||ne==="error"?n.jsxs(L,{variant:"hero",className:"w-full gap-2",onClick:F,children:[n.jsx(ss,{size:15})," ",e("googleAds.reconnect")]}):n.jsxs(L,{variant:"hero",className:"w-full gap-2",onClick:F,children:[n.jsx(Rs,{size:15})," ",e("googleAds.connect")]})}),n.jsx("p",{className:"text-[10px] text-muted-foreground/70 leading-relaxed",children:e("googleAds.note")})]})})]})]})};function Po(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:String(e)}function $be(e){const t=e.match(/PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?/);if(!t)return"";const s=t[1]?`${t[1]}:`:"",r=(t[2]??"0").padStart(s?2:1,"0"),a=(t[3]??"0").padStart(2,"0");return`${s}${r}:${a}`}const Lbe=()=>{const{t:e}=Oe("analytics"),{status:t,startConnect:s}=lo(),{session:r}=st(),{formatDate:a}=or(),[i,o]=h.useState(null),[l,c]=h.useState(!0),[d,u]=h.useState(null),[m,p]=h.useState(!1),f=h.useCallback(async(k=!1)=>{if(r!=null&&r.access_token){k?p(!0):c(!0),u(null);try{const{data:S,error:T}=await I.functions.invoke("youtube-analytics",{headers:{Authorization:`Bearer ${r.access_token}`}});if(T)throw new Error(T.message);if(S!=null&&S.error)throw new Error(S.error);o(S)}catch(S){u(S instanceof Error?S.message:"Unknown error")}finally{c(!1),p(!1)}}},[r==null?void 0:r.access_token]);if(h.useEffect(()=>{f()},[f]),l)return n.jsx(Ln,{message:e("loadingYouTube")});const g=(i==null?void 0:i.connected)===!0,x=i==null?void 0:i.channel,b=(i==null?void 0:i.recentVideos)??[],v=i==null?void 0:i.internal,y=["setup","publishing","streaming","monetization","scale"],w=g?((v==null?void 0:v.shortsPublished)??0)===0?0:((v==null?void 0:v.liveHeld)??0)===0?1:2:0,j=y.map((k,S)=>({label:e(`stages.${k}.label`),desc:e(`stages.${k}.desc`),active:S===w,done:S<w})),_=e("insights",{returnObjects:!0}),N=[Ns,St,co,ky];return Array.isArray(_)&&_.map((k,S)=>({icon:N[S],text:k})),n.jsxs("div",{className:"max-w-6xl mx-auto space-y-8",children:[n.jsxs(de.div,{...Te(),className:"flex items-start justify-between",children:[n.jsx("div",{children:n.jsxs("h1",{className:"font-heading font-bold text-2xl md:text-3xl text-foreground flex items-center gap-2",children:[n.jsx(by,{className:"text-primary",size:24}),e("pageTitle")]})}),g&&n.jsx(L,{variant:"outline",size:"sm",onClick:()=>f(!0),disabled:m,children:n.jsx(ss,{size:14,className:m?"animate-spin":""})})]}),d&&n.jsxs(de.div,{...Te(.05),className:"rounded-2xl bg-destructive/5 border border-destructive/20 p-5 flex items-center justify-between",children:[n.jsxs("p",{className:"text-sm text-destructive",children:[e("errorFetch"),": ",d]}),n.jsx(L,{variant:"outline",size:"sm",onClick:()=>f(!0),children:e("retry")})]}),!g&&!d&&n.jsxs(de.div,{...Te(.05),className:"rounded-2xl bg-surface-elevated border border-border/50 shadow-premium-sm p-8 text-center space-y-4",children:[n.jsx("div",{className:"w-16 h-16 rounded-2xl bg-destructive/10 flex items-center justify-center mx-auto",children:n.jsx(Ls,{size:32,className:"text-destructive"})}),n.jsx("h2",{className:"font-heading font-bold text-xl text-foreground",children:e("notConnected")}),n.jsx("p",{className:"text-sm text-muted-foreground max-w-md mx-auto",children:e("notConnectedDesc")}),n.jsxs(L,{onClick:s,className:"gap-2",children:[n.jsx(Pr,{size:16})," ",e("connectYouTube")]})]}),g&&x&&n.jsxs(n.Fragment,{children:[n.jsxs(de.div,{...Te(.05),className:"rounded-2xl bg-surface-elevated border border-border/50 shadow-premium-sm p-5 flex items-center gap-4",children:[x.thumbnail&&n.jsx("img",{src:x.thumbnail,alt:x.title,className:"w-12 h-12 rounded-full object-cover"}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("h2",{className:"font-heading font-semibold text-foreground truncate",children:x.title}),x.handle&&n.jsx("p",{className:"text-xs text-muted-foreground",children:x.handle})]}),n.jsxs(fe,{variant:"secondary",className:"gap-1 text-xs",children:[n.jsx(Ls,{size:12})," YouTube"]})]}
1033),n.jsx("div",{className:"grid grid-cols-2 lg:grid-cols-5 gap-3",children:[{label:e("kpis.subscribers"),value:Po(x.subscriberCount),icon:eo},{label:e("kpis.totalViews"),value:Po(x.viewCount),icon:oi},{label:e("kpis.videoCount"),value:Po(x.videoCount),icon:en},{label:e("kpis.shortsPublished"),value:String((v==null?void 0:v.shortsPublished)??0),icon:Ns},{label:e("kpis.liveHeld"),value:String((v==null?void 0:v.liveHeld)??0),icon:St}].map((k,S)=>n.jsxs(de.div,{...Te(.04*S),className:"rounded-2xl bg-surface-elevated border border-border/50 shadow-premium-sm p-5",children:[n.jsx("div",{className:"w-9 h-9 rounded-lg bg-primary/10 flex items-center justify-center mb-3",children:n.jsx(k.icon,{size:17,className:"text-primary"})}),n.jsx("p",{className:"font-heading font-bold text-2xl text-foreground",children:k.value}),n.jsx("p",{className:"text-[11px] text-muted-foreground mt-0.5",children:k.label})]},k.label))}),n.jsxs(de.div,{...Te(.15),className:"rounded-2xl bg-surface-elevated border border-border/50 shadow-premium-sm p-6 space-y-4",children:[n.jsxs("h2",{className:"font-heading font-semibold text-lg text-foreground flex items-center gap-2",children:[n.jsx(en,{size:18,className:"text-primary"})," ",e("recentVideosTitle")]}),b.length===0?n.jsx("p",{className:"text-sm text-muted-foreground py-6 text-center",children:e("recentVideosEmpty")}):n.jsx("div",{className:"space-y-3",children:b.map((k,S)=>n.jsxs(de.a,{href:`https://youtube.com/watch?v=${k.id}`,target:"_blank",rel:"noopener noreferrer",...Te(.02*S),className:"flex gap-3 rounded-xl border border-border/50 bg-muted/10 p-3 hover:bg-muted/30 transition-colors group",children:[n.jsxs("div",{className:"relative shrink-0 w-32 h-20 rounded-lg overflow-hidden bg-muted",children:[k.thumbnail&&n.jsx("img",{src:k.thumbnail,alt:k.title,className:"w-full h-full object-cover"}),k.duration&&n.jsx("span",{className:"absolute bottom-1 right-1 bg-black/80 text-white text-[10px] px-1.5 py-0.5 rounded font-mono",children:$be(k.duration)})]}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("p",{className:"text-sm font-medium text-foreground truncate group-hover:text-primary transition-colors",children:k.title}),n.jsxs("p",{className:"text-[11px] text-muted-foreground mt-1",children:[e("publishedAt")," ",a(k.publishedAt)]}),n.jsxs("div",{className:"flex items-center gap-4 mt-2",children:[n.jsxs("span",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[n.jsx(oi,{size:12})," ",Po(k.viewCount)," ",e("videoViews")]}),n.jsxs("span",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[n.jsx(I4,{size:12})," ",Po(k.likeCount)," ",e("videoLikes")]}),n.jsxs("span",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[n.jsx(up,{size:12})," ",Po(k.commentCount)," ",e("videoComments")]})]})]})]},k.id))})]})]}),n.jsxs(de.div,{...Te(.2),className:"rounded-2xl bg-surface-elevated border border-border/50 shadow-premium-sm p-6 space-y-4",children:[n.jsxs("h2",{className:"font-heading font-semibold text-lg text-foreground flex items-center gap-2",children:[n.jsx(uu,{size:18,className:"text-primary"})," ",e("stageTitle")]}),n.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-2",children:j.map((k,S)=>n.jsxs("div",{className:`rounded-xl border-2 p-4 transition-all ${k.active?"border-primary bg-primary/5":k.done?"border-emerald-400/40 bg-emerald-50/30":"border-border/40 bg-muted/10"}`,children:[n.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[n.jsx("span",{className:`text-[10px] font-bold ${k.active?"text-primary":k.done?"text-emerald-500":"text-muted-foreground"}`,children:S+1}),n.jsx("span",{className:`text-sm font-semibold truncate ${k.active?"text-foreground":k.done?"text-emerald-700":"text-muted-foreground"}`,children:k.label}),k.active&&n.jsx(fe,{className:"bg-primary/10 text-primary border-primary/20 text-[8px] ml-auto shrink-0",children:e("stageNow")})]}),n.jsx("p",{className:"text-[10px] text-muted-foreground leading-relaxed",children:k.desc})]},k.label))})]})]})};async function Xf(e,t={}){const{data:s,error:r}=await I.functions.invoke(`public-api-keys${e}`,{method:t.method??"GET",body:t.body});if(r)throw new Error(r.message);return s}function Ibe(){const{t:e}=Oe("settings"),[t,s]=h.useState([]),[r,a]=h.useState(!0),[i,o]=h.useState(null),[l,c]=h.useState(!1),[d,u]=
1033h.useState(""),[m,p]=h.useState(!1),[f,g]=h.useState(null),[x,b]=h.useState(!1),[v,y]=h.useState(!1),[w,j]=h.useState(!1),[_,N]=h.useState(!1),k="https://nfqxajdgklseicehjolk.functions.supabase.co/public-api",S=`curl -X POST ${k}/v1/avatar-videos \\
1034  -H "Authorization: Bearer plk_live_xxxxxxxx" \\
1035  -F "[email protected]" \\
1036  -F "[email protected]" \\
1037  -F "webhook_url=https://your-site.com/webhook"`,[T,C]=h.useState(null),[B,E]=h.useState(!1),H=async()=>{a(!0),o(null);try{const R=await Xf("");s(R.keys||[])}catch(R){o(R.message)}finally{a(!1)}};h.useEffect(()=>{H()},[]);const z=async()=>{if(d.trim()){p(!0);try{const R=await Xf("",{method:"POST",body:{name:d.trim()}});g(R),c(!1),u(""),await H()}catch(R){o(R.message)}finally{p(!1)}}},ne=async()=>{if(T){E(!0);try{await Xf(`/${T.id}`,{method:"DELETE"}),C(null),await H()}catch(R){o(R.message)}finally{E(!1)}}},V=async(R,F)=>{try{await navigator.clipboard.writeText(R),F==="key"?(b(!0),setTimeout(()=>b(!1),1500)):(y(!0),setTimeout(()=>y(!1),1500))}catch{}},te=R=>R?new Date(R).toLocaleString():"—";return n.jsxs(de.div,{...Te(),className:"rounded-2xl bg-surface-elevated border border-border/50 shadow-premium-sm p-6 space-y-5",children:[n.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[n.jsxs("div",{children:[n.jsxs("h2",{className:"font-heading font-semibold text-lg text-foreground flex items-center gap-2",children:[n.jsx(Py,{size:18,className:"text-primary"})," ",e("publicApi.title")]}),n.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:e("publicApi.subtitle")})]}),n.jsxs("div",{className:"flex gap-2",children:[n.jsxs(L,{variant:"outline",size:"sm",className:"gap-1.5",onClick:H,disabled:r,children:[n.jsx(ss,{size:14,className:r?"animate-spin":""})," ",e("publicApi.refresh")]}),n.jsxs(L,{variant:"hero",size:"sm",className:"gap-1.5",onClick:()=>c(!0),children:[n.jsx(sr,{size:14})," ",e("publicApi.createKey")]})]})]}),i&&n.jsxs("div",{className:"rounded-lg border border-destructive/30 bg-destructive/5 text-destructive px-3 py-2 text-xs flex items-center gap-2",children:[n.jsx(ft,{size:14})," ",i]}),n.jsxs("div",{className:"rounded-xl border border-border/50 bg-muted/10 p-4 space-y-3",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-xs font-medium text-muted-foreground mb-1.5",children:e("publicApi.endpoint.baseUrlLabel")}),n.jsxs("div",{className:"flex gap-2",children:[n.jsx(gt,{readOnly:!0,value:k,className:"font-mono text-xs"}),n.jsx(L,{variant:"outline",size:"icon",onClick:async()=>{await navigator.clipboard.writeText(k),j(!0),setTimeout(()=>j(!1),1500)},children:w?n.jsx(ms,{size:14}):n.jsx(Ma,{size:14})})]}),n.jsx("p",{className:"text-[11px] text-muted-foreground mt-1.5",children:e("publicApi.endpoint.authNote")})]}),n.jsxs("div",{children:[n.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[n.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:e("publicApi.endpoint.curlLabel")}),n.jsx(L,{variant:"ghost",size:"sm",className:"h-7 gap-1.5 text-xs",onClick:async()=>{await navigator.clipboard.writeText(S),N(!0),setTimeout(()=>N(!1),1500)},children:_?n.jsx(ms,{size:12}):n.jsx(Ma,{size:12})})]}),n.jsx("pre",{className:"rounded-lg border border-border/50 bg-background p-3 text-[11px] leading-relaxed font-mono text-foreground whitespace-pre overflow-x-auto",children:S})]}),n.jsxs("a",{href:"/docs/public-api",target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1.5 text-xs text-primary hover:underline",children:[n.jsx(Rs,{size:12})," ",e("publicApi.endpoint.docsLink")]})]}),n.jsx("div",{className:"rounded-xl border border-border/50 bg-muted/10 overflow-hidden",children:r?n.jsx("div",{className:"px-4 py-6 text-sm text-muted-foreground",children:e("publicApi.loading")}):t.length===0?n.jsx("div",{className:"px-4 py-8 text-sm text-muted-foreground text-center",children:e("publicApi.empty")}):n.jsxs("table",{className:"w-full text-sm",children:[n.jsx("thead",{className:"bg-muted/30 text-xs text-muted-foreground",children:n.jsxs("tr",{children:[n.jsx("th",{className:"text-left font-medium px-4 py-2",children:e("publicApi.col.name")}),n.jsx("th",{className:"text-left font-medium px-4 py-2",children:e("publicApi.col.prefix")}),n.jsx("th",{className:"text-left font-medium px-4 py-2",children:e("publicApi.col.created")}),n.jsx("th",{className:"text-left font-medium px-4 py-2",children:e("publicApi.col.lastUsed")}),n.jsx("th",{className:"text-left font-medium px-4 py-2",children:e("publicApi.col.status")}),n.jsx("th",{className:"px-4 py-2"})]})}),n.jsx("tbody",{children:t.map(R=>n.jsxs("tr",{className:"border-t border-border/40",children:[n.jsx("td",{className:"px-4 py-3 font-medium text-foreground",children:R.name}),n.jsxs("td",{className:"px-4 py-3 font-mono text-xs text-muted-foreground",children:[R.key_prefix,"…"]}),n.jsx("td",{className:"px-4 py-3 text-xs text-muted-foreground",children:te(R.created_at)}),n.jsx("td",{className:"px-4 py-3 text-xs text-muted-foreground",children:te(R.last_used_at)}),n.jsx("td",{className:"px-4 py-3",children:R.revoked_at?n.jsx(fe,{variant:"secondary",className:"text-[10px]",children:e("publicApi.revoked")}):n.jsx(fe,{className:"text-[10px] bg-emerald-50 text-emerald-600 hover:bg-emerald-50",children:e("publicApi.active")})}),n.jsx("td",{className:"px-4 py-3 text-right",children:!R.revoked_at&&n.jsxs(L,{variant:"ghost",size:"sm",className:"text-destructive hover:text-destructive gap-1.5",onClick:()=>C(R),children:[n.jsx(ci,{size:13})," ",e("publicApi.revoke")]})})]},R.id))})]})}),n.jsx(ns,{open:l,onOpenChange:c,children:n.jsxs(Zt,{children:[n.jsxs(Xt,{children:[n.jsx(es,{children:e("publicApi.createKey")}),n.jsx(us,{children:e("publicApi.createDesc")})]}),n.jsx(gt,{value:d,onChange:R=>u(R.target.value),placeholder:e("publicApi.namePlaceholder"),autoFocus:!0}),n.jsxs(Hl,{children:[n.jsx(L,{variant:"outline",onClick:()=>c(!1),children:e("publicApi.cancel")}),n.jsx(L,{variant:"hero",onClick:z,disabled:!d.trim()||m,children:e(m?"publicApi.creating":"publicApi.create")})]})]})}),n.jsx(ns,{open:!!f,onOpenChange:R=>!R&&g(null),children:n.jsxs(Zt,{className:"max-w-lg",children:[n.jsxs(Xt,{children:[n.jsx(es,{children:e("publicApi.savedTitle")}),n.jsx(us,{children:e("publicApi.savedDesc")})]}),f&&n.jsxs("div",{className:"space-y-4",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-xs font-medium text-muted-foreground mb-1.5",children:e("publicApi.apiKey")}),n.jsxs("div",{className:"flex gap-2",children:[n.jsx(gt,{readOnly:!0,value:f.full_key,className:"font-mono text-xs"}),n.jsx(L,{variant:"outline",size:"icon",onClick:()=>V(f.full_key,"key"),children:x?n.jsx(ms,{size:14}):n.jsx(Ma,{size:14})})]})]}),n.jsxs("div",{children:[n.jsx("p",{className:"text-xs font-medium text-muted-foreground mb-1.5",children:e("publicApi.webhookSecret")}),n.jsxs("div",{className:"flex gap-2",children:[n.jsx(gt,{readOnly:!0,value:f.webhook_secret,className:"font-mono text-xs"}),n.jsx(L,{variant:"outline",size:"icon",onClick:()=>V(f.webhook_secret,"secret"),children:v?n.jsx(ms,{size:14}):n.jsx(Ma,{size:14})})]})]}),n.jsxs("div",{className:"rounded-lg border border-amber-200 bg-amber-50 text-amber-800 px-3 py-2 text-xs flex items-start gap-2",children:[n.jsx(ft,{size:14,className:"mt-0.5 shrink-0"}),n.jsx("span",{children:e("publicApi.savedWarning")})]})]}),n.jsx(Hl,{children:n.jsx(L,{variant:"hero",onClick:()=>g(null),children:e("publicApi.done")})})]})}),n.jsx(bi,{open:!!T,onOpenChange:R=>
1037!R&&C(null),children:n.jsxs(oa,{children:[n.jsxs(la,{children:[n.jsx(da,{children:e("publicApi.revokeTitle")}),n.jsx(ua,{children:e("publicApi.revokeDesc",{name:(T==null?void 0:T.name)??""})})]}),n.jsxs(ca,{children:[n.jsx(ma,{disabled:B,children:e("publicApi.cancel")}),n.jsx(ha,{onClick:ne,disabled:B,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:e(B?"publicApi.revoking":"publicApi.revoke")})]})]})})]})}const Obe=()=>{var u,m,p;const{t:e}=Oe("settings"),{user:t,signOut:s}=st(),{isAdmin:r}=ar(),[a,i]=Gr("tab","profile"),o=(t==null?void 0:t.email)??"[email protected]",l=((u=t==null?void 0:t.user_metadata)==null?void 0:u.full_name)??"",c=(m=t==null?void 0:t.user_metadata)==null?void 0:m.avatar_url,d=l?l.split(" ").map(f=>f[0]).join("").toUpperCase().slice(0,2):((p=o[0])==null?void 0:p.toUpperCase())??"U";return n.jsxs("div",{className:"max-w-4xl mx-auto space-y-8",children:[n.jsx(de.div,{...Te(),children:n.jsxs("h1",{className:"font-heading font-bold text-2xl md:text-3xl text-foreground flex items-center gap-2",children:[n.jsx(pS,{className:"text-primary",size:24}),e("pageTitle")]})}),n.jsxs(Rp,{value:a,onValueChange:i,className:"space-y-6",children:[n.jsxs(ju,{className:"bg-muted/40",children:[n.jsxs(un,{value:"profile",className:"gap-1.5 text-xs",children:[n.jsx(Xs,{size:14})," ",e("tabs.profile")]}),n.jsxs(un,{value:"notifications",className:"gap-1.5 text-xs",children:[n.jsx(n4,{size:14})," ",e("tabs.notifications")]}),n.jsxs(un,{value:"security",className:"gap-1.5 text-xs",children:[n.jsx(li,{size:14})," ",e("tabs.security")]}),r&&n.jsxs(un,{value:"public-api",className:"gap-1.5 text-xs",children:[n.jsx(Py,{size:14})," ",e("tabs.publicApi")]})]}),n.jsx(hn,{value:"profile",children:n.jsxs(de.div,{...Te(),className:"rounded-2xl bg-surface-elevated border border-border/50 shadow-premium-sm p-6 space-y-5",children:[n.jsx("h2",{className:"font-heading font-semibold text-lg text-foreground",children:e("profile.title")}),n.jsxs("div",{className:"flex items-center gap-4 mb-2",children:[c?n.jsx("img",{src:c,alt:"",className:"w-16 h-16 rounded-full object-cover"}):n.jsx("div",{className:"w-16 h-16 rounded-full bg-gradient-primary flex items-center justify-center text-primary-foreground text-xl font-bold",children:d}),n.jsxs("div",{children:[n.jsx("p",{className:"font-heading font-semibold text-foreground",children:l||e("profile.user")}),n.jsx("p",{className:"text-xs text-muted-foreground",children:o}),n.jsxs(fe,{variant:"secondary",className:"text-[9px] mt-1 gap-1",children:[n.jsx(j4,{size:9})," ",e("profile.googleLogin")]})]})]}),n.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[n.jsx(Pe,{label:e("profile.name"),children:n.jsx(gt,{defaultValue:l||"",placeholder:e("profile.namePlaceholder"),className:"bg-muted/30"})}),n.jsx(Pe,{label:e("profile.email"),children:n.jsx(gt,{value:o,readOnly:!0,className:"bg-muted/30 opacity-60"})}),n.jsx(Pe,{label:e("profile.language"),children:n.jsx(gt,{defaultValue:e("profile.defaultLanguage"),className:"bg-muted/30"})}),n.jsx(Pe,{label:e("profile.timezone"),children:n.jsx(gt,{defaultValue:e("profile.defaultTimezone"),className:"bg-muted/30"})})]}),n.jsxs(L,{variant:"hero",className:"gap-2",children:[n.jsx(Id,{size:15})," ",e("profile.save")]})]})}),n.jsx(hn,{value:"notifications",children:n.jsxs(de.div,{...Te(),className:"rounded-2xl bg-surface-elevated border border-border/50 shadow-premium-sm p-6 space-y-4",children:[n.jsx("h2",{className:"font-heading font-semibold text-lg text-foreground",children:e("notifications.title")}),[{label:e("notifications.newFeatures"),on:!0},{label:e("notifications.liveStatus"),on:!0},{label:e("notifications.weeklyReport"),on:!1},{label:e("notifications.billing"),on:!0},{label:e("notifications.tips"),on:!1}].map(f=>n.jsxs("div",{className:"flex items-center justify-between rounded-xl border border-border/50 bg-muted/20 px-4 py-3",children:[n.jsx("span",{className:"text-sm font-medium text-foreground",children:f.label}),n.jsx(Ut,{defaultChecked:f.on})]},f.label)),n.jsxs(L,{variant:"hero",className:"gap-2",children:[n.jsx(Id,{size:15})," ",e("notifications.save")]})]})}),n.jsx(hn,{value:"security",children:n.jsxs(de.div,{...Te(),className:"rounded-2xl bg-surface-elevated border border-border/50 shadow-premium-sm p-6 space-y-5",children:[n.jsx("h2",{className:"font-heading font-semibold text-lg text-foreground",children:e("security.title")}),n.jsxs("div",{className:"rounded-xl border border-border/50 bg-muted/20 p-5 space-y-3",children:[n.jsx("h3",{className:"font-heading font-semibold text-sm text-foreground",children:e("security.loginMethod")}),n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("div",{className:"w-10 h-10 rounded-lg bg-muted/40 flex items-center justify-center",children:n.jsxs("svg",{className:"w-5 h-5",viewBox:"0 0 24 24",children:[n.jsx("path",{fill:"#4285F4",d:"M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92a5.06 5.06 0 01-2.2 3.32v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.1z"}),n.jsx("path",{fill:"#34A853",d:"M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"}),n.jsx("path",{fill:"#FBBC05",d:"M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"}),n.jsx("path",{fill:"#EA4335",d:"M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"})]})}),n.jsxs("div",{children:[n.jsx("p",{className:"text-sm font-medium text-foreground",children:e("security.googleAccount")}
1037),n.jsx("p",{className:"text-[11px] text-muted-foreground",children:o})]}),n.jsx(fe,{variant:"secondary",className:"ml-auto text-[9px]",children:e("security.active")})]})]}),n.jsxs("div",{className:"rounded-xl border border-border/50 bg-muted/20 p-5 space-y-3",children:[n.jsx("h3",{className:"font-heading font-semibold text-sm text-foreground",children:e("security.activeSessions")}),n.jsxs("div",{className:"rounded-xl border border-border/50 bg-card px-4 py-3 flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-sm font-medium text-foreground",children:e("security.currentBrowser")}),n.jsx("p",{className:"text-[10px] text-muted-foreground",children:e("security.lastActivity")})]}),n.jsx("span",{className:"text-[10px] font-semibold px-2 py-0.5 rounded-full bg-emerald-50 text-emerald-600",children:e("security.sessionActive")})]})]}),n.jsx("div",{className:"border-t border-border/40 pt-4",children:n.jsxs(L,{variant:"outline",className:"gap-2 text-destructive hover:text-destructive",onClick:s,children:[n.jsx(cS,{size:15})," ",e("security.signOut")]})})]})}),r&&n.jsx(hn,{value:"public-api",children:n.jsx(Ibe,{})})]})]})};function Dbe(){const{profile:e}=st(),[t,s]=h.useState(0),[r,a]=h.useState(500),[i,o]=h.useState(null),[l,c]=h.useState(!0),d=h.useCallback(async()=>{if(!(e!=null&&e.workspace_id)){c(!1);return}const{data:u}=await I.from("subscription_accounts").select("credits_balance, credits_monthly_allowance, credits_period_start").eq("workspace_id",e.workspace_id).maybeSingle();u&&(s(u.credits_balance??0),a(u.credits_monthly_allowance??500),o(u.credits_period_start??null)),c(!1)},[e==null?void 0:e.workspace_id]);return h.useEffect(()=>{d()},[d]),{balance:t,monthlyAllowance:r,periodStart:i,loading:l,refresh:d}}function Mbe(e=20){const{profile:t}=st(),[s,r]=h.useState([]),[a,i]=h.useState(!0);return h.useEffect(()=>{if(!(t!=null&&t.workspace_id)){i(!1);return}let o=!1;return(async()=>{const{data:l}=await I.from("credit_ledger").select("*").eq("workspace_id",t.workspace_id).order("created_at",{ascending:!1}).limit(e);o||(r(l||[]),i(!1))})(),()=>{o=!0}},[t==null?void 0:t.workspace_id,e]),{entries:s,loading:a}}const zbe={grant_monthly:"text-emerald-600",grant_initial:"text-emerald-600",topup:"text-emerald-600",refund:"text-emerald-600",consume_video:"text-amber-600",consume_live:"text-amber-600",admin_adjust:"text-muted-foreground"};function Fbe(){const{t:e}=Oe("billing"),{formatNumber:t,formatDate:s}=or(),{balance:r,monthlyAllowance:a,periodStart:i,loading:o}=Dbe(),{entries:l}=Mbe(10),c=a>0?Math.min(100,r/a*100):0,d=Math.floor(r/ih.video_per_second),u=Math.floor(r/ih.live_per_second),m=p=>`${Math.floor(p/60)} ${e("credits.min")}`;return n.jsxs(de.div,{...Te(.1),className:"rounded-2xl bg-surface-elevated border border-border/50 shadow-premium-sm p-6 space-y-5",children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("div",{className:"w-10 h-10 rounded-xl bg-primary/10 flex items-center justify-center",children:n.jsx(c4,{size:18,className:"text-primary"})}),n.jsxs("div",{children:[n.jsx("h2",{className:"font-heading font-semibold text-lg text-foreground",children:e("credits.title")}),i&&n.jsx("p",{className:"text-xs text-muted-foreground",children:e("credits.since",{date:s(i)})})]})]}),n.jsxs("div",{className:"text-right",children:[n.jsx("div",{className:"font-heading font-bold text-2xl text-foreground tabular-nums",children:o?"—":t(r)}),n.jsxs("div",{className:"text-xs text-muted-foreground",children:["/ ",t(a)]})]})]}),n.jsx("div",{className:"h-2 rounded-full bg-muted overflow-hidden",children:n.jsx("div",{className:"h-full bg-gradient-primary transition-all",style:{width:`${c}%`}})}),n.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[n.jsxs("div",{className:"rounded-xl border border-border/40 bg-muted/20 p-3 flex items-center gap-2.5",children:[n.jsx(Ns,{size:16,className:"text-primary/70 shrink-0"}),n.jsxs("div",{className:"min-w-0",children:[n.jsx("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground font-medium",children:e("credits.videoEquiv")}),n.jsxs("div",{className:"text-sm font-semibold text-foreground",children:["≈ ",m(d)]})]})]}),n.jsxs("div",{className:"rounded-xl border border-border/40 bg-muted/20 p-3 flex items-center gap-2.5",children:[n.jsx(St,{size:16,className:"text-primary/70 shrink-0"}),n.jsxs("div",{className:"min-w-0",children:[n.jsx("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground font-medium",children:e("credits.liveEquiv")}),n.jsxs("div",{className:"text-sm font-semibold text-foreground",children:["≈ ",m(u)]})]})]})]}),n.jsx("p",{className:"text-xs text-muted-foreground leading-relaxed",children:e("credits.rules",{videoCost:ih.video_per_second,liveCost:ih.live_per_second})}),l.length>0&&n.jsxs("div",{className:"pt-4 border-t border-border/40",children:[n.jsxs("div",{className:"flex items-center gap-2 mb-2.5",children:[n.jsx(oS,{size:13,className:"text-muted-foreground"}),n.jsx("h3",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wider",children:e("credits.historyTitle")})]}),n.jsx("div",{className:"space-y-1.5",children:l.map(p=>n.jsxs("div",{className:"flex items-center justify-between text-xs py-1",children:[n.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[n.jsxs("span",{className:`font-mono tabular-nums w-16 shrink-0 ${zbe[p.kind]||"text-foreground"}`,children:[p.amount>0?"+":"",t(p.amount)]}),n.jsx("span",{className:"text-foreground truncate",children:e(`credits.kinds.${p.kind}`,p.kind)})]}),n.jsx("span",{className:"text-muted-foreground shrink-0 ml-2",children:s(p.created_at)})]}
1037,p.id))})]})]})}const Q1={free:nr,pro:tt,business:_y},Ube=()=>{const{t:e}=Oe("billing"),{formatDate:t,formatNumber:s}=or(),{planKey:r,subscribed:a,status:i,subscriptionEnd:o,startCheckout:l,openPortal:c}=ar();st();const[d,u]=h.useState(!1),{t:m}=Oe("common"),p=kp({t:m,subStatus:i,planKey:r,onManageBilling:c,onUpgrade:()=>b("pro")}),f=Md[r],g=Q1[r],x=[{label:e("features.personas"),free:"1",pro:"5",business:e("features.unlimited")},{label:e("features.shortsPerMonth"),free:"10",pro:"100",business:e("features.unlimited")},{label:e("features.liveCenter"),free:e("features.no"),pro:e("features.yes"),business:e("features.yes")},{label:e("features.monetizationTools"),free:e("features.no"),pro:e("features.basic"),business:e("features.full")},{label:e("features.integrations"),free:"YouTube",pro:"YouTube + Patreon",business:e("features.all")},{label:e("features.analytics"),free:e("features.basic"),pro:e("features.extended"),business:e("features.complete")}],b=async v=>{const y=Md[v],w=d?y.yearly:y.monthly;w&&await l(w.priceId)};return n.jsxs("div",{className:"max-w-5xl mx-auto space-y-8",children:[n.jsx(de.div,{...Te(),children:n.jsxs("h1",{className:"font-heading font-bold text-2xl md:text-3xl text-foreground flex items-center gap-2",children:[n.jsx(Il,{className:"text-primary",size:24}),e("pageTitle")]})}),n.jsx(QC,{status:i,planKey:r,subscriptionEnd:o,onUpgrade:()=>b("pro"),onManage:c}),n.jsx(_p,{alerts:p}),n.jsx(Fbe,{}),n.jsx(de.div,{...Te(.05),className:"rounded-2xl bg-surface-elevated border border-border/50 shadow-premium-sm p-6",children:n.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[n.jsxs("div",{className:"flex items-center gap-4",children:[n.jsx("div",{className:"w-12 h-12 rounded-xl bg-primary/10 flex items-center justify-center",children:n.jsx(g,{size:22,className:"text-primary"})}),n.jsxs("div",{children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("h2",{className:"font-heading font-bold text-xl text-foreground",children:f.name}),n.jsx(yr,{status:a?i||"active":"inactive",size:"md"})]}),n.jsxs("div",{className:"flex flex-wrap items-center gap-3 mt-1 text-xs text-muted-foreground",children:[o&&n.jsxs("span",{className:"flex items-center gap-1",children:[n.jsx(yy,{size:11})," ",e("currentPlan.nextRenewal",{date:t(o)})]}),n.jsx("span",{children:e("currentPlan.cycle")})]})]})]}),n.jsxs("div",{className:"flex gap-2",children:[a&&n.jsxs(L,{variant:"outline",size:"sm",className:"gap-1.5 text-xs",onClick:c,children:[n.jsx(li,{size:13})," ",e("currentPlan.manageSub")]}),r==="free"&&n.jsxs(L,{variant:"hero",className:"gap-2 shrink-0",onClick:()=>b("pro"),children:[n.jsx(tt,{size:15})," ",e("currentPlan.upgradePro")]})]})]})}),n.jsxs(de.div,{...Te(.2),className:"space-y-4",children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsx("h2",{className:"font-heading font-semibold text-lg text-foreground",children:e("plans.title")}),n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("span",{className:`text-xs font-medium ${d?"text-muted-foreground":"text-foreground"}`,children:e("plans.monthly")}),n.jsx(Ut,{checked:d,onCheckedChange:u}),n.jsx("span",{className:`text-xs font-medium ${d?"text-foreground":"text-muted-foreground"}`,children:e("plans.yearly")}),d&&n.jsx(fe,{className:"bg-emerald-50 text-emerald-600 border-emerald-200 text-[9px] font-semibold",children:e("plans.discount")})]})]}),n.jsx("div",{className:"grid md:grid-cols-3 gap-4",children:hC.map(v=>{const y=v.key===r,w=v.key==="pro",j=Q1[v.key],_=d?v.yearly:v.monthly,N=_?`$${_.amount}`:"$0";return n.jsxs("div",{className:`relative rounded-2xl border-2 p-6 transition-all ${w?"border-primary shadow-premium-md bg-primary/[0.02]":y?"border-primary/30 bg-surface-elevated shadow-premium-sm":"border-border/50 bg-surface-elevated shadow-premium-sm"}`,children:[w&&n.jsx("div",{className:"absolute -top-3 left-1/2 -translate-x-1/2",children:n.jsx(fe,{className:"bg-gradient-primary text-primary-foreground text-[10px] shadow-premium-sm",children:e("plans.recommended")})}),n.jsxs("div",{className:"text-center space-y-3",children:[n.jsx(j,{size:24,className:w?"text-primary mx-auto":"text-muted-foreground mx-auto"}),n.jsx("h3",{className:"font-heading font-bold text-lg text-foreground",children:v.name}),n.jsxs("div",{children:[n.jsx("span",{className:"font-heading font-bold text-3xl text-foreground",children:N}),n.jsx("span",{className:"text-sm text-muted-foreground",children:e(d?"plans.perMonthYear":"plans.perMonth")})]}),n.jsx("p",{className:"text-xs text-muted-foreground",children:v.desc}),n.jsx("div",{className:"space-y-1.5 pt-2 text-left",children:x.map(k=>{const S=k[v.key],T=S!==e("features.no");return n.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[T?n.jsx(wt,{size:13,className:"text-primary shrink-0"}
vendor: 14,615 bytes, line 1037
1037):n.jsx(Ll,{size:13,className:"text-muted-foreground/30 shrink-0"}),n.jsxs("span",{className:T?"text-foreground":"text-muted-foreground/50",children:[k.label,": ",S]})]},k.label)})}),n.jsx(L,{variant:y?"secondary":w?"hero":"hero-outline",className:"w-full gap-1.5 mt-2",disabled:y||v.key==="free",onClick:()=>b(v.key),children:y?e("plans.currentPlan"):v.key==="free"?e("plans.free"):n.jsxs(n.Fragment,{children:[e("plans.select")," ",n.jsx(yn,{size:13})]})})]})]},v.key)})})]})]})};var av=["Enter"," "],Bbe=["ArrowDown","PageUp","Home"],FT=["ArrowUp","PageDown","End"],Vbe=[...Bbe,...FT],qbe={ltr:[...av,"ArrowRight"],rtl:[...av,"ArrowLeft"]},Hbe={ltr:["ArrowLeft"],rtl:["ArrowRight"]},Nu="Menu",[Vd,Wbe,Gbe]=zy(Nu),[mo,UT]=Is(Nu,[Gbe,gi,Ep]),Mp=gi(),BT=Ep(),[Ybe,po]=mo(Nu),[Kbe,Su]=mo(Nu),VT=e=>{const{__scopeMenu:t,open:s=!1,children:r,dir:a,onOpenChange:i,modal:o=!0}=e,l=Mp(t),[c,d]=h.useState(null),u=h.useRef(!1),m=Zn(i),p=yp(a);return h.useEffect(()=>{const f=()=>{u.current=!0,document.addEventListener("pointerdown",g,{capture:!0,once:!0}),document.addEventListener("pointermove",g,{capture:!0,once:!0})},g=()=>u.current=!1;return document.addEventListener("keydown",f,{capture:!0}),()=>{document.removeEventListener("keydown",f,{capture:!0}),document.removeEventListener("pointerdown",g,{capture:!0}),document.removeEventListener("pointermove",g,{capture:!0})}},[]),n.jsx(tp,{...l,children:n.jsx(Ybe,{scope:t,open:s,onOpenChange:m,content:c,onContentChange:d,children:n.jsx(Kbe,{scope:t,onClose:h.useCallback(()=>m(!1),[m]),isUsingKeyboardRef:u,dir:p,modal:o,children:r})})})};VT.displayName=Nu;var Qbe="MenuAnchor",sb=h.forwardRef((e,t)=>{const{__scopeMenu:s,...r}=e,a=Mp(s);return n.jsx(nu,{...a,...r,ref:t})});sb.displayName=Qbe;var nb="MenuPortal",[Jbe,qT]=mo(nb,{forceMount:void 0}),HT=e=>{const{__scopeMenu:t,forceMount:s,children:r,container:a}=e,i=po(nb,t);return n.jsx(Jbe,{scope:t,forceMount:s,children:n.jsx(sn,{present:s||i.open,children:n.jsx(ru,{asChild:!0,container:a,children:r})})})};HT.displayName=nb;var An="MenuContent",[Zbe,rb]=mo(An),WT=h.forwardRef((e,t)=>{const s=qT(An,e.__scopeMenu),{forceMount:r=s.forceMount,...a}=e,i=po(An,e.__scopeMenu),o=Su(An,e.__scopeMenu);return n.jsx(Vd.Provider,{scope:e.__scopeMenu,children:n.jsx(sn,{present:r||i.open,children:n.jsx(Vd.Slot,{scope:e.__scopeMenu,children:o.modal?n.jsx(Xbe,{...a,ref:t}):n.jsx(e0e,{...a,ref:t})})})})}),Xbe=h.forwardRef((e,t)=>{const s=po(An,e.__scopeMenu),r=h.useRef(null),a=bt(t,r);return h.useEffect(()=>{const i=r.current;if(i)return gp(i)},[]),n.jsx(ab,{...e,ref:a,trapFocus:s.open,disableOutsidePointerEvents:s.open,disableOutsideScroll:!0,onFocusOutside:Ee(e.onFocusOutside,i=>i.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>s.onOpenChange(!1)})}),e0e=h.forwardRef((e,t)=>{const s=po(An,e.__scopeMenu);return n.jsx(ab,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>s.onOpenChange(!1)})}),t0e=ni("MenuContent.ScrollLock"),ab=h.forwardRef((e,t)=>{const{__scopeMenu:s,loop:r=!1,trapFocus:a,onOpenAutoFocus:i,onCloseAutoFocus:o,disableOutsidePointerEvents:l,onEntryFocus:c,onEscapeKeyDown:d,onPointerDownOutside:u,onFocusOutside:m,onInteractOutside:p,onDismiss:f,disableOutsideScroll:g,...x}=e,b=po(An,s),v=Su(An,s),y=Mp(s),w=BT(s),j=Wbe(s),[_,N]=h.useState(null),k=h.useRef(null),S=bt(t,k,b.onContentChange),T=h.useRef(0),C=h.useRef(""),B=h.useRef(0),E=h.useRef(null),H=h.useRef("right"),z=h.useRef(0),ne=g?pu:h.Fragment,V=g?{as:t0e,allowPinchZoom:!0}:void 0,te=F=>{var A,oe;const $=C.current+F,J=j().filter(ue=>!ue.disabled),Y=document.activeElement,re=(A=J.find(ue=>ue.ref.current===Y))==null?void 0:A.textValue,G=J.map(ue=>ue.textValue),O=m0e(G,$,re),Z=(oe=J.find(ue=>ue.textValue===O))==null?void 0:oe.ref.current;(function ue(je){C.current=je,window.clearTimeout(T.current),je!==""&&(T.current=window.setTimeout(()=>ue(""),1e3))})($),Z&&setTimeout(()=>Z.focus())};h.useEffect(()=>()=>window.clearTimeout(T.current),[]),pp();const R=h.useCallback(F=>{var J,Y;return H.current===((J=E.current)==null?void 0:J.side)&&f0e(F,(Y=E.current)==null?void 0:Y.area)},[]);return n.jsx(Zbe,{scope:s,searchRef:C,onItemEnter:h.useCallback(F=>{R(F)&&F.preventDefault()},[R]),onItemLeave:h.useCallback(F=>{var $;R(F)||(($=k.current)==null||$.focus(),N(null))},[R]),onTriggerLeave:h.useCallback(F=>{R(F)&&F.preventDefault()},[R]),pointerGraceTimerRef:B,onPointerGraceIntentChange:h.useCallback(F=>{E.current=F},[]),children:n.jsx(ne,{...V,children:n.jsx(mu,{asChild:!0,trapped:a,onMountAutoFocus:Ee(i,F=>{var $;F.preventDefault(),($=k.current)==null||$.focus({preventScroll:!0})}),onUnmountAutoFocus:o,children:n.jsx(tc,{asChild:!0,disableOutsidePointerEvents:l,onEscapeKeyDown:d,onPointerDownOutside:u,onFocusOutside:m,onInteractOutside:p,onDismiss:f,children:n.jsx(F2,{asChild:!0,...w,dir:v.dir,orientation:"vertical",loop:r,currentTabStopId:_,onCurrentTabStopIdChange:N,onEntryFocus:Ee(c,F=>{v.isUsingKeyboardRef.current||F.preventDefault()}),preventScrollOnEntryFocus:!0,children:n.jsx(sp,{role:"menu","aria-orientation":"vertical","data-state":lP(b.open),"data-radix-menu-content":"",dir:v.dir,...y,...x,ref:S,style:{outline:"none",...x.style},onKeyDown:Ee(x.onKeyDown,F=>{const J=F.target.closest("[data-radix-menu-content]")===F.currentTarget,Y=F.ctrlKey||F.altKey||F.metaKey,re=F.key.length===1;J&&(F.key==="Tab"&&F.preventDefault(),!Y&&re&&te(F.key));const G=k.current;if(F.target!==G||!Vbe.includes(F.key))return;F.preventDefault();const Z=j().filter(A=>!A.disabled).map(A=>A.ref.current);FT.includes(F.key)&&Z.reverse(),u0e(Z)}),onBlur:Ee(e.onBlur,F=>{F.currentTarget.contains(F.target)||(window.clearTimeout(T.current),C.current="")}),onPointerMove:Ee(e.onPointerMove,qd(F=>{const $=F.target,J=z.current!==F.clientX;if(F.currentTarget.contains($)&&J){const Y=F.clientX>z.current?"right":"left";H.current=Y,z.current=F.clientX}}))})})})})})})});WT.displayName=An;var s0e="MenuGroup",ib=h.forwardRef((e,t)=>{const{__scopeMenu:s,...r}=e;return n.jsx(qe.div,{role:"group",...r,ref:t})});ib.displayName=s0e;var n0e="MenuLabel",GT=h.forwardRef((e,t)=>{const{__scopeMenu:s,...r}=e;return n.jsx(qe.div,{...r,ref:t})});GT.displayName=n0e;var Em="MenuItem",J1="menu.itemSelect",zp=h.forwardRef((e,t)=>{const{disabled:s=!1,onSelect:r,...a}=e,i=h.useRef(null),o=Su(Em,e.__scopeMenu),l=rb(Em,e.__scopeMenu),c=bt(t,i),d=h.useRef(!1),u=()=>{const m=i.current;if(!s&&m){const p=new CustomEvent(J1,{bubbles:!0,cancelable:!0});m.addEventListener(J1,f=>r==null?void 0:r(f),{once:!0}),Wk(m,p),p.defaultPrevented?d.current=!1:o.onClose()}};return n.jsx(YT,{...a,ref:c,disabled:s,onClick:Ee(e.onClick,u),onPointerDown:m=>{var p;(p=e.onPointerDown)==null||p.call(e,m),d.current=!0},onPointerUp:Ee(e.onPointerUp,m=>{var p;d.current||(p=m.currentTarget)==null||p.click()}),onKeyDown:Ee(e.onKeyDown,m=>{const p=l.searchRef.current!=="";s||p&&m.key===" "||av.includes(m.key)&&(m.currentTarget.click(),m.preventDefault())})})});zp.displayName=Em;var YT=h.forwardRef((e,t)=>{const{__scopeMenu:s,disabled:r=!1,textValue:a,...i}=e,o=rb(Em,s),l=BT(s),c=h.useRef(null),d=bt(t,c),[u,m]=h.useState(!1),[p,f]=h.useState("");return h.useEffect(()=>{const g=c.current;g&&f((g.textContent??"").trim())},[i.children]),n.jsx(Vd.ItemSlot,{scope:s,disabled:r,textValue:a??p,children:n.jsx(U2,{asChild:!0,...l,focusable:!r,children:n.jsx(qe.div,{role:"menuitem","data-highlighted":u?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...i,ref:d,onPointerMove:Ee(e.onPointerMove,qd(g=>{r?o.onItemLeave(g):(o.onItemEnter(g),g.defaultPrevented||g.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:Ee(e.onPointerLeave,qd(g=>o.onItemLeave(g))),onFocus:Ee(e.onFocus,()=>m(!0)),onBlur:Ee(e.onBlur,()=>m(!1))})})})}),r0e="MenuCheckboxItem",KT=h.forwardRef((e,t)=>{const{checked:s=!1,onCheckedChange:r,...a}=e;return n.jsx(eP,{scope:e.__scopeMenu,checked:s,children:n.jsx(zp,{role:"menuitemcheckbox","aria-checked":Am(s)?"mixed":s,...a,ref:t,"data-state":lb(s),onSelect:Ee(a.onSelect,()=>r==null?void 0:r(Am(s)?!0:!s),{checkForDefaultPrevented:!1})})})});KT.displayName=r0e;var QT="MenuRadioGroup",[a0e,i0e]=mo(QT,{value:void 0,onValueChange:()=>{}}),JT=h.forwardRef((e,t)=>{const{value:s,onValueChange:r,...a}=e,i=Zn(r);return n.jsx(a0e,{scope:e.__scopeMenu,value:s,onValueChange:i,children:n.jsx(ib,{...a,ref:t})})});JT.displayName=QT;var ZT="MenuRadioItem",XT=h.forwardRef((e,t)=>{const{value:s,...r}=e,a=i0e(ZT,e.__scopeMenu),i=s===a.value;return n.jsx(eP,{scope:e.__scopeMenu,checked:i,children:n.jsx(zp,{role:"menuitemradio","aria-checked":i,...r,ref:t,"data-state":lb(i),onSelect:Ee(r.onSelect,()=>{var o;return(o=a.onValueChange)==null?void 0:o.call(a,s)},{checkForDefaultPrevented:!1})})})});XT.displayName=ZT;var ob="MenuItemIndicator",[eP,o0e]=mo(ob,{checked:!1}),tP=h.forwardRef((e,t)=>{const{__scopeMenu:s,forceMount:r,...a}=e,i=o0e(ob,s);return n.jsx(sn,{present:r||Am(i.checked)||i.checked===!0,children:n.jsx(qe.span,{...a,ref:t,"data-state":lb(i.checked)})})});tP.displayName=ob;var l0e="MenuSeparator",sP=h.forwardRef((e,t)=>{const{__scopeMenu:s,...r}=e;return n.jsx(qe.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});sP.displayName=l0e;var c0e="MenuArrow",nP=h.forwardRef((e,t)=>{const{__scopeMenu:s,...r}=e,a=Mp(s);return n.jsx(np,{...a,...r,ref:t})});nP.displayName=c0e;var d0e="MenuSub",[sje,rP]=mo(d0e),Dc="MenuSubTrigger",aP=h.forwardRef((e,t)=>{const s=po(Dc,e.__scopeMenu),r=Su(Dc,e.__scopeMenu),a=rP(Dc,e.__scopeMenu),i=rb(Dc,e.__scopeMenu),o=h.useRef(null),{pointerGraceTimerRef:l,onPointerGraceIntentChange:c}=i,d={__scopeMenu:e.__scopeMenu},u=h.useCallback(()=>{o.current&&window.clearTimeout(o.current),o.current=null},[]);return h.useEffect(()=>u,[u]),h.useEffect(()=>{const m=l.current;return()=>{window.clearTimeout(m),c(null)}},[l,c]),n.jsx(sb,{asChild:!0,...d,children:n.jsx(YT,{id:a.triggerId,"aria-haspopup":"menu","aria-expanded":s.open,"aria-controls":a.contentId,"data-state":lP(s.open),...e,ref:Jm(t,a.onTriggerChange),onClick:m=>{var p;(p=e.onClick)==null||p.call(e,m),!(e.disabled||m.defaultPrevented)&&(m.currentTarget.focus(),s.open||s.onOpenChange(!0))},onPointerMove:Ee(e.onPointerMove,qd(m=>{i.onItemEnter(m),!m.defaultPrevented&&!e.disabled&&!s.open&&!o.current&&(i.onPointerGraceIntentChange(null),o.current=window.setTimeout(()=>{s.onOpenChange(!0),u()},100))})),onPointerLeave:Ee(e.onPointerLeave,qd(m=>{var f,g;u();const p=(f=s.content)==null?void 0:f.getBoundingClientRect();if(p){const x=(g=s.content)==null?void 0:g.dataset.side,b=x==="right",v=b?-5:5,y=p[b?"left":"right"],w=p[b?"right":"left"];i.onPointerGraceIntentChange({area:[{x:m.clientX+v,y:m.clientY},{x:y,y:p.top},{x:w,y:p.top},{x:w,y:p.bottom},{x:y,y:p.bottom}],side:x}),window.clearTimeout(l.current),l.current=window.setTimeout(()=>i.onPointerGraceIntentChange(null),300)}else{if(i.onTriggerLeave(m),m.defaultPrevented)return;i.onPointerGraceIntentChange(null)}})),onKeyDown:Ee(e.onKeyDown,m=>{var f;const p=i.searchRef.current!=="";e.disabled||p&&m.key===" "||qbe[r.dir].includes(m.key)&&(s.onOpenChange(!0),(f=s.content)==null||f.focus(),m.preventDefault())})})})});aP.displayName=Dc;var iP="MenuSubContent",oP=h.forwardRef((e,t)=>{const s=qT(An,e.__scopeMenu),{forceMount:r=s.forceMount,...a}=e,i=po(An,e.__scopeMenu),o=Su(An,e.__scopeMenu),l=rP(iP,e.__scopeMenu),c=h.useRef(null),d=bt(t,c);return n.jsx(Vd.Provider,{scope:e.__scopeMenu,children:n.jsx(sn,{present:r||i.open,children:n.jsx(Vd.Slot,{scope:e.__scopeMenu,children:n.jsx(ab,{id:l.contentId,"aria-labelledby":l.triggerId,...a,ref:d,align:"start",side:o.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:u=>{var m;o.isUsingKeyboardRef.current&&((m=c.current)==null||m.focus()),u.preventDefault()},onCloseAutoFocus:u=>u.preventDefault(),onFocusOutside:Ee(e.onFocusOutside,u=>{u.target!==l.trigger&&i.onOpenChange(!1)}),onEscapeKeyDown:Ee(e.onEscapeKeyDown,u=>{o.onClose(),u.preventDefault()}),onKeyDown:Ee(e.onKeyDown,u=>{var f;const m=u.currentTarget.contains(u.target),p=Hbe[o.dir].includes(u.key);m&&p&&(i.onOpenChange(!1),(f=l.trigger)==null||f.focus(),u.preventDefault())})})})})})});oP.displayName=iP;function lP(e){return e?"open":"closed"}function Am(e){return e==="indeterminate"}function lb(e){return Am(e)?"indeterminate":e?"checked":"unchecked"}function u0e(e){const t=document.activeElement;for(const s of e)if(s===t||(s.focus(),document.activeElement!==t))return}function h0e(e,t){return e.map((s,r)=>e[(t+r)%e.length])}function m0e(e,t,s){const a=t.length>1&&Array.from(t).every(d=>d===t[0])?t[0]:t,i=s?e.indexOf(s):-1;let o=h0e(e,Math.max(i,0));a.length===1&&(o=o.filter(d=>d!==s));const c=o.find(d=>d.toLowerCase().startsWith(a.toLowerCase()));return c!==s?c:void 0}function p0e(e,t){const{x:s,y:r}=e;let a=!1;for(let i=0,o=t.length-1;i<t.length;o=i++){const l=t[i],c=t[o],d=l.x,u=l.y,m=c.x,p=c.y;u>r!=p>r&&s<(m-d)*(r-u)/(p-u)+d&&(a=!a)}return a}function f0e(e,t){if(!t)return!1;const s={x:e.clientX,y:e.clientY};return p0e(s,t)}function qd(e){return t=>t.pointerType==="mouse"?e(t):void 0}var g0e=VT,x0e=sb,v0e=HT,y0e=WT,b0e=ib,w0e=GT,j0e=zp,_0e=KT,k0e=JT,N0e=XT,S0e=tP,C0e=sP,T0e=nP,P0e=aP,E0e=oP,Fp="DropdownMenu",[A0e,nje]=Is(Fp,[UT]),Bs=UT(),[R0e,cP]=A0e(Fp),dP=e=>{const{__scopeDropdownMenu:t,children:s,dir:r,open:a,defaultOpen:i,onOpenChange:o,modal:l=!0}=e,c=Bs(t),d=h.useRef(null),[u,m]=tr({prop:a,defaultProp:i??!1,onChange:o,caller:Fp});return n.jsx(R0e,{scope:t,triggerId:pn(),triggerRef:d,contentId:pn(),open:u,onOpenChange:m,onOpenToggle:h.useCallback(()=>m(p=>!p),[m]),modal:l,children:n.jsx(g0e,{...c,open:u,onOpenChange:m,dir:r,modal:l,children:s})})};dP.displayName=Fp;var uP="DropdownMenuTrigger",hP=h.forwardRef((e,t)=>{const{__scopeDropdownMenu:s,disabled:r=!1,...a}=e,i=cP(uP,s),o=Bs(s);return n.jsx(x0e,{asChild:!0,...o,children:n.jsx(qe.button,{type:"button",id:i.triggerId,"aria-haspopup":"menu","aria-expanded":i.open,"aria-controls":i.open?i.contentId:void 0,"data-state":i.open?"open":"closed","data-disabled":r?"":void 0,disabled:r,...a,ref:Jm(t,i.triggerRef),onPointerDown:Ee(e.onPointerDown,l=>{!r&&l.button===0&&l.ctrlKey===!1&&(i.onOpenToggle(),i.open||l.preventDefault())}),onKeyDown:Ee(e.onKeyDown,l=>{r||(["Enter"," "].includes(l.key)&&i.onOpenToggle(),l.key==="ArrowDown"&&i.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(l.key)&&l.preventDefault())})})})});hP.displayName=uP;var $0e="DropdownMenuPortal",mP=e=>{const{__scopeDropdownMenu:t,...s}=e,r=Bs(t);return n.jsx(v0e,{...r,...s})};mP.displayName=$0e;var pP="DropdownMenuContent",fP=h.forwardRef((e,t)=>
1037{const{__scopeDropdownMenu:s,...r}=e,a=cP(pP,s),i=Bs(s),o=h.useRef(!1);return n.jsx(y0e,{id:a.contentId,"aria-labelledby":a.triggerId,...i,...r,ref:t,onCloseAutoFocus:Ee(e.onCloseAutoFocus,l=>{var c;o.current||(c=a.triggerRef.current)==null||c.focus(),o.current=!1,l.preventDefault()}),onInteractOutside:Ee(e.onInteractOutside,l=>{const c=l.detail.originalEvent,d=c.button===0&&c.ctrlKey===!0,u=c.button===2||d;(!a.modal||u)&&(o.current=!0)}),style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});fP.displayName=pP;var L0e="DropdownMenuGroup",I0e=h.forwardRef((e,t)=>{const{__scopeDropdownMenu:s,...r}=e,a=Bs(s);return n.jsx(b0e,{...a,...r,ref:t})});I0e.displayName=L0e;var O0e="DropdownMenuLabel",gP=h.forwardRef((e,t)=>{const{__scopeDropdownMenu:s,...r}=e,a=Bs(s);return n.jsx(w0e,{...a,...r,ref:t})});gP.displayName=O0e;var D0e="DropdownMenuItem",xP=h.forwardRef((e,t)=>{const{__scopeDropdownMenu:s,...r}=e,a=Bs(s);return n.jsx(j0e,{...a,...r,ref:t})});xP.displayName=D0e;var M0e="DropdownMenuCheckboxItem",vP=h.forwardRef((e,t)=>{const{__scopeDropdownMenu:s,...r}=e,a=Bs(s);return n.jsx(_0e,{...a,...r,ref:t})});vP.displayName=M0e;var z0e="DropdownMenuRadioGroup",F0e=h.forwardRef((e,t)=>{const{__scopeDropdownMenu:s,...r}=e,a=Bs(s);return n.jsx(k0e,{...a,...r,ref:t})});F0e.displayName=z0e;var U0e="DropdownMenuRadioItem",yP=h.forwardRef((e,t)=>{const{__scopeDropdownMenu:s,...r}=e,a=Bs(s);return n.jsx(N0e,{...a,...r,ref:t})});yP.displayName=U0e;var B0e="DropdownMenuItemIndicator",bP=h.forwardRef((e,t)=>{const{__scopeDropdownMenu:s,...r}=e,a=Bs(s);return n.jsx(S0e,{...a,...r,ref:t})});bP.displayName=B0e;var V0e="DropdownMenuSeparator",wP=h.forwardRef((e,t)=>{const{__scopeDropdownMenu:s,...r}=e,a=Bs(s);return n.jsx(C0e,{...a,...r,ref:t})});wP.displayName=V0e;var q0e="DropdownMenuArrow",H0e=h.forwardRef((e,t)=>{const{__scopeDropdownMenu:s,...r}=e,a=Bs(s);return n.jsx(T0e,{...a,...r,ref:t})});H0e.displayName=q0e;var W0e="DropdownMenuSubTrigger",jP=h.forwardRef((e,t)=>{const{__scopeDropdownMenu:s,...r}=e,a=Bs(s);return n.jsx(P0e,{...a,...r,ref:t})});jP.displayName=W0e;var G0e="DropdownMenuSubContent",_P=h.forwardRef((e,t)=>{const{__scopeDropdownMenu:s,...r}=e,a=Bs(s);return n.jsx(E0e,{...a,...r,ref:t,style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});_P.displayName=G0e;var Y0e=dP,K0e=hP,Q0e=mP,kP=fP,NP=gP,SP=xP,CP=vP,TP=yP,PP=bP,EP=wP,AP=jP,RP=_P;const $P=Y0e,LP=K0e,J0e=h.forwardRef(({className:e,inset:t,children:s,...r},a)=>n.jsxs(AP,{ref:a,className:_e("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[state=open]:bg-accent focus:bg-accent",t&&"pl-8",e),...r,children:[s,n.jsx(yn,{className:"ml-auto h-4 w-4"})]}));J0e.displayName=AP.displayName;const Z0e=h.forwardRef(({className:e,...t},s)=>n.jsx(RP,{ref:s,className:_e("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...t}));Z0e.displayName=RP.displayName;const cb=h.forwardRef(({className:e,sideOffset:t=4,...s},r)=>
1037n.jsx(Q0e,{children:n.jsx(kP,{ref:r,sideOffset:t,className:_e("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...s})}));cb.displayName=kP.displayName;const Hd=h.forwardRef(({className:e,inset:t,...s},r)=>n.jsx(SP,{ref:r,className:_e("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors data-[disabled]:pointer-events-none data-[disabled]:opacity-50 focus:bg-accent focus:text-accent-foreground",t&&"pl-8",e),...s}));Hd.displayName=SP.displayName;const X0e=h.forwardRef(({className:e,children:t,checked:s,...r},a)=>n.jsxs(CP,{ref:a,className:_e("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors data-[disabled]:pointer-events-none data-[disabled]:opacity-50 focus:bg-accent focus:text-accent-foreground",e),checked:s,...r,children:[n.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:n.jsx(PP,{children:n.jsx(ms,{className:"h-4 w-4"})})}),t]}));X0e.displayName=CP.displayName;const ewe=h.forwardRef(({className:e,children:t,...s},r)=>n.jsxs(TP,{ref:r,className:_e("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors data-[disabled]:pointer-events-none data-[disabled]:opacity-50 focus:bg-accent focus:text-accent-foreground",e),...s,children:[n.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:n.jsx(PP,{children:n.jsx(Ll,{className:"h-2 w-2 fill-current"})})}),t]}));ewe.displayName=TP.displayName;const twe=h.forwardRef(({className:e,inset:t,...s},r)=>n.jsx(NP,{ref:r,className:_e("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",e),...s}));twe.displayName=NP.displayName;const IP=h.forwardRef(({className:e,...t},s)=>n.jsx(EP,{ref:s,className:_e("-mx-1 my-1 h-px bg-muted",e),...t}));IP.displayName=EP.displayName;function swe({offers:e,workspaceId:t,t:s,onToggleStatus:r,onDelete:a,onCreateLink:i,onOpenLinkInfo:o,linkCreating:l,expandedOffer:c,onExpandedChange:d}){const[u,m]=h.useState(null),p=c!==void 0?c:u,f=k=>{d?d(k):m(k)},[g,x]=h.useState({}),[b,v]=h.useState({}),[y,w]=h.useState(null),j=h.useCallback(async k=>{const{data:S}=await I.from("consultation_links").select("id, offer_id, status, client_name, created_at, used_at").eq("offer_id",k).eq("workspace_id",t).order("created_at",{ascending:!1});if(!S)return;x(E=>({...E,[k]:S}));const T=S.map(E=>E.id);if(T.length===0)return;const{data:C}=await I.from("jobs").select("id, status, payload_json, result_json").eq("workspace_id",t).eq("job_type","conduct_consultation").in("status",["completed","failed","running"]);if(!C)return;const B={};for(const E of C){const z=(E.payload_json||{}).link_id;if(!z||!T.includes(z))continue;const ne=E.result_json||{};let V=0;typeof ne.worker_active_seconds=="number"&&ne.worker_active_seconds>0?V=ne.worker_active_seconds:E.status==="running"&&typeof ne.worker_active_started_at=="string"&&(V=Math.max(0,Math.round((Date.now()-new Date(ne.worker_active_started_at).getTime())/1e3))),V>0&&(B[z]=(B[z]||0)+V/60)}v(E=>({...E,...B}))},[t]);h.useEffect(()=>{p&&!g[p]&&j(p)},[p,g,j]);const _=k=>{p===k?f(null):(f(k),j(k))},N=k=>{navigator.clipboard.writeText(`${window.location.origin}/consultation/${k}`),w(k),setTimeout(()=>w(null),2e3)};return e.length===0?null:n.jsxs(de.div,{...Te(.03),className:"rounded-2xl bg-surface-elevated border border-border/50 shadow-premium-sm p-6 space-y-4",children:[n.jsxs("h2",{className:"font-heading font-semibold text-lg text-foreground flex items-center gap-2",children:[n.jsx(Zs,{size:18,className:"text-primary"})," ",s("offersTitle")]}),n.jsx("div",{className:"space-y-3",children:e.map(k=>n.jsxs("div",{className:"rounded-xl border border-border/50 bg-muted/20 overflow-hidden",children:[n.jsxs("div",{className:"px-4 py-3 space-y-2 lg:space-y-0 lg:flex lg:items-center lg:justify-between",children:[n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("span",{className:"text-sm font-semibold text-foreground line-clamp-1",children:k.title}),k.duration_minutes&&n.jsx("span",{className:"text-[10px] text-muted-foreground block",children:s("duration",{min:k.duration_minutes})})]}),n.jsxs("div",{className:"flex items-center gap-3 flex-wrap lg:flex-nowrap",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:"text-[10px] text-muted-foreground whitespace-nowrap",children:s(`offerStatus.${k.status}`)}),n.jsx(Ut,{checked:k.status==="published",onCheckedChange:()=>r(k.id,k.status)})]}),n.jsxs("div",{className:"flex items-center gap-1",children:[k.status==="published"&&n.jsxs(L,{variant:"outline",size:"sm",className:"text-xs gap-1.5 h-8",disabled:l,onClick:()=>{i(k.id).then(()=>j(k.id))},children:[n.jsx(Pr,{size:12})," ",s("publishLink")]}),n.jsxs(L,{variant:"ghost",size:"sm",className:"text-xs gap-1 h-8",onClick:()=>_(k.id),children:[s("links.title"),p===k.id?n.jsx(wy,{size:12}):n.jsx(ps,{size:12})]}),n.jsxs($P,{children:[n.jsx(LP,{asChild:!0,children:n.jsx(L,{variant:"ghost",size:"icon",className:"h-8 w-8",children:n.jsx(h4,{size:14})})}),n.jsxs(cb,{align:"end",children:[n.jsxs(Hd,{className:"gap-2 text-xs",children:[n.jsx($d,{size:12})," ",s("editOffer")]}),n.jsxs(Hd,{className:"gap-2 text-xs text-destructive focus:text-destructive",onClick:()=>a(k.id),children:[n.jsx(ci,{size:12})," ",s("deleteOffer")]})]})]})]})]})]}),p===k.id&&n.jsxs("div",{className:"border-t border-border/30 bg-muted/10 px-4 py-3 space-y-2",children:[n.jsx("h4",{className:"text-xs font-medium text-muted-foreground",children:s("links.title")}),!g[k.id]||g[k.id].length===0?n.jsx("p",{className:"text-xs text-muted-foreground
1037/60",children:s("links.empty")}):n.jsx("div",{className:"space-y-1.5",children:g[k.id].map(S=>n.jsxs("div",{className:"flex items-center gap-2 text-xs rounded-lg bg-background/50 border border-border/30 px-3 py-2",children:[n.jsx(fe,{variant:S.status==="active"?"default":S.status==="used"?"secondary":"outline",className:"text-[10px] px-1.5 py-0 shrink-0",children:s(`links.status.${S.status==="active"&&!S.used_at?"new":S.status}`)}),S.client_name&&n.jsx("span",{className:"text-foreground font-medium truncate",children:S.client_name}),b[S.id]!=null&&b[S.id]>0&&n.jsxs("span",{className:"text-muted-foreground shrink-0 flex items-center gap-1",children:[n.jsx(ls,{size:10}),s("links.timeUsed",{used:Math.round(b[S.id]),total:k.duration_minutes||15})]}),n.jsx("span",{className:"flex-1"}),n.jsx(L,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 shrink-0",onClick:()=>o(S),title:s("links.info"),children:n.jsx(Ty,{size:12,className:"text-muted-foreground"})}),n.jsx(L,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 shrink-0",onClick:()=>N(S.id),children:y===S.id?n.jsx(ms,{size:12,className:"text-primary"}):n.jsx(Ma,{size:12})}),n.jsx("a",{href:`${window.location.origin}/consultation/${S.id}`,target:"_blank",rel:"noopener noreferrer",className:"shrink-0",children:n.jsx(Rs,{size:12,className:"text-muted-foreground hover:text-foreground"})})]},S.id))})]})]},k.id))})]})}function nwe({t:e,publishOffer:t,setPublishOffer:s,onPublishToLink:r,linkOffer:a,setLinkOffer:i,linkUrl:o,setLinkUrl:l,copied:c,onCopyLink:d,infoLink:u,setInfoLink:m,infoLinkSessions:p,infoLoading:f,copiedLinkId:g,onCopyLinkUrl:x,onDeactivateLink:b,deleteOfferId:v,setDeleteOfferId:y,onConfirmDelete:w}){return n.jsxs(n.Fragment,{children:[n.jsx(ns,{open:!!t,onOpenChange:j=>!j&&s(null),children:n.jsxs(Zt,{className:"sm:max-w-md",children:[n.jsxs(Xt,{children:[n.jsx(es,{children:e("publishModalTitle")}),n.jsx(us,{children:e("publishModalDesc")})]}),n.jsxs("div",{className:"space-y-3 pt-2",children:[n.jsxs("button",{className:"w-full flex items-center gap-3 rounded-xl border border-border/50 bg-muted/20 px-4 py-3 hover:bg-muted/40 transition-colors text-left",onClick:()=>{},children:[n.jsx("div",{className:"w-9 h-9 rounded-lg bg-[#FF424D]/10 flex items-center justify-center",children:n.jsx(co,{size:18,className:"text-[#FF424D]"})}),n.jsxs("div",{children:[n.jsx("span",{className:"text-sm font-semibold text-foreground",children:e("publishPatreon")}),n.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Patreon"})]})]}),n.jsxs("button",{className:"w-full flex items-center gap-3 rounded-xl border border-border/50 bg-muted/20 px-4 py-3 hover:bg-muted/40 transition-colors text-left",onClick:()=>t&&r(t),children:[n.jsx("div",{className:"w-9 h-9 rounded-lg bg-primary/10 flex items-center justify-center",children:n.jsx(Pr,{size:18,className:"text-primary"})}),n.jsxs("div",{children:[n.jsx("span",{className:"text-sm font-semibold text-foreground",children:e("publishLink")}),n.jsx("p",{className:"text-[10px] text-muted-foreground",children:e("linkDesc")})]})]})]})]})}),n.jsx(ns,{open:!!a,onOpenChange:j=>{j||(i(null),l(null))},children:n.jsxs(Zt,{className:"max-w-[calc(100vw-2rem)] sm:max-w-md",children:[n.jsxs(Xt,{children:[n.jsx(es,{children:e("linkTitle")}),n.jsx(us,{children:e("linkDesc")})]}),n.jsx("div",{className:"space-y-3 pt-2",children:n.jsxs("div",{className:"flex items-center gap-2 bg-muted/40 rounded-lg px-3 py-2 min-w-0 overflow-hidden",children:[n.jsx("code",{className:"text-xs text-muted-foreground flex-1 min-w-0 break-all line-clamp-2",children:o||"…"}),n.jsx(L,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 shrink-0",onClick:d,children:c?n.jsx(ms,{size:14,className:"text-primary"}):n.jsx(Ma,{size:14})})]})})]})}),n.jsx(ns,{open:!!u,onOpenChange:j=>{j||m(null)},children:n.jsxs(Zt,{className:"max-w-[calc(100vw-2rem)] sm:max-w-md",children:[n.jsx(Xt,{children:n.jsx(es,{children:e("links.infoTitle")})}),f?n.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:e("loading")}):u&&n.jsxs("div",{className:"space-y-4 pt-1",children:[n.jsxs("div",{className:"flex items-center gap-2 bg-muted/40 rounded-lg px-3 py-2 min-w-0 overflow-hidden",children:[n.jsx("code",{className:"text-xs text-muted-foreground flex-1 min-w-0 break-all line-clamp-1",children:`${window.location.origin}/consultation/${u.id}`}),n.jsx(L,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 shrink-0",onClick:()=>x(u.id),children:g===u.id?n.jsx(ms,{size:14,className:"text-primary"}):n.jsx(Ma,{size:14})})]}),n.jsxs("div",{className:"space-y-2 text-sm",children:[n.jsxs("div",{className:"flex justify-between",children:[n.jsx("span",{className:"text-muted-foreground",children:e("links.infoCreated")}),n.jsx("span",{className:"text-foreground",children:new Date(u.created_at).toLocaleStr
1037ing()})]}),n.jsxs("div",{className:"flex justify-between",children:[n.jsx("span",{className:"text-muted-foreground",children:e("links.infoStatus")}),n.jsx(fe,{variant:u.status==="active"?"default":"secondary",className:"text-[10px]",children:e(`links.status.${u.status}`)})]}),u.client_name&&n.jsxs("div",{className:"flex justify-between",children:[n.jsx("span",{className:"text-muted-foreground",children:e("links.infoClient")}),n.jsx("span",{className:"text-foreground",children:u.client_name})]}),n.jsxs("div",{className:"flex justify-between",children:[n.jsx("span",{className:"text-muted-foreground",children:e("links.infoSessions")}),n.jsx("span",{className:"text-foreground",children:p.length})]}),n.jsxs("div",{className:"flex justify-between",children:[n.jsx("span",{className:"text-muted-foreground",children:e("links.infoTotalTime")}),n.jsx("span",{className:"text-foreground",children:p.length>0?`${Math.round(p.reduce((j,_)=>j+_.elapsed_min,0))} ${e("links.min")}`:`0 ${e("links.min")}`})]})]}),p.length>0&&n.jsxs("div",{className:"space-y-1.5",children:[n.jsx("h4",{className:"text-xs font-medium text-muted-foreground",children:e("links.infoSessionsTitle")}),p.map((j,_)=>n.jsxs("div",{className:"flex items-center gap-2 text-xs rounded-lg bg-muted/20 border border-border/20 px-3 py-2",children:[n.jsxs("span",{className:"text-muted-foreground",children:["#",_+1]}),n.jsx("span",{className:"text-foreground",children:j.started_at?new Date(j.started_at).toLocaleString():"—"}),n.jsx("span",{className:"flex-1"}),n.jsxs("span",{className:"text-muted-foreground",children:[Math.round(j.elapsed_min)," ",e("links.min")]}),n.jsx(fe,{variant:j.status==="completed"?"default":"secondary",className:"text-[10px] px-1.5 py-0",children:j.status})]},j.id))]}),u.status==="active"&&n.jsx(L,{variant:"destructive",size:"sm",className:"w-full",onClick:()=>{b(u.id,u.offer_id),m(null)},children:e("links.deactivate")})]})]})}),n.jsx(bi,{open:!!v,onOpenChange:j=>
1037!j&&y(null),children:n.jsxs(oa,{children:[n.jsxs(la,{children:[n.jsx(da,{children:e("deleteConfirm")}),n.jsx(ua,{children:e("deleteConfirmDesc")})]}),n.jsxs(ca,{children:[n.jsx(ma,{children:e("cancel")}),n.jsx(ha,{onClick:()=>{v&&w(v),y(null)},children:e("confirm")})]})]})})]})}const OP=["quick","deep","strategy","qa","premium"],DP={quick:nr,deep:bn,strategy:jy,qa:cu,premium:_y},rwe={quick:15,deep:30,strategy:45,qa:30,premium:60},awe=()=>{const{t:e}=Oe("consultations"),{profile:t}=st(),{personas:s,loading:r}=tT(),[a,i,o]=dc("consultations:create",{name:"",desc:"",price:"from $100",selectedType:"strategy",duration:"45",topic:"",sttLanguage:"ru",greeting:"",continueText:"",language:"ru"}),{name:l,desc:c,price:d,selectedType:u,duration:m,topic:p,sttLanguage:f,greeting:g,continueText:x,language:b}=a,v=W=>i(ge=>({...ge,name:W})),y=W=>i(ge=>({...ge,desc:W})),w=W=>i(ge=>({...ge,price:W})),j=W=>i(ge=>({...ge,selectedType:W})),_=W=>i(ge=>({...ge,duration:W})),N=W=>i(ge=>({...ge,topic:W})),k=W=>i(ge=>({...ge,sttLanguage:W})),S=W=>i(ge=>({...ge,greeting:W})),T=W=>i(ge=>({...ge,continueText:W})),C=W=>i(ge=>({...ge,language:W})),[B,E]=h.useState(""),[H,z]=h.useState([]),[ne,V]=h.useState(!0),[te,R]=h.useState(!1),[F,$]=h.useState(!1),{fill:J,fillWithTopicCheck:Y,isLoading:re,topicModal:G}=pa(),[O,Z]=Gr("offer",""),[A,oe]=h.useState(null),[ue,je]=h.useState(null),[ae,ie]=h.useState(null),[we,Ae]=h.useState(!1),[nt,Qe]=h.useState(!1),[P,U]=h.useState(null),[Q,ve]=h.useState(null),[We,Ze]=h.useState([]),[Je,xt]=h.useState(!1),[Pt,K]=h.useState(null);h.useEffect(()=>{i(W=>({...W,name:W.name||e("defaultName"),desc:W.desc||e("defaultDesc"),topic:W.topic||e("defaultTopic")}))},[e]),h.useEffect(()=>{if(!B&&s.length>0){E(s[0].id);const W=s[0].language;W&&C(W)}},[s,B]);const ye=W=>{E(W);const ge=s.find(Ne=>Ne.id===W);ge!=null&&ge.language&&C(ge.language)},De=h.useCallback(async()=>{if(!(t!=null&&t.workspace_id))return;V(!0);const{data:W}=await I.from("offers").select("id, title, description, duration_minutes, status, metadata_json, pricing_note").eq("workspace_id",t.workspace_id).eq("offer_type","consultation").order("created_at",{ascending:!1});W&&z(W),V(!1)},[t==null?void 0:t.workspace_id]);h.useEffect(()=>{De()},[De]),h.useEffect(()=>{if(!(t!=null&&t.workspace_id))return;const W=t.workspace_id,ge=Sp({table:"offers",filter:`workspace_id=eq.${W}`,channelKey:`offers-${W}`,onChange:()=>{De()}}),Ne=()=>De(),rt=()=>{document.visibilityState==="visible"&&De()};return window.addEventListener("focus",Ne),document.addEventListener("visibilitychange",rt),()=>{window.removeEventListener("focus",Ne),document.removeEventListener("visibilitychange",rt),ge()}},[t==null?void 0:t.workspace_id,De]);const pt=h.useCallback(async()=>{if(!l.trim())return;const W=s.find(ge=>ge.id===B);$(!0);try{const{data:ge,error:Ne}=await I.functions.invoke("generate-auto-messages",{body:{persona_name:(W==null?void 0:W.name)||"Consultant",persona_id:B||null,language:b,title:l.trim(),description:c,session_type:"consultation"}});!Ne&&(ge!=null&&ge.greeting)&&(S(ge.greeting),T(ge.continue_talking))}catch{}$(!1)},[l,c,B,s,b]),kt=async()=>{if(!(t!=null&&t.workspace_id))return;R(!0);const{data:W,error:ge}=await I.from("offers").insert({workspace_id:t.workspace_id,persona_id:B||null,offer_type:"consultation",title:l,description:c,duration_minutes:parseInt(m),status:"draft",pricing_note:d,greeting_text:g||null,continue_text:x||null,metadata_json:{consultation_type:u,topic:p,stt_language:f}}).select("id, title, description, duration_minutes, status, metadata_json, pricing_note").single();!ge&&W&&(z(Ne=>[W,...Ne]),o()),R(!1)},X=async(W,ge)=>{const Ne=ge==="published"?"draft":"published",{error:rt}=await I.from("offers").update({status:Ne}).eq("id",W);rt||z(Re=>Re.map(lt=>lt.id===W?{...lt,status:Ne}:lt))},M=async W=>{await I.from("offers").delete().eq("id",W),z(ge=>ge.filter(Ne=>Ne.id!==W))},se=async W=>{if(!(t!=null&&t.workspace_id))return;Ae(!0);const{data:ge,error:Ne}=await I.from("consultation_links").insert({offer_id:W,workspace_id:t.workspace_id,status:"active"}).select("id").single();Ae(!1),!(Ne||!ge)&&(ie(`${window.location.origin}/consultation/${ge.id}`),je(W))},he=()=>{ae&&(navigator.clipboard.writeText(ae),Qe(!0),setTimeout(()=>Qe(!1),2e3))},Ce=W=>{navigator.clipboard.writeText(`${window.location.origin}/consultation/${W}`),K(W),setTimeout(()=>K(null),2e3)},Ve=async(W,ge)=>{await I.from("consultation_links").update({status:"expired"}).eq("id",W)},me=h.useCallback(async W=>{if(ve(W),Ze([]),xt(!0),!(t!=null&&t.workspace_id)){xt(!1);return}const{data:ge}=await I.from("jobs").select("id, status, started_at, completed_at, created_at, payload_json").eq("workspace_id",t.workspace_id).eq("job_type","conduct_consultation").in("status",["completed","failed","running"]);if(ge){const Ne=ge.filter(rt=>(rt.payload_json||{}).link_id===W.id).map(rt=>{const Re=rt.started_at||rt.created_at,lt=rt.completed_at||new Date().toISOString();return{id:rt.id,status:rt.status,started_at:rt.started_at,completed_at:rt.completed_at,elapsed_min:Math.max(0,(new Date(lt).getTime()-new Date(Re).getTime())/6e4)}}).sort((rt,Re)=>(rt.started_at||"").localeCompare(Re.started_at||""));Ze(Ne)}xt(!1)},[t==null?void 0:t.workspace_id]),Ge=W=>{oe(null),se(W)},Ye=u,ee=DP[Ye]||Zs;return ne||r?n.jsx(Ln,{message:e("loading")}):s.length===0?n.jsx(Er,{icon:Xs,title:e("noPersona"),description:e("noPersona")}
1037):n.jsxs("div",{className:"max-w-6xl mx-auto space-y-8",children:[n.jsx(de.div,{...Te(),children:n.jsxs("h1",{className:"font-heading font-bold text-2xl md:text-3xl text-foreground flex items-center gap-2",children:[n.jsx(Zs,{className:"text-primary",size:24}),e("pageTitle")]})}),n.jsx(swe,{offers:H,workspaceId:(t==null?void 0:t.workspace_id)||"",t:e,onToggleStatus:X,onDelete:W=>U(W),onCreateLink:se,onOpenLinkInfo:me,linkCreating:we,expandedOffer:O||null,onExpandedChange:W=>Z(W||"")}),n.jsx(nwe,{t:e,publishOffer:A,setPublishOffer:oe,onPublishToLink:Ge,linkOffer:ue,setLinkOffer:je,linkUrl:ae,setLinkUrl:ie,copied:nt,onCopyLink:he,infoLink:Q,setInfoLink:ve,infoLinkSessions:We,infoLoading:Je,copiedLinkId:Pt,onCopyLinkUrl:Ce,onDeactivateLink:Ve,deleteOfferId:P,setDeleteOfferId:U,onConfirmDelete:M}),H.length===0&&n.jsx(Er,{icon:Zs,title:e("emptyTitle"),description:e("emptyDesc")}),n.jsx(iwe,{selectedType:u,setSelectedType:j,t:e}),n.jsxs("div",{className:"grid lg:grid-cols-[1fr_360px] gap-6",children:[n.jsxs(de.div,{...Te(.1),className:"rounded-2xl bg-surface-elevated border border-border/50 shadow-premium-sm p-6 space-y-4",children:[n.jsxs("h2",{className:"font-heading font-semibold text-lg text-foreground flex items-center gap-2",children:[n.jsx(Xi,{size:18,className:"text-primary"})," ",e("createTitle")]}),n.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[n.jsx(Pe,{label:e("fields.name"),children:n.jsx(Ot,{value:l,onChange:W=>v(W.target.value),className:"bg-muted/30",aiLoading:re("name"),onAiFill:async()=>{const W=await Y({fieldName:"name",fieldLabel:e("fields.name"),currentValue:l,pageContext:{topic:p,type:u,language:b},personaId:B,language:b,topicValue:p,onTopicSet:N});W&&v(W)}})}),n.jsx(Pe,{label:e("fields.duration"),children:n.jsxs(ut,{value:m,onValueChange:_,children:[n.jsx(ct,{className:"bg-muted/30",children:n.jsx(ht,{})}),n.jsx(dt,{children:[15,30,45,60].map(W=>n.jsx(ce,{value:String(W),children:e("duration",{min:W})},W))})]})}),n.jsx(Pe,{label:e("fields.persona"),children:n.jsxs(ut,{value:B,onValueChange:ye,children:[n.jsx(ct,{className:"bg-muted/30",children:n.jsx(ht,{})}),n.jsx(dt,{children:s.map(W=>n.jsx(ce,{value:W.id,children:W.name},W.id))})]})}),n.jsx(Pe,{label:e("fields.topic"),children:n.jsx(Ot,{value:p,onChange:W=>N(W.target.value),className:"bg-muted/30",aiLoading:re("topic"),onAiFill:async()=>{const W=await J({fieldName:"topic",fieldLabel:e("fields.topic"),currentValue:p,pageContext:{name:l,type:u,description:c,language:b},personaId:B,language:b});W&&N(W)}})}),n.jsx(Pe,{label:e("fields.format"),children:n.jsxs(ut,{value:u,onValueChange:j,children:[n.jsx(ct,{className:"bg-muted/30",children:n.jsx(ht,{})}),n.jsx(dt,{children:OP.map(W=>n.jsx(ce,{value:W,children:e(`types.${W}.label`)},W))})]})}),n.jsx(Pe,{label:e("fields.price"),children:n.jsx(Ot,{value:d,onChange:W=>w(W.target.value),className:"bg-muted/30",placeholder:e("fields.pricePlaceholder"),aiLoading:re("price"),onAiFill:async()=>{const W=await Y({fieldName:"price",fieldLabel:e("fields.price"),currentValue:d,pageContext:{name:l,topic:p,type:u,duration:m,language:b},personaId:B,language:b,topicValue:p,onTopicSet:N});W&&w(W)}})}),n.jsx(Pe,{label:e("fields.sttLanguage"),children:n.jsxs(ut,{value:f,onValueChange:k,children:[n.jsx(ct,{className:"bg-muted/30",children:n.jsx(ht,{})}),n.jsxs(dt,{children:[n.jsx(ce,{value:"ru",children:e("languages.ru")}),n.jsx(ce,{value:"en",children:e("languages.en")}),n.jsx(ce,{value:"auto",children:e("languages.auto")})]})]})})]}),n.jsx(Pe,{label:e("fields.description"),children:n.jsx(os,{value:c,onChange:W=>y(W.target.value),className:"bg-muted/30 min-h-[72px] resize-none",aiLoading:re("description"),onAiFill:async()=>{const W=await Y({fieldName:"description",fieldLabel:e("fields.description"),currentValue:c,pageContext:{name:l,topic:p,type:u,price:d,language:b},personaId:B,language:b,topicValue:p,onTopicSet:N});W&&y(W)}})}),n.jsxs("div",{className:"rounded-xl border border-border/50 bg-muted/10 p-4 space-y-3",children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsx("span",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wider",children:e("autoMessages.sectionTitle")}),n.jsxs(L,{type:"button",variant:"ghost",size:"sm",className:"gap-1.5 text-xs h-7",onClick:pt,disabled:F||!l.trim(),children:[n.jsx(xi,{size:13,className:F?"animate-spin":""}),e(F?"autoMessages.generating":"autoMessages.generate")]})]}),n.jsx(Pe,{label:e("autoMessages.greetingLabel"),children:n.jsx(os,{value:g,onChange:W=>S(W.target.value),placeholder:e("autoMessages.greetingPlaceholder"),className:"bg-muted/30 min-h-[60
1037px] text-sm",rows:2,aiLoading:re("greeting"),onAiFill:async()=>{const W=await Y({fieldName:"greeting",fieldLabel:e("autoMessages.greetingLabel"),currentValue:g,pageContext:{name:l,topic:p,description:c,type:u,language:b},personaId:B,language:b,topicValue:p,onTopicSet:N});W&&S(W)}})}),n.jsx(Pe,{label:e("autoMessages.continueLabel"),children:n.jsx(os,{value:x,onChange:W=>T(W.target.value),placeholder:e("autoMessages.continuePlaceholder"),className:"bg-muted/30 min-h-[60px] text-sm",rows:2,aiLoading:re("continue"),onAiFill:async()=>{const W=await Y({fieldName:"continue_text",fieldLabel:e("autoMessages.continueLabel"),currentValue:x,pageContext:{name:l,topic:p,greeting:g,description:c,language:b},personaId:B,language:b,topicValue:p,onTopicSet:N});W&&T(W)}})})]}),n.jsxs(L,{variant:"hero",className:"w-full gap-2",onClick:kt,disabled:te||!l.trim(),children:[n.jsx(tt,{size:15})," ",e(te?"saving":"createOffer")]})]}),n.jsx(owe,{name:l,desc:c,price:d,activeTypeId:Ye,ActiveIcon:ee,duration:m,t:e})]}),n.jsx(Lp,{open:G.open,onConfirm:G.onConfirm,onCancel:G.onCancel})]})};function iwe({selectedType:e,setSelectedType:t,t:s}){return n.jsxs(de.div,{...Te(.05),className:"rounded-2xl bg-surface-elevated border border-border/50 shadow-premium-sm p-6 space-y-4",children:[n.jsxs("h2",{className:"font-heading font-semibold text-lg text-foreground flex items-center gap-2",children:[n.jsx(Zs,{size:18,className:"text-primary"})," ",s("typesTitle")]}),n.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-5 gap-3",children:OP.map(r=>{const a=e===r,i=DP[r];return n.jsxs("button",{onClick:()=>t(r),className:`rounded-xl border-2 p-4 text-left transition-all duration-200 ${a?"border-primary bg-primary/5 shadow-premium-sm":"border-border/50 bg-muted/20 hover:border-primary/30"}`,children:[n.jsx(i,{size:20,className:a?"text-primary":"text-muted-foreground"}),n.jsx("p",{className:`mt-2 text-sm font-semibold ${a?"text-foreground":"text-muted-foreground"}`,children:s(`types.${r}.label`)}),n.jsxs(fe,{variant:"secondary",className:"text-[9px] mt-2 gap-1",children:[n.jsx(ls,{size:8})," ",s("duration",{min:rwe[r]})]})]},r)})})]})}function owe({name:e,desc:t,price:s,activeTypeId:r,ActiveIcon:a,duration:i,t:o}){return n.jsx("div",{className:"space-y-5 lg:sticky lg:top-6 self-start",children:n.jsxs(de.div,{...Te(.12),className:"rounded-2xl border border-border/50 shadow-premium-md overflow-hidden",children:[n.jsxs("div",{className:"bg-gradient-primary p-5 pb-10 relative",children:[n.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(circle_at_70%_30%,hsl(195_85%_48%/0.3),transparent_60%)]"}),n.jsx("p",{className:"text-primary-foreground/60 text-[10px] font-medium uppercase tracking-wider relative z-10",children:o("previewLabel")})]}),n.jsxs("div",{className:"bg-surface-elevated px-5 pb-5 -mt-6 relative z-10",children:[n.jsx("div",{className:"w-14 h-14 rounded-2xl bg-gradient-primary shadow-premium-md flex items-center justify-center text-primary-foreground text-lg font-bold border-4 border-surface-elevated",children:n.jsx(Zs,{size:22})}),n.jsxs("div",{className:"mt-3 space-y-3",children:[n.jsxs("div",{children:[n.jsx("h3",{className:"font-heading font-bold text-lg text-foreground",children:e}),n.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1.5 mt-0.5",children:[n.jsx(a,{size:11}),o(`types.${r}.label`)," · ",o("duration",{min:i})]})]}),n.jsx("p",{className:"text-sm text-muted-foreground leading-relaxed",children:t}),n.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[n.jsxs(fe,{variant:"secondary",className:"text-[10px] gap-1",children:[n.jsx(cu,{size:9})," ",o("badgeVoice")]}),n.jsxs(fe,{variant:"secondary",className:"text-[10px] gap-1",children:[n.jsx(Xs,{size:9})," ",o("badge1on1")]}),n.jsxs(fe,{variant:"secondary",className:"text-[10px] gap-1",children:[n.jsx(li,{size:9})," ",o("badgePrivate")]})]}),n.jsxs("div",{className:"rounded-lg bg-primary/[0.04] border border-primary/10 p-3",children:[n.jsx("p",{className:"text-[10px] text-muted-foreground font-medium mb-1",children:o("clientPrice")}),n.jsx("p",{className:"text-lg font-heading font-bold text-foreground",children:s})]}),n.jsx(fe,{variant:"outline",className:"text-[10px]",children:o("draft")})]})]})]})})}const uh="webinars_paged";function lwe({page:e,pageSize:t,query:s}){var g,x;const{profile:r}=st(),a=r==null?void 0:r.workspace_id,i=na(),l=Zr({queryKey:["webinars_clip_ids",a,s],queryFn:async()=>{const b=s.replace(/[%_]/g,w=>`\\${w}`),{data:v,error:y}=await I.from("live_clips").select("live_session_id").eq("workspace_id",a).or(`spoken_text.ilike.%${b}%,highlight_reason.ilike.%${b}%`).limit(500);if(y)throw y;return Array.from(new Set((v||[]).map(w=>
1037w.live_session_id).filter(Boolean)))},enabled:!!a&&!!s}),c=s?l.data??null:null,u=Zr({queryKey:[uh,a,e,t,s,c],queryFn:async()=>{let b=I.from("live_sessions").select("*",{count:"exact"}).eq("workspace_id",a).eq("live_mode","webinar").order("created_at",{ascending:!1});if(s){const N=s.replace(/[%_]/g,S=>`\\${S}`),k=[`title.ilike.%${N}%`,`description.ilike.%${N}%`];c&&c.length>0&&k.push(`id.in.(${c.join(",")})`),b=b.or(k.join(","))}const v=(e-1)*t,y=v+t-1;b=b.range(v,y);const{data:w,count:j,error:_}=await b;if(_)throw _;return{items:w??[],total:j??0}},enabled:!!a&&(!s||l.isFetched),placeholderData:NR});lc({table:"live_sessions",filter:a?`workspace_id=eq.${a}`:void 0,queryKey:[uh,a],enabled:!!a});const m=h.useCallback(()=>{i.invalidateQueries({queryKey:[uh,a]})},[i,a]),p=h.useCallback((b,v)=>{i.setQueriesData({queryKey:[uh,a]},y=>y&&{...y,items:y.items.map(w=>w.id===b?{...w,...v}:w)})},[i,a]),f=h.useCallback(async b=>{const{data:v,error:y}=await I.from("live_sessions").select("*").eq("id",b).maybeSingle();return y?(console.warn("[useWebinarsPaged] fetchById failed:",y),null):v??null},[]);return{items:((g=u.data)==null?void 0:g.items)??[],total:((x=u.data)==null?void 0:x.total)??0,loading:u.isLoading||!!s&&l.isLoading,fetching:u.isFetching,refresh:m,patchSession:p,fetchById:f}}const Z1=["open","paid","closed","members","group"],cwe={open:Rd,paid:tt,closed:lS,members:eo,group:li},dwe=["ytMembers","patreonAccess","externalPremium"],uwe={ytMembers:Ls,patreonAccess:co,externalPremium:Ja},hwe=()=>{const{t:e}=Oe("webinars"),{profile:t}=st(),[s,r]=tu(),[a,i,o]=dc("webinars:create",{selectedFormat:"paid",topic:"",desc:"",plan:"",greeting:"",continueText:"",summaryText:"",language:"ru",platform:"restream",duration:"60",liveSubtitles:!0}),{selectedFormat:l,topic:c,desc:d,plan:u,greeting:m,continueText:p,summaryText:f,language:g,platform:x,duration:b,liveSubtitles:v}=a,y=D=>i(pe=>({...pe,selectedFormat:D})),w=D=>i(pe=>({...pe,topic:D})),j=D=>i(pe=>({...pe,desc:D})),_=D=>i(pe=>({...pe,plan:D})),N=D=>i(pe=>({...pe,greeting:D})),k=D=>i(pe=>({...pe,continueText:D})),S=D=>i(pe=>({...pe,summaryText:D})),T=D=>i(pe=>({...pe,language:D})),C=D=>i(pe=>({...pe,platform:D})),B=D=>i(pe=>({...pe,duration:D})),E=D=>i(pe=>({...pe,liveSubtitles:D})),[H,z]=_u(),[ne,V]=h.useState(!0),[te,R]=h.useState(!1),[F,$]=h.useState([]),[J,Y]=h.useState(()=>{try{return localStorage.getItem("webinar:selectedPersonaId")||""}catch{return""}});h.useEffect(()=>{try{J&&localStorage.setItem("webinar:selectedPersonaId",J)}catch{}},[J]);const{fill:re,fillWithTopicCheck:G,isLoading:O,topicModal:Z}=pa(),{create:A,updateStatus:oe,syncMeta:ue}=uo(),{jobs:je,dispatch:ae,refresh:ie}=ho(),{planKey:we}=ar(),[Ae,nt]=h.useState(!1),[Qe,P]=h.useState(null),[U,Q]=h.useState(null),[ve,We]=h.useState(null),[Ze,Je]=h.useState(null),[xt,Pt]=h.useState(new Set),[K,ye]=h.useState(null),De=h.useRef(!1),pt=h.useRef(!1),[kt,X]=h.useState(null),M=h.useRef(null),[se,he]=h.useState(""),[Ce,Ve]=h.useState("");h.useEffect(()=>{const D=setTimeout(()=>Ve(se.trim()),250);return()=>clearTimeout(D)},[se]);const me=10,[Ge,Ye]=h.useState(1),{items:ee,total:W,refresh:ge,patchSession:Ne,fetchById:rt}=lwe({page:Ge,pageSize:me,query:Ce}),Re=Math.max(1,Math.ceil(W/me));h.useEffect(()=>{Ye(1)},[Ce]),h.useEffect(()=>{Ge>Re&&Ye(Re)},[Ge,Re]);const lt=h.useMemo(()=>{var pe;const D=new Map;for(const Me of je){if(Me.job_type!==ql.CONDUCT_LIVE_SESSION)continue;const Wt=(pe=Me.payload_json)==null?void 0:pe.live_session_id;if(!Wt)continue;const rs=D.get(Wt);(!rs||new Date(Me.created_at)>new Date(rs.created_at))&&D.set(Wt,Me)}return D},[je]),at=(D,pe)=>{X({kind:D,text:pe}),setTimeout(()=>X(null),4e3)},vs=h.useCallback(async()=>{if(!(!c.trim()||De.current)){De.current=!0,nt(!0);try{const D={title:c.trim(),description:d||null,live_mode:"webinar",chat_reply_mode:"answer_after_topic",platform:x,persona_id:J||null,status:"draft",is_paid:l==="paid",greeting_text:m||null,continue_text:p||null,summary_text:f||null,webinar_plan:u||null,metadata_json:{planned_duration_min:parseInt(b)||0,access_format:l,live_subtitles:v,watermark_text:(H||"").trim().slice(0,120)}};if(ve){const{error:pe}=await I.from("live_sessions").update(D).eq("id",ve);if(pe){at("error",e("createErrorInline"));return}await ge(),ue(ve),o(),We(null),at("success",e("savedInline")),setTimeout(()=>{var Me;return(Me=M.current)==null?void 0:Me.scrollIntoView({behavior:"smooth",block:"start"})},100)}else{if(!await A(D)){at("error",e("createErrorInline"));return}o(),await ge(),at("success",e("createdInline")),setTimeout(()=>{var Me;return(Me=M.current)==null?void 0:Me.scrollIntoView({behavior:"smooth",block:"start"})},100)}}finally{nt(!1),De.current=!1}}},[c,d,x,J,l,u,m,p,f,b,ve,A,ge,o,ue,e]),Ht=h.useCallback(D=>{const pe=D.metadata_json||{};i(Me=>({...Me,topic:D.title||"",desc:D.description||"",plan:D.webinar_plan||"",greeting:D.greeting_text||"",continueText:D.continue_text||"",summaryText:D.summary_text||"",language:D.language||Me.language,platform:D.platform||Me.platform,selectedFormat:pe.access_format||(D.is_paid?"paid":Me.selectedFormat),duration:pe.planned_duration_min?String(pe.planned_duration_min):Me.duration,liveSubtitles:pe.live_subtitles!==!1})),typeof pe.watermark_text=="string"&&pe.watermark_text.trim()&&z(pe.watermark_text),D.persona_id&&Y(D.persona_id),We(D.id),at("success",e("editLoaded")),setTimeout(()=>{var Me;(Me=document.getElementById("webinar-create-form"))==null||Me.scrollIntoView({behavior:"smooth",block:"start"})},100)},[i,z,e]),On=h.useRef(null);h.useEffect(()=>{const D=s.get("edit");!D||On.current===D||(On.current=D,(async()=>{const pe=ee.find(Me=>Me.id===D)||await rt(D);pe&&(Ht(pe),s.delete("edit"),r(s,{replace:!0}))})())},[s,ee,Ht,r,rt]),h.useEffect(()=>{if(!ve)return;const D=ee.find(Me=>Me.id===ve);if(!D)return;const pe=D.metadata_json||{};pe.source!=="topic_discovery"||!pe.ai_fields_status||i(Me=>({...Me,desc:Me.desc||D.description||"",plan:Me.plan||D.webinar_plan||"",greeting:Me.greeting||D.greeting_text||"",continueText:Me.continueText||D.continue_text||"",summaryText:Me.summaryText||D.summary_text||""}))},[ve,ee,i]);const $r=h.useCallback(()=>{We(null),o()},[o]),nn=h.useCallback(async D=>
1037{if(!Ze&&window.confirm(e("cancelWebinarConfirm"))){Je(D);try{const{error:pe}=await I.from("live_sessions").update({status:"canceled",ended_at:new Date().toISOString()}).eq("id",D);if(pe){at("error",pe.message);return}ve===D&&(We(null),o()),ge()}finally{Je(null)}}},[Ze,ve,o,ge,at,e]),Dn=h.useCallback(async D=>{const pe=ee.find(mE=>mE.id===D)||await rt(D),Me=(pe==null?void 0:pe.persona_id)||J||null;if(!Me)return at("error",e("selectPersonaFirst","Select a persona first")),!1;const Wt=new Date().toISOString(),{error:rs}=await I.from("live_sessions").update({status:"live",started_at:Wt}).eq("id",D).in("status",["draft","scheduled","ready","review","approved"]);if(rs)return console.error("[Webinars] mark live failed:",rs),at("error",e("createErrorInline")),!1;Ne(D,{status:"live",started_at:Wt});const lr=(pe==null?void 0:pe.metadata_json)||{},kn=lr.live_subtitles!==!1,Cs=typeof lr.watermark_text=="string"?lr.watermark_text.trim().slice(0,120):"";return await ae({job_type:ql.CONDUCT_LIVE_SESSION,persona_id:Me,payload_json:{live_session_id:D,plan_key:we||"free",live_subtitles:kn,...Cs?{watermark_text:Cs}:{}}})?(ge(),ie(),!0):(await I.from("live_sessions").update({status:"draft",started_at:null}).eq("id",D).eq("status","live"),Ne(D,{status:"draft",started_at:null}),at("error",e("createErrorInline")),!1)},[ae,ee,rt,J,we,e,ge,ie,Ne,at]),oE=h.useCallback(async(D,pe)=>{if(!pt.current){pt.current=!0,Q(D);try{await Dn(D)}finally{Q(null),pt.current=!1}}},[Dn]),lE=h.useCallback(async D=>{if(Qe)return;P(D.id);const pe=new Date().toISOString();Ne(D.id,{status:"ended",ended_at:pe});try{if(D.platform==="youtube"&&D.platform_broadcast_id)try{await I.functions.invoke("youtube-live",{body:{action:"end_live",live_session_id:D.id}})}catch(Wt){console.error("[Webinars] end_live failed:",Wt)}const{error:Me}=await I.from("live_sessions").update({status:"ended",ended_at:pe}).eq("id",D.id).in("status",["live","ready","scheduled","draft"]);Me&&(console.error("[Webinars] stop session failed:",Me),Ne(D.id,{status:D.status,ended_at:D.ended_at})),ge(),ie()}finally{P(null)}},[Qe,Ne,ge,ie]),cE=h.useCallback(async D=>{var pe;if(!K){ye(D);try{const{data:Me}=await I.auth.getSession(),Wt=(pe=Me.session)==null?void 0:pe.access_token;if(!Wt){at("error",e("continueError"));return}const{data:rs,error:lr}=await I.functions.invoke("webinar-continue",{body:{session_id:D},headers:{Authorization:`Bearer ${Wt}`}});if(lr||!(rs!=null&&rs.success)||!(rs!=null&&rs.next)){at("error",e("continueError"));return}const kn=rs.next;i(Cs=>({...Cs,topic:kn.topic||Cs.topic,desc:kn.description||Cs.desc,plan:kn.plan||Cs.plan,greeting:kn.greeting||Cs.greeting,continueText:kn.continue_text||Cs.continueText,summaryText:kn.summary_text||Cs.summaryText,language:kn.language||Cs.language,selectedFormat:kn.access_format||Cs.selectedFormat,duration:kn.duration_min?String(kn.duration_min):Cs.duration})),rs.persona_id&&Y(rs.persona_id),at("success",e("continueFilled")),setTimeout(()=>{var Cs;(Cs=document.getElementById("webinar-create-form"))==null||Cs.scrollIntoView({behavior:"smooth",block:"start"})},100)}catch(Me){console.error("[Webinars] continue failed:",Me),at("error",e("continueError"))}finally{ye(null)}}},[K,i,e]),dE=h.useCallback(D=>{const pe=D.metadata_json||{};i(Me=>({...Me,topic:D.title??"",desc:D.description??"",plan:D.webinar_plan??"",greeting:D.greeting_text??"",continueText:D.continue_text??"",summaryText:D.summary_text??"",language:D.language||Me.language,platform:D.platform||Me.platform,selectedFormat:pe.access_format||(D.is_paid?"paid":Me.selectedFormat),duration:pe.planned_duration_min?String(pe.planned_duration_min):Me.duration})),D.persona_id&&Y(D.persona_id),at("success",e("repeatFilled")),setTimeout(()=>{var Me;(Me=document.getElementById("webinar-create-form"))==null||Me.scrollIntoView({behavior:"smooth",block:"start"})},100)},[i,e]);h.useEffect(()=>{i(D=>({...D,topic:D.topic||e("defaultTopic"),desc:D.desc||e("defaultDesc")}))},[e]),h.useEffect(()=>{t!=null&&t.workspace_id&&(V(!0),I.from("personas").select("id, name, language, prompt_config").eq("workspace_id",t.workspace_id).eq("status","active").then(({data:D})=>{if(D!=null&&D.length){const pe=D.map(Wt=>{var rs;return{id:Wt.id,name:Wt.name,language:Wt.language,orientation:((rs=Wt.prompt_config)==null?void 0:rs.orientation)||"portrait"}});$(pe),J&&pe.some(Wt=>Wt.id===J)||(Y(pe[0].id),pe[0].language&&T(pe[0].language))}}),V(!1))},[t==null?void 0:t.workspace_id]);const uE=D=>{Y(D);const pe=F.find(Me=>Me.id===D);pe!=null&&pe.language&&T(pe.language)},hE=h.useCallback(async()=>{var D;if(c.trim()){R(!0);try{const{data:pe,error:Me}=await I.functions.invoke("generate-auto-messages",{body:{persona_name:((D=F.find(Wt=>Wt.id===J))==null?void 0:D.name)||"Instructor",persona_id:J||null,language:g,title:c.trim(),description:d,session_type:"webinar"}});!Me&&(pe!=null&&pe.greeting)&&(N(pe.greeting),k(pe.continue_talking))}catch{}R(!1)}},[c,d]);return ne?n.jsx(Ln,{message:e("loading")}
1037):n.jsxs("div",{className:"max-w-6xl mx-auto space-y-8",children:[n.jsx(de.div,{...Te(),children:n.jsxs("h1",{className:"font-heading font-bold text-2xl md:text-3xl text-foreground flex items-center gap-2",children:[n.jsx(Ja,{className:"text-primary",size:24}),e("pageTitle")]})}),n.jsxs("div",{ref:M,className:"space-y-3",children:[n.jsxs("div",{className:"relative",children:[n.jsx(bn,{size:14,className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground pointer-events-none"}),n.jsx(gt,{value:se,onChange:D=>he(D.target.value),placeholder:e("searchPlaceholder"),className:"pl-9 pr-9 bg-surface-elevated"}),se&&n.jsx("button",{type:"button",onClick:()=>he(""),className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 rounded-md text-muted-foreground hover:text-foreground hover:bg-muted/40","aria-label":"Clear",children:n.jsx(Qn,{size:14})})]}),ee.length===0?Ce?n.jsx(Er,{icon:bn,title:e("searchEmptyTitle"),description:e("searchEmptyDesc")}):n.jsx(Er,{icon:Ja,title:e("emptyTitle"),description:e("emptyDesc")}):n.jsxs(de.div,{...Te(.02),className:"rounded-2xl bg-surface-elevated border border-border/50 shadow-premium-sm p-6 space-y-3",children:[n.jsxs("h2",{className:"font-heading font-semibold text-lg text-foreground flex items-center gap-2",children:[n.jsx(St,{size:18,className:"text-primary"})," ",e("mySessionsTitle")]}),n.jsx("div",{className:"space-y-2",children:ee.map(D=>{const pe=lt.get(D.id),Me=D.metadata_json||{},Wt={draft:"bg-muted text-muted-foreground",scheduled:"bg-primary/10 text-primary",ready:"bg-primary/10 text-primary",live:"bg-destructive/10 text-destructive",ended:"bg-muted text-muted-foreground",canceled:"bg-muted text-muted-foreground",failed:"bg-destructive/10 text-destructive"};return n.jsxs("div",{className:"rounded-xl border border-border/50 bg-muted/10 p-4",children:[n.jsxs("button",{type:"button",onClick:()=>Pt(rs=>{const lr=new Set(rs);return lr.has(D.id)?lr.delete(D.id):lr.add(D.id),lr}),className:"w-full flex items-start justify-between gap-3 flex-wrap text-left","aria-expanded":xt.has(D.id),children:[n.jsxs("div",{className:"min-w-0 flex-1 flex items-start gap-2",children:[n.jsx(ps,{size:14,className:`mt-1 text-muted-foreground shrink-0 transition-transform ${xt.has(D.id)?"":"-rotate-90"}`}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("p",{className:"font-semibold text-sm text-foreground truncate",children:D.title}),n.jsxs("div",{className:"flex flex-wrap items-center gap-2 mt-1 text-[11px] text-muted-foreground",children:[n.jsxs("span",{className:"inline-flex items-center gap-1",children:[n.jsx(Rd,{size:11}),e(`platforms.${D.platform||"youtube"}`,{defaultValue:D.platform||""})]}),Me.access_format&&n.jsxs("span",{children:["· ",e(`formats.${Me.access_format}.label`)]}),Me.planned_duration_min?n.jsxs("span",{children:["· ",e("duration",{min:Me.planned_duration_min})]}):Me.planned_duration_min===0?n.jsxs("span",{children:["· ",e("durationInfinite")]}):null,n.jsxs("span",{children:["· ",new Date(D.created_at).toLocaleString()]})]})]})]}),n.jsx(fe,{className:`${Wt[D.status]||"bg-muted text-muted-foreground"} border-0 text-[10px] uppercase tracking-wider`,children:e(`sessionStatus.${D.status}`,{defaultValue:D.status})})]}),xt.has(D.id)&&n.jsxs(n.Fragment,{children:[pe&&n.jsxs("div",{className:"mt-2 text-[11px] text-muted-foreground flex items-center gap-2",children:[n.jsx("span",{className:"font-medium text-foreground",children:e(`jobStage.${pe.status}`,{defaultValue:pe.status})}),pe.stage_label&&n.jsxs("span",{children:["· ",pe.stage_label]}),typeof pe.progress=="number"&&pe.progress>0&&pe.status==="running"&&n.jsxs("span",{children:["· ",pe.progress,"%"]}),pe.status==="failed"&&pe.error_text&&n.jsxs("span",{className:"text-destructive truncate",children:["· ",pe.error_text]})]}),n.jsx("div",{className:"mt-3",children:n.jsx(Jy,{entityType:"live_session",entityId:D.id,initialUrl:(Me==null?void 0:Me.thumbnail_url)??null,autoGenerate:!0,aspect:"16:9"})}),n.jsx(DT,{liveSessionId:D.id}),n.jsx("div",{className:"mt-3",children:n.jsx(zT,{liveSessionId:D.id})}),!["ended","canceled","failed"].includes(D.status)&&n.jsx("div",{className:"mt-3 flex justify-end gap-2",children:["live","scheduled","ready"].includes(D.status)?n.jsxs(L,{variant:"outline",size:"sm",className:"gap-1.5 h-7 text-xs",onClick:()=>lE(D),disabled:Qe===D.id,children:[n.jsx(du,{size:12}),Qe===D.id?e("stopping"):e("stopSession")]}):n.jsxs(n.Fragment,{children:[D.status==="draft"&&n.jsxs(L,{variant:"outline",size:"sm",className:"gap-1.5 h-7 text-xs",onClick:()=>Ht(D),children:[n.jsx($d,{size:12}),e("editDraft")]}),n.jsxs(L,{variant:"hero",size:"sm",className:"gap-1.5 h-7 text-xs",onClick:()=>oE(D.id,!1),disabled:U===D.id||Ze===D.id,children:[n.jsx(en,{size:12}),U===D.id?e("starting"):e("startSession")]}),n.jsxs(L,{variant:"outline",size:"sm",className:"gap-1.5 h-7 text-xs text-destructive hover:text-destructive",onClick:()=>nn(D.id),disabled:Ze===D.id||U===D.id,children:[n.jsx(Qn,{size:12}),Ze===D.id?e("cancelling"):e("cancelWebinar")]})]})}),["ended","failed","canceled"].includes(D.status)&&n.jsxs("div",{className:"mt-3 flex justify-end gap-2",children:[n.jsxs(L,{variant:"outline",size:"sm",className:"gap-1.5 h-7 text-xs",onClick:()=>dE(D),children:[n.jsx(Xi,{size:12}),e("repeatWebinar")]}),n.jsxs(L,{variant:"hero",size:"sm",className:"gap-1.5 h-7 text-xs",onClick:()=>cE(D.id),disabled:K===D.id,children:[n.jsx(tt,{size:12}),K===D.id?e("continueGenerating"):e("continueWebinar")]})]})]})]},D.id)})}),Re>1&&n.jsxs("div",{className:"flex items-center justify-between pt-3 border-t border-border/30",children:[n.jsxs("span",{className:"text-[11px] text-muted-foreground",children:[W," ",e("pagination.total","total")," · ",e("pagination.page",{page:Ge,totalPages:Re})]}),n.jsxs("div",{className:"flex items-center gap-1",children:[n.jsx(L,{variant:"ghost",size:"sm",className:"h-7 px-2 text-xs",disabled:Ge<=1,onClick:()=>Ye(D=>D-1),children:n.jsx(ou,{size:12})}),Array.from({length:Re},(D,pe)=>pe+1).map(D=>n.jsx(L,{variant:D===Ge?"outline":"ghost",size:"sm",className:`h-7 w-7 p-0 text-xs ${D===Ge?"border-primary/40 text-primary":""}`,onClick:()=>Ye(D),children:D},D)),n.jsx(L,{variant:"ghost",size:"sm",className:"h-7 px-2 text-xs",disabled:Ge>=Re,onClick:()=>Ye(D=>D+1),children:n.jsx(yn,{size:12})})]})]})]})]}),n.jsxs(de.div,{id:"webinar-create-form",...Te(.05),className:"rounded-2xl bg-surface-elevated border border-border/50 shadow-premium-sm p-6 space-y-4",children:[n.jsxs("h2",{className:"font-heading font-semibold text-lg text-foreground flex items-center gap-2",children:[n.jsx(Ja,{size:18,className:"text-primary"})," ",e("formatTitle")]}
1037),n.jsx("div",{className:"grid grid-cols-2 lg:grid-cols-5 gap-3",children:Z1.map(D=>{const pe=l===D,Me=cwe[D];return n.jsxs("button",{onClick:()=>y(D),className:`rounded-xl border-2 p-4 text-left transition-all duration-200 ${pe?"border-primary bg-primary/5 shadow-premium-sm":"border-border/50 bg-muted/20 hover:border-primary/30"}`,children:[n.jsx(Me,{size:20,className:pe?"text-primary":"text-muted-foreground"}),n.jsx("p",{className:`mt-2 text-sm font-semibold ${pe?"text-foreground":"text-muted-foreground"}`,children:e(`formats.${D}.label`)})]},D)})})]}),n.jsxs(de.div,{...Te(.1),className:"rounded-2xl bg-surface-elevated border border-border/50 shadow-premium-sm p-6 space-y-4",children:[n.jsxs("h2",{className:"font-heading font-semibold text-lg text-foreground flex items-center gap-2",children:[n.jsx(Xi,{size:18,className:"text-primary"})," ",e("sessionTitle")]}),n.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[n.jsx(Pe,{label:e("fields.topic"),children:n.jsx(Ot,{value:c,onChange:D=>w(D.target.value),className:"bg-muted/30",aiLoading:O("topic"),onAiFill:async()=>{const D=await re({fieldName:"topic",fieldLabel:e("fields.topic"),currentValue:c,pageContext:{format:l,description:d,language:g},personaId:J,language:g});D&&w(D)}})}),n.jsx(Pe,{label:e("fields.persona"),children:n.jsxs(ut,{value:J,onValueChange:uE,children:[n.jsx(ct,{className:"bg-muted/30",children:n.jsx(ht,{})}),n.jsx(dt,{children:F.map(D=>n.jsx(ce,{value:D.id,children:D.name},D.id))})]})}),n.jsx(Pe,{label:e("fields.duration"),children:n.jsxs(ut,{value:b,onValueChange:B,children:[n.jsx(ct,{className:"bg-muted/30",children:n.jsx(ht,{})}),n.jsxs(dt,{children:[[15,30,60,120].map(D=>n.jsx(ce,{value:String(D),children:e("duration",{min:D})},D)),n.jsx(ce,{value:"0",children:e("durationInfinite")})]})]})}),n.jsx(Pe,{label:e("fields.accessFormat"),children:n.jsxs(ut,{value:l,onValueChange:y,children:[n.jsx(ct,{className:"bg-muted/30",children:n.jsx(ht,{})}),n.jsx(dt,{children:Z1.map(D=>n.jsx(ce,{value:D,children:e(`formats.${D}.label`)},D))})]})}),n.jsx(Pe,{label:e("fields.platform"),children:n.jsxs(ut,{value:x,onValueChange:C,children:[n.jsx(ct,{className:"bg-muted/30",children:n.jsx(ht,{})}),n.jsxs(dt,{children:[n.jsx(ce,{value:"restream",children:e("platforms.restream",{defaultValue:"Restream (multistream)"})}),n.jsx(ce,{value:"youtube",children:e("platforms.youtube")})]})]})})]}),n.jsx(Pe,{label:e("fields.description"),children:n.jsx(os,{value:d,onChange:D=>j(D.target.value),className:"bg-muted/30 min-h-[72px] resize-none",aiLoading:O("description"),onAiFill:async()=>{const D=await G({fieldName:"description",fieldLabel:e("fields.description"),currentValue:d,pageContext:{topic:c,format:l,language:g},personaId:J,language:g,topicValue:c,onTopicSet:w});D&&j(D)}})}),n.jsxs("div",{className:"rounded-xl border border-border/50 bg-muted/10 p-4 space-y-3",children:[n.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2",children:[n.jsx("span",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wider",children:e("autoMessages.sectionTitle")}),n.jsx("div",{className:"flex items-center gap-1",children:n.jsxs(L,{type:"button",variant:"ghost",size:"sm",className:"gap-1.5 text-xs h-7",onClick:hE,disabled:te||!c.trim(),children:[n.jsx(xi,{size:13,className:te?"animate-spin":""}),e(te?"autoMessages.generating":"autoMessages.generate")]})})]}),n.jsx(Pe,{label:e("autoMessages.planLabel"),children:n.jsx(os,{value:u,onChange:D=>_(D.target.value),placeholder:e("autoMessages.planPlaceholder"),className:"bg-muted/30 min-h-[120px] text-sm",rows:6,aiLoading:O("webinar_plan"),onAiFill:async()=>{const D=await G({fieldName:"webinar_plan",fieldLabel:e("autoMessages.planLabel"),currentValue:u,pageContext:{topic:c,description:d,greeting:m,language:g},personaId:J,language:g,topicValue:c,onTopicSet:w});D&&_(D)}})}),n.jsx(Pe,{label:e("autoMessages.greetingLabel"),children:n.jsx(os,{value:m,onChange:D=>N(D.target.value),placeholder:e("autoMessages.greetingPlaceholder"),className:"bg-muted/30 min-h-[60px] text-sm",rows:2,aiLoading:O("greeting"),onAiFill:async()=>{const D=await G({fieldName:"greeting",fieldLabel:e("autoMessages.greetingLabel"),currentValue:m,pageContext:{topic:c,description:d,format:l,language:g},personaId:J,language:g,topicValue:c,onTopicSet:w});D&&N(D)}})}),n.jsx(Pe,{label:e("autoMessages.continueLabel"),children:n.jsx(os,{value:p,onChange:D=>k(D.target.value),placeholder:e("autoMessages.continuePlaceholder"),className:"bg-muted/30 min-h-[60
1037px] text-sm",rows:2,aiLoading:O("continue_text"),onAiFill:async()=>{const D=await G({fieldName:"continue_text",fieldLabel:e("autoMessages.continueLabel"),currentValue:p,pageContext:{topic:c,greeting:m,description:d,language:g},personaId:J,language:g,topicValue:c,onTopicSet:w});D&&k(D)}})}),n.jsx(Pe,{label:e("autoMessages.summaryLabel"),children:n.jsx(os,{value:f,onChange:D=>S(D.target.value),placeholder:e("autoMessages.summaryPlaceholder"),className:"bg-muted/30 min-h-[60px] text-sm",rows:2,aiLoading:O("summary_text"),onAiFill:async()=>{const D=await G({fieldName:"summary_text",fieldLabel:e("autoMessages.summaryLabel"),currentValue:f,pageContext:{topic:c,greeting:m,continueText:p,description:d,language:g},personaId:J,language:g,topicValue:c,onTopicSet:w});D&&S(D)}})})]}),n.jsxs("div",{className:"flex items-center justify-between rounded-xl border border-border/50 bg-muted/20 px-4 py-3",children:[n.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[n.jsx("div",{className:"w-8 h-8 rounded-lg bg-primary/10 flex items-center justify-center text-primary shrink-0",children:n.jsx(tt,{size:16})}),n.jsxs("div",{className:"min-w-0",children:[n.jsx("div",{className:"text-sm font-medium text-foreground",children:e("liveSubtitles")}),n.jsx("div",{className:"text-[11px] text-muted-foreground truncate",children:e("liveSubtitlesDesc")})]})]}),n.jsx(Ut,{checked:v,onCheckedChange:E})]}),n.jsxs("div",{className:"rounded-xl border border-border/50 bg-muted/20 px-4 py-3 space-y-2",children:[n.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[n.jsx("div",{className:"w-8 h-8 rounded-lg bg-primary/10 flex items-center justify-center text-primary shrink-0",children:n.jsx(tt,{size:16})}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("div",{className:"text-sm font-medium text-foreground",children:e("watermark")}),n.jsx("div",{className:"text-[11px] text-muted-foreground truncate",children:e("watermarkDesc")})]})]}),n.jsx(gt,{value:H,onChange:D=>z(D.target.value),maxLength:120,placeholder:e("watermarkPlaceholder"),className:"h-9 text-sm bg-background"})]}),n.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[n.jsxs("div",{className:"flex items-center justify-between rounded-xl border border-border/50 bg-muted/20 px-4 py-3",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("div",{className:"w-8 h-8 rounded-lg bg-primary/10 flex items-center justify-center text-primary",children:n.jsx(ii,{size:16})}),n.jsx("span",{className:"text-sm font-medium text-foreground",children:e("archiveLabel")})]}),n.jsx(Ut,{defaultChecked:!0})]}),n.jsxs("div",{className:"flex items-center justify-between rounded-xl border border-border/50 bg-muted/20 px-4 py-3",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("div",{className:"w-8 h-8 rounded-lg bg-primary/10 flex items-center justify-center text-primary",children:n.jsx(Rd,{size:16})}),n.jsx("span",{className:"text-sm font-medium text-foreground",children:e("publishLabel")})]}),n.jsx(Ut,{})]})]}),n.jsxs("div",{className:"flex gap-2",children:[ve&&n.jsxs(L,{variant:"outline",className:"gap-2",onClick:$r,disabled:Ae,children:[n.jsx(Qn,{size:15})," ",e("cancelEdit")]}),n.jsxs(L,{variant:"hero",className:"flex-1 gap-2",onClick:vs,disabled:Ae||!c.trim(),children:[n.jsx(tt,{size:15}),e(Ae?ve?"saving":"creating":ve?"saveChanges":"createSession")]})]}),kt&&n.jsxs("div",{className:`flex items-center gap-2 text-sm rounded-lg px-3 py-2 ${kt.kind==="success"?"bg-primary/10 text-primary":"bg-destructive/10 text-destructive"}`,children:[kt.kind==="success"?n.jsx(wt,{size:14}):n.jsx(Ad,{size:14}),n.jsx("span",{children:kt.text})]})]}),n.jsxs(de.div,{...Te(.15),className:"space-y-4",children:[n.jsxs("h2",{className:"font-heading font-semibold text-lg text-foreground flex items-center gap-2",children:[n.jsx(tt,{size:18,className:"text-primary"})," ",e("monetizationTitle")]}),n.jsx("div",{className:"grid md:grid-cols-3 gap-4",children:dwe.map(D=>{const pe=uwe[D];return n.jsxs("div",{className:"rounded-2xl border border-border/50 bg-surface-elevated shadow-premium-sm p-5 hover:shadow-
1037premium-md transition-shadow",children:[n.jsx("div",{className:"w-10 h-10 rounded-xl bg-primary/10 flex items-center justify-center text-primary mb-3",children:n.jsx(pe,{size:20})}),n.jsx("h3",{className:"font-heading font-semibold text-sm text-foreground",children:e(`monetizationPaths.${D}.title`)}),n.jsx("p",{className:"text-[11px] text-muted-foreground mt-1 leading-relaxed",children:e(`monetizationPaths.${D}.desc`)})]},D)})})]}),n.jsx(Lp,{open:Z.open,onConfirm:Z.onConfirm,onCancel:Z.onCancel})]})};function mwe(e){const{isAdmin:t}=ar(),{data:s,isLoading:r}=Zr({queryKey:["error-logs-count-24h"],queryFn:async()=>{const a=new Date(Date.now()-864e5).toISOString(),{count:i,error:o}=await I.from("error_logs").select("id",{count:"exact",head:!0}).gte("created_at",a);return o?(console.error("[useErrorLogsCount] query failed:",o),0):i??0},enabled:t,refetchInterval:6e4,staleTime:3e4});return{count:s??0,loading:r,enabled:t}}const X1={running:0,queued:1,failed:2,timed_out:3,completed:4,canceled:5},pwe=new Set(["conduct_live_session","conduct_consultation"]),fwe=5*60*1e3;function ej(e,t){const s=e.result_json??{},r=s.duration_seconds,a=typeof r=="number"&&Number.isFinite(r)&&r>=0?r:null,i=typeof s.duration_source=="string"?s.duration_source:null,o=pwe.has(e.job_type);let l;o&&a!=null?l=`${a.toFixed(1)}s`:e.started_at&&e.completed_at?l=`${((new Date(e.completed_at).getTime()-new Date(e.started_at).getTime())/1e3).toFixed(1)}s`:e.started_at?l=t("executing"):l="—";let c=null;return o&&i&&(i==="server_clamped"?c={label:t("durationSource.server_clamped","clamped"),className:"border-amber-300/60 bg-amber-50 text-amber-700",title:t("durationSourceHint.server_clamped","Worker reported a duration outside tolerance — server value used")}:i==="server_only"?c={label:t("durationSource.server_only","server"),className:"border-blue-300/60 bg-blue-50 text-blue-700",title:t("durationSourceHint.server_only","Worker did not report duration — server value used")}:i==="client"&&(c={label:t("durationSource.client","client"),className:"border-emerald-200/60 bg-emerald-50 text-emerald-700",title:t("durationSourceHint.client","Worker-reported duration accepted (within tolerance)")})),{label:l,sourceBadge:c}}const gwe=()=>{const{t:e}=Oe("operations"),{t}=Oe("common"),{profile:s}=st(),{isAdmin:r}=ar(),{active:a,sessions:i}=uo(),{status:o,error:l}=lo(),{status:c,error:d}=Cp(),{jobs:u,loading:m,refresh:p}=ho(),{count:f,enabled:g}=mwe(),x=na(),[b,v]=Gr("status","all"),[y,w]=Gr("type","all"),[j,_]=Gr("q",""),[N,k]=Tm("page",1),[S,T]=Tm("size",15),C=[15,25,50],B=u.filter(P=>P.status==="queued").length,E=u.filter(P=>P.status==="running").length,H=u.filter(P=>P.status==="failed"||P.status==="timed_out").length,z=u.filter(P=>P.status==="completed").length,ne=u.filter(P=>P.status==="canceled").length,V=i.filter(P=>P.status==="live").length,te=[];o==="expired"&&te.push({label:"YouTube",issue:e("tokenExpired")}),o==="error"&&te.push({label:"YouTube",issue:l||e("connectionError")}),c==="expired"&&te.push({label:"Patreon",issue:e("tokenExpired")}),c==="error"&&te.push({label:"Patreon",issue:d||e("connectionError")});const R=async P=>{await I.from("jobs").update({dismissed_at:new Date().toISOString()}).eq("id",P),x.setQueryData(["jobs",s==null?void 0:s.workspace_id],U=>(U??[]).map(Q=>Q.id===P?{...Q,dismissed_at:new Date().toISOString()}:Q))},F=u.filter(P=>(P.status==="failed"||P.status==="timed_out")&&!P.dismissed_at),$=i.filter(P=>P.status==="failed"),J=kp({t,ytStatus:o,ytError:l,patreonStatus:c,patreonError:d,failedJobs:F,failedLiveSessions:$,onDismissJob:R}),Y=u.filter(P=>P.status==="failed"||P.status==="timed_out"),re={};Y.forEach(P=>{const U=e(`jobTypes.${P.job_type}`,P.job_type);re[U]=(re[U]||0)+1});const G=Date.now(),O=u.filter(P=>P.status==="queued"&&t2.has(P.job_type)&&G-new Date(P.created_at).getTime()>=fwe),Z=Array.from(new Set(u.map(P=>P.job_type))).sort(),A=u.filter(P=>b==="all"||P.status===b).filter(P=>y==="all"||P.job_type===y).filter(P=>{if(!j)return!0;const U=j.toLowerCase();return P.id.toLowerCase().includes(U)||P.job_type.toLowerCase().includes(U)||(P.error_text||"").toLowerCase().includes(U)}).sort((P,U)=>(X1[P.status]??99)-(X1[U.status]??99)),oe=Math.max(1,Math.ceil(A.length/S)),ue=Math.min(N,oe),je=A.slice((ue-1)*S,ue*S),ae=P=>{v(P),k(1)},ie=P=>{w(P),k(1)},we=P=>{_(P.target.value),k(1)},Ae=[{label:e("kpis.queued"),value:B,icon:ls,color:"text-blue-600 bg-blue-50"},{label:e("kpis.running"),value:E,icon:xe,color:"text-primary bg-primary/10",spin:E>0},{label:e("kpis.errors"),value:H,icon:gn,color:"text-red-500 bg-red-50",alert:H>0},{label:e("kpis.done"),value:z,icon:wt,color:"text-emerald-600 bg-emerald-50"},{label:e("kpis.canceled"),value:ne,icon:iu,color:"text-muted-foreground bg-muted"},{label:e("kpis.liveSessions"),value:V,icon:St,color:"text-red-500 bg-red-50"},{label:e("kpis.attention"),value:te.length,icon:ft,color:"text-amber-600 bg-amber-50",alert:te.length>0},...g?[{label:e("kpis.errorLogs24h"),value:f,icon:ft,color:"text-orange-600 bg-orange-50",alert:f>=10,href:"/admin?tab=logs"}]:[]],{formatDateTime:nt,timeAgo:Qe}=or();return r?m?n.jsx(Ln,{message:e("loading")}
1037):n.jsxs("div",{className:"max-w-7xl mx-auto space-y-6",children:[n.jsxs(de.div,{...Te(),className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3",children:[n.jsxs("div",{children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsxs("h1",{className:"font-heading font-bold text-2xl md:text-3xl text-foreground flex items-center gap-2",children:[n.jsx(Ed,{className:"text-primary",size:24}),e("pageTitle")]}),n.jsx(kbe,{})]}),n.jsx("p",{className:"text-muted-foreground mt-1 text-sm max-w-xl",children:e("pageSubtitle")})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsxs(L,{variant:"outline",size:"sm",className:"gap-1.5 text-xs h-8",onClick:p,children:[n.jsx(ss,{size:12})," ",e("refresh")]}),n.jsxs(L,{variant:"outline",size:"sm",className:"gap-1.5 text-xs h-8",onClick:p,children:[n.jsx(ss,{size:12})," ",e("refresh")]})]})]}),n.jsx(_p,{alerts:J,title:e("needsAttention")}),O.length>0&&n.jsx(de.div,{...Te(.03),className:"rounded-2xl border border-amber-300/60 bg-amber-50/40 p-4 space-y-3",children:n.jsxs("div",{className:"flex items-start gap-3",children:[n.jsx("div",{className:"w-9 h-9 rounded-lg bg-amber-100 flex items-center justify-center flex-shrink-0",children:n.jsx(ft,{size:16,className:"text-amber-700"})}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("h3",{className:"font-heading font-semibold text-sm text-amber-900",children:e("stuckQueued.title",{count:O.length})}),n.jsx("p",{className:"text-xs text-amber-800/80 mt-1",children:e("stuckQueued.subtitle")}),n.jsxs("div",{className:"mt-3 space-y-1.5",children:[O.slice(0,5).map(P=>{const U=Math.floor((G-new Date(P.created_at).getTime())/6e4);return n.jsxs("div",{className:"flex items-center justify-between gap-3 text-[11px] bg-white/60 rounded-md px-2.5 py-1.5 border border-amber-200/50",children:[n.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[n.jsx(fe,{variant:"outline",className:"text-[9px] border-amber-300/60 bg-amber-50 text-amber-800 uppercase tracking-wider",children:e(`jobTypes.${P.job_type}`,P.job_type)}),n.jsx("code",{className:"font-mono text-amber-900/70 truncate",children:P.id.slice(0,8)})]}),n.jsx("span",{className:"text-amber-700 font-medium whitespace-nowrap",children:e("stuckQueued.waiting",{minutes:U})})]},P.id)}),O.length>5&&n.jsx("p",{className:"text-[10px] text-amber-700/70 pl-1",children:e("stuckQueued.andMore",{count:O.length-5})})]})]})]})}),n.jsx(de.div,{...Te(.05),className:"grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-3",children:Ae.map(P=>{const U=n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[n.jsx("div",{className:`w-7 h-7 rounded-lg flex items-center justify-center ${P.color}`,children:n.jsx(P.icon,{size:14,className:P.spin?"animate-spin":""})}),n.jsx("span",{className:"text-[10px] font-semibold text-muted-foreground uppercase tracking-wider",children:P.label})]}),n.jsx("p",{className:`font-heading font-bold text-2xl ${P.alert?"text-red-600":"text-foreground"}`,children:P.value})]}),Q=`rounded-xl border p-4 transition-all ${P.alert?"border-red-200/60 bg-red-50/20":"border-border/50 bg-surface-elevated shadow-premium-sm"}`;return P.href?n.jsx(zt,{to:P.href,className:`${Q} block hover:shadow-premium-md hover:-translate-y-0.5`,title:e("kpis.openLogsHint","Open Error Logs"),children:U},P.label):n.jsx("div",{className:Q,children:U},P.label)})}),n.jsxs(de.div,{...Te(.1),className:"rounded-2xl bg-surface-elevated border border-border/50 shadow-premium-sm p-5 space-y-4",children:[n.jsxs("h2",{className:"font-heading font-semibold text-base text-foreground flex items-center gap-2",children:[n.jsx(A4,{size:16,className:"text-primary"})," ",e("workers")]}),n.jsxs("div",{className:"grid sm:grid-cols-2 lg:grid-cols-3 gap-3",children:[n.jsxs("div",{className:"rounded-xl border border-border/40 bg-muted/10 p-4 space-y-2",children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(mm,{size:14,className:"text-primary"}),n.jsx("span",{className:"text-sm font-semibold text-foreground",children:"process-job"})]}),n.jsx(yr,{status:E>0?"running":"ready"})]}),n.jsxs("div",{className:"space-y-1 text-[11px] text-muted-foreground",children:[n.jsxs("p",{children:[e("workerType"),": ",n.jsx("span",{className:"text-foreground font-medium",children:"Edge Function Worker"})]}),n.jsxs("p",{children:[e("workerMode"),": ",n.jsx("span",{className:"text-foreground font-medium",children:e("workerProduction")})]}),n.jsxs("p",{children:[e("workerCurrentTasks"),": ",n.jsx("span",{className:"text-foreground font-medium",children:E})]}),n.jsxs("p",{children:[e("workerQueued"),": ",n.jsx("span",{className:"text-foreground font-medium",children:B})]})]})]}),n.jsxs("div",{className:"rounded-xl border border-border/40 bg-muted/10 p-4 space-y-2",children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Ed,{size:14,className:"text-emerald-500"}),n.jsx("span",{className:"text-sm font-semibold text-foreground",children:"tts-pipeline"})]}),n.jsx(yr,{status:"ready"})]}),n.jsxs("div",{className:"space-y-1 text-[11px] text-muted-foreground",children:[n.jsxs("p",{children:[e("workerType"),": ",n.jsx("span",{className:"text-foreground font-medium",children:"ElevenLabs TTS"})]}),n.jsxs("p",{children:[e("workerMode"),": ",n.jsx("span",{className:"text-foreground font-medium",children:e("workerProduction")})]}),n.jsxs("p",{children:[e("tableStatus"),": ",n.jsx("span",{className:"text-emerald-600 font-medium",children:e("workerReady")})]})]})]}),n.jsxs("div",{className:"rounded-xl border border-primary/20 bg-primary/5 p-4 space-y-2",children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Ns,{size:14,className:"text-primary"}),n.jsx("span",{className:"text-sm font-semibold text-foreground",children:"video-render"})]}),n.jsx(fe,{variant:"outline",className:"text-[9px] border-primary/30 text-primary",children:"Production"})]}),n.jsxs("div",{className:"space-y-1 text-[11px] text-muted-foreground",children:[n.jsxs("p",{children:[e("workerType"),": ",n.jsx("span",{className:"text-foreground font-medium",children:"Smart Avatar"})]}),n.jsxs("p",{children:[e("workerMode"),": ",n.jsx("span",{className:"text-primary font-medium",children:"Production"})]}),n.jsxs("p",{children:[e("workerOutput"),": ",n.jsx("span",{className:"text-foreground font-medium",children:e("workerOutputDesc")})]})]})]})]})]}),u.filter(P=>["queued","running"].includes(P.status)).length>0&&n.jsxs(de.div,{...Te(.12),className:"rounded-2xl bg-surface-elevated border border-border/50 shadow-premium-sm p-5 space-y-3",children:[n.jsxs("h2",{className:"font-heading font-semibold text-base text-foreground flex items-center gap-2",children:[n.jsx(xe,{size:16,className:"text-primary animate-spin"})," ",e("activeTasks"),n.jsx(fe,{variant:"outline",className:"text-[10px] ml-1",children:u.filter(P=>["queued","running"].includes(P.status)).length})]}),n.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-3 gap-3",children:u.filter(P=>["queued","running"].includes(P.status)).map(P=>n.jsx(ZC,{job:P},P.id))})]}),n.jsxs(de.div,{...Te(.15),className:"rounded-2xl bg-surface-elevated border border-border/50 shadow-premium-sm overflow-hidden",children:[n.jsxs("div",{className:"p-5 border-b border-border/40 flex flex-col sm:flex-row sm:items-center justify-between gap-3",children:[n.jsxs("h2",{className:"font-heading font-semibold text-base text-foreground flex items-center gap-2",children:[n.jsx(nr,{size:16,className:"text-primary"})," ",e("tasks")," (",A.length,")"]}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsxs("div",{className:"relative",children:[n.jsx(bn,{size:13,className:"absolute left-2.5 top-1/2 -translate-y-1/2 text-muted-foreground
1037/50"}),n.jsx(gt,{value:j,onChange:we,placeholder:e("searchPlaceholder"),className:"h-8 pl-8 pr-3 text-xs w-40 bg-muted/30"})]}),n.jsxs(ut,{value:b,onValueChange:ae,children:[n.jsxs(ct,{className:"h-8 w-28 text-xs bg-muted/30",children:[n.jsx(iS,{size:11,className:"mr-1"}),n.jsx(ht,{})]}),n.jsxs(dt,{children:[n.jsx(ce,{value:"all",children:e("filterAll")}),n.jsx(ce,{value:"queued",children:e("filterQueued")}),n.jsx(ce,{value:"running",children:e("filterRunning")}),n.jsx(ce,{value:"completed",children:e("filterDone")}),n.jsx(ce,{value:"failed",children:e("filterFailed")}),n.jsx(ce,{value:"timed_out",children:e("filterTimedOut")}),n.jsx(ce,{value:"canceled",children:e("filterCanceled")})]})]}),n.jsxs(ut,{value:y,onValueChange:ie,children:[n.jsxs(ct,{className:"h-8 w-36 text-xs bg-muted/30",children:[n.jsx(mm,{size:11,className:"mr-1"}),n.jsx(ht,{placeholder:e("filterAllTypes")})]}),n.jsxs(dt,{children:[n.jsx(ce,{value:"all",children:e("filterAllTypes")}),Z.map(P=>n.jsx(ce,{value:P,children:e(`jobTypes.${P}`,P)},P))]})]})]})]}),m?n.jsx("div",{className:"flex items-center justify-center py-12",children:n.jsx(xe,{size:20,className:"animate-spin text-primary"})}):A.length===0?n.jsxs("div",{className:"text-center py-12",children:[n.jsx(nr,{size:24,className:"mx-auto text-muted-foreground/40 mb-2"}),n.jsx("p",{className:"text-sm text-muted-foreground",children:b!=="all"?e("noJobsWithFilter",{filter:b}):e("noJobs")})]}):n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"hidden lg:block overflow-x-auto",children:n.jsxs("table",{className:"w-full text-xs",children:[n.jsx("thead",{children:n.jsxs("tr",{className:"bg-muted/20 text-muted-foreground text-[10px] uppercase tracking-wider",children:[n.jsx("th",{className:"text-left px-4 py-2.5 font-semibold",children:e("tableId")}),n.jsx("th",{className:"text-left px-4 py-2.5 font-semibold",children:e("tableType")}),n.jsx("th",{className:"text-left px-4 py-2.5 font-semibold",children:e("tableStatus")}),n.jsx("th",{className:"text-left px-4 py-2.5 font-semibold",children:e("tableWorker")}),n.jsx("th",{className:"text-left px-4 py-2.5 font-semibold",children:e("tableCreated")}),n.jsx("th",{className:"text-left px-4 py-2.5 font-semibold",children:e("tableDuration")}),n.jsx("th",{className:"text-left px-4 py-2.5 font-semibold",children:e("tableError")})]})}),n.jsx("tbody",{children:je.map(P=>{const U=ej(P,e);return n.jsxs("tr",{className:`border-t border-border/20 hover:bg-muted/10 transition-colors ${P.status==="failed"?"bg-red-50/30":""}`,children:[n.jsxs("td",{className:"px-4 py-2.5 font-mono text-muted-foreground",children:[P.id.slice(0,8),"…"]}),n.jsx("td",{className:"px-4 py-2.5",children:n.jsx("span",{className:"font-medium text-foreground",children:e(`jobTypes.${P.job_type}`,P.job_type)})}),n.jsx("td",{className:"px-4 py-2.5",children:n.jsx(yr,{status:P.status})}),n.jsx("td",{className:"px-4 py-2.5 text-muted-foreground",children:"prod-worker"}),n.jsx("td",{className:"px-4 py-2.5 text-muted-foreground",children:Qe(P.created_at)}),n.jsx("td",{className:"px-4 py-2.5",children:n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("span",{className:"font-mono text-muted-foreground",children:U.label}),U.sourceBadge&&n.jsx("span",{className:`text-[9px] font-semibold px-1.5 py-0.5 rounded uppercase tracking-wider border ${U.sourceBadge.className}`,title:U.sourceBadge.title,children:U.sourceBadge.label})]})}),n.jsx("td",{className:"px-4 py-2.5 max-w-[200px]",children:P.error_text&&n.jsxs("span",{className:"text-red-500 truncate block",title:P.error_text,children:[P.error_text.slice(0,60),P.error_text.length>60?"…":""]})})]},P.id)})})]})}),n.jsx("div",{className:"lg:hidden p-4 space-y-2",children:je.map(P=>{const U=ej(P,e);return n.jsxs("div",{className:`rounded-xl border p-3 space-y-1.5 ${P.status==="failed"?"border-red-200/50 bg-red-50/20":"border-border/40 bg-muted/10"}`,children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsx("span",{className:"text-xs font-semibold text-foreground",children:e(`jobTypes.${P.job_type}`,P.job_type)}),n.jsx(yr,{status:P.status})]}),n.jsxs("div",{className:"flex items-center gap-3 text-[10px] text-muted-foreground flex-wrap",children:[n.jsxs("span",{className:"font-mono",children:[P.id.slice(0,8),"…"]}),n.jsx("span",{children:Qe(P.created_at)}),n.jsx("span",{className:"font-mono",children:U.label}),U.sourceBadge&&n.jsx("span",{className:`text-[9px] font-semibold px-1.5 py-0.5 rounded uppercase tracking-wider border ${U.sourceBadge.className}`,title:U.sourceBadge.title,children:U.sourceBadge.label})]}),P.error_text&&n.jsx("p",{className:"text-[10px] text-red-500 leading-tight",children:P.error_text.slice(0,100)})]},P.id)})}),A.length>0&&n.jsxs("div",{className:"px-5 py-3 border-t border-border/40 flex items-center justify-between",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("span",{className:"text-[11px] text-muted-foreground",children:e("paginationInfo",{from:(ue-1)*S+1,to:Math.min(ue*S,A.length),total:A.length})}),n.jsxs(ut,{value:String(S),onValueChange:P=>{T(Number(P)),k(1)},children:[n.jsx(ct,{className:"h-7 w-[70px] text-[11px]",children:n.jsx(ht,{})}),n.jsx(dt,{children:C.map(P=>n.jsx(ce,{value:String(P),children:P},P))})]})]}),n.jsxs("div",{className:"flex items-center gap-1",children:[n.jsx(L,{variant:"ghost",size:"icon",className:"h-7 w-7",disabled:ue<=1,onClick:()=>k(ue-1),children:n.jsx(ou,{size:14})}),Array.from({length:oe},(P,U)=>U+1).filter(P=>P===1||P===oe||Math.abs(P-ue)<=1).reduce((P,U,Q,ve)=>(Q>0&&U-ve[Q-1]>
10371&&P.push("…"),P.push(U),P),[]).map((P,U)=>typeof P=="string"?n.jsx("span",{className:"text-[11px] text-muted-foreground px-1",children:"…"},`e${U}`):n.jsx(L,{variant:P===ue?"default":"ghost",size:"icon",className:"h-7 w-7 text-[11px]",onClick:()=>k(P),children:P},P)),n.jsx(L,{variant:"ghost",size:"icon",className:"h-7 w-7",disabled:ue>=oe,onClick:()=>k(ue+1),children:n.jsx(yn,{size:14})})]})]})]})]}),n.jsxs(de.div,{...Te(.2),className:"rounded-2xl bg-surface-elevated border border-border/50 shadow-premium-sm p-5 space-y-4",children:[n.jsxs("h2",{className:"font-heading font-semibold text-base text-foreground flex items-center gap-2",children:[n.jsx(St,{size:16,className:"text-red-500"})," ",e("liveRuntime")]}),i.filter(P=>["live","scheduled","ready","starting"].includes(P.status)).length===0?n.jsxs("div",{className:"text-center py-8",children:[n.jsx(St,{size:24,className:"mx-auto text-muted-foreground/30 mb-2"}),n.jsx("p",{className:"text-sm text-muted-foreground",children:e("noActiveLive")})]}):n.jsx("div",{className:"space-y-2",children:i.filter(P=>["live","scheduled","ready","starting"].includes(P.status)).map(P=>n.jsxs("div",{className:`rounded-xl border p-4 flex flex-col sm:flex-row sm:items-center justify-between gap-3 ${P.status==="live"?"border-red-200/50 bg-red-50/10":"border-border/40 bg-muted/10"}`,children:[n.jsxs("div",{className:"space-y-1",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:"text-sm font-semibold text-foreground",children:P.title}),n.jsx(yr,{status:P.status})]}),n.jsxs("div",{className:"flex items-center gap-3 text-[10px] text-muted-foreground",children:[n.jsxs("span",{children:[e("platform"),": ",P.platform??"YouTube"]}),n.jsxs("span",{children:[e("mode"),": ",P.live_mode??"free_live"]}),n.jsxs("span",{children:[e("chat"),": ",P.chat_reply_mode??"suggest_only"]})]})]}),_be()]},P.id))})]}),n.jsxs(de.div,{...Te(.25),className:"rounded-2xl bg-surface-elevated border border-border/50 shadow-premium-sm p-5 space-y-4",children:[n.jsxs("h2",{className:"font-heading font-semibold text-base text-foreground flex items-center gap-2",children:[n.jsx(ft,{size:16,className:"text-amber-500"})," ",e("errorsTitle")]}),Y.length===0&&te.length===0?n.jsxs("div",{className:"flex items-center gap-3 rounded-xl border border-emerald-200/50 bg-emerald-50/20 px-4 py-3",children:[n.jsx(wt,{size:16,className:"text-emerald-500"}),n.jsx("p",{className:"text-sm text-emerald-700 font-medium",children:e("allClear")})]}):n.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[Object.entries(re).map(([P,U])=>n.jsxs("div",{className:"flex items-center gap-3 rounded-xl border border-red-200/40 bg-red-50/20 px-4 py-3",children:[n.jsx(gn,{size:14,className:"text-red-500 shrink-0"}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("p",{className:"text-xs font-semibold text-foreground",children:P}),n.jsxs("p",{className:"text-[10px] text-muted-foreground",children:[U," ",e(U===1?"errorSingular":"errorPlural")]})]}),n.jsx(fe,{variant:"outline",className:"text-[9px] text-red-500 border-red-200/50",children:U})]},P)),te.map(P=>n.jsxs("div",{className:"flex items-center gap-3 rounded-xl border border-amber-200/40 bg-amber-50/20 px-4 py-3",children:[n.jsx(ft,{size:14,className:"text-amber-500 shrink-0"}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("p",{className:"text-xs font-semibold text-foreground",children:P.label}),n.jsx("p",{className:"text-[10px] text-muted-foreground",children:P.issue})]})]},P.label))]})]})]}):n.jsx(Al,{to:"/app",replace:!0})},tj={error:{className:"bg-destructive/10 text-destructive border-destructive/30",Icon:Ad},warn:{className:"bg-amber-100 text-amber-800 border-amber-300/60 dark:bg-amber-900/30 dark:text-amber-300",Icon:ft},info:{className:"bg-blue-100 text-blue-700 border-blue-300/60 dark:bg-blue-900/30 dark:text-blue-300",Icon:Ty}},eg=25;function xwe(){const{t:e}=Oe("admin"),{timeAgo:t,formatDateTime:s}=or(),[r,a]=h.useState([]),[i,o]=h.useState(!0),[l,c]=h.useState(null),[d,u]=Gr("logs_severity","all"),[m,p]=Gr("logs_s
1037ource","all"),[f,g]=Gr("logs_q",""),[x,b]=Tm("logs_page",1),[v,y]=h.useState(0),[w,j]=h.useState(null),_=h.useCallback(async()=>{o(!0),c(null);try{let C=I.from("error_logs").select("*",{count:"exact"}).order("created_at",{ascending:!1}).range((x-1)*eg,x*eg-1);d!=="all"&&(C=C.eq("severity",d)),m!=="all"&&(C=C.eq("source",m)),f.trim()&&(C=C.ilike("message",`%${f.trim()}%`));const{data:B,error:E,count:H}=await C;if(E)throw E;a(B??[]),y(H??0)}catch(C){c(C.message??"Failed to load logs")}finally{o(!1)}},[x,d,m,f]);h.useEffect(()=>{_()},[_]);const N=Array.from(new Set(r.map(C=>C.source))).sort(),k=Math.max(1,Math.ceil(v/eg)),S={error:r.filter(C=>C.severity==="error").length,warn:r.filter(C=>C.severity==="warn").length,info:r.filter(C=>C.severity==="info").length},T=async C=>{const B=JSON.stringify({id:C.id,created_at:C.created_at,severity:C.severity,source:C.source,category:C.category,message:C.message,stack:C.stack,context:C.context_json,workspace_id:C.workspace_id,user_id:C.user_id,job_id:C.job_id},null,2);try{await navigator.clipboard.writeText(B)}catch{}};return n.jsxs("div",{className:"space-y-4",children:[n.jsxs(de.div,{...Te(),className:"flex flex-wrap items-center gap-2",children:[n.jsxs(fe,{variant:"outline",className:"gap-1.5",children:[n.jsx(Ad,{size:12,className:"text-destructive"})," ",S.error]}),n.jsxs(fe,{variant:"outline",className:"gap-1.5",children:[n.jsx(ft,{size:12,className:"text-amber-600"})," ",S.warn]}),n.jsxs(fe,{variant:"outline",className:"gap-1.5",children:[n.jsx(Ty,{size:12,className:"text-blue-600"})," ",S.info]}),n.jsx("span",{className:"text-xs text-muted-foreground ml-2",children:e("errorLogs.total",{count:v})}),n.jsxs(L,{variant:"outline",size:"sm",className:"ml-auto h-8 gap-1.5 text-xs",onClick:()=>_(),disabled:i,children:[n.jsx(ss,{size:12,className:i?"animate-spin":""})," ",e("errorLogs.refresh")]})]}),n.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[n.jsx(bn,{size:13,className:"absolute left-2.5 top-1/2 -translate-y-1/2 text-muted-foreground/50"}),n.jsx(gt,{value:f,onChange:C=>{g(C.target.value),b(1)},placeholder:e("errorLogs.searchPlaceholder"),className:"h-8 pl-8 pr-3 text-xs bg-muted/30"})]}),n.jsxs(ut,{value:d,onValueChange:C=>{u(C),b(1)},children:[n.jsxs(ct,{className:"h-8 w-32 text-xs bg-muted/30",children:[n.jsx(iS,{size:11,className:"mr-1"}),n.jsx(ht,{})]}),n.jsxs(dt,{children:[n.jsx(ce,{value:"all",children:e("errorLogs.allLevels")}),n.jsx(ce,{value:"error",children:"Errors"}),n.jsx(ce,{value:"warn",children:"Warnings"}),n.jsx(ce,{value:"info",children:"Info"})]})]}),n.jsxs(ut,{value:m,onValueChange:C=>{p(C),b(1)},children:[n.jsx(ct,{className:"h-8 w-44 text-xs bg-muted/30",children:n.jsx(ht,{placeholder:e("errorLogs.allSources")})}),n.jsxs(dt,{children:[n.jsx(ce,{value:"all",children:e("errorLogs.allSources")}),N.map(C=>n.jsx(ce,{value:C,children:C},C))]})]})]}),l&&n.jsx("div",{className:"bg-destructive/10 text-destructive px-4 py-3 rounded-lg text-sm",children:l}),n.jsxs("div",{className:"bg-card border border-border rounded-xl overflow-hidden",children:[i&&r.length===0?n.jsx("div",{className:"flex items-center justify-center py-12",children:n.jsx(xe,{size:20,className:"animate-spin text-primary"})}):r.length===0?n.jsx("div",{className:"text-center py-12 text-sm text-muted-foreground",children:e("errorLogs.empty")}):n.jsx("div",{className:"divide-y divide-border",children:r.map(C=>{const B=tj[C.severity]??tj.info,E=w===C.id;return n.jsxs("div",{className:"p-3 hover:bg-muted/20 transition-colors",children:[n.jsxs("button",{onClick:()=>j(E?null:C.id),className:"w-full flex items-start gap-3 text-left",children:[n.jsxs(fe,{variant:"outline",className:`${B.className} text-[9px] uppercase tracking-wider gap-1 mt-0.5`,children:[n.jsx(B.Icon,{size:10})," ",C.severity]}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-1",children:[n.jsx("code",{className:"text-[10px] font-mono text-muted-foreground bg-muted/50 px-1.5 py-0.5 rounded",children:C.source}
1037),C.category&&n.jsx("code",{className:"text-[10px] font-mono text-muted-foreground/70",children:C.category}),n.jsx("span",{className:"text-[10px] text-muted-foreground ml-auto",title:s(C.created_at),children:t(C.created_at)})]}),n.jsx("p",{className:"text-sm text-foreground break-words",children:C.message})]}),n.jsx(ps,{size:14,className:`text-muted-foreground/50 mt-1 transition-transform ${E?"rotate-180":""}`})]}),E&&n.jsxs("div",{className:"mt-3 pl-[68px] space-y-2",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsxs(L,{size:"sm",variant:"outline",className:"h-7 gap-1.5 text-xs",onClick:()=>T(C),children:[n.jsx(l4,{size:11})," ",e("errorLogs.copyJson")]}),C.job_id&&n.jsxs("code",{className:"text-[10px] font-mono text-muted-foreground",children:["job: ",C.job_id.slice(0,8),"…"]}),C.workspace_id&&n.jsxs("code",{className:"text-[10px] font-mono text-muted-foreground",children:["ws: ",C.workspace_id.slice(0,8),"…"]})]}),C.stack&&n.jsx("pre",{className:"text-[10px] font-mono bg-muted/40 rounded p-2 overflow-x-auto whitespace-pre-wrap text-muted-foreground max-h-48 overflow-y-auto",children:C.stack}),C.context_json&&Object.keys(C.context_json).length>0&&n.jsx("pre",{className:"text-[10px] font-mono bg-muted/40 rounded p-2 overflow-x-auto whitespace-pre text-muted-foreground max-h-48 overflow-y-auto",children:JSON.stringify(C.context_json,null,2)})]})]},C.id)})}),k>1&&n.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-t border-border",children:[n.jsxs("p",{className:"text-xs text-muted-foreground",children:[x," / ",k]}),n.jsxs("div",{className:"flex items-center gap-1",children:[n.jsx(L,{variant:"outline",size:"sm",className:"h-7 w-7 p-0",disabled:x<=1||i,onClick:()=>b(Math.max(1,x-1)),children:n.jsx(ou,{size:14})}),n.jsx(L,{variant:"outline",size:"sm",className:"h-7 w-7 p-0",disabled:x>=k||i,onClick:()=>b(Math.min(k,x+1)),children:n.jsx(yn,{size:14})})]})]})]})]})}var MP={exports:{}},zP={};/**
1038 * @license React
1039 * use-sync-external-store-shim.production.js
1040 *
1041 * Copyright (c) Meta Platforms, Inc. and affiliates.
1042 *
1043 * This source code is licensed under the MIT license found in the
1044 * LICENSE file in the root directory of this source tree.
1045 */var Yl=h;function vwe(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var ywe=typeof Object.is=="function"?Object.is:vwe,bwe=Yl.useState,wwe=Yl.useEffect,jwe=Yl.useLayoutEffect,_we=Yl.useDebugValue;function kwe(e,t){var s=t(),r=bwe({inst:{value:s,getSnapshot:t}}),a=r[0].inst,i=r[1];return jwe(function(){a.value=s,a.getSnapshot=t,tg(a)&&i({inst:a})},[e,s,t]),wwe(function(){return tg(a)&&i({inst:a}),e(function(){tg(a)&&i({inst:a})})},[e]),_we(s),s}function tg(e){var t=e.getSnapshot;e=e.value;try{var s=t();return!ywe(e,s)}catch{return!0}}function Nwe(e,t){return t()}var Swe=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?Nwe:kwe;zP.useSyncExternalStore=Yl.useSyncExternalStore!==void 0?Yl.useSyncExternalStore:Swe;MP.exports=zP;var Cwe=MP.exports;function Twe(){return Cwe.useSyncExternalStore(Pwe,()=>!0,()=>!1)}function Pwe(){return()=>{}}var db="Avatar",[Ewe,rje]=Is(db),[Awe,FP]=Ewe(db),UP=h.forwardRef((e,t)=>{const{__scopeAvatar:s,...r}=e,[a,i]=h.useState("idle");return n.jsx(Awe,{scope:s,imageLoadingStatus:a,onImageLoadingStatusChange:i,children:n.jsx(qe.span,{...r,ref:t})})});UP.displayName=db;var BP="AvatarImage",VP=h.forwardRef((e,t)=>{const{__scopeAvatar:s,src:r,onLoadingStatusChange:a=()=>{},...i}=e,o=FP(BP,s),l=Rwe(r,i),c=Zn(d=>{a(d),o.onImageLoadingStatusChange(d)});return cs(()=>{l!=="idle"&&c(l)},[l,c]),l==="loaded"?n.jsx(qe.img,{...i,ref:t,src:r}):null});VP.displayName=BP;var qP="AvatarFallback",HP=h.forwardRef((e,t)=>{const{__scopeAvatar:s,delayMs:r,...a}=e,i=FP(qP,s),[o,l]=h.useState(r===void 0);return h.useEffect(()=>{if(r!==void 0){const c=window.setTimeout(()=>l(!0),r);return()=>window.clearTimeout(c)}},[r]),o&&i.imageLoadingStatus!=="loaded"?n.jsx(qe.span,{...a,ref:t}):null});HP.displayName=qP;function sj(e,t){return e?t?(e.src!==t&&(e.src=t),e.complete&&e.naturalWidth>0?"loaded":"loading"):"error":"idle"}function Rwe(e,{referrerPolicy:t,crossOrigin:s}
1045){const r=Twe(),a=h.useRef(null),i=r?(a.current||(a.current=new window.Image),a.current):null,[o,l]=h.useState(()=>sj(i,e));return cs(()=>{l(sj(i,e))},[i,e]),cs(()=>{const c=m=>()=>{l(m)};if(!i)return;const d=c("loaded"),u=c("error");return i.addEventListener("load",d),i.addEventListener("error",u),t&&(i.referrerPolicy=t),typeof s=="string"&&(i.crossOrigin=s),()=>{i.removeEventListener("load",d),i.removeEventListener("error",u)}},[i,s,t]),o}var WP=UP,GP=VP,YP=HP;const ub=h.forwardRef(({className:e,...t},s)=>n.jsx(WP,{ref:s,className:_e("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",e),...t}));ub.displayName=WP.displayName;const hb=h.forwardRef(({className:e,...t},s)=>n.jsx(GP,{ref:s,className:_e("aspect-square h-full w-full",e),...t}));hb.displayName=GP.displayName;const mb=h.forwardRef(({className:e,...t},s)=>n.jsx(YP,{ref:s,className:_e("flex h-full w-full items-center justify-center rounded-full bg-muted",e),...t}));mb.displayName=YP.displayName;const KP={admin:"bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400",creator:"bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-400",moderator:"bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400",user:"bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400"},pb={admin:_y,creator:Od,moderator:Od,user:li};function QP({user:e,currentUserId:t,acting:s,onConfirm:r,t:a}){const i=e.id===t;return n.jsxs($P,{children:[n.jsx(LP,{asChild:!0,children:n.jsxs(L,{variant:"ghost",size:"sm",className:"h-7 text-xs gap-1",disabled:s,children:[a("actions")," ",n.jsx(ps,{size:12})]})}),n.jsxs(cb,{align:"end",children:[["admin","creator","moderator","user"].map(o=>{const l=e.roles.includes(o),c=pb[o];return n.jsxs(Hd,{onClick:()=>r({type:"role",userId:e.id,role:o,remove:l,userName:e.full_name||e.email||e.id}),children:[n.jsx(c,{size:14,className:"mr-2"}),l?a("removeRole",{role:o}):a("assignRole",{role:o}),l&&n.jsx(fe,{className:"ml-auto text-[9px] bg-muted text-muted-foreground border-0",children:"✓"})]},o)}),!i&&n.jsxs(n.Fragment,{children:[n.jsx(IP,{}),n.jsxs(Hd,{className:e.is_banned?"text-green-600":"text-destructive",onClick:()=>r({type:"ban",userId:e.id,ban:!e.is_banned,userName:e.full_name||e.email||e.id}),children:[e.is_banned?n.jsx(aS,{size:14,className:"mr-2"}):n.jsx(iu,{size:14,className:"mr-2"}),e.is_banned?a("unban"):a("ban")]})]})]})]})}function $we({banned:e,label:t}){return e?n.jsxs(fe,{className:"bg-destructive/10 text-destructive border-0 text-[10px] gap-1",children:[n.jsx(iu,{size:10})," ",t]}):null}function Lwe({user:e,currentUserId:t,acting:s,timeAgo:r,onConfirm:a,t:i}){return n.jsxs("div",{className:`bg-card border rounded-xl p-4 space-y-3 ${e.is_banned?"border-destructive/40 opacity-75":"border-border"}`,children:[n.jsxs("div",{className:"flex items-start justify-between gap-2",children:[n.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[n.jsxs(ub,{className:"h-10 w-10 shrink-0",children:[n.jsx(hb,{src:e.avatar_url??void 0}),n.jsx(mb,{className:"text-sm",children:(e.full_name??e.email??"?").charAt(0).toUpperCase()})]}),n.jsxs("div",{className:"min-w-0",children:[n.jsx("p",{className:"font-medium text-foreground truncate",children:e.full_name||"—"}),n.jsx("p",{className:"text-xs text-muted-foreground truncate",children:e.email})]})]}),n.jsx(QP,{user:e,currentUserId:t,acting:s,onConfirm:a,t:i})]}),n.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n.jsx($we,{banned:e.is_banned,label:i("banned")}),e.roles.length>0?e.roles.map(o=>{const l=pb[o]??li;return n.jsxs(fe,{className:`${KP[o]??""} text-[10px] gap-1 border-0`,children:[n.jsx(l,{size:10})," ",o]},o)}):!e.is_banned&&n.jsx("span",{className:"text-muted-foreground text-xs",children:i("noRoles")})]}),n.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[n.jsx("span",{children:e.workspace?n.jsxs(n.Fragment,{children:[e.workspace.name," · ",n.jsx(fe,{variant:"outline",className:"text-[10px]",children:e.workspace.plan})]}):i("noWorkspace")}),n.jsx("span",{children:e.last_login_at?r(e.last_login_at):"—"})]})]})}function nj({page:e,totalPages:t,acting:s,setPage:r}){return t<=1?null:n.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-t border-border",children:[n.jsxs("p",{className:"text-xs text-muted-foreground",children:[e," / ",t]}),n.jsxs("div",{className:"flex items-center gap-1",children:[n.jsx(L,{variant:"outline",size:"sm",className:"h-7 w-7 p-0",disabled:e<=1||s,onClick:()=>r(Math.max(1,e-1)),children:n.jsx(ou,{size:14})}),Array.from({length:Math.min(t,5)},(a,i)=>{let o;return t<=5||e<=3?o=i+1:e>=t-2?o=t-4+i:o=e-2+i,n.jsx(L,{variant:o===e?"default":"outline",size:"sm",className:"h-7 w-7 p-0 text-xs hidden sm:inline-flex",disabled:s,onClick:()=>r(o),children:o},o)}),n.jsx(L,{variant:"outline",size:"sm",className:"h-7 w-7 p-0",disabled:e>=t||s,onClick:()=>r(Math.min(t,e+1)),children:n.jsx(yn,{size:14})})]})]})}const Iwe=()=>{var Y;const{t:e}=Oe("admin"),{session:t}=st(),{isAdmin:s}=ar(),{timeAgo:r}=or(),[a,i]=tu(),o=a.get("tab")==="logs"?"logs":"users",l=re=>{const G=new URLSearchParams(a);re==="users"?G.delete("tab"):G.set("tab",re),i(G,{replace:!0})},[c,d]=h.useState([]),[u,m]=h.useState(!0),[p,f]=h.useState(null),[g,x]=h.useState(""),[b,v]=h.useState(""),[y,w]=h.useState(!1),[j,_]=h.useState(1),[N,k]=h.useState(1),[S,T]=h.useState(0),[C,B]=h.useState(null),E=h.useRef();h.useEffect(()=>(E.current=setTimeout(()=>{v(g),_(1)},400),()=>clearTimeout(E.current)),[g]);const H=h.useCallback(async(re=j,G=b)=>{if(t!=null&&t.access_token){f(null);
1045try{const O=new URLSearchParams({action:"list",page:String(re)});G&&O.set("search",G);const{data:Z,error:A}=await I.functions.invoke(`admin-users?${O}`,{headers:{Authorization:`Bearer ${t.access_token}`}});if(A)throw A;d((Z==null?void 0:Z.users)??[]),k((Z==null?void 0:Z.totalPages)??1),T((Z==null?void 0:Z.totalCount)??0)}catch(O){f(O.message||"Failed to load users")}finally{m(!1)}}},[t==null?void 0:t.access_token,j,b]);h.useEffect(()=>{H()},[H]);const z=async(re,G,O)=>{if(t!=null&&t.access_token){w(!0);try{const{error:Z}=await I.functions.invoke("admin-users?action=set_role",{headers:{Authorization:`Bearer ${t.access_token}`},body:{target_user_id:re,role:G,remove:O}});if(Z)throw Z;await H()}catch(Z){f(Z.message||"Failed to update role")}finally{w(!1),B(null)}}},ne=async(re,G)=>{if(t!=null&&t.access_token){w(!0);try{const{error:O}=await I.functions.invoke("admin-users?action=ban",{headers:{Authorization:`Bearer ${t.access_token}`},body:{target_user_id:re,ban:G}});if(O)throw O;await H()}catch(O){f(O.message||"Failed to update ban status")}finally{w(!1),B(null)}}},V=()=>{C&&(C.type==="role"?z(C.userId,C.role,C.remove):ne(C.userId,C.ban))},te=re=>B(re);if(!s)return n.jsxs("div",{className:"flex flex-col items-center justify-center min-h-[60vh] gap-4 px-4 text-center",children:[n.jsx(fS,{className:"w-12 h-12 sm:w-16 sm:h-16 text-destructive"}),n.jsx("h2",{className:"text-lg sm:text-xl font-semibold",children:e("accessDenied")}),n.jsx("p",{className:"text-muted-foreground text-sm",children:e("accessDeniedDesc")})]});if(u&&c.length===0)return n.jsx(Ln,{message:e("loadingUsers")});const R=((Y=t==null?void 0:t.user)==null?void 0:Y.id)??"";let F="",$="",J=!1;return(C==null?void 0:C.type)==="role"?(F=C.remove?e("confirm.removeRoleTitle"):e("confirm.assignRoleTitle"),$=C.remove?e("confirm.removeRoleDesc",{role:C.role,user:C.userName}):e("confirm.assignRoleDesc",{role:C.role,user:C.userName}),J=C.remove):(C==null?void 0:C.type)==="ban"&&(F=C.ban?e("confirm.banTitle"):e("confirm.unbanTitle"),$=C.ban?e("confirm.banDesc",{user:C.userName}):e("confirm.unbanDesc",{user:C.userName}),J=C.ban),n.jsxs("div",{className:"max-w-6xl mx-auto space-y-4 sm:space-y-6 px-1 sm:px-0",children:[n.jsx(de.div,{...Te(),className:"flex flex-col gap-3",children:n.jsxs("div",{children:[n.jsxs("h1",{className:"font-heading font-bold text-xl sm:text-2xl md:text-3xl text-foreground flex items-center gap-2",children:[n.jsx(D4,{className:"text-primary shrink-0",size:22}),e("title")]}),n.jsx("p",{className:"text-muted-foreground mt-1 text-xs sm:text-sm",children:e("subtitle")})]})}),n.jsxs(Rp,{value:o,onValueChange:l,className:"w-full",children:[n.jsxs(ju,{children:[n.jsxs(un,{value:"users",className:"gap-1.5",children:[n.jsx(eo,{size:14})," ",e("tabs.users")]}),n.jsxs(un,{value:"logs",className:"gap-1.5",children:[n.jsx(ft,{size:14})," ",e("tabs.logs")]})]}),n.jsxs(hn,{value:"users",className:"space-y-4 sm:space-y-6 mt-4",children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsx("p",{className:"text-muted-foreground text-xs sm:text-sm",children:e("totalUsers",{count:S})}),n.jsxs(L,{variant:"outline",size:"sm",className:"gap-1.5",onClick:()=>H(),disabled:y,children:[n.jsx(ss,{size:14,className:y?"animate-spin":""}),e("refresh")]})]}),p&&n.jsx("div",{className:"bg-destructive/10 text-destructive px-4 py-3 rounded-lg text-sm",children:p}),n.jsxs("div",{className:"relative",children:[n.jsx(bn,{className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground",size:16}),n.jsx(gt,{placeholder:e("search"),value:g,onChange:re=>x(re.target.value),className:"pl-9"})]}),n.jsx(de.div,{...Te(.1),className:"grid grid-cols-2 gap-3",children:[{label:e("stats.total"),value:S,icon:eo,color:"text-foreground"},{label:e("stats.onPage"),value:c.length,icon:li,color:"text-primary"}].map(re=>n.jsxs("div",{className:"bg-card border border-border rounded-xl p-3 sm:p-4 flex items-center gap-3",children:[n.jsx(re.icon,{className:`${re.color} shrink-0`,size:18}),n.jsxs("div",{children:[n.jsx("p",{className:"text-xl sm:text-2xl font-bold text-foreground",children:re.value}),n.jsx("p",{className:"text-[10px] sm:text-xs text-muted-foreground",children:re.label})]})]},re.label))}),n.jsxs(de.div,{...Te(.2),className:"lg:hidden space-y-3",children:[c.map(re=>n.jsx(Lwe,{user:re,currentUserId:R,acting:y,timeAgo:r,onConfirm:te,t:e},re.id)),c.length===0&&n.jsx("div",{className:"py-12 text-center text-muted-foreground text-sm",children:e(b?"nothingFound":"noUsers")}),n.jsx(nj,{page:j,totalPages:N,acting:y,setPage:_})]}),n.jsxs(de.div,{...Te(.2),className:"hidden lg:block bg-card border border-border rounded-xl overflow-hidden",children:[n.jsx("div",{className:"overflow-x-auto",children:n.jsxs("table",{className:"w-full text-sm",children:[n.jsx("thead",{children:n.jsxs("tr",{className:"border-b border-border bg-muted/30",children:[n.jsx("th",{className:"text-left px-4 py-3 font-medium text-muted-foreground",children:e("table.user")}),n.jsx("th",{className:"text-left px-4 py-3 font-medium text-muted-foreground",children:e("table.status")}),n.jsx("th",{className:"text-left px-4 py-3 font-medium text-muted-foreground",children:e("table.roles")}),n.jsx("th",{className:"text-left px-4 py-3 font-medium text-muted-foreground",children:e("table.workspace")}),n.jsx("th",{className:"text-left px-4 py-3 font-medium text-muted-foreground",children:e("table.lastLogin")}),n.jsx("th",{className:"text-right px-4 py-3 font-medium text-muted-foreground",children:e("table.actions")})]})}),n.jsx("tbody",{children:c.map(re=>n.jsxs("tr",{className:`border-b border-border/50 hover:bg-muted/20 transition-colors ${re.is_banned?"opacity-60":""}`,children:[n.jsx("td",{className:"px-4 py-3",children:n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsxs(ub,{className:"h-8 w-8",children:[n.jsx(hb,{src:re.avatar_url??void 0}),n.jsx(mb,{className:"text-xs",children:(re.full_name??re.email??"?").charAt(0).toUpperCase()})]}),n.jsxs("div",{className:"min-w-0",children:[n.jsx("p",{className:"font-medium text-foreground truncate",children:re.full_name||"—"}),n.jsx("p",{className:"text-xs text-muted-foreground truncate",children:re.email})]})]})}),n.jsx("td",{className:"px-4 py-3",children:re.is_banned?n.jsxs(fe,{className:"bg-destructive/10 text-destructive border-0 text-[10px] gap-1",children:[n.jsx(iu,{size:10})," ",e("banned")]}):n.jsxs(fe,{className:"bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400 border-0 text-[10px] gap-1",children:[n.jsx(aS,{size:10})," ",e("active")]})}),n.jsx("td",{className:"px-4 py-3",children:n.jsx("div",{className:"flex flex-wrap gap-1",children:re.roles.length>0?re.roles.map(G=>{const O=pb[G]??li;return n.jsxs(fe,{className:`${KP[G]??""} text-[10px] gap-1 border-0`,children:[n.jsx(O,{size:10})," ",G]},G)}):n.jsx("span",{className:"text-muted-foreground text-xs",children:e("noRoles")})})}),n.jsx("td",{className:"px-4 py-3",children:re.workspace?n.jsxs("div",{children:[n.jsx("p",{className:"text-foreground truncate max-w-[150px]",children:re.workspace.name}),n.jsx(fe,{variant:"outline",className:"text-[10px] mt-0.5",children:re.workspace.plan})]}):n.jsx("span",{className:"text-muted-foreground",children:"—"})}),n.jsx("td",{className:"px-4 py-3 text-muted-foreground text-xs",children:re.last_login_at?r(re.last_login_at):"—"}),n.jsx("td",{className:"px-4 py-3 text-right",children:n.jsx(QP,{user:re,currentUserId:R,acting:y,onConfirm:te,t:e})})]},re.id))})]})}),c.length===0&&n.jsx("div",{className:"py-12 text-center text-muted-foreground",children:e(b?"nothingFound":"noUsers")}),n.jsx(nj,{page:j,totalPages:N,acting:y,setPage:_})]}),n.jsx(bi,{open:!!C,onOpenChange:()=>
1045B(null),children:n.jsxs(oa,{className:"max-w-[90vw] sm:max-w-md",children:[n.jsxs(la,{children:[n.jsx(da,{children:F}),n.jsx(ua,{children:$})]}),n.jsxs(ca,{className:"flex-col sm:flex-row gap-2",children:[n.jsx(ma,{className:"w-full sm:w-auto",children:e("confirm.cancel")}),n.jsxs(ha,{onClick:V,className:`w-full sm:w-auto ${J?"bg-destructive hover:bg-destructive/90":""}`,children:[y&&n.jsx(xe,{className:"w-4 h-4 mr-2 animate-spin"}),(C==null?void 0:C.type)==="ban"?C.ban?e("confirm.ban"):e("confirm.unban"):(C==null?void 0:C.type)==="role"&&C.remove?e("confirm.remove"):e("confirm.assign")]})]})]})})]}),n.jsx(hn,{value:"logs",className:"mt-4",children:n.jsx(xwe,{})})]})]})},Owe={live:"Live / Эфиры",content:"Контент-студия",discovery:"Discovery / Темы",helper:"Вспомогательные"},Dwe=["live","content","discovery","helper"],Mwe=()=>{var j;const{isAdmin:e}=ar(),[t,s]=h.useState([]),[r,a]=h.useState(!0),[i,o]=h.useState(null),[l,c]=h.useState(""),[d,u]=h.useState(""),[m,p]=h.useState(!1),f=async()=>{const{data:_,error:N}=await I.from("prompt_templates").select("*").order("category").order("slot_key");if(N)Le.error("Не удалось загрузить промпты",{description:N.message});
1045else{const k=_??[];s(k),!i&&k.length&&o(k[0].id)}a(!1)};h.useEffect(()=>{f()},[]);const g=h.useMemo(()=>t.find(_=>_.id===i)??null,[t,i]);h.useEffect(()=>{g&&u(g.body??"")},[i,g==null?void 0:g.version]);const x=h.useMemo(()=>{var k;const _=t.filter(S=>{if(!l)return!0;const T=l.toLowerCase();return S.title.toLowerCase().includes(T)||S.slot_key.toLowerCase().includes(T)||S.description.toLowerCase().includes(T)}),N={};for(const S of _)(N[k=S.category]??(N[k]=[])).push(S);return N},[t,l]),b=!!g&&d!==g.body,v=!!g&&g.body!==g.default_body,y=async()=>{if(!g)return;p(!0);const{error:_}=await I.from("prompt_templates").update({body:d,version:g.version+1}).eq("id",g.id);p(!1),_?Le.error("Не сохранилось",{description:_.message}):(Le.success("Промпт сохранён"),await f())},w=async()=>{if(!g||!confirm("Сбросить промпт к заводской версии? Текущие правки будут потеряны."))return;p(!0);const{error:_}=await I.from("prompt_templates").update({body:g.default_body,version:g.version+1}).eq("id",g.id);p(!1),_?Le.error("Не получилось сбросить",{description:_.message}):(Le.success("Сброшено к заводской версии"),await f())};return e?r?n.jsx(Ln,{message:"Загрузка промптов..."}):n.jsxs("div",{className:"max-w-7xl mx-auto px-1 sm:px-0 space-y-4",children:[n.jsxs(de.div,{...Te(),className:"space-y-1",children:[n.jsxs("h1",{className:"font-heading font-bold text-xl sm:text-2xl md:text-3xl text-foreground flex items-center gap-2",children:[n.jsx(tt,{className:"text-primary shrink-0",size:22}),"Промпты движка (дефолты)"]}),n.jsx("p",{className:"text-muted-foreground text-xs sm:text-sm",children:"Глобальные системные тексты, которые модель получает в момент генерации. На каждое действие — один дефолтный промпт. На странице персоны или конкретного эфира его можно переопределить."})]}),n.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-[320px_1fr] gap-4",children:[n.jsxs("aside",{className:"bg-card border border-border rounded-xl overflow-hidden flex flex-col max-h-[80vh]",children:[n.jsx("div",{className:"p-3 border-b border-border",children:n.jsxs("div",{className:"relative",children:[n.jsx(bn,{className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground",size:14}),n.jsx(gt,{value:l,onChange:_=>c(_.target.value),placeholder:"Поиск по слоту...",className:"pl-8 h-8 text-sm"})]})}),n.jsxs("div",{className:"overflow-y-auto flex-1",children:[Dwe.filter(_=>{var N;return(N=x[_])==null?void 0:N.length}).map(_=>n.jsxs("div",{className:"py-1",children:[n.jsx("div",{className:"px-3 py-1.5 text-[10px] uppercase tracking-wider text-muted-foreground/70 font-medium",children:Owe[_]??_}),x[_].map(N=>{const k=N.body!==N.default_body,S=N.id===i;return n.jsxs("button",{onClick:()=>o(N.id),className:`w-full text-left px-3 py-2 flex items-center gap-2 text-sm hover:bg-muted/40 transition ${S?"bg-muted/60":""}`,children:[n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("span",{className:"truncate font-medium text-foreground",children:N.title}),k&&n.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-primary shrink-0",title:"Изменён от дефолта"})]}),n.jsx("div",{className:"text-[10px] text-muted-foreground truncate font-mono",children:N.slot_key})]}),n.jsx(yn,{size:14,className:"text-muted-foreground/50 shrink-0"})]},N.id)})]},_)),Object.keys(x).length===0&&n.jsx("div",{className:"py-12 text-center text-sm text-muted-foreground",children:"Ничего не найдено"})]})]}),n.jsx("section",{className:"bg-card border border-border rounded-xl p-4 sm:p-6 space-y-4",children:g?n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"space-y-2",children:[n.jsxs("div",{className:"flex flex-wrap items-start gap-2 justify-between",children:[n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsxs("h2",{className:"font-heading font-semibold text-lg text-foreground flex items-center gap-2",children:[g.title,v&&n.jsxs(fe,{variant:"outline",className:"text-[10px] gap-1",children:[n.jsx(ms,{size:10})," изменён"]})]}),n.jsx("div",{className:"text-[11px] font-mono text-muted-foreground mt-0.5",children:g.slot_key})]}),n.jsxs("div",{className:"flex gap-2 shrink-0",children:[n.jsxs(L,{variant:"outline",size:"sm",onClick:w,disabled:m||!v,className:"gap-1.5",children:[n.jsx(hS,{size:14})," Сбросить"]}),n.jsxs(L,{size:"sm",onClick:y,disabled:m||!b,className:"gap-1.5",children:[m?n.jsx(xe,{size:14,className:"animate-spin"}):n.jsx(Id,{size:14}),"Сохранить"]})]})]}),g.description&&n.jsx("p",{className:"text-sm text-muted-foreground",children:g.description}),g.where_used&&n.jsxs("div",{className:"text-xs bg-muted/40 rounded-lg px-3 py-2 text-muted-foreground",children:[n.jsx("span",{className:"font-medium text-foreground",children:"Куда уходит:"})," ",g.where_used]}),((j=g.variables)==null?void 0:j.length)>0&&n.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[n.jsx("span",{className:"text-xs text-muted-foreground",children:"Доступные переменные:"}),g.variables.map(_=>n.jsx("code",{className:"text-[11px] bg-muted px-1.5 py-0.5 rounded font-mono text-foreground",children:`{{${_}}}`},_))]})]}),n.jsx(Fs,{value:d,onChange:_=>u(_.target.value),rows:20,className:"font-mono text-xs leading-relaxed"}),n.jsxs("details",{className:"text-xs",children:[n.jsx("summary",{className:"cursor-pointer text-muted-foreground hover:text-foreground",children:"Показать заводской текст"}),n.jsx("pre",{className:"mt-2 bg-muted/40 rounded-lg p-3 text-xs whitespace-pre-wrap font-mono max-h-80 overflow-y-auto",children:g.default_body||"(пусто)"})]}),n.jsxs("div",{className:"text-[10px] text-muted-foreground flex justify-between pt-2 border-t border-border",children:[n.jsxs("span",{children:["Версия ",g.version]}),n.jsxs("span",{children:["Обновлено ",new Date(g.updated_at).toLocaleStr
1045ing()]})]})]}):n.jsx("div",{className:"py-20 text-center text-muted-foreground text-sm",children:"Выберите промпт слева"})})]})]}):n.jsxs("div",{className:"flex flex-col items-center justify-center min-h-[60vh] gap-4 px-4 text-center",children:[n.jsx(fS,{className:"w-12 h-12 text-destructive"}),n.jsx("h2",{className:"text-lg font-semibold",children:"Доступ запрещён"}),n.jsx("p",{className:"text-muted-foreground text-sm",children:"Эта страница доступна только администраторам."})]})},zwe=["all","US","GB","RU","DE","FR","ES","BR","IN","JP"],Fwe=["all","youtube","reddit","hackernews"],sg=e=>e==="youtube"?n.jsx(Ls,{className:"w-3 h-3"}):e==="reddit"?n.jsx(lu,{className:"w-3 h-3"}):e==="hackernews"?n.jsx(Ol,{className:"w-3 h-3"}):n.jsx(u4,{className:"w-3 h-3"}),ng=e=>e==="youtube"?"YouTube":e==="reddit"?"Reddit":e==="hackernews"?"HN":e,Uwe=({onSeed:e})=>{const{t}=Oe("topic-discovery"),[s,r]=h.useState([]),[a,i]=h.useState([]),[o,l]=h.useState("all"),[c,d]=h.useState("all"),[u,m]=h.useState(!0),[p,f]=h.useState(null),g=async()=>{const v=new Date(Date.now()-216e5).toISOString(),y=new Date(Date.now()-24*60*60*1e3).toISOString(),[w,j]=await Promise.all([I.from("trending_themes").select("id,theme,description,why_now,emotion,angle,opening_line,talking_points,avoid,strength,regions,sources,captured_at,video_ids").gte("captured_at",v).order("strength",{ascending:!1}).limit(12),I.from("trending_signals").select("id,source,source_id,title,author,subreddit,url,thumbnail_url,regions,velocity_score,hotness,last_score,last_comments,published_at").gte("last_seen_at",y).order("velocity_score",{ascending:!1}).limit(120)]);r(w.data||[]),i(j.data||[]),m(!1)};h.useEffect(()=>{g()},[]);const x=h.useMemo(()=>{let v=a;return c!=="all"&&(v=v.filter(y=>y.source===c)),o!=="all"&&(v=v.filter(y=>{var w;return!((w=y.regions)!=null&&w.length)||y.regions.includes(o)})),v.slice(0,12)},[a,o,c]),b=h.useMemo(()=>{let v=s;return o!=="all"&&(v=v.filter(y=>{var w;return!((w=y.regions)!=null&&w.length)||y.regions.includes(o)})),c!=="all"&&(v=v.filter(y=>(y.sources||[]).includes(c))),v},[s,o,c]);return u||s.length===0&&a.length===0?null:n.jsxs("div",{className:"space-y-6",children:[n.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Ol,{className:"w-4 h-4 text-orange-500"}),n.jsx("h2",{className:"text-sm font-semibold uppercase tracking-wider text-muted-foreground",children:t("trending.themesTitle")})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("div",{className:"flex rounded-lg border border-border/60 bg-card p-0.5",children:Fwe.map(v=>n.jsxs("button",{onClick:()=>d(v),className:`px-2.5 py-1 text-[11px] font-medium rounded-md transition-colors flex items-center gap-1 ${c===v?"bg-primary text-primary-foreground":"text-muted-foreground hover:text-foreground"}`,children:[v!=="all"&&sg(v),v==="all"?"All":ng(v)]},v))}),n.jsxs(ut,{value:o,onValueChange:l,children:[n.jsx(ct,{className:"w-[140px] h-8 text-xs",children:n.jsx(ht,{})}),n.jsx(dt,{children:zwe.map(v=>n.jsx(ce,{value:v,children:v==="all"?t("trending.regionsAll"):v},v))})]})]})]}),b.length===0?n.jsx("div",{className:"rounded-xl border border-dashed border-border/60 p-6 text-center text-sm text-muted-foreground",children:t("trending.themesEmpty")}):n.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:b.map(v=>{var j;const y=p===v.id,w=!!(v.angle||v.opening_line||v.talking_points&&v.talking_points.length);return n.jsxs("div",{className:"rounded-xl border border-border/60 bg-card hover:border-primary/40 transition-all overflow-hidden",children:[n.jsxs("div",{className:"p-4",children:[n.jsxs("div",{className:"flex items-start justify-between gap-2",children:[n.jsx("div",{className:"font-semibold text-sm leading-tight flex-1",children:v.theme}),n.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[v.emotion&&n.jsx(fe,{variant:"outline",className:"text-[10px] capitalize",children:v.emotion}),n.jsxs(fe,{variant:"secondary",className:"text-[10px]",children:[n.jsx(Ol,{className:"w-3 h-3 mr-1 text-orange-500"}),Math.round((v.strength||0)*100)]})]})]}),v.description&&n.jsx("p",{className:"text-xs text-muted-foreground mt-2 line-clamp-2",children:v.description}),n.jsxs("div",{className:"mt-3 flex items-center justify-between gap-2",children:[n.jsxs("div",{className:"flex gap-1 flex-wrap items-center",children:[(v.sources||[]).map(_=>n.jsxs(fe,{variant:"outline",className:"text-[9px] gap-1 px-1.5 py-0",children:[sg(_)," ",ng(_)]},_)),(j=v.regions)==null?void 0:j.slice(0,3).map(_=>n.jsx("span",{className:"text-[10px] text-muted-foreground",children:_},_))]}),n.jsxs("div",{className:"flex items-center gap-2",children:[w&&n.jsxs("button",{onClick:()=>f(y?null:v.id),className:"text-[11px] text-muted-foreground hover:text-foreground flex items-center gap-1",children:[n.jsx(ps,{className:`w-3 h-3 transition-transform ${y?"rotate-180":""}`}),t("trending.angle")]}),n.jsxs("button",{onClick:()=>e(v.theme),className:"text-[11px] text-primary hover:underline flex items-center gap-1",children:[n.jsx(tt,{className:"w-3 h-3"})," ",t("trending.useAsSeed")]})]})]})]}),y&&w&&n.jsxs("div",{className:"border-t border-border/60 bg-muted/30 p-4 space-y-3 text-xs",children:[v.why_now&&n.jsxs("div",{children:[n.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted-foreground mb-1",children:t("trending.whyNow")}
1045),n.jsx("p",{className:"text-foreground/90",children:v.why_now})]}),v.angle&&n.jsxs("div",{children:[n.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted-foreground mb-1",children:t("trending.angle")}),n.jsx("p",{className:"text-foreground/90 italic",children:v.angle})]}),v.opening_line&&n.jsxs("div",{children:[n.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted-foreground mb-1",children:t("trending.openingLine")}),n.jsxs("p",{className:"text-foreground/90 font-medium",children:["«",v.opening_line,"»"]})]}),v.talking_points&&v.talking_points.length>0&&n.jsxs("div",{children:[n.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted-foreground mb-1",children:t("trending.talkingPoints")}),n.jsx("ul",{className:"space-y-1",children:v.talking_points.map((_,N)=>n.jsxs("li",{className:"flex gap-2",children:[n.jsx("span",{className:"text-primary",children:"•"}),n.jsx("span",{children:_})]},N))})]}),v.avoid&&v.avoid.length>0&&n.jsxs("div",{children:[n.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted-foreground mb-1",children:t("trending.avoid")}),n.jsx("ul",{className:"space-y-1",children:v.avoid.map((_,N)=>n.jsxs("li",{className:"flex gap-2 text-muted-foreground line-through",children:[n.jsx("span",{children:"✕"}),n.jsx("span",{children:_})]},N))})]})]})]},v.id)})}),n.jsxs("div",{className:"flex items-center gap-2 pt-2",children:[n.jsx(Ld,{className:"w-4 h-4 text-primary"}),n.jsx("h2",{className:"text-sm font-semibold uppercase tracking-wider text-muted-foreground",children:t("trending.surgingTitle")})]}),x.length===0?n.jsx("div",{className:"rounded-xl border border-dashed border-border/60 p-6 text-center text-sm text-muted-foreground",children:t("trending.surgingEmpty")}):n.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3",children:x.map(v=>{const y=v.source==="youtube",w=y?v.source_id:null,j=v.source==="reddit"?`r/${v.subreddit||"?"}`:v.source==="hackernews"?"Hacker News":v.author||"YouTube";return n.jsxs("div",{className:"rounded-xl border border-border/60 bg-card overflow-hidden hover:shadow-md transition-shadow",children:[y&&w&&n.jsx("a",{href:`https://www.youtube.com/watch?v=${w}`,target:"_blank",rel:"noreferrer",className:"block relative aspect-video bg-muted",children:v.thumbnail_url&&n.jsx("img",{src:v.thumbnail_url,alt:v.title||"",className:"w-full h-full object-cover",loading:"lazy"})}),n.jsxs("div",{className:"p-3 space-y-1.5",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsxs(fe,{variant:"outline",className:"text-[9px] gap-1 px-1.5 py-0",children:[sg(v.source)," ",ng(v.source)]}),n.jsxs("div",{className:"text-[10px] text-muted-foreground flex items-center gap-1",children:[n.jsx(Ld,{className:"w-3 h-3 text-primary"}),Math.round(v.velocity_score)," /h"]})]}),n.jsx("div",{className:"text-sm font-medium line-clamp-2 leading-snug",children:v.title}),n.jsx("div",{className:"text-[11px] text-muted-foreground truncate",children:j}),n.jsxs("div",{className:"flex items-center justify-between gap-2 pt-1",children:[n.jsxs("button",{type:"button",onClick:()=>e(v.title||""),className:"text-[11px] text-primary hover:underline flex items-center gap-1",children:[n.jsx(tt,{className:"w-3 h-3"})," ",t("trending.useAsSeed")]}),v.url&&n.jsx("a",{href:v.url,target:"_blank",rel:"noreferrer",className:"text-[11px] text-muted-foreground hover:text-foreground",children:n.jsx(Rs,{className:"w-3 h-3"})})]})]})]},v.id)})})]})};function fb(e){const[t,s]=h.useState({}),[r,a]=h.useState(!1);h.useEffect(()=>{let o=!1;if(!e){s({});return}return a(!0),I.from("personas").select("prompt_config").eq("id",e).maybeSingle().then(({data:l})=>{o||s((l==null?void 0:l.prompt_config)||{})}).then(()=>!o&&a(!1)),()=>{o=!0}},[e]);const i=h.useCallback(async o=>{e&&(s(o.prompt_config),await I.from("personas").update({prompt_config:o.prompt_config}).eq("id",e))},[e]);return{promptConfig:t,loading:r,update:i}}const Bwe=["US","GB","RU","DE","FR","ES","BR","IN","JP","UA","PL"],Vwe=[{code:"en",label:"English"},{code:"ru",label:"Русский"},{code:"es",label:"Español"},{code:"de",label:"Deutsch"},{code:"fr",label:"Français"},{code:"pt",label:"Português"},{code:"uk",label:"Українська"},{code:"ja",label:"日本語"}],rj=["trends","pains","combo"],aj={trends:uu,pains:k4,combo:Ey},qwe=()=>{var Z;const{t:e}=Oe("topic-discovery"),{profile:t}=st(),s=fi(),r=t==null?void 0:t.workspace_id,{personas:a}=wi(),[i,o]=h.useState(""),l=i||((Z=a[0])==null?void 0:Z.id)||"",{promptConfig:c,update:d}=fb(l||null),[u,m]=h.useState("trends"),[p,f]=h.useState(""),[g,x]=h.useState("US"),[b,v]=h.useState("en"),[y,w]=h.useState(15),[j,_]=h.useState(12),[N,k]=h.useState(10),[S,T]=h.useState(10),[C,B]=h.useState(""),[E,H]=h.useState(!1),[z,ne]=h.useState([]),[V,te]=h.useState(!0),R=A=>e(`modes.${A}.label`),F=A=>e(`modes.${A}.desc`),$=A=>e(`status.${A}`,{defaultValue:A}),J=async()=>
1045{if(!r)return;const{data:A}=await I.from("discovery_queries").select("id,query,mode,region,language,status,created_at,updated_at").eq("workspace_id",r).order("created_at",{ascending:!1}).limit(25);ne(A||[]),te(!1)};h.useEffect(()=>{J()},[r]),h.useEffect(()=>{if(!z.some(ue=>["pending","searching","fetching_transcripts","synthesizing"].includes(ue.status)))return;const oe=setInterval(J,3500);return()=>clearInterval(oe)},[z]);const Y=u==="trends"?j:u==="pains"?N:S,re=async()=>{if(r){H(!0);try{const{data:A,error:oe}=await I.functions.invoke("discovery-run",{body:{workspace_id:r,persona_id:l||void 0,mode:u,query:p.trim(),region:g,language:b,min_duration_sec:u==="pains"?0:y*60,max_results:Y,extra_instructions:C.trim()||void 0}});if(oe)throw oe;A!=null&&A.query_id&&(Le.success(p.trim()?e("form.launchedToast",{mode:R(u)}):e("form.launchedGlobalToast",{mode:R(u)})),f(""),J())}catch(A){Le.error((A==null?void 0:A.message)||e("form.launchFailed"))}finally{H(!1)}}},G=e(u==="trends"?"form.placeholderTrends":u==="pains"?"form.placeholderPains":"form.placeholderCombo"),O=p.trim()?e("form.submitWith",{mode:R(u)}):e("form.submitGlobal",{mode:R(u),region:g});return n.jsxs("div",{className:"space-y-6 max-w-6xl",children:[n.jsxs(de.div,{initial:{opacity:0,y:8},animate:{opacity:1,y:0},className:"flex items-center gap-3",children:[n.jsx("div",{className:"w-10 h-10 rounded-xl bg-primary/10 flex items-center justify-center",children:n.jsx(jy,{className:"w-5 h-5 text-primary"})}),n.jsxs("div",{children:[n.jsx("h1",{className:"text-2xl font-heading font-bold tracking-tight",children:e("pageTitle")}),n.jsx("p",{className:"text-sm text-muted-foreground",children:e("pageSubtitle")})]})]}),n.jsx(Uwe,{onSeed:A=>{f(A),m("trends"),window.scrollTo({top:400,behavior:"smooth"})}}),n.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:rj.map(A=>{const oe=aj[A],ue=u===A;return n.jsxs("button",{type:"button",onClick:()=>m(A),className:`text-left rounded-xl border-2 p-4 transition-all ${ue?"border-primary bg-primary/5 shadow-sm":"border-border/60 bg-card hover:border-primary/40"}`,children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(oe,{className:`w-4 h-4 ${ue?"text-primary":"text-muted-foreground"}`}),n.jsx("span",{className:`font-semibold text-sm ${ue?"text-foreground":"text-foreground/80"}`,children:R(A)})]}),n.jsx("p",{className:"text-xs text-muted-foreground mt-1.5 leading-relaxed",children:F(A)})]},A)})}),n.jsxs("div",{className:"rounded-2xl border border-border/60 bg-card p-6 space-y-5",children:[n.jsx(Pe,{label:e("form.queryLabel"),children:n.jsx(gt,{placeholder:G,value:p,onChange:A=>f(A.target.value),onKeyDown:A=>A.key==="Enter"&&!E&&re()})}),n.jsx(Pe,{label:`${e("form.focusLabel")} ${e("form.focusOptional")}`,children:n.jsx(Fs,{placeholder:e("form.focusPlaceholder"),value:C,onChange:A=>B(A.target.value),rows:3,className:"resize-y"})}),n.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[n.jsx(Pe,{label:e("form.regionLabel"),children:n.jsxs(ut,{value:g,onValueChange:x,children:[n.jsx(ct,{children:n.jsx(ht,{})}),n.jsx(dt,{children:Bwe.map(A=>n.jsx(ce,{value:A,children:A},A))})]})}),n.jsx(Pe,{label:e("form.languageLabel"),children:n.jsxs(ut,{value:b,onValueChange:v,children:[n.jsx(ct,{children:n.jsx(ht,{})}),n.jsx(dt,{children:Vwe.map(A=>n.jsx(ce,{value:A.code,children:A.label},A.code))})]})})]}),a.length>0&&n.jsx(Pe,{label:e("form.personaLabel",{defaultValue:"Persona (для промптов)"}),children:n.jsxs(ut,{value:l,onValueChange:o,children:[n.jsx(ct,{children:n.jsx(ht,{})}),n.jsx(dt,{children:a.map(A=>n.jsx(ce,{value:A.id,children:A.name},A.id))})]})}),l&&n.jsx($p,{personaPromptConfig:c,update:d,keys:["topic_synthesis","webinar_plan_block"],title:e("form.promptsTitle",{defaultValue:"Промпты Topic Discovery"}),subtitle:e("form.promptsSubtitle",{defaultValue:"Синтез темы и блок плана вебинара. Сохраняется в персоне — пока не сбросить, остаётся ваше."})}),n.jsxs("div",{className:"rounded-xl border border-border/40 bg-muted/20 p-4 space-y-4",children:[n.jsxs("div",{className:"text-[11px] font-semibold uppercase tracking-wider text-muted-foreground",children:[e("form.modeSettings"),": ",R(u)]}),u==="trends"&&n.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[n.jsx(Pe,{label:e("form.minDuration",{min:y}),children:n.jsx("input",{type:"range",min:5,max:60,step:5,value:y,onChange:A=>w(Number(A.target.value)),className:"w-full accent-primary"})}),n.jsx(Pe,{label:e("form.trendsMax",{n:j}),children:n.jsx("input",{type:"range",min:5,max:20,step:1,value:j,onChange:A=>_(Number(A.target.value)),className:"w-full accent-primary"})})]}),u==="pains"&&n.jsxs(Pe,{label:e("form.painsMax",{n:N}),children:[n.jsx("input",{type:"range",min:5,max:20,step:1,value:N,onChange:A=>k(Number(A.target.value)),className:"w-full accent-primary"}),n.jsx("p",{className:"text-[11px] text-muted-foreground mt-1.5",children:e("form.painsHint")})]}),u==="combo"&&n.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[n.jsx(Pe,{label:e("form.minDuration",{min:y}),children:n.jsx("input",{type:"range",min:5,max:60,step:5,value:y,onChange:A=>w(Number(A.target.value)),className:"w-full accent-primary"})}),n.jsx(Pe,{label:e("form.comboMax",{n:S}),children:n.jsx("input",{type:"range",min:5,max:15,step:1,value:S,onChange:A=>T(Number(A.target.value)),className:"w-full accent-primary"})})]})]}),n.jsx("div",{className:"flex justify-end",children:n.jsxs(L,{onClick:re,disabled:E||!r,children:[E?n.jsx(xe,{className:"w-4 h-4 mr-2 animate-spin"}):n.jsx(bn,{className:"w-4 h-4 mr-2"}),O]})})]}),n.jsxs("div",{className:"space-y-3",children:[n.jsx("h2",{className:"text-sm font-semibold text-muted-foreground uppercase tracking-wider",children:e("recent.title")}),V?n.jsx(Ln,{}):z.length===0?n.jsx(Er,{icon:tt,title:e("recent.empty"),description:e("recent.emptyDesc")}):n.jsx("div",{className:"grid gap-3",children:z.map(A=>{const oe=A.status==="completed",ue=A.status==="failed",je=!oe&&!ue,ae
1045=Date.now()-new Date(A.updated_at).getTime(),ie=je&&ae>5*60*1e3,we=rj.includes(A.mode)?A.mode:"trends",Ae=aj[we],nt=async Qe=>{Qe.stopPropagation();try{await I.from("discovery_queries").update({status:"failed",error_text:"Marked failed by user (hung)"}).eq("id",A.id);const{error:P}=await I.functions.invoke("discovery-run",{body:{workspace_id:r,mode:we,query:A.query,region:A.region,language:A.language,min_duration_sec:we==="pains"?0:15*60,max_results:12}});if(P)throw P;Le.success(e("recent.retry")),J()}catch(P){Le.error((P==null?void 0:P.message)||e("form.launchFailed"))}};return n.jsx("button",{onClick:()=>oe&&s(`/app/topic-discovery/${A.id}`),disabled:!oe,className:`text-left rounded-xl border p-4 transition-all ${ie?"border-amber-500/60 bg-amber-500/5":"border-border/60 bg-card"} ${oe?"hover:border-primary/50 hover:shadow-md cursor-pointer":"opacity-90"}`,children:n.jsxs("div",{className:"flex items-center justify-between gap-3",children:[n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsxs("div",{className:"font-medium truncate flex items-center gap-2",children:[n.jsx(Ae,{className:"w-3.5 h-3.5 text-primary shrink-0"}),A.query]}),n.jsxs("div",{className:"text-xs text-muted-foreground mt-1 flex items-center gap-2 flex-wrap",children:[n.jsx(fe,{variant:"secondary",className:"text-[10px]",children:R(we)}),n.jsxs("span",{children:[A.region," · ",A.language]}),ie&&n.jsxs(fe,{variant:"outline",className:"text-[10px] border-amber-500/60 text-amber-700",children:[n.jsx(ft,{className:"w-3 h-3 mr-1"}),e("recent.hung")]})]})]}),n.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[ie&&n.jsxs(L,{size:"sm",variant:"outline",onClick:nt,className:"h-7 text-xs",children:[n.jsx(E4,{className:"w-3 h-3 mr-1"}),e("recent.retry")]}),je&&!ie&&n.jsx(xe,{className:"w-4 h-4 animate-spin text-primary"}),oe&&n.jsx(wt,{className:"w-4 h-4 text-emerald-600"}),ue&&n.jsx(gn,{className:"w-4 h-4 text-destructive"}),n.jsx("span",{className:"text-xs text-muted-foreground",children:$(A.status)}),oe&&n.jsx(Tr,{className:"w-4 h-4 text-muted-foreground"})]})]})},A.id)})})]})]})};var gb="Progress",xb=100,[Hwe,aje]=Is(gb),[Wwe,Gwe]=Hwe(gb),JP=h.forwardRef((e,t)=>{const{__scopeProgress:s,value:r=null,max:a,getValueLabel:i=Ywe,...o}=e;(a||a===0)&&!ij(a)&&console.error(Kwe(`${a}`,"Progress"));const l=ij(a)?a:xb;r!==null&&!oj(r,l)&&console.error(Qwe(`${r}`,"Progress"));const c=oj(r,l)?r:null,d=Rm(c)?i(c,l):void 0;return n.jsx(Wwe,{scope:s,value:c,max:l,children:n.jsx(qe.div,{"aria-valuemax":l,"aria-valuemin":0,"aria-valuenow":Rm(c)?c:void 0,"aria-valuetext":d,role:"progressbar","data-state":eE(c,l),"data-value":c??void 0,"data-max":l,...o,ref:t})})});JP.displayName=gb;var ZP="ProgressIndicator",XP=h.forwardRef((e,t)=>{const{__scopeProgress:s,...r}=e,a=Gwe(ZP,s);return n.jsx(qe.div,{"data-state":eE(a.value,a.max),"data-value":a.value??void 0,"data-max":a.max,...r,ref:t})});XP.displayName=ZP;function Ywe(e,t){return`${Math.round(e/t*100)}%`}function eE(e,t){return e==null?"indeterminate":e===t?"complete":"loading"}function Rm(e){return typeof e=="number"}function ij(e){return Rm(e)&&!isNaN(e)&&e>0}function oj(e,t){return Rm(e)&&!isNaN(e)&&e<=t&&e>=0}function Kwe(e,t){return`Invalid prop \`max\` of value \`${e}\` supplied to \`${t}\`. Only numbers greater than 0 are valid max values. Defaulting to \`${xb}\`.`}function Qwe(e,t){return`Invalid prop \`value\` of value \`${e}\` supplied to \`${t}\`. The \`value\` prop must be:
1046  - a positive number
1047  - less than the value passed to \`max\` (or ${xb} if no \`max\` prop is set)
1048  - \`null\` or \`undefined\` if the progress is indeterminate.
1049
1050Defaulting to \`null\`.`}var tE=JP,Jwe=XP;const sE=h.forwardRef(({className:e,value:t,...s},r)=>n.jsx(tE,{ref:r,className:_e("relative h-4 w-full overflow-hidden rounded-full bg-secondary",e),...s,children:n.jsx(Jwe,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));sE.displayName=tE.displayName;const Zwe=e=>{const t=Math.floor(e/60),s=Math.floor(t/60);return s?`${s}h ${t%60}m`:`${t}m`},Xwe=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:String(e),e1e=()=>{const{t:e}=Oe("topic-discovery"),{queryId:t}=R$(),{profile:s}=st(),r=fi(),[a,i]=h.useState(null),[o,l]=h.useState([]),[c,d]=h.useState(null),[u,m]=h.useState([]),[p,f]=h.useState(!0),[g,x]=h.useState(!1),[b,v]=h.useState(null),[y,w]=h.useState([]),[j,_]=h.useState(""),[N,k]=h.useState(""),[S,T]=h.useState(null),[C,B]=h.useState(null),E=h.useRef(null);h.useEffect(()=>{t&&(async()=>{const[{data:z},{data:ne},{data:V}]=await Promise.all([I.from("discovery_queries").select("id,query,status,language").eq("id",t).maybeSingle(),I.from("discovery_videos").select("*").eq("query_id",t).order("score",{ascending:!1}),I.from("discovery_topics").select("*").eq("query_id",t).order("created_at",{ascending:!1}).limit(1)]);i(z),l(ne||[]);const te=(V||[])[0];if(d(te||null),te){const{data:R}=await I.from("discovery_quotes").select("id,quote_text,host_comment,source_url,video_id").eq("topic_id",te.id).order("ord");
1050m(R||[])}f(!1)})()},[t]),h.useEffect(()=>{s!=null&&s.workspace_id&&I.from("personas").select("id, name, language").eq("workspace_id",s.workspace_id).order("created_at",{ascending:!1}).then(({data:z})=>{const ne=z||[];w(ne),_(V=>{var te;return V||((te=ne[0])==null?void 0:te.id)||""})})},[s==null?void 0:s.workspace_id]);const H=async()=>{if(c){if(!j){Le.error(e("result.selectPersonaFirst"));return}x(!0),B(null),T(null);try{const{data:z,error:ne}=await I.functions.invoke("discovery-to-webinar",{body:{topic_id:c.id,persona_id:j,extra_instructions:N.trim()||void 0}});if(ne)throw ne;z!=null&&z.live_session_id&&T(z.live_session_id)}catch(z){Le.error((z==null?void 0:z.message)||e("result.createFailed")),x(!1)}}};return h.useEffect(()=>{if(!S)return;let z=!1;const ne=async()=>{const{data:V}=await I.from("live_sessions").select("metadata_json").eq("id",S).maybeSingle();if(z)return;const te=(V==null?void 0:V.metadata_json)||{},R={plan_blocks_expected:Number(te.plan_blocks_expected||0),plan_blocks_generated:Number(te.plan_blocks_generated||0),greeting_ready:!!te.greeting_ready,description_ready:!!te.description_ready,continue_ready:!!te.continue_ready,summary_ready:!!te.summary_ready,plan_ready:!!te.plan_ready,ai_fields_status:String(te.ai_fields_status||"generating")};B(R),(R.ai_fields_status==="ready"||R.ai_fields_status==="partial")&&(E.current&&(window.clearInterval(E.current),E.current=null),Le.success(e("result.webinarReady")),r(`/app/webinars?edit=${S}`))};return ne(),E.current=window.setInterval(ne,2e3),()=>{z=!0,E.current&&(window.clearInterval(E.current),E.current=null)}},[S,r]),p?n.jsx(Ln,{}):a?n.jsxs("div",{className:"space-y-6 max-w-5xl",children:[n.jsx("div",{className:"flex items-center justify-between gap-4",children:n.jsxs(zt,{to:"/app/topic-discovery",className:"inline-flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground",children:[n.jsx(Hi,{className:"w-4 h-4"})," ",e("result.backLink")]})}),c&&n.jsxs("div",{className:"rounded-2xl border border-border/60 bg-card p-4 space-y-3",children:[n.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-end gap-3",children:[n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsxs("div",{className:"text-[11px] uppercase tracking-wider text-muted-foreground mb-1.5 flex items-center gap-1.5",children:[n.jsx(Xs,{className:"w-3 h-3"})," ",e("result.personaLabel")]}),y.length===0?n.jsxs("div",{className:"text-sm text-muted-foreground",children:[e("result.noPersonas"),n.jsx(zt,{to:"/app/personas",className:"text-primary hover:underline",children:e("result.noPersonasCreate")}),"."]}):n.jsxs(ut,{value:j,onValueChange:_,children:[n.jsx(ct,{children:n.jsx(ht,{placeholder:e("result.selectPersonaPlaceholder")})}),n.jsx(dt,{children:y.map(z=>n.jsxs(ce,{value:z.id,children:[z.name,z.language?` · ${z.language}`:""]},z.id))})]})]}),n.jsxs(L,{onClick:H,disabled:g||!j,size:"lg",className:"sm:shrink-0",children:[g?n.jsx(xe,{className:"w-4 h-4 mr-2 animate-spin"}):n.jsx(xi,{className:"w-4 h-4 mr-2"}),e(g?"result.generating":"result.createWebinar")]})]}),n.jsxs("div",{children:[n.jsxs("div",{className:"text-[11px] uppercase tracking-wider text-muted-foreground mb-1.5",children:[e("result.extraInstructions")," ",n.jsx("span",{className:"normal-case tracking-normal text-muted-foreground/70",children:e("result.extraOptional")})]}),n.jsx(Fs,{value:N,onChange:z=>k(z.target.value),placeholder:e("result.extraPlaceholder"),rows:3,maxLength:2e3,disabled:g})]}),g&&n.jsx(s1e,{progress:C})]}),c?n.jsxs("div",{className:"rounded-2xl border border-border/60 bg-gradient-to-br from-primary/5 to-transparent p-6 space-y-4",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-xs uppercase tracking-wider text-muted-foreground mb-1",children:e("result.topicTitle")}),n.jsx("h1",{className:"text-2xl font-heading font-bold tracking-tight",children:c.title})]}),Array.isArray(c.key_points)&&c.key_points.length>0&&n.jsxs("div",{children:[n.jsx("div",{className:"text-xs uppercase tracking-wider text-muted-foreground mb-2",children:e("result.keyPoints")}),n.jsx("ul",{className:"space-y-1.5 text-sm",children:c.key_points.map((z,ne)=>n.jsxs("li",{className:"flex gap-2",children:[n.jsx("span",{className:"text-primary",children:"•"}),n.jsx("span",{children:z})]},ne))})]}),c.summary_md&&n.jsxs("div",{children:[n.jsx("div",{className:"text-xs uppercase tracking-wider text-muted-foreground mb-2",children:e("result.summary")}
1050),n.jsx("div",{className:"text-sm whitespace-pre-wrap leading-relaxed text-foreground/90",children:c.summary_md})]}),c.suggested_intro&&n.jsxs("div",{children:[n.jsx("div",{className:"text-xs uppercase tracking-wider text-muted-foreground mb-2",children:e("result.suggestedIntro")}),n.jsx("div",{className:"text-sm italic whitespace-pre-wrap leading-relaxed bg-background/60 rounded-lg p-3 border border-border/40",children:c.suggested_intro})]})]}):n.jsxs("div",{className:"rounded-2xl border border-border/60 bg-card p-6 text-sm text-muted-foreground",children:[e("result.topicNotReady"),n.jsx("b",{children:a.status})]}),(c==null?void 0:c.freeform_md)&&n.jsxs("div",{className:"rounded-2xl border border-primary/30 bg-card p-6 space-y-3",children:[n.jsxs("div",{className:"text-xs uppercase tracking-wider text-primary font-semibold flex items-center gap-2",children:[n.jsx(tt,{className:"w-3.5 h-3.5"})," ",e("result.freeformTitle")]}),n.jsx("div",{className:"text-sm whitespace-pre-wrap leading-relaxed text-foreground/90",children:c.freeform_md})]}),(c==null?void 0:c.pain_clusters)&&n.jsx(t1e,{clusters:c.pain_clusters,t:e}),u.length>0&&n.jsxs("div",{className:"space-y-3",children:[n.jsxs("h2",{className:"text-sm font-semibold uppercase tracking-wider text-muted-foreground flex items-center gap-2",children:[n.jsx(P4,{className:"w-4 h-4"})," ",e("result.quotesTitle")]}),n.jsx("div",{className:"space-y-3",children:u.map(z=>n.jsxs("div",{className:"rounded-xl border border-border/60 bg-card p-4",children:[n.jsxs("div",{className:"text-sm leading-relaxed italic",children:['"',z.quote_text,'"']}),n.jsxs("a",{href:z.source_url,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 text-xs text-primary mt-1 hover:underline",children:[e("result.source")," ",n.jsx(Rs,{className:"w-3 h-3"})]}),z.host_comment&&n.jsxs("div",{className:"mt-3 pl-3 border-l-2 border-primary/40 text-sm text-foreground/90",children:[n.jsx("span",{className:"text-xs uppercase tracking-wider text-primary mr-2",children:e("result.hostSays")}),z.host_comment]})]},z.id))})]}),n.jsxs("div",{className:"space-y-3",children:[n.jsxs("h2",{className:"text-sm font-semibold uppercase tracking-wider text-muted-foreground flex items-center gap-2",children:[n.jsx(Ns,{className:"w-4 h-4"})," ",e("result.sourceVideos",{count:o.length})]}),n.jsx("div",{className:"grid gap-3",children:o.map(z=>n.jsxs("div",{className:"rounded-xl border border-border/60 bg-card overflow-hidden",children:[n.jsxs("div",{className:"flex gap-4 p-3",children:[z.thumbnail_url&&n.jsx("a",{href:`https://youtu.be/${z.youtube_video_id}`,target:"_blank",rel:"noreferrer",className:"shrink-0",children:n.jsx("img",{src:z.thumbnail_url,alt:"",className:"w-40 aspect-video object-cover rounded-lg",loading:"lazy"})}),n.jsxs("div",{className:"min-w-0 flex-1 space-y-1",children:[n.jsx("div",{className:"font-medium leading-snug line-clamp-2",children:z.title}),n.jsx("div",{className:"text-xs text-muted-foreground",children:z.channel_title}),n.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-xs text-muted-foreground pt-1",children:[n.jsx("span",{children:Zwe(z.duration_sec||0)}),n.jsx("span",{children:"·"}),n.jsxs("span",{children:[Xwe(z.view_count||0)," ",e("result.views")]}),z.talk_density&&n.jsxs(fe,{variant:z.is_conversational?"default":"secondary",className:"text-[10px]",children:[Math.round(z.talk_density)," w/min"]})]}),z.transcript_text&&n.jsx("button",{onClick:()=>v(b===z.id?null:z.id),className:"text-xs text-primary hover:underline mt-1",children:b===z.id?e("result.hideTranscript"):e("result.showTranscript")})]})]}),b===z.id&&z.transcript_text&&n.jsx("div",{className:"max-h-72 overflow-y-auto border-t border-border/40 px-4 py-3 text-xs leading-relaxed text-muted-foreground bg-background/40",children:z.transcript_text})]},z.id))})]})]}):n.jsx(Er,{icon:tt,title:e("result.notFound"),description:e("result.notFoundDesc")})};function t1e({clusters:e,t}){const s=[{key:"questions",title:t("result.clusters.questions"),accent:"border-primary/30 bg-primary/5"},{key:"objections",title:t("result.clusters.objections"),accent:"border-amber-300 bg-amber-50 dark:bg-amber-950/20"},{key:"pains",title:t("result.clusters.pains"),accent:"border-rose-300 bg-rose-50 dark:bg-rose-950/20"}];return s.some(a=>{var i;return(((i=e[a.key])==null?void 0:i.length)??0)>0}
1050)?n.jsxs("div",{className:"space-y-3",children:[n.jsxs("h2",{className:"text-sm font-semibold uppercase tracking-wider text-muted-foreground flex items-center gap-2",children:[n.jsx(tt,{className:"w-4 h-4"})," ",t("result.audienceSays")]}),n.jsx("div",{className:"space-y-4",children:s.map(a=>{const i=e[a.key];return i!=null&&i.length?n.jsxs("div",{children:[n.jsx("h3",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground mb-2",children:a.title}),n.jsx("div",{className:"space-y-2",children:i.map((o,l)=>{var c;return n.jsxs("div",{className:`rounded-lg border p-3 ${a.accent}`,children:[n.jsxs("div",{className:"flex items-start justify-between gap-2",children:[n.jsx("div",{className:"text-sm font-medium",children:o.text}),typeof o.count=="number"&&n.jsxs("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-background/60 border border-border/40 shrink-0",children:["×",o.count]})]}),(c=o.quotes)!=null&&c.length?n.jsx("ul",{className:"mt-2 space-y-1",children:o.quotes.slice(0,3).map((d,u)=>n.jsxs("li",{className:"text-[12px] text-muted-foreground italic leading-snug",children:["«",d,"»"]},u))}):null]},l)})})]},a.key):null})})]}):null}function s1e({progress:e}){const{t}=Oe("topic-discovery"),s=(e==null?void 0:e.plan_blocks_expected)||0,r=(e==null?void 0:e.plan_blocks_generated)||0,a=s?Math.round(r/s*100):0,i=4+(s||1),o=(e!=null&&e.greeting_ready?1:0)+(e!=null&&e.description_ready?1:0)+(e!=null&&e.continue_ready?1:0)+(e!=null&&e.summary_ready?1:0)+r,l=Math.min(100,Math.round(o/i*100)),c=[{key:"description",label:t("result.progress.description"),done:!!(e!=null&&e.description_ready)},{key:"greeting",label:t("result.progress.greeting"),done:!!(e!=null&&e.greeting_ready)},{key:"plan",label:t("result.progress.plan"),done:!!(e!=null&&e.plan_ready),sub:s?t("result.progress.planBlocks",{generated:r,expected:s}):t("result.progress.planPreparing")},{key:"continue",label:t("result.progress.continue"),done:!!(e!=null&&e.continue_ready)},{key:"summary",label:t("result.progress.summary"),done:!!(e!=null&&e.summary_ready)}];return n.jsxs("div",{className:"rounded-xl border border-border/60 bg-muted/30 p-4 space-y-3",children:[n.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[n.jsxs("div",{className:"text-sm font-medium flex items-center gap-2",children:[n.jsx(xe,{className:"w-4 h-4 animate-spin text-primary"}),t("result.progress.header",{pct:l})]}),n.jsx("div",{className:"text-[11px] text-muted-foreground",children:t("result.progress.tail")})]}),n.jsx(sE,{value:l,className:"h-2"}),n.jsx("ul",{className:"space-y-1.5 pt-1",children:c.map(d=>n.jsxs("li",{className:"flex items-center gap-2 text-[13px]",children:[d.done?n.jsx(ms,{className:"w-3.5 h-3.5 text-emerald-500 shrink-0"}):n.jsx(xe,{className:"w-3.5 h-3.5 animate-spin text-muted-foreground/60 shrink-0"}),n.jsxs("span",{className:d.done?"text-foreground":"text-muted-foreground",children:[d.label,d.sub&&!d.done&&n.jsxs("span",{className:"text-muted-foreground/70",children:[" — ",d.sub]}),d.key==="plan"&&d.done&&s>0&&n.jsxs("span",{className:"text-muted-foreground/70",children:[" — ",t("result.progress.planDone",{count:s})]})]})]},d.key))}),s>0&&n.jsx("div",{className:"text-[11px] text-muted-foreground",children:t("result.progress.planLine",{pct:a,generated:r,expected:s})})]})}const lj={active:"default",paused:"secondary",draft:"outline",archived:"outline",error:"destructive"};function n1e(){const{t:e}=Oe("ads"),{status:t,account:s}=eb(),r=ET(),[a,i]=h.useState(!1),[o,l]=h.useState(null),[c,d]=h.useState(null),u=t==="connected"&&(s==null?void 0:s.adAccountId)&&(s==null?void 0:s.pageId),{status:m,account:p}=tb(),f=OT(),[g,x]=h.useState(!1),[b,v]=h.useState(null),[y,w]=h.useState(null),j=m==="connected"&&!!(p!=null&&p.customerId),_=async(k,S)=>{if(!(S==="delete"&&!window.confirm(e("deleteConfirm")))){d(k.id);try{await r.updateStatus(k.id,S),Le.success(e(`actions.${S}`))}catch(T){Le.error(T.message||e("errors.updateFailed"))}finally{d(null)}}},N=async(k,S)=>{if(!(S==="delete"&&!window.confirm(e("deleteConfirm")))){w(k.id);try{await f.updateStatus(k.id,S),Le.success(e(`actions.${S}`))}catch(T){Le.error(T.message||e("errors.updateFailed"))}finally{w(null)}}};
1050return n.jsxs("div",{className:"max-w-5xl mx-auto space-y-8",children:[n.jsx(de.div,{...Te(),className:"flex items-start justify-between gap-4 flex-wrap",children:n.jsxs("div",{children:[n.jsxs("h1",{className:"font-heading font-bold text-2xl md:text-3xl text-foreground flex items-center gap-2",children:[n.jsx(za,{className:"text-primary",size:26}),e("pageTitle")]}),n.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:e("pageSubtitle")})]})}),n.jsxs(Rp,{defaultValue:"meta",className:"space-y-6",children:[n.jsxs(ju,{children:[n.jsx(un,{value:"meta",children:e("tabs.meta")}),n.jsxs(un,{value:"google",className:"gap-1.5",children:[n.jsx(Ls,{size:14,className:"text-red-600"})," ",e("tabs.google")]})]}),n.jsxs(hn,{value:"meta",className:"space-y-6 mt-0",children:[n.jsxs("div",{className:"flex items-center justify-between gap-4 flex-wrap",children:[u&&(s!=null&&s.adAccountName||s!=null&&s.pageName)?n.jsxs("div",{className:"rounded-xl bg-surface-elevated border border-border/50 px-4 py-3 flex items-center gap-3 flex-wrap text-xs",children:[n.jsxs("span",{className:"text-muted-foreground",children:[e("activeAccountLabel"),":"]}),n.jsx("span",{className:"font-medium text-foreground",children:(s==null?void 0:s.adAccountName)||(s==null?void 0:s.adAccountId)}),(s==null?void 0:s.pageName)&&n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"text-border",children:"·"}),n.jsx("span",{className:"font-medium text-foreground",children:s.pageName})]}),n.jsx(L,{asChild:!0,variant:"ghost",size:"sm",className:"h-7 text-[11px] ml-1",children:n.jsx(zt,{to:"/app/integrations",children:e("changeAccount")})})]}):n.jsx("div",{}),u&&n.jsxs(L,{variant:"hero",className:"gap-2",onClick:()=>i(!0),children:[n.jsx(sr,{size:16})," ",e("createCampaign")]})]}),u?r.loading?n.jsx("div",{className:"flex items-center justify-center py-12",children:n.jsx(xe,{className:"animate-spin text-muted-foreground"})}):r.campaigns.length===0?n.jsx("div",{className:"rounded-2xl bg-surface-elevated border border-border/50 p-8 text-center text-sm text-muted-foreground",children:e("noCampaigns")}):n.jsx("div",{className:"space-y-3",children:r.campaigns.map(k=>{var T;const S=k.daily_budget_cents?`$${(k.daily_budget_cents/100).toFixed(2)}`:"—";return n.jsx("div",{className:"rounded-2xl bg-surface-elevated border border-border/50 shadow-premium-sm p-5",children:n.jsxs("div",{className:"flex items-start justify-between gap-4 flex-wrap",children:[n.jsxs("div",{className:"flex-1 min-w-0 space-y-1.5",children:[n.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[n.jsx("h3",{className:"font-semibold text-foreground truncate",children:k.name}),n.jsx(fe,{variant:lj[k.status]||"secondary",className:"text-[10px]",children:e(`status.${k.status}`)}),n.jsx(fe,{variant:"outline",className:"text-[10px]",children:e(`objective.${k.objective}`)})]}),n.jsxs("div",{className:"text-xs text-muted-foreground flex gap-3 flex-wrap",children:[n.jsxs("span",{children:[e("dailyBudget"),": ",n.jsxs("span",{className:"text-foreground font-medium",children:[S,e("perDay")]})]}),((T=k.creative)==null?void 0:T.link)&&n.jsxs("a",{href:k.creative.link,target:"_blank",rel:"noreferrer",className:"text-primary inline-flex items-center gap-1 hover:underline",children:[n.jsx(Rs,{size:11})," ",k.creative.link]})]}),k.last_error&&n.jsxs("p",{className:"text-[11px] text-destructive flex items-start gap-1",children:[n.jsx(ft,{size:12,className:"shrink-0 mt-0.5"})," ",k.last_error]})]}),n.jsxs("div",{className:"flex gap-1.5 flex-wrap",children:[n.jsxs(L,{size:"sm",variant:"outline",className:"gap-1.5",onClick:()=>l(k),disabled:c===k.id,children:[n.jsx($d,{size:13})," ",e("actions.edit",{defaultValue:"Изменить"})]}),k.status!=="active"&&k.status!=="archived"&&n.jsxs(L,{size:"sm",variant:"outline",className:"gap-1.5",disabled:c===k.id,onClick:()=>_(k,"activate"),children:[c===k.id?n.jsx(xe,{size:13,className:"animate-spin"}):n.jsx(en,{size:13})," ",e("actions.activate")]}),k.status==="active"&&n.jsxs(L,{size:"sm",variant:"outline",className:"gap-1.5",disabled:c===k.id,onClick:()=>_(k,"pause"),children:[c===k.id?n.jsx(xe,{size:13,className:"animate-spin"}):n.jsx($x,{size:13})," ",e("actions.pause")]}),k.status!=="archived"&&n.jsxs(L,{size:"sm",variant:"ghost",className:"gap-1.5 text-muted-foreground",disabled:c===k.id,onClick:()=>_(k,"archive"),children:[n.jsx(ii,{size:13})," ",e("actions.archive")]}),n.jsx(L,{size:"sm",variant:"ghost",className:"gap-1.5 text-destructive hover:text-destructive",disabled:c===k.id,onClick:()=>_(k,"delete"),children:n.jsx(ci,{size:13})})]})]})},k.id)})}):n.jsxs("div",{className:"rounded-2xl bg-surface-elevated border border-border/50 shadow-premium-sm p-8 text-center space-y-4",children:[n.jsx("div",{className:"w-14 h-14 roun
1050ded-2xl bg-amber-50 flex items-center justify-center mx-auto",children:n.jsx(ft,{className:"text-amber-500",size:26})}),n.jsxs("div",{className:"space-y-2",children:[n.jsx("h2",{className:"font-heading font-bold text-lg",children:e("notConnectedTitle")}),n.jsx("p",{className:"text-sm text-muted-foreground max-w-md mx-auto",children:e("notConnectedDesc")})]}),n.jsx(L,{asChild:!0,variant:"hero",className:"gap-2",children:n.jsxs(zt,{to:"/app/integrations",children:[n.jsx(Pr,{size:15})," ",e("goToIntegrations")]})})]})]}),n.jsxs(hn,{value:"google",className:"space-y-6 mt-0",children:[n.jsxs("div",{className:"flex items-center justify-between gap-4 flex-wrap",children:[j&&(p!=null&&p.customerDescriptiveName||p!=null&&p.customerId)?n.jsxs("div",{className:"rounded-xl bg-surface-elevated border border-border/50 px-4 py-3 flex items-center gap-3 flex-wrap text-xs",children:[n.jsxs("span",{className:"text-muted-foreground",children:[e("google.activeAccountLabel"),":"]}),n.jsx("span",{className:"font-medium text-foreground",children:(p==null?void 0:p.customerDescriptiveName)||(p==null?void 0:p.customerId)}),(p==null?void 0:p.customerCurrencyCode)&&n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"text-border",children:"·"}),n.jsx("span",{className:"text-foreground",children:p.customerCurrencyCode})]}),n.jsx(L,{asChild:!0,variant:"ghost",size:"sm",className:"h-7 text-[11px] ml-1",children:n.jsx(zt,{to:"/app/integrations",children:e("changeAccount")})})]}):n.jsx("div",{}),j&&n.jsxs(L,{variant:"hero",className:"gap-2",onClick:()=>x(!0),children:[n.jsx(sr,{size:16})," ",e("google.createCampaign")]})]}),j?f.loading?n.jsx("div",{className:"flex items-center justify-center py-12",children:n.jsx(xe,{className:"animate-spin text-muted-foreground"})}):f.campaigns.length===0?n.jsx("div",{className:"rounded-2xl bg-surface-elevated border border-border/50 p-8 text-center text-sm text-muted-foreground",children:e("google.noCampaigns")}):n.jsx("div",{className:"space-y-3",children:f.campaigns.map(k=>{var B,E;const S=k.daily_budget_micros?`${(k.daily_budget_micros/1e6).toFixed(2)} ${k.currency||"USD"}`:"—",T=(B=k.creative)==null?void 0:B.youtube_video_id,C=T?`https://www.youtube.com/watch?v=${T}`:(E=k.creative)==null?void 0:E.final_url;return n.jsx("div",{className:"rounded-2xl bg-surface-elevated border border-border/50 shadow-premium-sm p-5",children:n.jsxs("div",{className:"flex items-start justify-between gap-4 flex-wrap",children:[n.jsxs("div",{className:"flex-1 min-w-0 space-y-1.5",children:[n.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[n.jsx("h3",{className:"font-semibold text-foreground truncate",children:k.name}),n.jsx(fe,{variant:lj[k.status]||"secondary",className:"text-[10px]",children:e(`status.${k.status}`)}),n.jsxs(fe,{variant:"outline",className:"text-[10px] gap-1",children:[n.jsx(Ls,{size:10,className:"text-red-600"})," ",e("google.campaignType")]})]}),n.jsxs("div",{className:"text-xs text-muted-foreground flex gap-3 flex-wrap",children:[n.jsxs("span",{children:[e("dailyBudget"),": ",n.jsxs("span",{className:"text-foreground font-medium",children:[S,e("perDay")]})]}),C&&n.jsxs("a",{href:C,target:"_blank",rel:"noreferrer",className:"text-primary inline-flex items-center gap-1 hover:underline",children:[n.jsx(Rs,{size:11})," ",C]})]}),k.last_error&&n.jsxs("p",{className:"text-[11px] text-destructive flex items-start gap-1",children:[n.jsx(ft,{size:12,className:"shrink-0 mt-0.5"})," ",k.last_error]})]}),n.jsxs("div",{className:"flex gap-1.5 flex-wrap",children:[n.jsxs(L,{size:"sm",variant:"outline",className:"gap-1.5",onClick:()=>v(k),disabled:y===k.id,children:[n.jsx($d,{size:13})," ",e("actions.edit",{defaultValue:"Изменить"})]}),k.status!=="active"&&k.status!=="archived"&&n.jsxs(L,{size:"sm",variant:"outline",className:"gap-1.5",disabled:y===k.id,onClick:()=>N(k,"activate"),children:[y===k.id?n.jsx(xe,{size:13,className:"animate-spin"}):n.jsx(en,{size:13})," ",e("actions.activate")]}),k.status==="active"&&n.jsxs(L,{size:"sm",variant:"outline",className:"gap-1.5",disabled:y===k.id,onClick:()=>N(k,"pause"),children:[y===k.id?n.jsx(xe,{size:13,className:"animate-spin"}):n.jsx($x,{size:13})," ",e("actions.pause")]}),k.status!=="archived"&&n.jsxs(L,{size:"sm",variant:"ghost",className:"gap-1.5 text-muted-foreground",disabled:y===k.id,onClick:()=>N(k,"archive"),children:[n.jsx(ii,{size:13})," ",e("actions.archive")]}),n.jsx(L,{size:"sm",variant:"ghost",className:"gap-1.5 text-destructive hover:text-destructive",disabled:y===k.id,onClick:()=>N(k,"delete"),children:n.jsx(ci,{size:13})})]})]})},k.id)})}):n.jsxs("div",{className:"rounded-2xl bg-surface-elevated border border-border/50 shadow-premium-sm p-8 text-center space-y-4",children:[n.jsx("div",{className:"w-14 h-14 roun
1050ded-2xl bg-amber-50 flex items-center justify-center mx-auto",children:n.jsx(ft,{className:"text-amber-500",size:26})}),n.jsxs("div",{className:"space-y-2",children:[n.jsx("h2",{className:"font-heading font-bold text-lg",children:e("google.notConnectedTitle")}),n.jsx("p",{className:"text-sm text-muted-foreground max-w-md mx-auto",children:e("google.notConnectedDesc")})]}),n.jsx(L,{asChild:!0,variant:"hero",className:"gap-2",children:n.jsxs(zt,{to:"/app/integrations",children:[n.jsx(Pr,{size:15})," ",e("goToIntegrations")]})})]})]})]}),n.jsx(nv,{open:a,onOpenChange:i,onCreate:async k=>{try{await r.create(k),Le.success(e("createCampaign")),i(!1)}catch(S){Le.error(S.message||e("errors.createFailed"))}}}),n.jsx(nv,{open:!!o,onOpenChange:k=>!k&&l(null),editing:o,onUpdate:async(k,S)=>{try{await r.update(k,S),Le.success(e("actions.saved",{defaultValue:"Сохранено"})),l(null)}catch(T){Le.error(T.message||e("errors.updateFailed"))}}}),n.jsx(rv,{open:g,onOpenChange:x,onCreate:async k=>{try{await f.create(k),Le.success(e("google.createCampaign")),x(!1)}catch(S){Le.error(S.message||e("errors.createFailed"))}}}),n.jsx(rv,{open:!!b,onOpenChange:k=>!k&&v(null),editing:b,onUpdate:async(k,S)=>{try{await f.update(k,S),Le.success(e("actions.saved",{defaultValue:"Сохранено"})),v(null)}catch(T){Le.error(T.message||e("errors.updateFailed"))}}})]})}function r1e({sessionId:e}){const[t,s]=h.useState({}),[r,a]=h.useState([]),[i,o]=h.useState([]),[l,c]=h.useState(new Set),[d,u]=h.useState(!0);h.useEffect(()=>{let w=!1;const j=async()=>{const[N,k,S,T]=await Promise.all([I.from("trending_themes").select("id,theme,strength,captured_at").eq("session_id",e).order("captured_at",{ascending:!1}).limit(50),I.from("trending_topic_prefetch").select("id,theme_id,status,created_at").eq("session_id",e).in("status",["ready","queued","rendering"]).order("created_at",{ascending:!0}).limit(20),I.from("trending_topic_deliveries").select("id,theme_id,delivered_at,status").eq("session_id",e).order("delivered_at",{ascending:!1}).limit(10),I.from("trending_topic_deliveries").select("theme_id").eq("session_id",e)]);if(w)return;const C={};(N.data||[]).forEach(B=>{C[B.id]=B}),s(C),a(k.data||[]),o(S.data||[]),c(new Set((T.data||[]).map(B=>B.theme_id))),u(!1)};j();const _=window.setInterval(j,8e3);return()=>{w=!0,window.clearInterval(_)}},[e]);const m=new Set(r.map(w=>w.theme_id)),p=i[0],f=r.map(w=>({q:w,theme:t[w.theme_id]})).filter(w=>w.theme),g=i.slice(1).map(w=>({d:w,theme:t[w.theme_id]})).filter(w=>w.theme),x=Object.values(t).filter(w=>!l.has(w.id)&&!m.has(w.id)).slice(0,8),b=Object.keys(t).length,v=l.size,y=!d&&x.length===0&&f.length===0&&b>0;return d?n.jsx("div",{className:"text-xs text-muted-foreground",children:"Загружаем темы…"}):n.jsxs("div",{className:"space-y-4 rounded-lg border border-border/40 bg-muted/20 p-4",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsxs("div",{className:"text-sm font-semibold flex items-center gap-2",children:[n.jsx(tt,{className:"w-3.5 h-3.5 text-primary"}),"Темы эфира"]}),n.jsxs("div",{className:"text-[11px] text-muted-foreground tabular-nums",children:["собрано ",b," · отыграно ",v]})]}),y&&n.jsx("div",{className:"text-xs rounded-md border border-amber-500/30 bg-amber-500/5 p-2 text-amber-700 dark:text-amber-300",children:"Все собранные темы по запросу отыграны — собираем новый батч в фоне."}),n.jsxs("div",{className:"space-y-1.5",children:[n.jsxs("div",{className:"text-xs text-muted-foreground flex items-center gap-1.5",children:[n.jsx(St,{className:"w-3 h-3 text-destructive"}),"Сейчас в эфире"]}),p&&t[p.theme_id]?n.jsxs("div",{className:"rounded-md border border-primary/30 bg-primary/5 p-2.5 text-sm",children:[n.jsx("div",{className:"font-medium",children:t[p.theme_id].theme}),n.jsxs("div",{className:"text-[11px] text-muted-foreground mt-0.5",children:["взято ",new Date(p.delivered_at).toLocaleTimeString()]})]}):n.jsx("div",{className:"text-xs text-muted-foreground italic",children:"Ещё ничего не произносилось."})]}),n.jsxs("div",{className:"space-y-1.5",children:[n.jsxs("div",{className:"text-xs text-muted-foreground flex items-center gap-1.5",children:[n.jsx(ls,{className:"w-3 h-3"}),"В очереди (",f.length,")"]}),f.length===0?n.jsx("div",{className:"text-xs text-muted-foreground italic",children:"Очередь пуста — готовится фоном."}):n.jsx("ul",{className:"space-y-1",children:f.map(({q:w,theme:j})=>n.jsxs("li",{className:"text-sm flex items-start gap-2 rounded-md border border-border/40 bg-card px-2.5 py-1.5",children:[n.jsx("span",{className:"text-[10px] uppercase tracking-wider text-primary/70 mt-0.5",children:w.status}),n.jsx("span",{className:"flex-1 min-w-0 truncate",children:j.theme})]},w.id))})]}),x.length>0&&n.jsxs("div",{className:"space-y-1.5",children:[n.jsxs("div",{className:"text-xs text-muted-foreground",children:["Пул кандидатов (",x.length,")"]}),n.jsx("ul",{className:"space-y-1",children:x.map(w=>n.jsxs("li",{className:"text-sm flex items-center gap-2 text-muted-foreground",children:[n.jsx("span",{className:"text-[10px] tabular-nums w-8 text-right",children:w.strength!=null?w.strength.toFixed(2):"—"}),n.jsx("span",{className:"flex-1 min-w-0 truncate",children:w.theme})]},w.id))})]}),g.length>0&&n.jsxs("div",{className:"space-y-1.5",children:[n.jsxs("div",{className:"text-xs text-muted-foreground flex items-center gap-1.5",children:[n.jsx(wt,{className:"w-3 h-3"}),"Уже было (",g.length,")"]}),n.jsx("ul",{className:"space-y-1",children:g.map(({d:w,theme:j})=>n.jsxs("li",{className:"text-xs flex items-center gap-2 text-muted-foreground
1050/80",children:[n.jsx("span",{className:"tabular-nums",children:new Date(w.delivered_at).toLocaleTimeString()}),n.jsx("span",{className:"flex-1 min-w-0 truncate",children:j.theme})]},w.id))})]})]})}function a1e({session:e,patchSession:t,onStop:s,stopping:r}){const{t:a}=Oe("trends"),i=e.metadata_json||{},{fill:o,isLoading:l}=pa(),{promptConfig:c,update:d}=fb(e.persona_id||null),[u,m]=h.useState(()=>({title:e.title||"",description:e.description||"",language:i.language||"ru",chatReplyFirst:i.chat_reply_first!==!1,subtitles:i.subtitles_enabled!==!1,refreshHot:typeof i.refresh_hot_minutes=="number",refreshHotMinutes:i.refresh_hot_minutes||30,watermark:i.watermark_text||"",topicQuery:i.topic_query||"",useTranscripts:i.use_transcripts===!0,liveCommentTracking:i.live_comment_tracking!==!1})),[p,f]=h.useState(!1),g=h.useMemo(()=>({title:e.title||"",description:e.description||"",language:i.language||"ru",chatReplyFirst:i.chat_reply_first!==!1,subtitles:i.subtitles_enabled!==!1,refreshHot:typeof i.refresh_hot_minutes=="number",refreshHotMinutes:i.refresh_hot_minutes||30,watermark:i.watermark_text||"",topicQuery:i.topic_query||"",useTranscripts:i.use_transcripts===!0,liveCommentTracking:i.live_comment_tracking!==!1}),[e.id,e.title,e.description,i.language,i.chat_reply_first,i.subtitles_enabled,i.refresh_hot_minutes,i.watermark_text,i.topic_query,i.use_transcripts,i.live_comment_tracking]);JSON.stringify(u),JSON.stringify(g);const x=Math.max(5,Math.min(240,Number(u.refreshHotMinutes)||30)),b=async()=>{f(!0);try{const y=(u.topicQuery||"").trim(),w={...i,language:u.language,chat_reply_first:u.chatReplyFirst,subtitles_enabled:u.subtitles,refresh_hot_minutes:u.refreshHot?x:null,watermark_text:u.watermark||null,topic_query:y||null,use_transcripts:u.useTranscripts,live_comment_tracking:u.liveCommentTracking},j=(u.title||"").trim()||e.title,_=(u.description||"").trim()||e.description,{error:N}=await I.from("live_sessions").update({metadata_json:w,title:j,description:_,chat_reply_mode:u.chatReplyFirst?"auto_reply":"suggest_only"}).eq("id",e.id);if(N)throw N;t(e.id,{metadata_json:w,title:j,description:_,chat_reply_mode:u.chatReplyFirst?"auto_reply":"suggest_only"}),I.functions.invoke("trending-query-themes",{body:{session_id:e.id}}).catch(k=>console.error("trending-query-themes invoke failed",k))}catch(y){console.error("Failed to save active session",y)}finally{f(!1)}},v=y=>m(w=>({...w,...y}));return n.jsxs("div",{className:"rounded-lg border border-border/40 bg-card p-4 space-y-4",children:[n.jsxs("div",{className:"flex items-center justify-between gap-3",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsx("div",{className:"font-medium truncate",children:e.title}),n.jsxs("div",{className:"text-xs text-muted-foreground",children:[a("statusLabel"),": ",e.status," · ",a("startedAt"),":"," ",new Date(e.created_at).toLocaleString()]})]}),n.jsxs(L,{variant:"outline",size:"sm",onClick:()=>s(e.id),disabled:r,className:"gap-2",children:[n.jsx(du,{className:"w-3.5 h-3.5"}),a(r?"stopping":"stopBtn")]})]}),n.jsx(r1e,{sessionId:e.id}),n.jsxs("div",{className:"grid md:grid-cols-2 gap-4",children:[n.jsx(Pe,{label:a("languageLabel"),children:n.jsxs(ut,{value:u.language,onValueChange:y=>v({language:y}),children:[n.jsx(ct,{children:n.jsx(ht,{})}),n.jsxs(dt,{children:[n.jsx(ce,{value:"ru",children:"Русский"}),n.jsx(ce,{value:"en",children:"English"})]})]})}),n.jsx(Pe,{label:a("watermarkLabel"),children:n.jsx(gt,{value:u.watermark,onChange:y=>v({watermark:y.target.value}),placeholder:a("watermarkPlaceholder")})}),n.jsxs(Pe,{label:a("topicQueryLabel"),children:[n.jsx(gt,{value:u.topicQuery,onChange:y=>v({topicQuery:y.target.value}),placeholder:a("topicQueryPlaceholder")}),n.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:a("liveTopicQueryHint")})]})]}),u.topicQuery.trim().length>0&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-lg border border-border/40 bg-muted/30 p-3",children:[n.jsxs("div",{className:"text-sm",children:[n.jsx("div",{children:a("liveCommentTracking")}),n.jsx("div",{className:"text-xs text-muted-foreground",children:a("liveCommentTrackingHint")})]}),n.jsx(Ut,{checked:u.liveCommentTracking,onCheckedChange:y=>v({liveCommentTracking:y})})]}),n.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-lg border border-border/40 bg-muted/30 p-3",children:[n.jsxs("div",{className:"text-sm",children:[n.jsx("div",{children:"Deep audie
1050nce analysis (transcripts)"}),n.jsx("div",{className:"text-xs text-muted-foreground",children:"Adds Supadata transcript excerpts of top videos into the brief. Slower + uses Supadata quota."})]}),n.jsx(Ut,{checked:u.useTranscripts,onCheckedChange:y=>v({useTranscripts:y})})]})]}),n.jsx(Pe,{label:a("titleLabel"),children:n.jsx(Ot,{value:u.title,onChange:y=>v({title:y.target.value}),placeholder:a("titlePlaceholder"),aiLoading:l("trend_title"),onAiFill:async()=>{const y=await o({fieldName:"trend_title",fieldLabel:a("titleLabel"),currentValue:u.title,pageContext:{topic_query:u.topicQuery,format:"nonstop_trends",language:u.language},personaId:e.persona_id,language:u.language});y&&v({title:y})}})}),n.jsx(Pe,{label:a("descriptionLabel"),children:n.jsx(os,{value:u.description,onChange:y=>v({description:y.target.value}),placeholder:a("descriptionPlaceholder"),rows:3,aiLoading:l("trend_description"),onAiFill:async()=>{const y=await o({fieldName:"trend_description",fieldLabel:a("descriptionLabel"),currentValue:u.description,pageContext:{title:u.title,topic_query:u.topicQuery,format:"nonstop_trends",language:u.language},personaId:e.persona_id,language:u.language});y&&v({description:y})}})}),n.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-lg border border-border/40 bg-muted/30 p-3",children:[n.jsx("div",{className:"text-sm",children:a("subtitlesLabel")}),n.jsx(Ut,{checked:u.subtitles,onCheckedChange:y=>v({subtitles:y})})]}),n.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-lg border border-border/40 bg-muted/30 p-3",children:[n.jsx("div",{className:"text-sm",children:a("chatReplyLabel")}),n.jsx(Ut,{checked:u.chatReplyFirst,onCheckedChange:y=>v({chatReplyFirst:y})})]}),n.jsxs("div",{className:"rounded-lg border border-border/40 bg-muted/30 p-3 space-y-3",children:[n.jsxs("div",{className:"flex items-center justify-between gap-3",children:[n.jsxs("div",{className:"text-sm flex items-center gap-2",children:[n.jsx(ss,{className:"w-3.5 h-3.5 text-primary"}),a("refreshHotLabel")]}),n.jsx(Ut,{checked:u.refreshHot,onCheckedChange:y=>v({refreshHot:y})})]}),u.refreshHot&&n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx(gt,{type:"number",min:5,max:240,step:5,value:u.refreshHotMinutes,onChange:y=>v({refreshHotMinutes:Number(y.target.value)||30}),className:"w-24"}),n.jsx("span",{className:"text-xs text-muted-foreground",children:a("refreshHotHint")})]})]}),e.persona_id&&n.jsx($p,{personaPromptConfig:c,update:d,keys:["trending_juice","trending_cluster","speaking_format"],title:a("promptsTitle"),subtitle:a("promptsSubtitle"),defaultOpen:!0}),n.jsxs(L,{onClick:b,disabled:p,className:"gap-2",children:[n.jsx(ms,{className:"w-4 h-4"}),a(p?"savingAll":"saveAll")]})]})}var Up="Collapsible",[i1e,ije]=Is(Up),[o1e,vb]=i1e(Up),nE=h.forwardRef((e,t)=>{const{__scopeCollapsible:s,open:r,defaultOpen:a,disabled:i,onOpenChange:o,...l}=e,[c,d]=tr({prop:r,defaultProp:a??!1,onChange:o,caller:Up});return n.jsx(o1e,{scope:s,disabled:i,contentId:pn(),open:c,onOpenToggle:h.useCallback(()=>d(u=>!u),[d]),children:n.jsx(qe.div,{"data-state":bb(c),"data-disabled":i?"":void 0,...l,ref:t})})});nE.displayName=Up;var rE="CollapsibleTrigger",aE=h.forwardRef((e,t)=>{const{__scopeCollapsible:s,...r}=e,a=vb(rE,s);return n.jsx(qe.button,{type:"button","aria-controls":a.contentId,"aria-expanded":a.open||!1,"data-state":bb(a.open),"data-disabled":a.disabled?"":void 0,disabled:a.disabled,...r,ref:t,onClick:Ee(e.onClick,a.onOpenToggle)})});aE.displayName=rE;var yb="CollapsibleContent",iE=h.forwardRef((e,t)=>{const{forceMount:s,...r}=e,a=vb(yb,e.__scopeCollapsible);return n.jsx(sn,{present:s||a.open,children:({present:i})=>n.jsx(l1e,{...r,ref:t,present:i})})});iE.displayName=yb;var l1e=h.forwardRef((e,t)=>{const{__scopeCollapsible:s,present:r,children:a,...i}=e,o=vb(yb,s),[l,c]=h.useState(r),d=h.useRef(null),u=bt(t,d),m=h.useRef(0),p=m.current,f=h.useRef(0),g=f.current,x=o.open||l,b=h.useRef(x),v=h.useRef(void 0);return h.useEffect(()=>{const y=requestAnimationFrame(()=>b.current=!1);return()=>cancelAnimationFrame(y)},[]),cs(()=>{const y=d.current;if(y){v.current=v.current||{transitionDuration:y.style.transitionDuration,animationName:y.style.animationName},y.style.transitionDuration="0s",y.style.animationName="none";const w=y.getBoundingClientRect();m.current=w.height,f.current=w.width,b.current||(y.style.transitionDuration=v.current.transitionDuration,y.style.animationName=v.current.animationName),c(r)}},[o.open,r]),n.jsx(qe.div,{"data-state":bb(o.open),"data-disabled":o.disabled?"":void 0,id:o.contentId,hidden:!x,...i,ref:u,style:{"--radix-collapsible-content-height":p?`${p}px`:void 0,"--radix-collapsible-content-width":g?`${g}px`:void 0,...e.style},children:x&&a})});function bb(e){return e?"open":"closed"}var c1e=nE;const d1e=c1e,u1e=aE,h1e=iE;function Eo(e){return Array.isArray(e)?e.map(t=>
1050typeof t=="string"?t:JSON.stringify(t)).filter(Boolean):[]}function m1e({sessionId:e,onLaunch:t,launching:s,onCancel:r,canceling:a}){const[i,o]=h.useState([]),[l,c]=h.useState({}),[d,u]=h.useState(!0),[m,p]=h.useState(null);h.useEffect(()=>{let v=!1;const y=async()=>{const[j,_]=await Promise.all([I.from("trending_themes").select("id,theme,description,strength,captured_at,opening_line,talking_points,why_now,emotion,hook,contrarian_angle,pains,desires,debates,quotes,fresh_wave").eq("session_id",e).order("strength",{ascending:!1}).limit(50),I.from("trending_topic_prefetch").select("theme_id,status").eq("session_id",e).in("status",["queued","rendering","ready"])]);if(v)return;o(j.data||[]);const N={};for(const k of _.data||[]){const S=N[k.theme_id];(!S||S==="queued"&&k.status!=="queued"||S==="rendering"&&k.status==="ready")&&(N[k.theme_id]=k.status)}c(N),u(!1)};y();const w=window.setInterval(y,4e3);return()=>{v=!0,window.clearInterval(w)}},[e]);const f=h.useMemo(()=>i.map(v=>{const y=l[v.id];return{th:v,status:y==="ready"?"ready":y==="rendering"||y==="queued"?"preparing":"draft"}}),[i,l]),g=f.filter(v=>v.status==="ready").length,x=f.filter(v=>v.status==="preparing").length,b=i.find(v=>v.id===m)||null;return n.jsxs("div",{className:"rounded-xl border border-primary/30 bg-primary/5 p-5 space-y-4",children:[n.jsxs("div",{className:"flex items-start justify-between gap-3",children:[n.jsxs("div",{className:"space-y-1",children:[n.jsxs("div",{className:"text-sm font-semibold flex items-center gap-2",children:[n.jsx(tt,{className:"w-4 h-4 text-primary"}),"Подготовка тем"]}),n.jsxs("div",{className:"text-xs text-muted-foreground",children:["Найдено: ",n.jsx("span",{className:"font-medium tabular-nums",children:i.length})," · готовы к эфиру: ",n.jsx("span",{className:"font-medium tabular-nums text-primary",children:g}),x>0&&n.jsxs(n.Fragment,{children:[" · готовятся: ",n.jsx("span",{className:"tabular-nums",children:x})]})]})]}),n.jsx(L,{variant:"ghost",size:"sm",onClick:r,disabled:a||s,className:"text-muted-foreground",children:a?"Отмена…":"Отменить"})]}),d&&i.length===0&&n.jsxs("div",{className:"text-xs text-muted-foreground flex items-center gap-2 py-4",children:[n.jsx(xe,{className:"w-3.5 h-3.5 animate-spin"}),"Ищем темы по запросу — это занимает 30–90 сек…"]}),!d&&i.length===0&&n.jsx("div",{className:"text-xs text-muted-foreground italic py-2",children:"Пока ничего не найдено. Подождите ещё немного — функция собирает топ-видео и комментарии."}),n.jsx("ul",{className:"space-y-1.5",children:f.map(({th:v,status:y})=>n.jsx("li",{children:n.jsxs(d1e,{children:[n.jsx("div",{className:"flex items-stretch gap-2 rounded-lg border border-border/40 bg-card overflow-hidden",children:n.jsx(u1e,{asChild:!0,children:n.jsxs("button",{className:"flex-1 min-w-0 flex items-center gap-3 px-3 py-2.5 text-left hover:bg-muted/40 transition-colors",children:[n.jsx(p1e,{status:y}),n.jsx("span",{className:"flex-1 min-w-0 truncate text-sm font-medium",children:v.theme}),n.jsx("span",{className:"text-[11px] tabular-nums text-muted-foreground shrink-0",children:v.strength!=null?v.strength.toFixed(2):"—"}),n.jsx(ps,{className:"w-3.5 h-3.5 text-muted-foreground transition-transform ui-state-open:rotate-180"})]})})}),n.jsx(h1e,{children:n.jsxs("div",{className:"rounded-b-lg border border-t-0 border-border/40 bg-muted/30 px-4 py-3 space-y-2.5 -mt-px",children:[v.description&&n.jsx("p",{className:"text-xs text-muted-foreground leading-relaxed",children:v.description}),v.opening_line&&n.jsxs("div",{children:[n.jsx("div",{className:"text-[10px] uppercase tracking-wider text-primary/70 mb-1",children:"Открытие"}),n.jsxs("div",{className:"text-sm italic",children:['"',v.opening_line,'"']})]}),Eo(v.talking_points).length>0&&n.jsxs("div",{children:[n.jsx("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground mb-1",children:"О чём говорит"}),n.jsx("ol",{className:"text-sm space-y-1 list-decimal pl-5",children:Eo(v.talking_points).map((w,j)=>n.jsx("li",{children:w},j))})]}),n.jsxs(L,{variant:"ghost",size:"sm",className:"h-7 text-xs gap-1.5",onClick:()=>p(v.id),children:[n.jsx(Xi,{className:"w-3 h-3"}),"Полный бриф"]})]})})]})},v.id))}),n.jsx("div",{className:"flex flex-col sm:flex-row items-stretch sm:items-center gap-2 pt-2 border-t border-border/40",children:n.jsxs(L,{size:"lg",onClick:t,disabled:s||g===0,
1050className:"gap-2 flex-1",children:[s?n.jsx(xe,{className:"w-4 h-4 animate-spin"}):n.jsx(en,{className:"w-4 h-4"}),s?"Запускаем эфир…":g===0?i.length===0?"Ищем темы…":`Готовим брифы… (${i.length} тем найдено)`:`Старт эфира (${g} готово)`]})}),n.jsx(ns,{open:!!b,onOpenChange:v=>!v&&p(null),children:n.jsx(Zt,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:b&&n.jsxs(n.Fragment,{children:[n.jsx(Xt,{children:n.jsx(es,{className:"pr-8",children:b.theme})}),n.jsxs("div",{className:"space-y-4 text-sm",children:[b.description&&n.jsx(Ao,{label:"Описание",children:b.description}),b.why_now&&n.jsx(Ao,{label:"Why now",children:b.why_now}),b.emotion&&n.jsx(Ao,{label:"Эмоция",children:b.emotion}),b.hook&&n.jsx(Ao,{label:"Хук",children:b.hook}),b.opening_line&&n.jsx(Ao,{label:"Открытие",children:n.jsxs("span",{className:"italic",children:['"',b.opening_line,'"']})}),n.jsx(hh,{label:"Talking points",items:Eo(b.talking_points)}),n.jsx(hh,{label:"Pains",items:Eo(b.pains)}),n.jsx(hh,{label:"Desires",items:Eo(b.desires)}),n.jsx(hh,{label:"Quotes",items:Eo(b.quotes)}),b.contrarian_angle&&n.jsx(Ao,{label:"Contrarian angle",children:b.contrarian_angle}),Array.isArray(b.debates)&&b.debates.length>0&&n.jsxs("div",{children:[n.jsx("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground mb-1",children:"Debates"}),n.jsx("ul",{className:"space-y-1.5",children:b.debates.map((v,y)=>n.jsxs("li",{className:"text-xs rounded-md border border-border/40 bg-muted/30 p-2",children:[n.jsxs("div",{children:[n.jsx("span",{className:"font-medium",children:"A:"})," ",v.side_a]}),n.jsxs("div",{children:[n.jsx("span",{className:"font-medium",children:"B:"})," ",v.side_b]})]},y))})]})]})]})})})]})}function p1e({status:e}){return e==="ready"?n.jsxs(fe,{variant:"default",className:"gap-1 h-5 px-1.5 text-[10px]",children:[n.jsx(wt,{className:"w-2.5 h-2.5"}),"ready"]}):e==="preparing"?n.jsxs(fe,{variant:"secondary",className:"gap-1 h-5 px-1.5 text-[10px]",children:[n.jsx(xe,{className:"w-2.5 h-2.5 animate-spin"}),"preparing"]}):n.jsxs(fe,{variant:"outline",className:"gap-1 h-5 px-1.5 text-[10px] text-muted-foreground",children:[n.jsx(ls,{className:"w-2.5 h-2.5"}),"draft"]})}function Ao({label:e,children:t}){return n.jsxs("div",{children:[n.jsx("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground mb-1",children:e}),n.jsx("div",{className:"text-sm leading-relaxed",children:t})]})}function hh({label:e,items:t}){return t.length===0?null:n.jsxs("div",{children:[n.jsx("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground mb-1",children:e}),n.jsx("ul",{className:"list-disc pl-5 space-y-0.5",children:t.map((s,r)=>n.jsx("li",{children:s},r))})]})}const f1e=()=>{var P;const{t:e}=Oe("trends"),{personas:t,loading:s}=wi(),{sessions:r,loading:a,create:i,updateStatus:o,patchSession:l}=uo(),{dispatch:c}=ho(),[d,u]=_u(),[m,p,f]=dc("trends:create",{personaId:"",language:"ru",chatReplyFirst:!0,subtitles:!0,refreshHot:!0,refreshHotMinutes:30,topicQuery:"",title:"",description:"",liveCommentTracking:!0,useTranscripts:!1}),{personaId:g,language:x,chatReplyFirst:b,subtitles:v,refreshHot:y,refreshHotMinutes:w,topicQuery:j,title:_,description:N,liveCommentTracking:k,useTranscripts:S}=m,{fill:T,isLoading:C}=pa(),[B,E]=h.useState(null),[H,z]=h.useState(!1),[ne,V]=h.useState(!1),[te,R]=h.useState(!1),[F,$]=h.useState(null),[J,Y]=h.useState(null),re=h.useMemo(()=>r.filter(U=>{var Q;return((Q=U.metadata_json)==null?void 0:Q.mode)==="nonstop_trends"}),[r]),G=re.filter(U=>["queued","ready","live","scheduled"].includes(U.status)&&U.id!==B),O=re.filter(U=>["ended","canceled","failed"].includes(U.status)),Z=t.find(U=>U.id===g),A=g||((P=t[0])==null?void 0:P.id)||"",oe=x||(Z==null?void 0:Z.language)||"ru",{promptConfig:ue,update:je}=fb(A||null),ae=Math.max(5,Math.min(240,Number(w)||30)),ie=async()=>{if(!(!A||B)){z(!0),$(null);try{const U=await i({persona_id:A,title:(_||"").trim()||`Nonstop Trends — ${new Date().toLocaleString()}`,description:(N||"").trim()||"Auto-pulled trending topics, nonstop.",platform:"restream",live_mode:"nonstop_trends",chat_reply_mode:b?"auto_reply":"suggest_only",status:"draft",archive_enabled:!0,is_paid:!1,duration_seconds:null,metadata_json:{mode:"nonstop_trends",language:oe,chat_reply_first:b,subtitles_enabled:v,refresh_hot_minutes:y?ae:null,watermark_text:d||null,topic_query:(j||"").trim()||null,live_comment_tracking:k,use_transcripts:S}});if(!U)throw new Error("Failed to create session");E(U.id),I.functions.invoke("trending-query-themes",{body:{session_id:U.id}}).catch(Q=>console.error("trending-query-themes invoke failed",Q))}catch(U){console.error("Failed to start scouting",U),$(U.message||"Failed to start scouting")}finally{z(!1)}}},we=async()=>
1050{if(!(!B||!A)){V(!0),$(null);try{await o(B,"ready"),await c({job_type:ql.CONDUCT_LIVE_SESSION,persona_id:A,payload_json:{live_session_id:B,live_mode:"nonstop_trends",subtitles_enabled:v,refresh_hot_minutes:y?ae:void 0,watermark_text:d||void 0,topic_query:(j||"").trim()||void 0,live_comment_tracking:k,use_transcripts:S}}),E(null),f()}catch(U){console.error("Failed to launch nonstop trends",U),$(U.message||"Failed to launch")}finally{V(!1)}}},Ae=async()=>{if(B){R(!0);try{await o(B,"canceled"),E(null)}finally{R(!1)}}},nt=async U=>{Y(U);try{await o(U,"ended")}finally{Y(null)}},Qe=U=>{const Q=U.metadata_json||{};p(ve=>({...ve,personaId:U.persona_id||ve.personaId,language:typeof Q.language=="string"&&Q.language||ve.language,chatReplyFirst:typeof Q.chat_reply_first=="boolean"?Q.chat_reply_first:ve.chatReplyFirst,subtitles:typeof Q.subtitles_enabled=="boolean"?Q.subtitles_enabled:ve.subtitles,refreshHot:Q.refresh_hot_minutes!=null,refreshHotMinutes:typeof Q.refresh_hot_minutes=="number"?Q.refresh_hot_minutes:ve.refreshHotMinutes,topicQuery:typeof Q.topic_query=="string"&&Q.topic_query||"",title:U.title||ve.title,description:U.description||ve.description,liveCommentTracking:typeof Q.live_comment_tracking=="boolean"?Q.live_comment_tracking:ve.liveCommentTracking,useTranscripts:typeof Q.use_transcripts=="boolean"?Q.use_transcripts:ve.useTranscripts})),typeof Q.watermark_text=="string"&&u(Q.watermark_text),window.scrollTo({top:0,behavior:"smooth"})};return n.jsxs("div",{className:"space-y-8",children:[n.jsxs(de.div,{...Te,className:"space-y-2",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("div",{className:"p-2 rounded-lg bg-primary/10 text-primary",children:n.jsx(uu,{className:"w-5 h-5"})}),n.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:e("pageTitle")})]}),n.jsx("p",{className:"text-muted-foreground max-w-3xl",children:e("pageSubtitle")})]}),n.jsx(de.div,{...Te,className:"rounded-xl border border-border/50 bg-card p-6 space-y-5",children:s?n.jsx(Ln,{}):t.length===0?n.jsx(Er,{icon:tt,title:e("noPersona"),description:""}):n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"grid md:grid-cols-2 gap-4",children:[n.jsx(Pe,{label:e("personaLabel"),children:n.jsxs(ut,{value:A,onValueChange:U=>p(Q=>({...Q,personaId:U})),children:[n.jsx(ct,{children:n.jsx(ht,{placeholder:e("personaPlaceholder")})}),n.jsx(dt,{children:t.map(U=>n.jsx(ce,{value:U.id,children:U.name},U.id))})]})}),n.jsx(Pe,{label:e("languageLabel"),children:n.jsxs(ut,{value:oe,onValueChange:U=>p(Q=>({...Q,language:U})),children:[n.jsx(ct,{children:n.jsx(ht,{})}),n.jsxs(dt,{children:[n.jsx(ce,{value:"ru",children:"Русский"}),n.jsx(ce,{value:"en",children:"English"})]})]})}),n.jsx(Pe,{label:e("platformLabel"),children:n.jsx(gt,{value:e("platformRestream"),disabled:!0})}),n.jsx(Pe,{label:e("watermarkLabel"),children:n.jsx(gt,{value:d,onChange:U=>u(U.target.value),placeholder:e("watermarkPlaceholder")})}),n.jsxs(Pe,{label:e("topicQueryLabel"),children:[n.jsx(gt,{value:j,onChange:U=>p(Q=>({...Q,topicQuery:U.target.value})),placeholder:e("topicQueryPlaceholder")}),n.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:e("topicQueryHint")})]})]}),n.jsx(Pe,{label:e("titleLabel"),children:n.jsx(Ot,{value:_,onChange:U=>p(Q=>({...Q,title:U.target.value})),placeholder:e("titlePlaceholder"),aiLoading:C("trend_title"),onAiFill:async()=>{const U=await T({fieldName:"trend_title",fieldLabel:e("titleLabel"),currentValue:_,pageContext:{topic_query:j,format:"nonstop_trends",language:oe,persona:(Z==null?void 0:Z.name)||""},personaId:A,language:oe});U&&p(Q=>({...Q,title:U}))}})}),n.jsx(Pe,{label:e("descriptionLabel"),children:n.jsx(os,{value:N,onChange:U=>p(Q=>({...Q,description:U.target.value})),placeholder:e("descriptionPlaceholder"),rows:3,aiLoading:C("trend_description"),onAiFill:async()=>{const U=await T({fieldName:"trend_description",fieldLabel:e("descriptionLabel"),currentValue:N,pageContext:{title:_,topic_query:j,format:"nonstop_trends",language:oe,persona:(Z==null?void 0:Z.name)||""},personaId:A,language:oe});U&&p(Q=>({...Q,description:U}))}})}),n.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-lg border border-border/40 bg-muted/30 p-3",children:[n.jsx("div",{className:"text-sm",children:e("subtitlesLabel")}),n.jsx(Ut,{checked:v,onCheckedChange:U=>p(Q=>({...Q,subtitles:U}))})]}),n.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-lg border border-border/40 bg-muted/30 p-3",children:[n.jsx("div",{className:"text-sm",children:e("chatReplyLabel")}),n.jsx(Ut,{checked:b,onCheckedChange:U=>p(Q=>({...Q,chatReplyFirst:U}))})]}),j.trim().length>0&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-lg border border-border/40 bg-muted/30 p-3",children:[n.jsxs("div",{className:"text-sm",children:[n.jsx("div",{children:e("liveCommentTracking")}),n.jsx("div",{className:"text-xs text-muted-foreground",children:e("liveCommentTrackingHint")})]}),n.jsx(Ut,{checked:k,onCheckedChange:U=>p(Q=>({...Q,liveCommentTracking:U}))})]}),n.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-lg border border-border/40 bg-muted/30 p-3",children:[n.jsxs("div",{className:"text-sm",children:[n.jsx("div",{children:"Deep audie
1050nce analysis (transcripts)"}),n.jsx("div",{className:"text-xs text-muted-foreground",children:"Adds Supadata transcript excerpts of top videos into the brief. Slower + uses Supadata quota."})]}),n.jsx(Ut,{checked:S,onCheckedChange:U=>p(Q=>({...Q,useTranscripts:U}))})]})]}),n.jsxs("div",{className:"rounded-lg border border-border/40 bg-muted/30 p-3 space-y-3",children:[n.jsxs("div",{className:"flex items-center justify-between gap-3",children:[n.jsxs("div",{className:"text-sm flex items-center gap-2",children:[n.jsx(ss,{className:"w-3.5 h-3.5 text-primary"}),e("refreshHotLabel")]}),n.jsx(Ut,{checked:y,onCheckedChange:U=>p(Q=>({...Q,refreshHot:U}))})]}),y&&n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx(gt,{type:"number",min:5,max:240,step:5,value:w,onChange:U=>p(Q=>({...Q,refreshHotMinutes:Number(U.target.value)||30})),className:"w-24"}),n.jsx("span",{className:"text-xs text-muted-foreground",children:e("refreshHotHint")})]})]}),A&&n.jsx($p,{personaPromptConfig:ue,update:je,keys:["trending_juice","trending_cluster","speaking_format"],title:e("promptsTitle"),subtitle:e("promptsSubtitle"),defaultOpen:!0}),B?n.jsx(m1e,{sessionId:B,onLaunch:we,launching:ne,onCancel:Ae,canceling:te}):n.jsxs(L,{size:"lg",onClick:ie,disabled:H||!A,className:"gap-2",children:[n.jsx(en,{className:"w-4 h-4"}),H?"Создаём сессию…":"Найти темы"]}),F&&n.jsx("p",{className:"text-sm text-destructive",children:F})]})}),n.jsxs("section",{className:"space-y-3",children:[n.jsxs("h2",{className:"font-semibold flex items-center gap-2",children:[n.jsx(St,{className:"w-4 h-4 text-primary"})," ",e("activeTitle")]}),a?n.jsx(Ln,{}):G.length===0?n.jsx("div",{className:"text-sm text-muted-foreground",children:e("emptyActive")}):n.jsx("div",{className:"space-y-3",children:G.map(U=>n.jsx(a1e,{session:U,patchSession:l,onStop:nt,stopping:J===U.id},U.id))})]}),n.jsxs("section",{className:"space-y-3",children:[n.jsx("h2",{className:"font-semibold",children:e("historyTitle")}),O.length===0?n.jsx("div",{className:"text-sm text-muted-foreground",children:e("emptyHistory")}):n.jsx("div",{className:"space-y-2",children:O.slice(0,20).map(U=>n.jsxs("div",{className:"rounded-lg border border-border/40 bg-card/50 p-3 text-sm flex items-center justify-between gap-3",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsx("div",{className:"font-medium truncate",children:U.title}),n.jsxs("div",{className:"text-xs text-muted-foreground",children:[U.status," · ",new Date(U.created_at).toLocaleString()]})]}),n.jsxs(L,{size:"sm",variant:"outline",onClick:()=>Qe(U),className:"gap-1.5 shrink-0",children:[n.jsx(uS,{className:"w-3.5 h-3.5"}),e("repeatBtn")]})]},U.id))})]}),n.jsxs("section",{className:"rounded-xl border border-border/40 bg-muted/20 p-5 space-y-2",children:[n.jsx("h3",{className:"font-semibold text-sm",children:e("howItWorksTitle")}),n.jsx("ol",{className:"list-decimal pl-5 text-sm text-muted-foreground space-y-1",children:e("howItWorks",{returnObjects:!0}).map((U,Q)=>n.jsx("li",{children:U},Q))})]})]})},Do=h.forwardRef(({className:e,...t},s)=>n.jsx("div",{ref:s,className:_e("rounded-lg border bg-card text-card-foreground shadow-sm",e),...t}));Do.displayName="Card";const g1e=h.forwardRef(({className:e,...t},s)=>n.jsx("div",{ref:s,className:_e("flex flex-col space-y-1.5 p-6",e),...t}));g1e.displayName="CardHeader";const x1e=h.forwardRef(({className:e,...t},s)=>n.jsx("h3",{ref:s,className:_e("text-2xl font-semibold leading-none tracking-tight",e),...t}));x1e.displayName="CardTitle";const v1e=h.forwardRef(({className:e,...t},s)=>n.jsx("p",{ref:s,className:_e("text-sm text-muted-foreground",e),...t}));v1e.displayName="CardDescription";const y1e=h.forwardRef(({className:e,...t},s)=>n.jsx("div",{ref:s,className:_e("p-6 pt-0",e),...t}));y1e.displayName="CardContent";const b1e=h.forwardRef(({className:e,...t},s)=>n.jsx("div",{ref:s,className:_e("flex items-center p-6 pt-0",e),...t}));b1e.displayName="CardFooter";const w1e=["us","gb","ru","de","fr","es","it","ca","au","in","jp","cn","br","mx"],cj=["general","technology","business","science","health","entertainment","sports"],dj=["technology","business","science","health","general"],j1e=()=>{var G;const{t:e}=Oe("news"),{personas:t}=wi(),{sessions:s,loading:r,create:a,updateStatus:i,patchSession:o}=uo(),{dispatch:l}=ho(),[c,d]=_u(),[u,m,p]=dc("news:create",{personaId:"",language:"ru",mode:"surprise",chatReplyFirst:!0,subtitles:!0,title:"",description:"",q:"",country:"",category:"",domains:"",surpriseCategories:dj}),{personaId:f,language:g,mode:x,chatReplyFirst:b,subtitles:v,title:y,description:w,q:j,country:_,category:N,domains:k,surpriseCategories:S}=u,[T,C]=h.useState(!1),[B,E]=h.useState(null),[H,z]=h.useState(null),ne=h.useMemo(()=>s.filter(O=>{var Z;return((Z=O.metadata_json)==null?void 0:Z.mode)==="nonstop_news"}),[s]),V=ne.filter(O=>["queued","ready","live","scheduled"].includes(O.status)),te=ne.filter(O=>["ended","canceled","failed"].includes(O.status)),R=t.find(O=>O.id===f),F=f||((G=t[0])==null?void 0:G.id)||"",$=g||(R==null?void 0:R.language)||"ru",J=async()=>
1050{if(!F){z(e("noPersona"));return}if(!T){C(!0),z(null);try{const O={mode:x,language:$};x==="query"&&(O.q=(j||"").trim()||null),x==="region"&&(O.country=_||null,O.category=N||null),x==="domains"&&(O.domains=(k||"").split(",").map(ue=>ue.trim()).filter(Boolean)),x==="surprise"&&(O.surprise_categories=S);const Z=await a({persona_id:F,title:(y||"").trim()||`Nonstop News — ${new Date().toLocaleString()}`,description:(w||"").trim()||"Auto-pulled news from NewsAPI.",platform:"restream",live_mode:"nonstop_news",chat_reply_mode:b?"auto_reply":"suggest_only",status:"ready",archive_enabled:!0,is_paid:!1,duration_seconds:null,metadata_json:{mode:"nonstop_news",language:$,chat_reply_first:b,subtitles_enabled:v,watermark_text:c||null,news:O}});if(!Z)throw new Error("Failed to create session");const A=new Date().toISOString(),{error:oe}=await I.from("live_sessions").update({status:"live",started_at:A}).eq("id",Z.id);if(oe)throw oe;o(Z.id,{status:"live",started_at:A}),await l({job_type:ql.CONDUCT_LIVE_SESSION,persona_id:F,payload_json:{live_session_id:Z.id,live_mode:"nonstop_news",subtitles_enabled:v,watermark_text:c||void 0}}),p()}catch(O){console.error("nonstop_news launch failed",O),z(O.message||e("createError"))}finally{C(!1)}}},Y=async O=>{E(O);try{await i(O,"ended")}finally{E(null)}},re=O=>{const Z=O.metadata_json||{},A=Z.news||{};m(oe=>({...oe,personaId:O.persona_id||oe.personaId,language:Z.language||oe.language,mode:A.mode||oe.mode,chatReplyFirst:typeof Z.chat_reply_first=="boolean"?Z.chat_reply_first:oe.chatReplyFirst,subtitles:typeof Z.subtitles_enabled=="boolean"?Z.subtitles_enabled:oe.subtitles,title:O.title||oe.title,description:O.description||oe.description,q:A.q||"",country:A.country||"",category:A.category||"",domains:Array.isArray(A.domains)?A.domains.join(", "):"",surpriseCategories:Array.isArray(A.surprise_categories)?A.surprise_categories:dj})),typeof Z.watermark_text=="string"&&d(Z.watermark_text),window.scrollTo({top:0,behavior:"smooth"})};return n.jsxs("div",{className:"space-y-8",children:[n.jsxs("div",{className:"space-y-2",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx(Qc,{className:"h-6 w-6 text-primary"}),n.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:e("pageTitle")})]}),n.jsx("p",{className:"text-muted-foreground max-w-3xl",children:e("pageSubtitle")})]}),n.jsxs(Do,{className:"p-6 space-y-5",children:[n.jsx("div",{className:"grid gap-4 md:grid-cols-2",children:n.jsx(Pe,{label:e("personaLabel"),children:n.jsxs(ut,{value:f,onValueChange:O=>m(Z=>({...Z,personaId:O})),children:[n.jsx(ct,{children:n.jsx(ht,{placeholder:e("personaPlaceholder")})}),n.jsx(dt,{children:t.map(O=>n.jsx(ce,{value:O.id,children:O.name},O.id))})]})})}),n.jsx(Pe,{label:e("languageLabel"),children:n.jsxs(ut,{value:g,onValueChange:O=>m(Z=>({...Z,language:O})),children:[n.jsx(ct,{children:n.jsx(ht,{})}),n.jsxs(dt,{children:[n.jsx(ce,{value:"ru",children:"Русский"}),n.jsx(ce,{value:"en",children:"English"}),n.jsx(ce,{value:"es",children:"Español"}),n.jsx(ce,{value:"de",children:"Deutsch"}),n.jsx(ce,{value:"fr",children:"Français"}),n.jsx(ce,{value:"it",children:"Italiano"}),n.jsx(ce,{value:"pt",children:"Português"})]})]})}),n.jsx(Pe,{label:e("titleLabel"),children:n.jsx(gt,{value:y,onChange:O=>m(Z=>({...Z,title:O.target.value})),placeholder:e("titlePlaceholder")})}),n.jsx(Pe,{label:e("watermarkLabel"),children:n.jsx(gt,{value:c,onChange:O=>d(O.target.value),placeholder:e("watermarkPlaceholder")})}),n.jsx("div",{className:"md:col-span-2",children:n.jsx(Pe,{label:e("descriptionLabel"),children:n.jsx(Fs,{value:w,onChange:O=>m(Z=>({...Z,description:O.target.value})),placeholder:e("descriptionPlaceholder"),rows:2})})}),n.jsxs("div",{className:"flex flex-wrap items-center gap-6",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Ut,{checked:b,onCheckedChange:O=>m(Z=>({...Z,chatReplyFirst:O}))}),n.jsx(Jt,{className:"text-sm",children:e("chatReplyLabel")})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Ut,{checked:v,onCheckedChange:O=>m(Z=>({...Z,subtitles:O}))}),n.jsx(Jt,{className:"text-sm",children:e("subtitlesLabel")})]})]})]}),n.jsxs(Do,{className:"p-6 space-y-5",children:[n.jsxs("div",{children:[n.jsx("h2",{className:"text-lg font-semibold",children:e("sourceTitle")}),n.jsx("p",{className:"text-sm text-muted-foreground",children:e("sourceSubtitle")})]}),n.jsx(Pe,{label:e("modeLabel"),children:n.jsxs(ut,{value:x,onValueChange:O=>m(Z=>({...Z,mode:O})),children:[n.jsx(ct,{children:n.jsx(ht,{})}),n.jsxs(dt,{children:[n.jsx(ce,{value:"surprise",children:e("modeSurprise")}),n.jsx(ce,{value:"query",children:e("modeQuery")}),n.jsx(ce,{value:"region",children:e("modeRegion")}),n.jsx(ce,{value:"domains",children:e("modeDomains")})]})]})}),x==="surprise"&&n.jsxs("div",{className:"space-y-3",children:[n.jsx("p",{className:"text-xs text-muted-foreground",children:e("modeSurpriseHint")}),n.jsx(Jt,{className:"text-sm",children:e("surpriseCategoriesLabel")}),n.jsx("div",{className:"flex flex-wrap gap-3",children:cj.map(O=>n.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[n.jsx(Wl,{checked:S.includes(O),onCheckedChange:Z=>m(A=>({...A,surpriseCategories:Z?Array.from(new Set([...A.surpriseCategories||[],O])):(A.surpriseCategories||[]).filter(oe=>oe!==O)}))}),e(`categories.${O}`)]},O))})]}),x==="query"&&n.jsx(Pe,{label:e("queryLabel"),children:n.jsx(gt,{value:j,onChange:O=>m(Z=>({...Z,q:O.target.value})),placeholder:e("queryPlaceholder")})}),x==="region"&&n.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[n.jsx(Pe,{label:e("countryLabel"),children:n.jsxs(ut,{value:_||"any",onValueChange:O=>m(Z=>({...Z,country:O==="any"?"":O})),children:[n.jsx(ct,{children:n.jsx(ht,{})}),n.jsxs(dt,{children:[n.jsx(ce,{value:"any",children:e("anyCountry")}),w1e.map(O=>n.jsx(ce,{value:O,children:O.toUpperCase()},O))]})]})}),n.jsx(Pe,{label:e("categoryLabel"),children:n.jsxs(ut,{value:N||"any",onValueChange:O=>m(Z=>({...Z,category:O==="any"?"":O})),children:[n.jsx(ct,{children:n.jsx(ht,{})}),n.jsxs(dt,{children:[n.jsx(ce,{value:"any",children:e("anyCategory")}),cj.map(O=>n.jsx(ce,{value:O,children:e(`categories.${O}`)},O))]})]})})]}),x==="domains"&&n.jsx(Pe,{label:e("domainsLabel"),children:n.jsx(gt,{value:k,onChange:O=>m(Z=>({...Z,domains:O.target.value})),placeholder:e("domainsPlaceholder")})}),H&&n.jsx("p",{className:"text-sm text-destructive",children:H}),n.jsx("div",{className:"flex justify-end",children:n.jsxs(L,{onClick:J,disabled:T||!F,size:"lg",children:[n.jsx(en,{className:"h-4 w-4 mr-2"}),e(T?"starting":"startBtn")]})})]}),n.jsxs("section",{className:"space-y-3",children:[n.jsx("h2",{className:"text-lg font-semibold",children:e("activeTitle")}),r?n.jsx(Ln,{}):V.length===0?n.jsx(Er,{icon:Qc,title:e("emptyActive"),description:e("emptyActiveDesc")}):n.jsx("div",{className:"grid gap-3",children:V.map(O=>n.jsxs(Do,{className:"p-4 flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("div",{className:"font-medium",children:O.title}),n.jsxs("div",{className:"text-xs text-muted-foreground",children:[e("statusLabel"),": ",O.status]})]}),n.jsxs(L,{variant:"outline",size:"sm",onClick:()=>Y(O.id),disabled:B===O.id,children:[n.jsx(du,{className:"h-3 w-3 mr-1"}),B===O.id?e("stopping"):e("stopBtn")]})]},O.id))})]}),n.jsxs("section",{className:"space-y-3",children:[n.jsx("h2",{className:"text-lg font-semibold",children:e("historyTitle")}),te.length===0?n.jsx(Er,{icon:Qc,title:e("emptyHistory"),description:e("emptyHistoryDesc")}):n.jsx("div",{className:"grid gap-2",children:te.slice(0,20).map(O=>n.jsxs(Do,{className:"p-3 flex items-center justify-between text-sm",children:[n.jsxs("div",{children:[n.jsx("div",{className:"font-medium",children:O.title}),n.jsxs("div",{className:"text-xs text-muted-foreground",children:[O.status," · ",O.started_at?new Date(O.started_at).toLocaleStr
1050ing():"—"]})]}),n.jsxs(L,{variant:"ghost",size:"sm",onClick:()=>re(O),children:[n.jsx(uS,{className:"h-3 w-3 mr-1"}),e("repeatBtn")]})]},O.id))})]}),n.jsxs(Do,{className:"p-6 bg-muted/30 space-y-2",children:[n.jsx("h3",{className:"font-semibold",children:e("howItWorksTitle")}),n.jsx("ul",{className:"text-sm text-muted-foreground space-y-1 list-disc pl-5",children:e("howItWorks",{returnObjects:!0}).map((O,Z)=>n.jsx("li",{children:O},Z))})]})]})};function _1e(){return n.jsx(Al,{to:"/app/live?mode=sim",replace:!0})}const k1e=h.lazy(()=>tn(()=>import("./Index-q8qT46dB.js"),__vite__mapDeps([0,1,2,3,4,5]))),N1e=h.lazy(()=>tn(()=>import("./Pricing-DMm2lYTW.js"),__vite__mapDeps([6,1,2,3,4,7,5]))),S1e=h.lazy(()=>tn(()=>import("./HowItWorks-_cuCEH65.js"),__vite__mapDeps([8,1,2,3,5]))),C1e=h.lazy(()=>tn(()=>import("./UseCases-RYWmpFrm.js"),__vite__mapDeps([9,1,2,3,5]))),T1e=h.lazy(()=>tn(()=>import("./Login-DSKS4TJz.js"),__vite__mapDeps([10,1,2,5]))),P1e=h.lazy(()=>tn(()=>import("./ResetPassword-BVFrw4My.js"),__vite__mapDeps([11,1,2,5]))),E1e=h.lazy(()=>tn(()=>import("./PrivacyPolicy-B4miPBfo.js"),__vite__mapDeps([12,1,2,13,3,5]))),A1e=h.lazy(()=>tn(()=>import("./Terms-Cmmy9S02.js"),__vite__mapDeps([14,1,2,13,3,5]))),R1e=h.lazy(()=>tn(()=>import("./Offer-D2FrWIDu.js"),__vite__mapDeps([15,1,2,13,3,7,5]))),$1e=h.lazy(()=>tn(()=>import("./CookiePolicy-CrZOIHG-.js"),__vite__mapDeps([16,1,2,13,3,5]))),L1e=h.lazy(()=>tn(()=>import("./DocsWorkerApi-0QAhqdjZ.js"),__vite__mapDeps([17,1,2]))),I1e=h.lazy(()=>tn(()=>import("./DocsPublicApi-CsIq8G0q.js"),__vite__mapDeps([18,1,2,5]))),O1e=h.lazy(()=>tn(()=>import("./ConsultationJoin-Dbs2vVKM.js"),__vite__mapDeps([19,1,2,5]))),D1e=h.lazy(()=>tn(()=>import("./NotFound-Bb4y9ocl.js"),__vite__mapDeps([20,1,2,5]))),M1e=()=>n.jsx("div",{className:"flex items-center justify-center min-h-[60vh]",children:n.jsx(xe,{className:"w-8 h-8 animate-spin text-primary"})}),z1e=new UR({defaultOptions:{queries:{staleTime:3e4,gcTime:5*6e4,retry:2,retryDelay:e=>Math.min(1e3*2**e,1e4),refetchOnWindowFocus:!1},mutations:{retry:1}}}),F1e=()=>n.jsx(HR,{client:z1e,children:n.jsx($N,{children:n.jsxs(nL,{children:[n.jsx(uL,{}),n.jsx(LM,{}),n.jsx(QD,{children:n.jsx(JD,{children:n.jsx(ZD,{children:n.jsxs(XD,{children:[n.jsx(UM,{fallbackRoute:"/",children:n.jsx(h.Suspense,{fallback:n.jsx(M1e,{}),children:n.jsxs(Y$,{children:[n.jsx(vt,{path:"/",element:n.jsx(k1e,{})}),n.jsx(vt,{path:"/pricing",element:n.jsx(N1e,{})}),n.jsx(vt,{path:"/how-it-works",element:n.jsx(S1e,{})}),n.jsx(vt,{path:"/use-cases",element:n.jsx(C1e,{})}),n.jsx(vt,{path:"/login",element:n.jsx(T1e,{})}),n.jsx(vt,{path:"/reset-password",element:n.jsx(P1e,{})}),n.jsx(vt,{path:"/privacy",element:n.jsx(E1e,{})}),n.jsx(vt,{path:"/terms",element:n.jsx(A1e,{})}),n.jsx(vt,{path:"/offer",element:n.jsx(R1e,{})}),n.jsx(vt,{path:"/cookies",element:n.jsx($1e,{})}),n.jsx(vt,{path:"/docs/worker-api",element:n.jsx(L1e,{})}),n.jsx(vt,{path:"/docs/public-api",element:n.jsx(I1e,{})}),n.jsx(vt,{path:"/consultation/:offerId",element:n.jsx(O1e,{})}),n.jsx(vt,{path:"/app/onboarding",element:n.jsx(z4,{children:n.jsx(d6,{})})}),n.jsxs(vt,{path:"/app",element:n.jsx($w,{children:n.jsx(u1,{})}),children:[n.jsx(vt,{index:!0,element:n.jsx(n8,{})}),n.jsx(vt,{path:"persona",element:n.jsx(K8,{})}),n.jsx(vt,{path:"content",element:n.jsx(Or,{children:n.jsx(jB,{})})}),n.jsx(vt,{path:"live",element:n.jsx(Or,{children:n.jsx(Cbe,{})})}),n.jsx(vt,{path:"simulator",element:n.jsx(Or,{children:n.jsx(_1e,{})})}),n.jsx(vt,{path:"monetization",element:n.jsx(Ebe,{})}),n.jsx(vt,{path:"integrations",element:n.jsx(Rbe,{})}),n.jsx(vt,{path:"ads",element:n.jsx(n1e,{})}),n.jsx(vt,{path:"analytics",element:n.jsx(Lbe,{})}),n.jsx(vt,{path:"settings",element:n.jsx(Obe,{})}),n.jsx(vt,{path:"billing",element:n.jsx(Ube,{})}),n.jsx(vt,{path:"consultations",element:n.jsx(Or,{children:n.jsx(awe,{})})}),n.jsx(vt,{path:"webinars",element:n.jsx(Or,{children:n.jsx(hwe,{})})}),n.jsx(vt,{path:"trends",element:n.jsx(Or,{children:n.jsx(f1e,{})})}),n.jsx(vt,{path:"news",element:n.jsx(Or,{children:n.jsx(j1e,{})})}),n.jsx(vt,{path:"topic-discovery",element:n.jsx(Or,{children:n.jsx(qwe,{})})}),n.jsx(vt,{path:"topic-discovery/:queryId",element:n.jsx(Or,{children:n.jsx(e1e,{})})})]}),n.jsxs(vt,{path:"/admin",element:n.jsx($w,{children:n.jsx(u1,{})}),children:[n.jsx(vt,{index:!0,element:n.jsx(Iwe,{})}),n.jsx(vt,{path:"operations",element:n.jsx(gwe,{})}),n.jsx(vt,{path:"prompts",element:n.jsx(Mwe,{})})]}),n.jsx(vt,{path:"*",element:n.jsx(D1e,{})})]})})}),n.jsx(RM,{})]})})})})]})})});FM();jk(document.getElementById("root")).render(n.jsx(F1e,{}));export{ce as $,Tr as A,L as B,wt as C,en as D,zy as E,tr as F,Cy as G,co as H,gt as I,dy as J,Fy as K,zt as L,j4 as M,Al as N,IN as O,Ja as P,ut as Q,St as R,pm as S,LN as T,Xs as U,Ns as V,ct as W,Qn as X,Ls as Y,v4 as Z,dt as _,Zs as a,fy as a0,cu as a1,MB as a2,zB as a3,PT as a4,R$ as a5,cc as a6,Sp as a7,XF as a8,rr as a9,fe as b,eo as c,st as d,fi as e,xe as f,lS as g,Ad as h,xs as i,ps as j,le as k,Is as l,bt as m,yp as n,qe as o,sn as p,Ee as q,Zn as r,I as s,cs as t,Oe as u,d1 as v,_e as w,Za as x,ls as y,yy as z};

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.