1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/UpgradePage-CZ8BaBrH.js","assets/vendor-react-E2ZKvWZZ.js","assets/EinstellungenPage-CvIYgqKZ.js","assets/ReviewDashboard_v2-CeH0FaaE.js","assets/constants-CRIPzz9l.js","assets/demoData-CA6jZwID.js","assets/vendor-recharts-C184l3rR.js","assets/feedbackApi-CzC6scnT.js","assets/InsightsPage-DHL-O1fO.js","assets/MonitoringPage-D9SPIw0E.js","assets/DemoShell-kZD-1Lh6.js"])))=>i.map(i=>d[i]); 2import{a as Ki,b as Ji,g as Gi,r as h,N as ee,u as Se,d as $n,L as nn,R as Dn,e as pr,f as K,h as Zs,i as Zi,j as qr,B as Yi}from"./vendor-react-E2ZKvWZZ.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))s(i);new MutationObserver(i=>{for(const o of i)if(o.type==="childList")for(const a of o.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&s(a)}).observe(document,{childList:!0,subtree:!0});function n(i){const o={};return i.integrity&&(o.integrity=i.integrity),i.referrerPolicy&&(o.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?o.credentials="include":i.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function s(i){if(i.ep)return;i.ep=!0;const o=n(i);fetch(i.href,o)}})();var sn={exports:{}},rr={};/** 3 * @license React 4 * react-jsx-runtime.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 */var es;function Xi(){if(es)return rr;es=1;var r=Ki(),e=Symbol.for("react.element"),n=Symbol.for("react.fragment"),s=Object.prototype.hasOwnProperty,i=r.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,o={key:!0,ref:!0,__self:!0,__source:!0};function a(l,c,d){var u,f={},p=null,x=null;d!==void 0&&(p=""+d),c.key!==void 0&&(p=""+c.key),c.ref!==void 0&&(x=c.ref);for(u in c)s.call(c,u)&&!o.hasOwnProperty(u)&&(f[u]=c[u]);if(l&&l.defaultProps)for(u in c=l.defaultProps,c)f[u]===void 0&&(f[u]=c[u]);return{$$typeof:e,type:l,key:p,ref:x,props:f,_owner:i.current}}return rr.Fragment=n,rr.jsx=a,rr.jsxs=a,rr}var ts;function Qi(){return ts||(ts=1,sn.exports=Xi()),sn.exports}var t=Qi(),Sr={},rs;function eo(){if(rs)return Sr;rs=1;var r=Ji();return Sr.createRoot=r.createRoot,Sr.hydrateRoot=r.hydrateRoot,Sr}var to=eo();const ro=Gi(to),Ft=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__,et=globalThis,cr="10.46.0";function Ys(){return Un(et),et}function Un(r){const e=r.__SENTRY__=r.__SENTRY__||{};return e.version=e.version||cr,e[cr]=e[cr]||{}}function Mn(r,e,n=et){const s=n.__SENTRY__=n.__SENTRY__||{},i=s[cr]=s[cr]||{};return i[r]||(i[r]=e())}const no="Sentry Logger ",ns={};function so(r){if(!("console"in et))return r();const e=et.console,n={},s=Object.keys(ns);s.forEach(i=>{const o=ns[i];n[i]=e[i],e[i]=o});try{return r()}finally{s.forEach(i=>{e[i]=n[i]})}}function io(){Nn().enabled=!0}function oo(){Nn().enabled=!1}function Xs(){return Nn().enabled}function ao(...r){Wn("log",...r)}function lo(...r){Wn("warn",...r)}function co(...r){Wn("error",...r)}function Wn(r,...e){Ft&&Xs()&&so(()=>{et.console[r](`${no}[${r}]:`,...e)})}function Nn(){return Ft?Mn("loggerSettings",()=>({enabled:!1})):{enabled:!1}}const $r={enable:io,disable:oo,isEnabled:Xs,log:ao,warn:lo,error:co},uo=Object.prototype.toString;function ho(r,e){return uo.call(r)===`[object ${e}]`}function fo(r){return ho(r,"Object")}function po(r){return!!(r!=null&&r.then&&typeof r.then=="function")}function go(r,e,n){try{Object.defineProperty(r,e,{value:n,writable:!0,configurable:!0})}catch{Ft&&$r.log(`Failed to add non-enumerable property "${e}" to object`,r)}}let Ct;function Kr(r){if(Ct!==void 0)return Ct?Ct(r):r();const e=Symbol.for("__SENTRY_SAFE_RANDOM_ID_WRAPPER__"),n=et;return e in n&&typeof n[e]=="function"?(Ct=n[e],Ct(r)):(Ct=null,r())}function jn(){return Kr(()=>Math.random())}function mo(){return Kr(()=>Date.now())}function yo(r,e=0){return typeof r!="string"||e===0||r.length<=e?r:`${r.slice(0,e)}...`}function xo(){const r=et;return r.crypto||r.msCrypto}let on;function bo(){return jn()*16}function dr(r=xo()){try{if(r!=null&&r.randomUUID)return Kr(()=>r.randomUUID()).replace(/-/g,"")}catch{}return on||(on="10000000100040008000"+1e11),on.replace(/[018]/g,e=>(e^(bo()&15)>>e/4).toString(16))}const Qs=1e3;function ei(){return mo()/Qs}function vo(){const{performance:r}=et;if(!(r!=null&&r.now)||!r.timeOrigin)return ei;const e=r.timeOrigin;return()=>(e+Kr(()=>r.now()))/Qs}let ss;function wo(){return(ss??(ss=vo()))()}function _o(r,e={}){if(e.user&&(!r.ipAddress&&e.user.ip_address&&(r.ipAddress=e.user.ip_address),!r.did&&!e.did&&(r.did=e.user.id||e.user.email||e.user.username)),r.timestamp=e.timestamp||wo(),e.abnormal_mechanism&&(r.abnormal_mechanism=e.abnormal_mechanism),e.ignoreDuration&&(r.ignoreDuration=e.ignoreDuration),e.sid&&(r.sid=e.sid.length===32?e.sid:dr()),e.init!==void 0&&(r.init=e.init),!r.did&&e.did&&(r.did=`${e.did}`),typeof e.started=="number"&&(r.started=e.started),r.ignoreDuration)r.duration=void 0;else if(typeof e.duration=="number")r.duration=e.duration;else{const n=r.timestamp-r.started;r.duration=n>=0?n:0}e.release&&(r.release=e.release),e.environment&&(r.environment=e.environment),!r.ipAddress&&e.ipAddress&&(r.ipAddress=e.ipAddress),!r.userAgent&&e.userAgent&&(r.userAgent=e.userAgent),t
vendor: 5,903 bytes, line 10
10ypeof e.errors=="number"&&(r.errors=e.errors),e.status&&(r.status=e.status)}function ti(r,e,n=2){if(!e||typeof e!="object"||n<=0)return e;if(r&&Object.keys(e).length===0)return r;const s={...r};for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(s[i]=ti(s[i],e[i],n-1));return s}function is(){return dr()}const Sn="_sentrySpan";function os(r,e){e?go(r,Sn,e):delete r[Sn]}function as(r){return r[Sn]}const jo=100;class dt{constructor(){this._notifyingListeners=!1,this._scopeListeners=[],this._eventProcessors=[],this._breadcrumbs=[],this._attachments=[],this._user={},this._tags={},this._attributes={},this._extra={},this._contexts={},this._sdkProcessingMetadata={},this._propagationContext={traceId:is(),sampleRand:jn()}}clone(){const e=new dt;return e._breadcrumbs=[...this._breadcrumbs],e._tags={...this._tags},e._attributes={...this._attributes},e._extra={...this._extra},e._contexts={...this._contexts},this._contexts.flags&&(e._contexts.flags={values:[...this._contexts.flags.values]}),e._user=this._user,e._level=this._level,e._session=this._session,e._transactionName=this._transactionName,e._fingerprint=this._fingerprint,e._eventProcessors=[...this._eventProcessors],e._attachments=[...this._attachments],e._sdkProcessingMetadata={...this._sdkProcessingMetadata},e._propagationContext={...this._propagationContext},e._client=this._client,e._lastEventId=this._lastEventId,e._conversationId=this._conversationId,os(e,as(this)),e}setClient(e){this._client=e}setLastEventId(e){this._lastEventId=e}getClient(){return this._client}lastEventId(){return this._lastEventId}addScopeListener(e){this._scopeListeners.push(e)}addEventProcessor(e){return this._eventProcessors.push(e),this}setUser(e){return this._user=e||{email:void 0,id:void 0,ip_address:void 0,username:void 0},this._session&&_o(this._session,{user:e}),this._notifyScopeListeners(),this}getUser(){return this._user}setConversationId(e){return this._conversationId=e||void 0,this._notifyScopeListeners(),this}setTags(e){return this._tags={...this._tags,...e},this._notifyScopeListeners(),this}setTag(e,n){return this.setTags({[e]:n})}setAttributes(e){return this._attributes={...this._attributes,...e},this._notifyScopeListeners(),this}setAttribute(e,n){return this.setAttributes({[e]:n})}removeAttribute(e){return e in this._attributes&&(delete this._attributes[e],this._notifyScopeListeners()),this}setExtras(e){return this._extra={...this._extra,...e},this._notifyScopeListeners(),this}setExtra(e,n){return this._extra={...this._extra,[e]:n},this._notifyScopeListeners(),this}setFingerprint(e){return this._fingerprint=e,this._notifyScopeListeners(),this}setLevel(e){return this._level=e,this._notifyScopeListeners(),this}setTransactionName(e){return this._transactionName=e,this._notifyScopeListeners(),this}setContext(e,n){return n===null?delete this._contexts[e]:this._contexts[e]=n,this._notifyScopeListeners(),this}setSession(e){return e?this._session=e:delete this._session,this._notifyScopeListeners(),this}getSession(){return this._session}update(e){if(!e)return this;const n=typeof e=="function"?e(this):e,s=n instanceof dt?n.getScopeData():fo(n)?e:void 0,{tags:i,attributes:o,extra:a,user:l,contexts:c,level:d,fingerprint:u=[],propagationContext:f,conversationId:p}=s||{};return this._tags={...this._tags,...i},this._attributes={...this._attributes,...o},this._extra={...this._extra,...a},this._contexts={...this._contexts,...c},l&&Object.keys(l).length&&(this._user=l),d&&(this._level=d),u.length&&(this._fingerprint=u),f&&(this._propagationContext=f),p&&(this._conversationId=p),this}clear(){return this._breadcrumbs=[],this._tags={},this._attributes={},this._extra={},this._user={},this._contexts={},this._level=void 0,this._transactionName=void 0,this._fingerprint=void 0,this._session=void 0,this._conversationId=void 0,os(this,void 0),this._attachments=[],this.setPropagationContext({traceId:is(),sampleRand:jn()}),this._notifyScopeListeners(),this}addBreadcrumb(e,n){var o;const s=typeof n=="number"?n:jo;if(s<=0)return this;const i={timestamp:ei(),...e,message:e.message?yo(e.message,2048):e.message};return this._breadcrumbs.push(i),this._breadcrumbs.length>s&&(this._breadcrumbs=this._breadcrumbs.slice(-s),(o=this._client)==null||o.recordDroppedEvent("buffer_overflow","log_item")),this._notifyScopeListeners(),this}getLastBreadcrumb(){return this._breadcrumbs[this._breadcrumbs.length-1]}clearBreadcrumbs(){return this._breadcrumbs=[],this._notifyScopeListeners(),this}addAttachment(e){return this._attachments.push(e),this}clearAttachments(){return this._attachments=[],this}getScopeData(){return{breadcrumbs:this._breadcrumbs,attachments:this._attachments,contexts:this._contexts,tags:this._tags,attributes:this._attributes,extra:this._extra,user:this._user,level:this._level,fingerprint:this._fingerprint||[],eventProcessors:this._eventProcessors,propagationContext:this._propagationContext,sdkProcessingMetadata:this._sdkProcessingMetadata,transactionName:this._transactionName,span:as(this),conversationId:this._conversationId}}setSDKProcessingMetadata(e){return this._sdkProcessingMetadata=ti(this._sdkProcessingMetadata,e,2),this}setPropagationContext(e){return this._propagationContext=e,this}getPropagationContext(){return this._propagationContext}captureException(e,n){const s=(n==null?void 0:n.event_id)||dr();if(!this._client)return Ft&&$r.warn("No client configured on scope - will not capture exception!"),s;const i=new Error("Sentry syntheticException");return this._client.captureException(e,{originalException:e,syntheticException:i,...n,event_id:s},this),s}captureMessage(e,n,s){const i=(s==null?void 0:s.event_id)||dr();if(!this._client)return Ft&&$r.warn("No client configured on scope - will not capture message!"),i;const o=(s==null?void 0:s.syntheticException)??new Error(e);return this._client.captureMessage(e,n,{originalException:e,syntheticException:o,...s,event_id:i},this),i}
10captureEvent(e,n){const s=e.event_id||(n==null?void 0:n.event_id)||dr();return this._client?(this._client.captureEvent(e,{...n,event_id:s},this),s):(Ft&&$r.warn("No client configured on scope - will not capture event!"),s)}_notifyScopeListeners(){this._notifyingListeners||(this._notifyingListeners=!0,this._scopeListeners.forEach(e=>{e(this)}),this._notifyingListeners=!1)}}function So(){return Mn("defaultCurrentScope",()=>new dt)}function ko(){return Mn("defaultIsolationScope",()=>new dt)}const ls=r=>r instanceof Promise&&!r[ri],ri=Symbol("chained PromiseLike"),Eo=(r,e,n)=>{const s=r.then(i=>(e(i),i),i=>{throw n(i),i});return ls(s)&&ls(r)?s:Co(r,s)},Co=(r,e)=>{let n=!1;for(const s in r){if(s in e)continue;n=!0;const i=r[s];typeof i=="function"?Object.defineProperty(e,s,{value:(...o)=>i.apply(r,o),enumerable:!0,configurable:!0,writable:!0}):e[s]=i}return n&&Object.assign(e,{[ri]:!0}),e};class Ao{constructor(e,n){let s;e?s=e:s=new dt;let i;n?i=n:i=new dt,this._stack=[{scope:s}],this._isolationScope=i}withScope(e){const n=this._pushScope();let s;try{s=e(n)}catch(i){throw this._popScope(),i}return po(s)?Eo(s,()=>this._popScope(),()=>this._popScope()):(this._popScope(),s)}getClient(){return this.getStackTop().client}getScope(){return this.getStackTop().scope}getIsolationScope(){return this._isolationScope}getStackTop(){return this._stack[this._stack.length-1]}_pushScope(){const e=this.getScope().clone();return this._stack.push({client:this.getClient(),scope:e}),e}_popScope(){return this._stack.length<=1?!1:!!this._stack.pop()}}function Vt(){const r=Ys(),e=Un(r);return e.stack=e.stack||new Ao(So(),ko())}function Ro(r){return Vt().withScope(r)}function To(r,e){const n=Vt();return n.withScope(()=>(n.getStackTop().scope=r,e(r)))}function cs(r){return Vt().withScope(()=>r(Vt().getIsolationScope()))}function Io(){return{withIsolationScope:cs,withScope:Ro,withSetScope:To,withSetIsolationScope:(r,e)=>cs(e),getCurrentScope:()=>Vt().getScope(),getIsolationScope:()=>Vt().getIsolationScope()}}function Po(r){const e=Un(r);return e.acs?e.acs:Io()}function Oo(){const r=Ys();return Po(r).getCurrentScope()}function Lo(r){if(r)return zo(r)?{captureContext:r}:$o(r)?{captureContext:r}:r}function zo(r){return r instanceof dt||typeof r=="function"}const Bo=["user","level","extra","contexts","tags","fingerprint","propagationContext"];function $o(r){return Object.keys(r).some(e=>Bo.includes(e))}function Do(r,e){return Oo().captureException(r,Lo(e))}function Jr(r,e){var n={};for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&e.indexOf(s)<0&&(n[s]=r[s]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,s=Object.getOwnPropertySymbols(r);i<s.length;i++)e.indexOf(s[i])<0&&Object.prototype.propertyIsEnumerable.call(r,s[i])&&(n[s[i]]=r[s[i]]);return n}function Uo(r,e,n,s){function i(o){return o instanceof n?o:new n(function(a){a(o)})}return new(n||(n=Promise))(function(o,a){function l(u){try{d(s.next(u))}catch(f){a(f)}}function c(u){try{d(s.throw(u))}catch(f){a(f)}}function d(u){u.done?o(u.value):i(u.value).then(l,c)}d((s=s.apply(r,e||[])).next())})}const Mo=r=>r?(...e)=>r(...e):(...e)=>fetch(...e);class Fn extends Error{constructor(e,n="FunctionsError",s){super(e),this.name=n,this.context=s}}class Wo extends Fn{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class ds extends Fn{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class us extends Fn{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var kn;(function(r){r.Any="any",r.ApNortheast1="ap-northeast-1",r.ApNortheast2="ap-northeast-2",r.ApSouth1="ap-south-1",r.ApSoutheast1="ap-southeast-1",r.ApSoutheast2="ap-southeast-2",r.CaCentral1="ca-central-1",r.EuCentral1="eu-central-1",r.EuWest1="eu-west-1",r.EuWest2="eu-west-2",r.EuWest3="eu-west-3",r.SaEast1="sa-east-1",r.UsEast1="us-east-1",r.UsWest1="us-west-1",r.UsWest2="us-west-2"})(kn||(kn={}));class No{constructor(e,{headers:n={},customFetch:s,region:i=kn.Any}={}){this.url=e,this.headers=n,this.region=i,this.fetch=Mo(s)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return Uo(this,arguments,void 0,function*(n,s={}){var i;let o,a;try{const{headers:l,method:c,body:d,signal:u,timeout:f}=s;let p={},{region:x}=s;x||(x=this.region);const g=new URL(`${this.url}/${n}`);x&&x!=="any"&&(p["x-region"]=x,g.searchParams.set("forceFunctionRegion",x));let v;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",v=d):typeof d=="str
10ing"?(p["Content-Type"]="text/plain",v=d):typeof FormData<"u"&&d instanceof FormData?v=d:(p["Content-Type"]="application/json",v=JSON.stringify(d)):d&&typeof d!="string"&&!(typeof Blob<"u"&&d instanceof Blob)&&!(d instanceof ArrayBuffer)&&!(typeof FormData<"u"&&d instanceof FormData)?v=JSON.stringify(d):v=d;let m=u;f&&(a=new AbortController,o=setTimeout(()=>a.abort(),f),u?(m=a.signal,u.addEventListener("abort",()=>a.abort())):m=a.signal);const w=yield this.fetch(g.toString(),{method:c||"POST",headers:Object.assign(Object.assign(Object.assign({},p),this.headers),l),body:v,signal:m}).catch(k=>{throw new Wo(k)}),_=w.headers.get("x-relay-error");if(_&&_==="true")throw new ds(w);if(!w.ok)throw new us(w);let b=((i=w.headers.get("Content-Type"))!==null&&i!==void 0?i:"text/plain").split(";")[0].trim(),y;return b==="application/json"?y=yield w.json():b==="application/octet-stream"||b==="application/pdf"?y=yield w.blob():b==="text/event-stream"?y=w:b==="multipart/form-data"?y=yield w.formData():y=yield w.text(),{data:y,error:null,response:w}}catch(l){return{data:null,error:l,response:l instanceof us||l instanceof ds?l.context:void 0}}finally{o&&clearTimeout(o)}})}}var Fo=class extends Error{constructor(r){super(r.message),this.name="PostgrestError",this.details=r.details,this.hint=r.hint,this.co
10de=r.code}},Ho=class{constructor(r){var e,n,s;this.shouldThrowOnError=!1,this.method=r.method,this.url=r.url,this.headers=new Headers(r.headers),this.schema=r.schema,this.body=r.body,this.shouldThrowOnError=(e=r.shouldThrowOnError)!==null&&e!==void 0?e:!1,this.signal=r.signal,this.isMaybeSingle=(n=r.isMaybeSingle)!==null&&n!==void 0?n:!1,this.urlLengthLimit=(s=r.urlLengthLimit)!==null&&s!==void 0?s:8e3,r.fetch?this.fetch=r.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(r,e){return this.headers=new Headers(this.headers),this.headers.set(r,e),this}then(r,e){var n=this;this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),this.method!=="GET"&&this.method!=="HEAD"&&this.headers.set("Content-Type","application/json");const s=this.fetch;let i=s(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async o=>{let a=null,l=null,c=null,d=o.status,u=o.statusText;if(o.ok){var f,p;if(n.method!=="HEAD"){var x;const w=await o.text();w===""||(n.headers.get("Accept")==="text/csv"||n.headers.get("Accept")&&(!((x=n.headers.get("Accept"))===null||x===void 0)&&x.includes("application/vnd.pgrst.plan+text"))?l=w:l=JSON.parse(w))}const v=(f=n.headers.get("Prefer"))===null||f===void 0?void 0:f.match(/count=(exact|planned|estimated)/),m=(p=o.headers.get("content-range"))===null||p===void 0?void 0:p.split("/");v&&m&&m.length>1&&(c=parseInt(m[1])),n.isMaybeSingle&&n.method==="GET"&&Array.isArray(l)&&(l.length>1?(a={code:"PGRST116",details:`Results contain ${l.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},l=null,c=null,d=406,u="Not Acceptable"):l.length===1?l=l[0]:l=null)}else{var g;const v=await o.text();try{a=JSON.parse(v),Array.isArray(a)&&o.status===404&&(l=[],a=null,d=200,u="OK")}catch{o.status===404&&v===""?(d=204,u="No Content"):a={message:v}}if(a&&n.isMaybeSingle&&(!(a==null||(g=a.details)===null||g===void 0)&&g.includes("0 rows"))&&(a=null,d=200,u="OK"),a&&n.shouldThrowOnError)throw new Fo(a)}return{error:a,data:l,count:c,status:d,statusText:u}});return this.shouldThrowOnError||(i=i.catch(o=>{var a;let l="",c="",d="";const u=o==null?void 0:o.cause;if(u){var f,p,x,g;const w=(f=u==null?void 0:u.message)!==null&&f!==void 0?f:"",_=(p=u==null?void 0:u.code)!==null&&p!==void 0?p:"";l=`${(x=o==null?void 0:o.name)!==null&&x!==void 0?x:"FetchError"}: ${o==null?void 0:o.message}`,l+=` 11 12Caused by: ${(g=u==null?void 0:u.name)!==null&&g!==void 0?g:"Error"}: ${w}`,_&&(l+=` (${_})`),u!=null&&u.stack&&(l+=` 13${u.stack}`)}else{var v;l=(v=o==null?void 0:o.stack)!==null&&v!==void 0?v:""}const m=this.url.toString().length;return(o==null?void 0:o.name)==="AbortError"||(o==null?void 0:o.code)==="ABORT_ERR"?(d="",c="Request was aborted (timeout or manual cancellation)",m>this.urlLengthLimit&&(c+=`. Note: Your request URL is ${m} 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)",m>this.urlLengthLimit&&(c+=`. Your request URL is ${m} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`)),{error:{message:`${(a=o==null?void 0:o.name)!==null&&a!==void 0?a:"FetchError"}: ${o==null?void 0:o.message}`,details:l,hint:c,code:d},data:null,count:null,status:0,statusText:""}})),i.then(r,e)}returns(){return this}overrideTypes(){return this}},Vo=class extends Ho{select(r){let e=!1;const n=(r??"*").split("").map(s=>/\s/.test(s)&&!e?"":(s==='"'&&(e=!e),s)).join("");return this.url.searchParams.set("select",n),this.headers.append("Prefer","return=representation"),this}order(r,{ascending:e=!0,nullsFirst:n,foreignTable:s,referencedTable:i=s}={}){const o=i?`${i}.order`:"order",a=this.url.searchParams.get(o);return this.url.searchParams.set(o,`${a?`${a},`:""}${r}.${e?"asc":"desc"}${n===void 0?"":n?".nullsfirst":".nullslast"}`),this}limit(r,{foreignTable:e,referencedTable:n=e}={}){const s=typeof n>"u"?"limit":`${n}.limit`;return this.url.searchParams.set(s,`${r}`),this}range(r,e,{foreignTable:n,referencedTable:s=n}={}){const i=typeof s>"u"?"offset":`${s}.offset`,o=typeof s>"u"?"limit":`${s}.limit`;return this.url.searchParams.set(i,`${r}`),this.url.searchParams.set(o,`${e-r+1}`),this}abortSignal(r){return this.signal=r,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.method==="GET"?this.headers.set("Accept","application/json"):this.headers.set("Accept","application/vnd.pgrst.object+json"),this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}
13explain({analyze:r=!1,verbose:e=!1,settings:n=!1,buffers:s=!1,wal:i=!1,format:o="text"}={}){var a;const l=[r?"analyze":null,e?"verbose":null,n?"settings":null,s?"buffers":null,i?"wal":null].filter(Boolean).join("|"),c=(a=this.headers.get("Accept"))!==null&&a!==void 0?a:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${o}; for="${c}"; options=${l};`),o==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(r){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${r}`),this}};const hs=new RegExp("[,()]");var zt=class extends Vo{eq(r,e){return this.url.searchParams.append(r,`eq.${e}`),this}neq(r,e){return this.url.searchParams.append(r,`neq.${e}`),this}gt(r,e){return this.url.searchParams.append(r,`gt.${e}`),this}gte(r,e){return this.url.searchParams.append(r,`gte.${e}`),this}lt(r,e){return this.url.searchParams.append(r,`lt.${e}`),this}lte(r,e){return this.url.searchParams.append(r,`lte.${e}`),this}like(r,e){return this.url.searchParams.append(r,`like.${e}`),this}likeAllOf(r,e){return this.url.searchParams.append(r,`like(all).{${e.join(",")}}`),this}likeAnyOf(r,e){return this.url.searchParams.append(r,`like(any).{${e.join(",")}}`),this}ilike(r,e){return this.url.searchParams.append(r,`ilike.${e}`),this}ilikeAllOf(r,e){return this.url.searchParams.append(r,`ilike(all).{${e.join(",")}}`),this}ilikeAnyOf(r,e){return this.url.searchParams.append(r,`ilike(any).{${e.join(",")}}`),this}regexMatch(r,e){return this.url.searchParams.append(r,`match.${e}`),this}regexIMatch(r,e){return this.url.searchParams.append(r,`imatch.${e}`),this}is(r,e){return this.url.searchParams.append(r,`is.${e}`),this}isDistinct(r,e){return this.url.searchParams.append(r,`isdistinct.${e}`),this}in(r,e){const n=Array.from(new Set(e)).map(s=>typeof s=="string"&&hs.test(s)?`"${s}"`:`${s}`).join(",");return this.url.searchParams.append(r,`in.(${n})`),this}notIn(r,e){const n=Array.from(new Set(e)).map(s=>typeof s=="string"&&hs.test(s)?`"${s}"`:`${s}`).join(",");return this.url.searchParams.append(r,`not.in.(${n})`),this}contains(r,e){return typeof e=="string"?this.url.searchParams.append(r,`cs.${e}`):Array.isArray(e)?this.url.searchParams.append(r,`cs.{${e.join(",")}}`):this.url.searchParams.append(r,`cs.${JSON.stringify(e)}`),this}containedBy(r,e){return typeof e=="string"?this.url.searchParams.append(r,`cd.${e}`):Array.isArray(e)?this.url.searchParams.append(r,`cd.{${e.join(",")}}`):this.url.searchParams.append(r,`cd.${JSON.stringify(e)}`),this}rangeGt(r,e){return this.url.searchParams.append(r,`sr.${e}`),this}rangeGte(r,e){return this.url.searchParams.append(r,`nxl.${e}`),this}rangeLt(r,e){return this.url.searchParams.append(r,`sl.${e}`),this}rangeLte(r,e){return this.url.searchParams.append(r,`nxr.${e}`),this}rangeAdjacent(r,e){return this.url.searchParams.append(r,`adj.${e}`),this}overlaps(r,e){return typeof e=="string"?this.url.searchParams.append(r,`ov.${e}`):this.url.searchParams.append(r,`ov.{${e.join(",")}}`),this}textSearch(r,e,{config:n,type:s}={}){let i="";s==="plain"?i="pl":s==="phrase"?i="ph":s==="websearch"&&(i="w");const o=n===void 0?"":`(${n})`;return this.url.searchParams.append(r,`${i}fts${o}.${e}`),this}match(r){return Object.entries(r).forEach(([e,n])=>{this.url.searchParams.append(e,`eq.${n}`)}),this}not(r,e,n){return this.url.searchParams.append(r,`not.${e}.${n}`),this}or(r,{foreignTable:e,referencedTable:n=e}={}){const s=n?`${n}.or`:"or";return this.url.searchParams.append(s,`(${r})`),this}filter(r,e,n){return this.url.searchParams.append(r,`${e}.${n}`),this}},qo=class{constructor(r,{headers:e={},schema:n,fetch:s,urlLengthLimit:i=8e3}){this.url=r,this.headers=new Headers(e),this.schema=n,this.fetch=s,this.urlLengthLimit=i}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(r,e){const{head:n=!1,count:s}=e??{},i=n?"HEAD":"GET";let o=!1;const a=(r??"*").split("").map(d=>/\s/.test(d)&&!o?"":(d==='"'&&(o=!o),d)).join(""),{url:l,headers:c}=this.cloneRequestState();return l.searchParams.set("select",a),s&&c.append("Prefer",`count=${s}`),new zt({method:i,url:l,headers:c,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}insert(r,{count:e,defaultToNull:n=!0}={}){var s;const i="POST",{url:o,headers:a}=this.cloneRequestState();if(e&&a.append("Prefer",`count=${e}`),n||a.append("Prefer","missing=default"),Array.isArray(r)){const l=r.reduce((c,d)=>c.concat(Object.keys(d)),[]);if(l.length>0){const c=[...new Set(l)].map(d=>`"${d}"`);o.searchParams.set("columns",c.join(","))}}return new zt({method:i,url:o,headers:a,schema:this.schema,body:r,fetch:(s=this.fetch)!==null&&s!==void 0?s:fetch,urlLengthLimit:this.urlLengthLimit})}upsert(r,{onConflict:e,ignoreDuplicates:n=!1,count:s,defaultToNull:i=!0}={}){var o;const a="POST",{url:l,headers:c}=this.cloneRequestState();if(c.append("Prefer",`resolution=${n?"ignore":"merge"}-duplicates`),e!==void 0&&l.searchParams.set("on_conflict",e),s&&c.append("Prefer",`count=${s}`),i||c.append("Prefer","missing=default"),Array.isArray(r)){const d=r.reduce((u,f)=>u.concat(Object.keys(f)),[]);if(d.length>0){const u=[...new Set(d)].map(f=>`"${f}"`);l.searchParams.set("columns",u.join(","))}}return new zt({method:a,url:l,headers:c,schema:this.schema,body:r,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch,urlLengthLimit:this.urlLengthLimit})}update(r,{count:e}={}){var n;const s="PATCH",{url:i,headers:o}=this.cloneRequestState();return e&&o.append("Prefer",`count=${e}`),new zt({method:s,url:i,headers:o,schema:this.schema,body:r,fetch:(n=this.fetch)!==null&&n!==void 0?n:fetch,urlLengthLimit:this.urlLengthLimit})}delete({count:r}={}){var e;const n="DELETE",{url:s,headers:i}=this.cloneRequestState();return r&&i.append("Prefer",`count=${r}`),new zt({method:n,url:s,headers:i,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit})}};function gr(r){"@babel/helpers - typeof";return gr=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},gr(r)}function Ko(r,e){if(gr(r)!="object"||!r)return r;var n=r[Symbol.toPrimitive];if(n!==void 0){var s=n.call(r,e);if(gr(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(r)}function Jo(r){var e=Ko(r,"string");return gr(e)=="symbol"?e:e+""}function Go(r,e,n){return(e=Jo(e))in r?Object.defineProperty(r,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):r[e]=n,r}function fs(r,e){var n=Object.keys(r);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(r);e&&(s=s.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),n.push.apply(n,s)}return n}function kr(r){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};
13e%2?fs(Object(n),!0).forEach(function(s){Go(r,s,n[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(n)):fs(Object(n)).forEach(function(s){Object.defineProperty(r,s,Object.getOwnPropertyDescriptor(n,s))})}return r}var Zo=class ni{constructor(e,{headers:n={},schema:s,fetch:i,timeout:o,urlLengthLimit:a=8e3}={}){this.url=e,this.headers=new Headers(n),this.schemaName=s,this.urlLengthLimit=a;const l=i??globalThis.fetch;o!==void 0&&o>0?this.fetch=(c,d)=>{const u=new AbortController,f=setTimeout(()=>u.abort(),o),p=d==null?void 0:d.signal;if(p){if(p.aborted)return clearTimeout(f),l(c,d);const x=()=>{clearTimeout(f),u.abort()};return p.addEventListener("abort",x,{once:!0}),l(c,kr(kr({},d),{},{signal:u.signal})).finally(()=>{clearTimeout(f),p.removeEventListener("abort",x)})}return l(c,kr(kr({},d),{},{signal:u.signal})).finally(()=>clearTimeout(f))}:this.fetch=l}from(e){if(!e||typeof e!="string"||e.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new qo(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(e){return new ni(this.url,{headers:this.headers,schema:e,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}rpc(e,n={},{head:s=!1,get:i=!1,count:o}={}){var a;let l;const c=new URL(`${this.url}/rpc/${e}`);let d;const u=x=>x!==null&&typeof x=="object"&&(!Array.isArray(x)||x.some(u)),f=s&&Object.values(n).some(u);f?(l="POST",d=n):s||i?(l=s?"HEAD":"GET",Object.entries(n).filter(([x,g])=>g!==void 0).map(([x,g])=>[x,Array.isArray(g)?`{${g.join(",")}}`:`${g}`]).forEach(([x,g])=>{c.searchParams.append(x,g)})):(l="POST",d=n);const p=new Headers(this.headers);return f?p.set("Prefer",o?`count=${o},return=minimal`:"return=minimal"):o&&p.set("Prefer",`count=${o}`),new zt({method:l,url:c,headers:p,schema:this.schemaName,body:d,fetch:(a=this.fetch)!==null&&a!==void 0?a:fetch,urlLengthLimit:this.urlLengthLimit})}};class Yo{constructor(){}static detectEnvironment(){var e;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"&&(!((e=navigator.userAgent)===null||e===void 0)&&e.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 n=globalThis.process;if(n){const s=n.versions;if(s&&s.node){const i=s.node,o=parseInt(i.replace(/^v/,"").split(".")[0]);return o>=22?typeof globalThis.WebSocket<"u"?{type:"native",constructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${o} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${o} detected without native WebSocket support.`,workaround:`For Node.js < 22, install "ws" package and provide it via the transport option: 14import ws from "ws" 15new 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 e=this.detectEnvironment();if(e.constructor)return e.constructor;let n=e.error||"WebSocket not supported in this environment.";throw e.workaround&&(n+=` 16 17Suggested solution: ${e.workaround}`),new Error(n)}static createWebSocket(e,n){const s=this.getWebSocketConstructor();return new s(e,n)}static isWebSocketSupported(){try{const e=this.detectEnvironment();return e.type==="native"||e.type==="ws"}catch{return!1}}}const Xo="2.99.0",Qo=`realtime-js/${Xo}`,ea="1.0.0",si="2.0.0",ps=si,En=1e4,ta=1e3,ra=100;var lt;(function(r){r[r.connecting=0]="connecting",r[r.open=1]="open",r[r.closing=2]="closing",r[r.closed=3]="closed"})(lt||(lt={}));var ge;(function(r){r.closed="closed",r.errored="errored",r.joined="joined",r.joining="joining",r.leaving="leaving"})(ge||(ge={}));var Fe;(function(r){r.close="phx_close",r.error="phx_error",r.join="phx_join",r.reply="phx_reply",r.leave="phx_leave",r.access_token="access_token"})(Fe||(Fe={}));var Cn;(function(r){r.websocket="websocket"})(Cn||(Cn={}));var wt;(function(r){r.Connecting="connecting",r.Open="open",r.Closing="closing",r.Closed="closed"})(wt||(wt={}));
17class na{constructor(e){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=e??[]}encode(e,n){if(e.event===this.BROADCAST_EVENT&&!(e.payload instanceof ArrayBuffer)&&typeof e.payload.event=="string")return n(this._binaryEncodeUserBroadcastPush(e));let s=[e.join_ref,e.ref,e.topic,e.event,e.payload];return n(JSON.stringify(s))}_binaryEncodeUserBroadcastPush(e){var n;return this._isArrayBuffer((n=e.payload)===null||n===void 0?void 0:n.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){var n,s;const i=(s=(n=e.payload)===null||n===void 0?void 0:n.payload)!==null&&s!==void 0?s:new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,i)}_encodeJsonUserBroadcastPush(e){var n,s;const i=(s=(n=e.payload)===null||n===void 0?void 0:n.payload)!==null&&s!==void 0?s:{},a=new TextEncoder().encode(JSON.stringify(i)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,a)}_encodeUserBroadcastPush(e,n,s){var i,o;const a=e.topic,l=(i=e.ref)!==null&&i!==void 0?i:"",c=(o=e.join_ref)!==null&&o!==void 0?o:"",d=e.payload.event,u=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},f=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(a.length>255)throw new Error(`topic length ${a.length} exceeds maximum of 255`);if(d.length>255)throw new Error(`userEvent length ${d.length} exceeds maximum of 255`);if(f.length>255)throw new Error(`metadata length ${f.length} exceeds maximum of 255`);const p=this.USER_BROADCAST_PUSH_META_LENGTH+c.length+l.length+a.length+d.length+f.length,x=new ArrayBuffer(this.HEADER_LENGTH+p);let g=new DataView(x),v=0;g.setUint8(v++,this.KINDS.userBroadcastPush),g.setUint8(v++,c.length),g.setUint8(v++,l.length),g.setUint8(v++,a.length),g.setUint8(v++,d.length),g.setUint8(v++,f.length),g.setUint8(v++,n),Array.from(c,w=>g.setUint8(v++,w.charCodeAt(0))),Array.from(l,w=>g.setUint8(v++,w.charCodeAt(0))),Array.from(a,w=>g.setUint8(v++,w.charCodeAt(0))),Array.from(d,w=>g.setUint8(v++,w.charCodeAt(0))),Array.from(f,w=>g.setUint8(v++,w.charCodeAt(0)));var m=new Uint8Array(x.byteLength+s.byteLength);return m.set(new Uint8Array(x),0),m.set(new Uint8Array(s),x.byteLength),m.buffer}decode(e,n){if(this._isArrayBuffer(e)){let s=this._binaryDecode(e);return n(s)}if(typeof e=="string"){const s=JSON.parse(e),[i,o,a,l,c]=s;return n({join_ref:i,ref:o,topic:a,event:l,payload:c})}return n({})}_binaryDecode(e){const n=new DataView(e),s=n.getUint8(0),i=new TextDecoder;switch(s){case this.KINDS.userBroadcast:return this._decodeUserBroadcast(e,n,i)}}_decodeUserBroadcast(e,n,s){const i=n.getUint8(1),o=n.getUint8(2),a=n.getUint8(3),l=n.getUint8(4);let c=this.HEADER_LENGTH+4;const d=s.decode(e.slice(c,c+i));c=c+i;const u=s.decode(e.slice(c,c+o));c=c+o;const f=s.decode(e.slice(c,c+a));c=c+a;const p=e.slice(c,e.byteLength),x=l===this.JSON_ENCODING?JSON.parse(s.decode(p)):p,g={type:this.BROADCAST_EVENT,event:u,payload:x};return a>0&&(g.meta=JSON.parse(f)),{join_ref:null,ref:null,topic:d,event:this.BROADCAST_EVENT,payload:g}}_isArrayBuffer(e){var n;return e instanceof ArrayBuffer||((n=e==null?void 0:e.constructor)===null||n===void 0?void 0:n.name)==="ArrayBuffer"}_pick(e,n){return!e||typeof e!="object"?{}:Object.fromEntries(Object.entries(e).filter(([s])=>n.includes(s)))}}class ii{constructor(e,n){this.callback=e,this.timerCalc=n,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=n}reset(){this.tries=0,clearTimeout(this.timer),this.timer=void 0}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}}var ae;(function(r){r.abstime="abstime",r.bool="bool",r.date="date",r.daterange="daterange",r.float4="float4",r.float8="float8",r.int2="int2",r.int4="int4",r.int4range="int4range",r.int8="int8",r.int8range="int8range",r.json="json",r.jsonb="jsonb",r.money="money",r.numeric="numeric",r.oid="oid",r.reltime="reltime",r.text="text",r.time="time",r.timestamp="timestamp",r.timestamptz="timestamptz",r.timetz="timetz",r.tsrange="tsrange",r.tstzrange="tstzrange"})(ae||(ae={}));const gs=(r,e,n={})=>{var s;const i=(s=n.skipTypes)!==null&&s!==void 0?s:[];return e?Object.keys(e).reduce((o,a)=>(o[a]=sa(a,r,e,i),o),{}):{}},sa=(r,e,n,s)=>{const i=e.find(l=>
17l.name===r),o=i==null?void 0:i.type,a=n[r];return o&&!s.includes(o)?oi(o,a):An(a)},oi=(r,e)=>{if(r.charAt(0)==="_"){const n=r.slice(1,r.length);return la(e,n)}switch(r){case ae.bool:return ia(e);case ae.float4:case ae.float8:case ae.int2:case ae.int4:case ae.int8:case ae.numeric:case ae.oid:return oa(e);case ae.json:case ae.jsonb:return aa(e);case ae.timestamp:return ca(e);case ae.abstime:case ae.date:case ae.daterange:case ae.int4range:case ae.int8range:case ae.money:case ae.reltime:case ae.text:case ae.time:case ae.timestamptz:case ae.timetz:case ae.tsrange:case ae.tstzrange:return An(e);default:return An(e)}},An=r=>r,ia=r=>{switch(r){case"t":return!0;case"f":return!1;default:return r}},oa=r=>{if(typeof r=="string"){const e=parseFloat(r);if(!Number.isNaN(e))return e}return r},aa=r=>{if(typeof r=="string")try{return JSON.parse(r)}catch{return r}return r},la=(r,e)=>{if(typeof r!="string")return r;const n=r.length-1,s=r[n];if(r[0]==="{"&&s==="}"){let o;const a=r.slice(1,n);try{o=JSON.parse("["+a+"]")}catch{o=a?a.split(","):[]}return o.map(l=>oi(e,l))}return r},ca=r=>typeof r=="string"?r.replace(" ","T"):r,ai=r=>{const e=new URL(r);return e.protocol=e.protocol.replace(/^ws/i,"http"),e.pathname=e.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),e.pathname===""||e.pathname==="/"?e.pathname="/api/broadcast":e.pathname=e.pathname+"/api/broadcast",e.href};class an{constructor(e,n,s={},i=En){this.channel=e,this.event=n,this.payload=s,this.timeout=i,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,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()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,n){var s;return this._hasReceived(e)&&n((s=this.receivedResp)===null||s===void 0?void 0:s.response),this.recHooks.push({status:e,callback:n}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);const e=n=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=n,this._matchReceive(n)};this.channel._on(this.refEvent,{},e),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,n){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:n})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:n}){this.recHooks.filter(s=>s.status===e).forEach(s=>s.callback(n))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}}var ms;(function(r){r.SYNC="sync",r.JOIN="join",r.LEAVE="leave"})(ms||(ms={}));class ur{constructor(e,n){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.enabled=!1,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};const s=(n==null?void 0:n.events)||{state:"presence_state",diff:"presence_diff"};this.channel._on(s.state,{},i=>{const{onJoin:o,onLeave:a,onSync:l}=this.caller;this.joinRef=this.channel._joinRef(),this.state=ur.syncState(this.state,i,o,a),this.pendingDiffs.forEach(c=>{this.state=ur.syncDiff(this.state,c,o,a)}),this.pendingDiffs=[],l()}),this.channel._on(s.diff,{},i=>{const{onJoin:o,onLeave:a,onSync:l}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(i):(this.state=ur.syncDiff(this.state,i,o,a),l())}),this.onJoin((i,o,a)=>{this.channel._trigger("presence",{event:"join",key:i,currentPresences:o,newPresences:a})}),this.onLeave((i,o,a)=>{this.channel._trigger("presence",{event:"leave",key:i,currentPresences:o,leftPresences:a})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,n,s,i){const o=this.cloneDeep(e),a=this.transformState(n),l={},c={};return this.map(o,(d,u)=>{a[d]||(c[d]=u)}),this.map(a,(d,u)=>{const f=o[d];if(f){const p=u.map(m=>m.presence_ref),x=f.map(m=>m.presence_ref),g=u.filter(m=>x.indexOf(m.presence_ref)<0),v=f.filter(m=>p.indexOf(m.presence_ref)<0);g.length>0&&(l[d]=g),v.length>0&&(c[d]=v)}else l[d]=u}),this.syncDiff(o,{joins:l,leaves:c},s,i)}static syncDiff(e,n,s,i){const{joins:o,leaves:a}={joins:this.transformState(n.joins),leaves:this.transformState(n.leaves)};return s||(s=()=>{}),i||(i=()=>{}),this.map(o,(l,c)=>{var d;const u=(d=e[l])!==null&&d!==void 0?d:[];if(e[l]=this.cloneDeep(c),u.length>0){const f=e[l].map(x=>x.presence_ref),p=u.filter(x=>f.indexOf(x.presence_ref)<0);e[l].unshift(...p)}s(l,u,c)}),this.map(a,(l,c)=>{let d=e[l];
17if(!d)return;const u=c.map(f=>f.presence_ref);d=d.filter(f=>u.indexOf(f.presence_ref)<0),e[l]=d,i(l,d,c),d.length===0&&delete e[l]}),e}static map(e,n){return Object.getOwnPropertyNames(e).map(s=>n(s,e[s]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((n,s)=>{const i=e[s];return"metas"in i?n[s]=i.metas.map(o=>(o.presence_ref=o.phx_ref,delete o.phx_ref,delete o.phx_ref_prev,o)):n[s]=i,n},{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}}var ys;(function(r){r.ALL="*",r.INSERT="INSERT",r.UPDATE="UPDATE",r.DELETE="DELETE"})(ys||(ys={}));var hr;(function(r){r.BROADCAST="broadcast",r.PRESENCE="presence",r.POSTGRES_CHANGES="postgres_changes",r.SYSTEM="system"})(hr||(hr={}));var Xe;(function(r){r.SUBSCRIBED="SUBSCRIBED",r.TIMED_OUT="TIMED_OUT",r.CLOSED="CLOSED",r.CHANNEL_ERROR="CHANNEL_ERROR"})(Xe||(Xe={}));class Wt{constructor(e,n={config:{}},s){var i,o;if(this.topic=e,this.params=n,this.socket=s,this.bindings={},this.state=ge.closed,this.joinedOnce=!1,this.pushBuffer=[],this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},n.config),this.timeout=this.socket.timeout,this.joinPush=new an(this,Fe.join,this.params,this.timeout),this.rejoinTimer=new ii(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=ge.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(a=>a.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=ge.closed,this.socket._remove(this)}),this._onError(a=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,a),this.state=ge.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=ge.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("error",a=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,a),this.state=ge.errored,this.rejoinTimer.scheduleTimeout())}),this._on(Fe.reply,{},(a,l)=>{this._trigger(this._replyEventName(l),a)}),this.presence=new ur(this),this.broadcastEndpointURL=ai(this.socket.endPoint),this.private=this.params.config.private||!1,!this.private&&(!((o=(i=this.params.config)===null||i===void 0?void 0:i.broadcast)===null||o===void 0)&&o.replay))throw`tried to use replay on public channel '${this.topic}'. It must be a private channel.`}subscribe(e,n=this.timeout){var s,i,o;if(this.socket.isConnected()||this.socket.connect(),this.state==ge.closed){const{config:{broadcast:a,presence:l,private:c}}=this.params,d=(i=(s=this.bindings.postgres_changes)===null||s===void 0?void 0:s.map(x=>x.filter))!==null&&i!==void 0?i:[],u=!!this.bindings[hr.PRESENCE]&&this.bindings[hr.PRESENCE].length>0||((o=this.params.config.presence)===null||o===void 0?void 0:o.enabled)===!0,f={},p={broadcast:a,presence:Object.assign(Object.assign({},l),{enabled:u}),postgres_changes:d,private:c};this.socket.accessTokenValue&&(f.access_token=this.socket.accessTokenValue),this._onError(x=>e==null?void 0:e(Xe.CHANNEL_ERROR,x)),this._onClose(()=>e==null?void 0:e(Xe.CLOSED)),this.updateJoinPayload(Object.assign({config:p},f)),this.joinedOnce=!0,this._rejoin(n),this.joinPush.receive("ok",async({postgres_changes:x})=>{var g;if(this.socket._isManualToken()||this.socket.setAuth(),x===void 0){e==null||e(Xe.SUBSCRIBED);return}else{const v=this.bindings.postgres_changes,m=(g=v==null?void 0:v.length)!==null&&g!==void 0?g:0,w=[];for(let _=0;_<m;_++){const b=v[_],{filter:{event:y,schema:k,table:S,filter:T}}=b,V=x&&x[_];if(V&&V.event===y&&Wt.isFilterValueEqual(V.schema,k)&&Wt.isFilterValueEqual(V.table,S)&&Wt.isFilterValueEqual(V.filter,T))w.push(Object.assign(Object.assign({},b),{id:V.id}));else{this.unsubscribe(),this.state=ge.errored,e==null||e(Xe.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=w,e&&e(Xe.SUBSCRIBED);return}}).receive("error",x=>{this.state=ge.errored,e==null||e(Xe.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(x).join(", ")||"error")))}).receive("timeout",()=>{e==null||e(Xe.TIMED_OUT)})}return this}presenceState(){return this.presence.state}async track(e,n={}){return await this.send({type:"presence",event:"track",payload:e},n.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,n,s){return this.state===ge.joined&&e===hr.PRESENCE&&(this.socket.log("channel",`resubscribe to ${this.topic} due to change in presence callbacks on joined channel`),this.unsubscribe().then(async()=>await this.subscribe())),this._on(e,n,s)}async httpSend(e,n,s={}){var i;if(n==null)return Promise.reject("Payload is required for httpSend()");const o={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(o.Authorization=`Bearer ${this.socket.accessTokenValue}`);const a={method:"POST",headers:o,body:JSON.stringify({messages:[{topic:this.subTopic,event:e,payload:n,private:this.private}]})},l=await this._fetchWithTimeout(this.broadcastEndpointURL,a,(i=s.timeout)!==null&&i!==void 0?i:this.timeout);if(l.status===202)return{success:!0};let c=l.statusText;
17try{const d=await l.json();c=d.error||d.message||c}catch{}return Promise.reject(new Error(c))}async send(e,n={}){var s,i;if(!this._canPush()&&e.type==="broadcast"){console.warn("Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery.");const{event:o,payload:a}=e,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:o,payload:a,private:this.private}]})};try{const d=await this._fetchWithTimeout(this.broadcastEndpointURL,c,(s=n.timeout)!==null&&s!==void 0?s:this.timeout);return await((i=d.body)===null||i===void 0?void 0:i.cancel()),d.ok?"ok":"error"}catch(d){return d.name==="AbortError"?"timed out":"error"}}else return new Promise(o=>{var a,l,c;const d=this._push(e.type,e,n.timeout||this.timeout);e.type==="broadcast"&&!(!((c=(l=(a=this.params)===null||a===void 0?void 0:a.config)===null||l===void 0?void 0:l.broadcast)===null||c===void 0)&&c.ack)&&o("ok"),d.receive("ok",()=>o("ok")),d.receive("error",()=>o("error")),d.receive("timeout",()=>o("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=ge.leaving;const n=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(Fe.close,"leave",this._joinRef())};this.joinPush.destroy();let s=null;return new Promise(i=>{s=new an(this,Fe.leave,{},e),s.receive("ok",()=>{n(),i("ok")}).receive("timeout",()=>{n(),i("timed out")}).receive("error",()=>{i("error")}),s.send(),this._canPush()||s.trigger("ok",{})}).finally(()=>{s==null||s.destroy()})}teardown(){this.pushBuffer.forEach(e=>e.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=ge.closed,this.bindings={}}async _fetchWithTimeout(e,n,s){const i=new AbortController,o=setTimeout(()=>i.abort(),s),a=await this.socket.fetch(e,Object.assign(Object.assign({},n),{signal:i.signal}));return clearTimeout(o),a}_push(e,n,s=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let i=new an(this,e,n,s);return this._canPush()?i.send():this._addToPushBuffer(i),i}_addToPushBuffer(e){if(e.startTimeout(),this.pushBuffer.push(e),this.pushBuffer.length>ra){const n=this.pushBuffer.shift();n&&(n.destroy(),this.socket.log("channel",`discarded push due to buffer overflow: ${n.event}`,n.payload))}}_onMessage(e,n,s){return n}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,n,s){var i,o;const a=e.toLocaleLowerCase(),{close:l,error:c,leave:d,join:u}=Fe;if(s&&[l,c,d,u].indexOf(a)>=0&&s!==this._joinRef())return;let p=this._onMessage(a,n,s);if(n&&!p)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(a)?(i=this.bindings.postgres_changes)===null||i===void 0||i.filter(x=>{var g,v,m;return((g=x.filter)===null||g===void 0?void 0:g.event)==="*"||((m=(v=x.filter)===null||v===void 0?void 0:v.event)===null||m===void 0?void 0:m.toLocaleLowerCase())===a}).map(x=>x.callback(p,s)):(o=this.bindings[a])===null||o===void 0||o.filter(x=>{var g,v,m,w,_,b;if(["broadcast","presence","postgres_changes"].includes(a))if("id"in x){const y=x.id,k=(g=x.filter)===null||g===void 0?void 0:g.event;return y&&((v=n.ids)===null||v===void 0?void 0:v.includes(y))&&(k==="*"||(k==null?void 0:k.toLocaleLowerCase())===((m=n.data)===null||m===void 0?void 0:m.type.toLocaleLowerCase()))}else{const y=(_=(w=x==null?void 0:x.filter)===null||w===void 0?void 0:w.event)===null||_===void 0?void 0:_.toLocaleLowerCase();return y==="*"||y===((b=n==null?void 0:n.event)===null||b===void 0?void 0:b.toLocaleLowerCase())}else return x.type.toLocaleLowerCase()===a}).map(x=>{if(typeof p=="object"&&"ids"in p){const g=p.data,{schema:v,table:m,commit_timestamp:w,type:_,errors:b}=g;p=Object.assign(Object.assign({},{schema:v,table:m,commit_timestamp:w,eventType:_,new:{},old:{},errors:b}),this._getPayloadRecords(g))}
17x.callback(p,s)})}_isClosed(){return this.state===ge.closed}_isJoined(){return this.state===ge.joined}_isJoining(){return this.state===ge.joining}_isLeaving(){return this.state===ge.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,n,s){const i=e.toLocaleLowerCase(),o={type:i,filter:n,callback:s};return this.bindings[i]?this.bindings[i].push(o):this.bindings[i]=[o],this}_off(e,n){const s=e.toLocaleLowerCase();return this.bindings[s]&&(this.bindings[s]=this.bindings[s].filter(i=>{var o;return!(((o=i.type)===null||o===void 0?void 0:o.toLocaleLowerCase())===s&&Wt.isEqual(i.filter,n))})),this}static isEqual(e,n){if(Object.keys(e).length!==Object.keys(n).length)return!1;for(const s in e)if(e[s]!==n[s])return!1;return!0}static isFilterValueEqual(e,n){return(e??void 0)===(n??void 0)}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(Fe.close,{},e)}_onError(e){this._on(Fe.error,{},n=>e(n))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=ge.joining,this.joinPush.resend(e))}_getPayloadRecords(e){const n={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(n.new=gs(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(n.old=gs(e.columns,e.old_record)),n}}const ln=()=>{},Er={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},da=[1e3,2e3,5e3,1e4],ua=1e4,ha=` 18 addEventListener("message", (e) => { 19 if (e.data.event === "start") { 20 setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval); 21 } 22 });`;class fa{constructor(e,n){var s;if(this.accessTokenValue=null,this.apiKey=null,this._manuallySetToken=!1,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers={},this.params={},this.timeout=En,this.transport=null,this.heartbeatIntervalMs=Er.HEARTBEAT_INTERVAL,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=ln,this.ref=0,this.reconnectTimer=null,this.vsn=ps,this.logger=ln,this.conn=null,this.sendBuffer=[],this.serializer=new na,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._connectionState="disconnected",this._wasManualDisconnect=!1,this._authPromise=null,this._heartbeatSentAt=null,this._resolveFetch=i=>i?(...o)=>i(...o):(...o)=>fetch(...o),!(!((s=n==null?void 0:n.params)===null||s===void 0)&&s.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=n.params.apikey,this.endPoint=`${e}/${Cn.websocket}`,this.httpEndpoint=ai(e),this._initializeOptions(n),this._setupReconnectionTimer(),this.fetch=this._resolveFetch(n==null?void 0:n.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.conn!==null&&this.isConnected())){if(this._setConnectionState("connecting"),this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this.transport)this.conn=new this.transport(this.endpointURL());else try{this.conn=Yo.createWebSocket(this.endpointURL())}catch(e){this._setConnectionState("disconnected");const n=e.message;throw n.includes("Node.js")?new Error(`${n} 23 24To use Realtime in Node.js, you need to provide a WebSocket implementation: 25 26Option 1: Use Node.js 22+ which has native WebSocket support 27Option 2: Install and provide the "ws" package: 28 29 npm install ws 30 31 import ws from "ws" 32 const client = new RealtimeClient(url, { 33 ...options, 34 transport: ws 35 })`):new Error(`WebSocket not available: ${n}`)}this._setupConnectionHandlers()}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:this.vsn}))}disconnect(e,n){if(!this.isDisconnecting())if(this._setConnectionState("disconnecting",!0),this.conn){const s=setTimeout(()=>{this._setConnectionState("disconnected")},100);this.conn.onclose=()=>{clearTimeout(s),this._setConnectionState("disconnected")},typeof this.conn.close=="function"&&(e?this.conn.close(e,n??""):this.conn.close()),this._teardownConnection()}else this._setConnectionState("disconnected")}getChannels(){return this.channels}async removeChannel(e){const n=await e.unsubscribe();return this.channels.length===0&&this.disconnect(),n}async removeAllChannels(){const e=await Promise.all(this.channels.map(n=>n.unsubscribe()));return this.channels=[],this.disconnect(),e}log(e,n,s){this.logger(e,n,s)}connectionState(){switch(this.conn&&this.conn.readyState){case lt.connecting:return wt.Connecting;case lt.open:return wt.Open;case lt.closing:return wt.Closing;default:return wt.Closed}}isConnected(){return this.connectionState()===wt.Open}isConnecting(){return this._connectionState==="connecting"}isDisconnecting(){return this._connectionState==="disconnecting"}
35channel(e,n={config:{}}){const s=`realtime:${e}`,i=this.getChannels().find(o=>o.topic===s);if(i)return i;{const o=new Wt(`realtime:${e}`,n,this);return this.channels.push(o),o}}push(e){const{topic:n,event:s,payload:i,ref:o}=e,a=()=>{this.encode(e,l=>{var c;(c=this.conn)===null||c===void 0||c.send(l)})};this.log("push",`${n} ${s} (${o})`,i),this.isConnected()?a():this.sendBuffer.push(a)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){var e;if(!this.isConnected()){try{this.heartbeatCallback("disconnected")}catch(n){this.log("error","error in heartbeat callback",n)}return}if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this._heartbeatSentAt=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(n){this.log("error","error in heartbeat callback",n)}this._wasManualDisconnect=!1,(e=this.conn)===null||e===void 0||e.close(ta,"heartbeat timeout"),setTimeout(()=>{var n;this.isConnected()||(n=this.reconnectTimer)===null||n===void 0||n.scheduleTimeout()},Er.HEARTBEAT_TIMEOUT_FALLBACK);return}this._heartbeatSentAt=Date.now(),this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(n){this.log("error","error in heartbeat callback",n)}this._setAuthSafely("heartbeat")}onHeartbeat(e){this.heartbeatCallback=e}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let n=this.channels.find(s=>s.topic===e&&(s._isJoined()||s._isJoining()));n&&(this.log("transport",`leaving duplicate topic "${e}"`),n.unsubscribe())}_remove(e){this.channels=this.channels.filter(n=>n.topic!==e.topic)}_onConnMessage(e){this.decode(e.data,n=>{if(n.topic==="phoenix"&&n.event==="phx_reply"&&n.ref&&n.ref===this.pendingHeartbeatRef){const d=this._heartbeatSentAt?Date.now()-this._heartbeatSentAt:void 0;try{this.heartbeatCallback(n.payload.status==="ok"?"ok":"error",d)}catch(u){this.log("error","error in heartbeat callback",u)}this._heartbeatSentAt=null,this.pendingHeartbeatRef=null}const{topic:s,event:i,payload:o,ref:a}=n,l=a?`(${a})`:"",c=o.status||"";this.log("receive",`${c} ${s} ${i} ${l}`.trim(),o),this.channels.filter(d=>d._isMember(s)).forEach(d=>d._trigger(i,o,a)),this._triggerStateCallbacks("message",n)})}_clearTimer(e){var n;e==="heartbeat"&&this.heartbeatTimer?(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0):e==="reconnect"&&((n=this.reconnectTimer)===null||n===void 0||n.reset())}_clearAllTimers(){this._clearTimer("heartbeat"),this._clearTimer("reconnect")}_setupConnectionHandlers(){this.conn&&("binaryType"in this.conn&&(this.conn.binaryType="arraybuffer"),this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e),this.conn.readyState===lt.open&&this._onConnOpen())}_teardownConnection(){if(this.conn){if(this.conn.readyState===lt.open||this.conn.readyState===lt.connecting)try{this.conn.close()}catch(e){this.log("error","Error closing connection",e)}this.conn.onopen=null,this.conn.onerror=null,this.conn.onmessage=null,this.conn.onclose=null,this.conn=null}this._clearAllTimers(),this._terminateWorker(),this.channels.forEach(e=>e.teardown())}_onConnOpen(){this._setConnectionState("connected"),this.log("transport",`connected to ${this.endpointURL()}`),(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).then(()=>{this.accessTokenValue&&(this.channels.forEach(n=>{n.updateJoinPayload({access_token:this.accessTokenValue})}),this.sendBuffer=[],this.channels.forEach(n=>{n._isJoining()&&(n.joinPush.sent=!1,n.joinPush.send())})),this.flushSendBuffer()}).catch(n=>{this.log("error","error waiting for auth on connect",n),this.flushSendBuffer()}),this._clearTimer("reconnect"),this.worker?this.workerRef||this._startWorkerHeartbeat():this._startHeartbeat(),this._triggerStateCallbacks("open")}_startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");const e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=n=>{this.log("worker","worker error",n.message),this._terminateWorker()},this.workerRef.onmessage=n=>{n.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)}_onConnClose(e){var n;this._setConnectionState("disconnected"),this.log("transport","close",e),this._triggerChanError(),this._clearTimer("heartbeat"),this._wasManualDisconnect||(n=this.reconnectTimer)===null||n===void 0||n.scheduleTimeout(),this._triggerStateCallbacks("close",e)}_onConnError(e){this._setConnectionState("disconnected"),this.log("transport",`${e}`),this._triggerChanError(),this._triggerStateCallbacks("error",e);try{this.heartbeatCallback("error")}catch(n){this.log("error","error in heartbeat callback",n)}}
35_triggerChanError(){this.channels.forEach(e=>e._trigger(Fe.error))}_appendParams(e,n){if(Object.keys(n).length===0)return e;const s=e.match(/\?/)?"&":"?",i=new URLSearchParams(n);return`${e}${s}${i}`}_workerObjectUrl(e){let n;if(e)n=e;else{const s=new Blob([ha],{type:"application/javascript"});n=URL.createObjectURL(s)}return n}_setConnectionState(e,n=!1){this._connectionState=e,e==="connecting"?this._wasManualDisconnect=!1:e==="disconnecting"&&(this._wasManualDisconnect=n)}async _performAuth(e=null){let n,s=!1;if(e)n=e,s=!0;else if(this.accessToken)try{n=await this.accessToken()}catch(i){this.log("error","Error fetching access token from callback",i),n=this.accessTokenValue}else n=this.accessTokenValue;s?this._manuallySetToken=!0:this.accessToken&&(this._manuallySetToken=!1),this.accessTokenValue!=n&&(this.accessTokenValue=n,this.channels.forEach(i=>{const o={access_token:n,version:Qo};n&&i.updateJoinPayload(o),i.joinedOnce&&i._isJoined()&&i._push(Fe.access_token,{access_token:n})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e="general"){this._isManualToken()||this.setAuth().catch(n=>{this.log("error",`Error setting auth in ${e}`,n)})}_triggerStateCallbacks(e,n){try{this.stateChangeCallbacks[e].forEach(s=>{try{s(n)}catch(i){this.log("error",`error in ${e} callback`,i)}})}catch(s){this.log("error",`error triggering ${e} callbacks`,s)}}_setupReconnectionTimer(){this.reconnectTimer=new ii(async()=>{setTimeout(async()=>{await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()},Er.RECONNECT_DELAY)},this.reconnectAfterMs)}_initializeOptions(e){var n,s,i,o,a,l,c,d,u,f,p,x;switch(this.transport=(n=e==null?void 0:e.transport)!==null&&n!==void 0?n:null,this.timeout=(s=e==null?void 0:e.timeout)!==null&&s!==void 0?s:En,this.heartbeatIntervalMs=(i=e==null?void 0:e.heartbeatIntervalMs)!==null&&i!==void 0?i:Er.HEARTBEAT_INTERVAL,this.worker=(o=e==null?void 0:e.worker)!==null&&o!==void 0?o:!1,this.accessToken=(a=e==null?void 0:e.accessToken)!==null&&a!==void 0?a:null,this.heartbeatCallback=(l=e==null?void 0:e.heartbeatCallback)!==null&&l!==void 0?l:ln,this.vsn=(c=e==null?void 0:e.vsn)!==null&&c!==void 0?c:ps,e!=null&&e.params&&(this.params=e.params),e!=null&&e.logger&&(this.logger=e.logger),(e!=null&&e.logLevel||e!=null&&e.log_level)&&(this.logLevel=e.logLevel||e.log_level,this.params=Object.assign(Object.assign({},this.params),{log_level:this.logLevel})),this.reconnectAfterMs=(d=e==null?void 0:e.reconnectAfterMs)!==null&&d!==void 0?d:(g=>da[g-1]||ua),this.vsn){case ea:this.encode=(u=e==null?void 0:e.encode)!==null&&u!==void 0?u:((g,v)=>v(JSON.stringify(g))),this.decode=(f=e==null?void 0:e.decode)!==null&&f!==void 0?f:((g,v)=>v(JSON.parse(g)));break;case si:this.encode=(p=e==null?void 0:e.encode)!==null&&p!==void 0?p:this.serializer.encode.bind(this.serializer),this.decode=(x=e==null?void 0:e.decode)!==null&&x!==void 0?x:this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${this.vsn}`)}if(this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=e==null?void 0:e.workerUrl}}}var mr=class extends Error{constructor(r,e){var n;super(r),this.name="IcebergError",this.status=e.status,this.icebergType=e.icebergType,this.icebergCode=e.icebergCode,this.details=e.details,this.isCommitStateUnknown=e.icebergType==="CommitStateUnknownException"||[500,502,504].includes(e.status)&&((n=e.icebergType)==null?void 0:n.includes("CommitState"))===!0}isNotFound(){return this.status===404}isConflict(){return this.status===409}isAuthenticationTimeout(){return this.status===419}};function pa(r,e,n){const s=new URL(e,r);if(n)for(const[i,o]of Object.entries(n))o!==void 0&&s.searchParams.set(i,o);return s.toString()}async function ga(r){return!r||r.type==="none"?{}:r.type==="bearer"?{Authorization:`Bearer ${r.token}`}:r.type==="header"?{[r.name]:r.value}:r.type==="custom"?await r.getHeaders():{}}function ma(r){const e=r.fetchImpl??globalThis.fetch;return{async request({method:n,path:s,query:i,body:o,headers:a}){const l=pa(r.baseUrl,s,i),c=await ga(r.auth),d=await e(l,{method:n,headers:{...o?{"Content-Type":"application/json"}:{},...c,...a},body:o?JSON.stringify(o):void 0}),u=await d.text(),f=(d.headers.get("content-type")||"").includes("application/json"),p=f&&u?JSON.parse(u):u;if(!d.ok){const x=f?p:void 0,g=x==null?void 0:x.error;throw new mr((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:x})}return{status:d.status,headers:d.headers,data:p}}}}function Cr(r){return r.join("�")}var ya=class{constructor(r,e=""){this.client=r,this.prefix=e}async listNamespaces(r){const e=r?{parent:Cr(r.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:e})).data.namespaces.map(s=>({namespace:s}))}async createNamespace(r,e){const n={namespace:r.namespace,properties:e==null?void 0:e.properties};return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:n})).data}async dropNamespace(r){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${Cr(r.namespace)}`})}async loadNamespaceMetadata(r){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Cr(r.namespace)}`})).data.properties}}async namespaceExists(r){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${Cr(r.namespace)}`}),!0}catch(e){if(e instanceof mr&&e.status===404)return!1;throw e}}async createNamespaceIfNotExists(r,e){try{return await this.createNamespace(r,e)}catch(n){if(n instanceof mr&&n.status===409)return;throw n}}};function At(r){return r.join("�")}var xa=class{constructor(r,e="",n){this.client=r,this.prefix=e,this.accessDelegation=n}async listTables(r){return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${At(r.namespace)}/tables`})).data.identifiers}async createTable(r,e){const n={};return this.accessDelegation&&(n["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${At(r.namespace)}/tables`,body:e,headers:n})).data.metadata}async updateTable(r,e){const n=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${At(r.namespace)}/tables/${r.name}`,body:e});return{"metadata-location":n.data["metadata-location"],metadata:n.data.metadata}}async dropTable(r,e){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${At(r.namespace)}/tables/${r.name}`,query:{purgeRequested:String((e==null?void 0:e.purge)??!1)}})}async loadTable(r){const e={};return this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${At(r.namespace)}/tables/${r.name}`,headers:e})).data.metadata}async tableExists(r){const e={};this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${At(r.namespace)}/tables/${r.name}`,headers:e}),!0}catch(n){if(n instanceof mr&&n.status===404)return!1;throw n}}async createTableIfNotExists(r,e){try{return await this.createTable(r,e)}catch(n){if(n instanceof mr&&n.status===409)return await this.loadTable({namespace:r.namespace,name:e.name});throw n}}},ba=class{constructor(r){var s;let e="v1";r.catalogName&&(e+=`/${r.catalogName}`);const n=r.baseUrl.endsWith("/")?r.baseUrl:`${r.baseUrl}/`;this.client=ma({baseUrl:n,auth:r.auth,fetchImpl:r.fetch}),this.accessDelegation=(s=r.accessDelegation)==null?void 0:s.join(","),this.namespaceOps=new ya(this.client,e),this.tableOps=new xa(this.client,e,this.accessDelegation)}async listNamespaces(r){return this.namespaceOps.listNamespaces(r)}async createNamespace(r,e){return this.namespaceOps.createNamespace(r,e)}async dropNamespace(r){await this.namespaceOps.dropNamespace(r)}async loadNamespaceMetadata(r){return this.namespaceOps.loadNamespaceMetadata(r)}
35async listTables(r){return this.tableOps.listTables(r)}async createTable(r,e){return this.tableOps.createTable(r,e)}async updateTable(r,e){return this.tableOps.updateTable(r,e)}async dropTable(r,e){await this.tableOps.dropTable(r,e)}async loadTable(r){return this.tableOps.loadTable(r)}async namespaceExists(r){return this.namespaceOps.namespaceExists(r)}async tableExists(r){return this.tableOps.tableExists(r)}async createNamespaceIfNotExists(r,e){return this.namespaceOps.createNamespaceIfNotExists(r,e)}async createTableIfNotExists(r,e){return this.tableOps.createTableIfNotExists(r,e)}},Gr=class extends Error{constructor(r,e="storage",n,s){super(r),this.__isStorageError=!0,this.namespace=e,this.name=e==="vectors"?"StorageVectorsError":"StorageError",this.status=n,this.statusCode=s}};function Zr(r){return typeof r=="object"&&r!==null&&"__isStorageError"in r}var or=class extends Gr{constructor(r,e,n,s="storage"){super(r,s,e,n),this.name=s==="vectors"?"StorageVectorsApiError":"StorageApiError",this.status=e,this.statusCode=n}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}},li=class extends Gr{constructor(r,e,n="storage"){super(r,n),this.name=n==="vectors"?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=e}};const va=r=>r?(...e)=>r(...e):(...e)=>fetch(...e),wa=r=>{if(typeof r!="object"||r===null)return!1;const e=Object.getPrototypeOf(r);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in r)&&!(Symbol.iterator in r)},Rn=r=>{if(Array.isArray(r))return r.map(n=>Rn(n));if(typeof r=="function"||r!==Object(r))return r;const e={};return Object.entries(r).forEach(([n,s])=>{const i=n.replace(/([-_][a-z])/gi,o=>o.toUpperCase().replace(/[-_]/g,""));e[i]=Rn(s)}),e},_a=r=>!r||typeof r!="string"||r.length===0||r.length>100||r.trim()!==r||r.includes("/")||r.includes("\\")?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(r);function yr(r){"@babel/helpers - typeof";return yr=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},yr(r)}function ja(r,e){if(yr(r)!="object"||!r)return r;var n=r[Symbol.toPrimitive];if(n!==void 0){var s=n.call(r,e);if(yr(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(r)}function Sa(r){var e=ja(r,"string");return yr(e)=="symbol"?e:e+""}function ka(r,e,n){return(e=Sa(e))in r?Object.defineProperty(r,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):r[e]=n,r}function xs(r,e){var n=Object.keys(r);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(r);e&&(s=s.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),n.push.apply(n,s)}return n}function W(r){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?xs(Object(n),!0).forEach(function(s){ka(r,s,n[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(n)):xs(Object(n)).forEach(function(s){Object.defineProperty(r,s,Object.getOwnPropertyDescriptor(n,s))})}return r}const bs=r=>{var e;return r.msg||r.message||r.error_description||(typeof r.error=="string"?r.error:(e=r.error)===null||e===void 0?void 0:e.message)||JSON.stringify(r)},Ea=async(r,e,n,s)=>{if(r&&typeof r=="object"&&"status"in r&&"ok"in r&&typeof r.status=="number"){const i=r,o=i.status||500;if(typeof i.json=="function")i.json().then(a=>{const l=(a==null?void 0:a.statusCode)||(a==null?void 0:a.code)||o+"";e(new or(bs(a),o,l,s))}).catch(()=>{if(s==="vectors"){const a=o+"";e(new or(i.statusText||`HTTP ${o} error`,o,a,s))}else{const a=o+"";e(new or(i.statusText||`HTTP ${o} error`,o,a,s))}});else{const a=o+"";e(new or(i.statusText||`HTTP ${o} error`,o,a,s))}}else e(new li(bs(r),r,s))},Ca=(r,e,n,s)=>{const i={method:r,headers:(e==null?void 0:e.headers)||{}};return r==="GET"||r==="HEAD"||!s?W(W({},i),n):(wa(s)?(i.headers=W({"Content-Type":"application/json"},e==null?void 0:e.headers),i.body=JSON.stringify(s)):i.body=s,e!=null&&e.duplex&&(i.duplex=e.duplex),W(W({},i),n))};async function nr(r,e,n,s,i,o,a){return new Promise((l,c)=>{r(n,Ca(e,s,i,o)).then(d=>{if(!d.ok)throw d;if(s!=null&&s.noResolveJson)return d;if(a==="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=>Ea(d,c,s,a))})}function ci(r="storage"){return{get:async(e,n,s,i)=>nr(e,"GET",n,s,i,void 0,r),post:async(e,n,s,i,o)=>nr(e,"POST",n,i,o,s,r),put:async(e,n,s,i,o)=>nr(e,"PUT",n,i,o,s,r),head:async(e,n,s,i)=>nr(e,"HEAD",n,W(W({},s),{},{noResolveJson:!0}),i,void 0,r),remove:async(e,n,s,i,o)=>nr(e,"DELETE",n,i,o,s,r)}}const Aa=ci("storage"),{get:xr,post:Ne,put:Tn,head:Ra,remove:Hn}=Aa,Le=ci("vectors");var Kt=class{constructor(r,e={},n,s="storage"){this.shouldThrowOnError=!1,this.url=r,this.headers=e,this.fetch=va(n),this.namespace=s}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(r,e){return this.headers=W(W({},this.headers),{},{[r]:e}),this}async handleOperation(r){var e=this;try{return{data:await r(),error:null}}catch(n){if(e.shouldThrowOnError)throw n;if(Zr(n))return{data:null,error:n};throw n}}},Ta=class{constructor(r,e){this.downloadFn=r,this.shouldThrowOnError=e}then(r,e){return this.execute().then(r,e)}async execute(){var r=this;try{return{data:(await r.downloadFn()).body,error:null}}catch(e){if(r.shouldThrowOnError)throw e;if(Zr(e))return{data:null,error:e};throw e}}};let di;di=Symbol.toStringTag;var Ia=class{constructor(r,e){this.downloadFn=r,this.shouldThrowOnError=e,this[di]="BlobDownloadBuilder",this.promise=null}asStream(){return new Ta(this.downloadFn,this.shouldThrowOnError)}then(r,e){return this.getPromise().then(r,e)}catch(r){return this.getPromise().catch(r)}finally(r){return this.getPromise().finally(r)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){var r=this;try{return{data:await(await r.downloadFn()).blob(),error:null}}catch(e){if(r.shouldThrowOnError)throw e;if(Zr(e))return{data:null,error:e};throw e}}};const Pa={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},vs={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};var Oa=class extends Kt{constructor(r,e={},n,s){super(r,e,s,"storage"),this.bucketId=n}async uploadOrUpdate(r,e,n,s){var i=this;return i.handleOperation(async()=>{let o;const a=W(W({},vs),s);let l=W(W({},i.headers),r==="POST"&&{"x-upsert":String(a.upsert)});const c=a.metadata;typeof Blob<"u"&&n instanceof Blob?(o=new FormData,o.append("cacheControl",a.cacheControl),c&&o.append("metadata",i.encodeMetadata(c)),o.append("",n)):typeof FormData<"u"&&n instanceof FormData?(o=n,o.has("cacheControl")||o.append("cacheControl",a.cacheControl),c&&!o.has("metadata")&&o.append("metadata",i.encodeMetadata(c))):(o=n,l["cache-control"]=`max-age=${a.cacheControl}`,l["content-type"]=a.contentType,c&&(l["x-metadata"]=i.toBase64(i.encodeMetadata(c))),(typeof ReadableStream<"u"&&o instanceof ReadableStream||o&&typeof o=="object"&&"pipe"in o&&typeof o.pipe=="function")&&!a.duplex&&(a.duplex="half")),s!=null&&s.headers&&(l=W(W({},l),s.headers));const d=i._removeEmptyFolders(e),u=i._getFinalPath(d),f=await(r=="PUT"?Tn:Ne)(i.fetch,`${i.url}/object/${u}`,o,W({headers:l},a!=null&&a.duplex?{duplex:a.duplex}:{}));return{path:d,id:f.Id,fullPath:f.Key}})}async upload(r,e,n){return this.uploadOrUpdate("POST",r,e,n)}async uploadToSignedUrl(r,e,n,s){var i=this;const o=i._removeEmptyFolders(r),a=i._getFinalPath(o),l=new URL(i.url+`/object/upload/sign/${a}`);return l.searchParams.set("token",e),i.handleOperation(async()=>{let c;const d=W({upsert:vs.upsert},s),u=W(W({},i.headers),{"x-upsert":String(d.upsert)});return typeof Blob<"u"&&n instanceof Blob?(c=new FormData,c.append("cacheControl",d.cacheControl),c.append("",n)):typeof FormData<"u"&&n instanceof FormData?(c=n,c.append("cacheControl",d.cacheControl)):(c=n,u["cache-control"]=`max-age=${d.cacheControl}`,u["content-type"]=d.contentType),{path:o,fullPath:(await Tn(i.fetch,l.toString(),c,{headers:u})).Key}})}async createSignedUploadUrl(r,e){var n=this;return n.handleOperation(async()=>{let s=n._getFinalPath(r);const i=W({},n.headers);e!=null&&e.upsert&&(i["x-upsert"]="true");const o=await Ne(n.fetch,`${n.url}/object/upload/sign/${s}`,{},{headers:i}),a=new URL(n.url+o.url),l=a.searchParams.get("token");if(!l)throw new Gr("No token returned by API");return{signedUrl:a.toString(),path:r,token:l}})}async update(r,e,n){return this.uploadOrUpdate("PUT",r,e,n)}async move(r,e,n){var s=this;return s.handleOperation(async()=>await Ne(s.fetch,`${s.url}/object/move`,{bucketId:s.bucketId,sourceKey:r,destinationKey:e,destinationBucket:n==null?void 0:n.destinationBucket},{headers:s.headers}))}async copy(r,e,n){var s=this;return s.handleOperation(async()=>({path:(await Ne(s.fetch,`${s.url}/object/copy`,{bucketId:s.bucketId,sourceKey:r,destinationKey:e,destinationBucket:n==null?void 0:n.destinationBucket},{headers:s.headers})).Key}))}async createSignedUrl(r,e,n){var s=this;return s.handleOperation(async()=>{let i=s._getFinalPath(r),o=await Ne(s.fetch,`${s.url}/object/sign/${i}
35`,W({expiresIn:e},n!=null&&n.transform?{transform:n.transform}:{}),{headers:s.headers});const a=n!=null&&n.download?`&download=${n.download===!0?"":n.download}`:"",l=n!=null&&n.transform&&o.signedURL.includes("/object/sign/")?o.signedURL.replace("/object/sign/","/render/image/sign/"):o.signedURL;return{signedUrl:encodeURI(`${s.url}${l}${a}`)}})}async createSignedUrls(r,e,n){var s=this;return s.handleOperation(async()=>{const i=await Ne(s.fetch,`${s.url}/object/sign/${s.bucketId}`,{expiresIn:e,paths:r},{headers:s.headers}),o=n!=null&&n.download?`&download=${n.download===!0?"":n.download}`:"";return i.map(a=>W(W({},a),{},{signedUrl:a.signedURL?encodeURI(`${s.url}${a.signedURL}${o}`):null}))})}download(r,e,n){const s=typeof(e==null?void 0:e.transform)<"u"?"render/image/authenticated":"object",i=this.transformOptsToQueryString((e==null?void 0:e.transform)||{}),o=i?`?${i}`:"",a=this._getFinalPath(r),l=()=>xr(this.fetch,`${this.url}/${s}/${a}${o}`,{headers:this.headers,noResolveJson:!0},n);return new Ia(l,this.shouldThrowOnError)}async info(r){var e=this;const n=e._getFinalPath(r);return e.handleOperation(async()=>Rn(await xr(e.fetch,`${e.url}/object/info/${n}`,{headers:e.headers})))}async exists(r){var e=this;const n=e._getFinalPath(r);try{return await Ra(e.fetch,`${e.url}/object/${n}`,{headers:e.headers}),{data:!0,error:null}}catch(i){if(e.shouldThrowOnError)throw i;if(Zr(i)){var s;const o=i instanceof or?i.status:i instanceof li?(s=i.originalError)===null||s===void 0?void 0:s.status:void 0;if(o!==void 0&&[400,404].includes(o))return{data:!1,error:i}}throw i}}getPublicUrl(r,e){const n=this._getFinalPath(r),s=[],i=e!=null&&e.download?`download=${e.download===!0?"":e.download}`:"";i!==""&&s.push(i);const o=typeof(e==null?void 0:e.transform)<"u"?"render/image":"object",a=this.transformOptsToQueryString((e==null?void 0:e.transform)||{});a!==""&&s.push(a);let l=s.join("&");return l!==""&&(l=`?${l}`),{data:{publicUrl:encodeURI(`${this.url}/${o}/public/${n}${l}`)}}}async remove(r){var e=this;return e.handleOperation(async()=>await Hn(e.fetch,`${e.url}/object/${e.bucketId}`,{prefixes:r},{headers:e.headers}))}async list(r,e,n){var s=this;return s.handleOperation(async()=>{const i=W(W(W({},Pa),e),{},{prefix:r||""});return await Ne(s.fetch,`${s.url}/object/list/${s.bucketId}`,i,{headers:s.headers},n)})}async listV2(r,e){var n=this;return n.handleOperation(async()=>{const s=W({},r);return await Ne(n.fetch,`${n.url}/object/list-v2/${n.bucketId}`,s,{headers:n.headers},e)})}encodeMetadata(r){return JSON.stringify(r)}toBase64(r){return typeof Buffer<"u"?Buffer.from(r).toString("base64"):btoa(r)}_getFinalPath(r){return`${this.bucketId}/${r.replace(/^\/+/,"")}`}_removeEmptyFolders(r){return r.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(r){const e=[];return r.width&&e.push(`width=${r.width}`),r.height&&e.push(`height=${r.height}`),r.resize&&e.push(`resize=${r.resize}`),r.format&&e.push(`format=${r.format}`),r.quality&&e.push(`quality=${r.quality}`),e.join("&")}};const La="2.99.0",_r={"X-Client-Info":`storage-js/${La}`};var za=class extends Kt{constructor(r,e={},n,s){const i=new URL(r);s!=null&&s.useNewHostname&&/supabase\.(co|in|red)$/.test(i.hostname)&&!i.hostname.includes("storage.supabase.")&&(i.hostname=i.hostname.replace("supabase.","storage.supabase."));const o=i.href.replace(/\/$/,""),a=W(W({},_r),e);super(o,a,n,"storage")}async listBuckets(r){var e=this;return e.handleOperation(async()=>{const n=e.listBucketOptionsToQueryString(r);return await xr(e.fetch,`${e.url}/bucket${n}`,{headers:e.headers})})}async getBucket(r){var e=this;return e.handleOperation(async()=>await xr(e.fetch,`${e.url}/bucket/${r}`,{headers:e.headers}))}async createBucket(r,e={public:!1}){var n=this;return n.handleOperation(async()=>await Ne(n.fetch,`${n.url}/bucket`,{id:r,name:r,type:e.type,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:n.headers}))}async updateBucket(r,e){var n=this;return n.handleOperation(async()=>await Tn(n.fetch,`${n.url}/bucket/${r}`,{id:r,name:r,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:n.headers}))}async emptyBucket(r){var e=this;return e.handleOperation(async()=>await Ne(e.fetch,`${e.url}/bucket/${r}/empty`,{},{headers:e.headers}))}async deleteBucket(r){var e=this;return e.handleOperation(async()=>await Hn(e.fetch,`${e.url}/bucket/${r}`,{},{headers:e.headers}))}listBucketOptionsToQueryString(r){const e={};return r&&("limit"in r&&(e.limit=String(r.limit)),"offset"in r&&(e.offset=String(r.offset)),r.search&&(e.search=r.search),r.s
35ortColumn&&(e.sortColumn=r.sortColumn),r.sortOrder&&(e.sortOrder=r.sortOrder)),Object.keys(e).length>0?"?"+new URLSearchParams(e).toString():""}},Ba=class extends Kt{constructor(r,e={},n){const s=r.replace(/\/$/,""),i=W(W({},_r),e);super(s,i,n,"storage")}async createBucket(r){var e=this;return e.handleOperation(async()=>await Ne(e.fetch,`${e.url}/bucket`,{name:r},{headers:e.headers}))}async listBuckets(r){var e=this;return e.handleOperation(async()=>{const n=new URLSearchParams;(r==null?void 0:r.limit)!==void 0&&n.set("limit",r.limit.toString()),(r==null?void 0:r.offset)!==void 0&&n.set("offset",r.offset.toString()),r!=null&&r.sortColumn&&n.set("sortColumn",r.sortColumn),r!=null&&r.sortOrder&&n.set("sortOrder",r.sortOrder),r!=null&&r.search&&n.set("search",r.search);const s=n.toString(),i=s?`${e.url}/bucket?${s}`:`${e.url}/bucket`;return await xr(e.fetch,i,{headers:e.headers})})}async deleteBucket(r){var e=this;return e.handleOperation(async()=>await Hn(e.fetch,`${e.url}/bucket/${r}`,{},{headers:e.headers}))}from(r){var e=this;if(!_a(r))throw new Gr("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 n=new ba({baseUrl:this.url,catalogName:r,auth:{type:"custom",getHeaders:async()=>e.headers},fetch:this.fetch}),s=this.shouldThrowOnError;return new Proxy(n,{get(i,o){const a=i[o];return typeof a!="function"?a:async(...l)=>{try{return{data:await a.apply(i,l),error:null}}catch(c){if(s)throw c;return{data:null,error:c}}}}})}},$a=class extends Kt{constructor(r,e={},n){const s=r.replace(/\/$/,""),i=W(W({},_r),{},{"Content-Type":"application/json"},e);super(s,i,n,"vectors")}async createIndex(r){var e=this;return e.handleOperation(async()=>await Le.post(e.fetch,`${e.url}/CreateIndex`,r,{headers:e.headers})||{})}async getIndex(r,e){var n=this;return n.handleOperation(async()=>await Le.post(n.fetch,`${n.url}/GetIndex`,{vectorBucketName:r,indexName:e},{headers:n.headers}))}async listIndexes(r){var e=this;return e.handleOperation(async()=>await Le.post(e.fetch,`${e.url}/ListIndexes`,r,{headers:e.headers}))}async deleteIndex(r,e){var n=this;return n.handleOperation(async()=>await Le.post(n.fetch,`${n.url}/DeleteIndex`,{vectorBucketName:r,indexName:e},{headers:n.headers})||{})}},Da=class extends Kt{constructor(r,e={},n){const s=r.replace(/\/$/,""),i=W(W({},_r),{},{"Content-Type":"application/json"},e);super(s,i,n,"vectors")}async putVectors(r){var e=this;if(r.vectors.length<1||r.vectors.length>500)throw new Error("Vector batch size must be between 1 and 500 items");return e.handleOperation(async()=>await Le.post(e.fetch,`${e.url}/PutVectors`,r,{headers:e.headers})||{})}async getVectors(r){var e=this;return e.handleOperation(async()=>await Le.post(e.fetch,`${e.url}/GetVectors`,r,{headers:e.headers}))}async listVectors(r){var e=this;if(r.segmentCount!==void 0){if(r.segmentCount<1||r.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");if(r.segmentIndex!==void 0&&(r.segmentIndex<0||r.segmentIndex>=r.segmentCount))throw new Error(`segmentIndex must be between 0 and ${r.segmentCount-1}`)}return e.handleOperation(async()=>await Le.post(e.fetch,`${e.url}/ListVectors`,r,{headers:e.headers}))}async queryVectors(r){var e=this;return e.handleOperation(async()=>await Le.post(e.fetch,`${e.url}/QueryVectors`,r,{headers:e.headers}))}async deleteVectors(r){var e=this;if(r.keys.length<1||r.keys.length>500)throw new Error("Keys batch size must be between 1 and 500 items");return e.handleOperation(async()=>await Le.post(e.fetch,`${e.url}/DeleteVectors`,r,{headers:e.headers})||{})}},Ua=class extends Kt{constructor(r,e={},n){const s=r.replace(/\/$/,""),i=W(W({},_r),{},{"Content-Type":"application/json"},e);super(s,i,n,"vectors")}async createBucket(r){var e=this;return e.handleOperation(async()=>await Le.post(e.fetch,`${e.url}/CreateVectorBucket`,{vectorBucketName:r},{headers:e.headers})||{})}async getBucket(r){var e=this;return e.handleOperation(async()=>await Le.post(e.fetch,`${e.url}/GetVectorBucket`,{vectorBucketName:r},{headers:e.headers}))}async listBuckets(r={}){var e=this;return e.handleOperation(async()=>await Le.post(e.fetch,`${e.url}/ListVectorBuckets`,r,{headers:e.headers}))}async deleteBucket(r){var e=this;return e.handleOperation(async()=>await Le.post(e.fetch,`${e.url}/DeleteVectorBucket`,{vectorBucketName:r},{headers:e.headers})||{})}},Ma=class extends Ua{constructor(r,e={}){super(r,e.headers||{},e.fetch)}from(r){return new Wa(this.url,this.headers,r,this.fetch)}async createBucket(r){var e=()=>super.createBucket,n=this;return e().call(n,r)}async getBucket(r){var e=()=>super.getBucket,n=this;return e().call(n,r)}async listBuckets(r={}){var e=()=>super.listBuckets,n=this;return e().call(n,r)}async deleteBucket(r){var e=()=>super.deleteBucket,n=this;return e().call(n,r)}},Wa=class extends $a{constructor(r,e,n,s){super(r,e,s),this.vectorBucketName=n}async createIndex(r){var e=()=>super.createIndex,n=this;return e().call(n,W(W({},r),{},{vectorBucketName:n.vectorBucketName}))}async listIndexes(r={}){var e=()=>super.listIndexes,n=this;return e().call(n,W(W({},r),{},{vectorBucketName:n.vectorBucketName}))}async getIndex(r){var e=()=>super.getIndex,n=this;return e().call(n,n.vectorBucketName,r)}async deleteIndex(r){var e=()=>super.deleteIndex,n=this;return e().call(n,n.vectorBucketName,r)}index(r){return new Na(this.url,this.headers,this.vectorBucketName,r,this.fetch)}},Na=class extends Da{constructor(r,e,n,s,i){super(r,e,i),this.vectorBucketName=n,this.indexName=s}async putVectors(r){var e=()=>super.putVectors,n=this;return e().call(n,W(W({},r),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}async getVectors(r){var e=()=>super.getVectors,n=this;return e().call(n,W(W({},r),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}async listVectors(r={}){var e=()=>super.listVectors,n=this;return e().call(n,W(W({},r),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}async queryVectors(r){var e=()=>super.queryVectors,n=this;return e().call(n,W(W({},r),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}async deleteVectors(r){var e=()=>super.deleteVectors,n=this;return e().call(n,W(W({},r),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}},Fa=class extends za{constructor(r,e={},n,s){super(r,e,n,s)}from(r){return new Oa(this.url,this.headers,r,this.fetch)}get vectors(){return new Ma(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new Ba(this.url+"/iceberg",this.headers,this.fetch)}};const ui="2.99.0",Bt=30*1e3,In=3,cn=In*Bt,Ha="http://localhost:9999",Va="supabase.auth.token",qa={"X-Client-Info":`gotrue-js/${ui}`},Pn="X-Supabase-Api-Version",hi={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},Ka=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,Ja=600*1e3;
35class br extends Error{constructor(e,n,s){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=n,this.code=s}}function L(r){return typeof r=="object"&&r!==null&&"__isAuthError"in r}class Ga extends br{constructor(e,n,s){super(e,n,s),this.name="AuthApiError",this.status=n,this.code=s}}function Za(r){return L(r)&&r.name==="AuthApiError"}class _t extends br{constructor(e,n){super(e),this.name="AuthUnknownError",this.originalError=n}}class tt extends br{constructor(e,n,s,i){super(e,s,i),this.name=n,this.status=s}}class Oe extends tt{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function dn(r){return L(r)&&r.name==="AuthSessionMissingError"}class Rt extends tt{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class Ar extends tt{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class Rr extends tt{constructor(e,n=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=n}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}function Ya(r){return L(r)&&r.name==="AuthImplicitGrantRedirectError"}class ws extends tt{constructor(e,n=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=n}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class Xa extends tt{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 On extends tt{constructor(e,n){super(e,"AuthRetryableFetchError",n,void 0)}}function un(r){return L(r)&&r.name==="AuthRetryableFetchError"}class _s extends tt{constructor(e,n,s){super(e,"AuthWeakPasswordError",n,"weak_password"),this.reasons=s}}class Ln extends tt{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}const Ur="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),js=` 36\r=`.split(""),Qa=(()=>{const r=new Array(128);for(let e=0;e<r.length;e+=1)r[e]=-1;for(let e=0;e<js.length;e+=1)r[js[e].charCodeAt(0)]=-2;for(let e=0;e<Ur.length;e+=1)r[Ur[e].charCodeAt(0)]=e;return r})();function Ss(r,e,n){if(r!==null)for(e.queue=e.queue<<8|r,e.queuedBits+=8;e.queuedBits>=6;){const s=e.queue>>e.queuedBits-6&63;n(Ur[s]),e.queuedBits-=6}else if(e.queuedBits>0)for(e.queue=e.queue<<6-e.queuedBits,e.queuedBits=6;e.queuedBits>=6;){const s=e.queue>>e.queuedBits-6&63;n(Ur[s]),e.queuedBits-=6}}function fi(r,e,n){const s=Qa[r];if(s>-1)for(e.queue=e.queue<<6|s,e.queuedBits+=6;e.queuedBits>=8;)n(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else{if(s===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(r)}"`)}}function ks(r){const e=[],n=a=>{e.push(String.fromCodePoint(a))},s={utf8seq:0,codepoint:0},i={queue:0,queuedBits:0},o=a=>{rl(a,s,n)};for(let a=0;a<r.length;a+=1)fi(r.charCodeAt(a),i,o);return e.join("")}function el(r,e){if(r<=127){e(r);return}else if(r<=2047){e(192|r>>6),e(128|r&63);return}else if(r<=65535){e(224|r>>12),e(128|r>>6&63),e(128|r&63);return}else if(r<=1114111){e(240|r>>18),e(128|r>>12&63),e(128|r>>6&63),e(128|r&63);return}throw new Error(`Unrecognized Unicode codepoint: ${r.toString(16)}`)}function tl(r,e){for(let n=0;n<r.length;n+=1){let s=r.charCodeAt(n);if(s>55295&&s<=56319){const i=(s-55296)*1024&65535;s=(r.charCodeAt(n+1)-56320&65535|i)+65536,n+=1}el(s,e)}}function rl(r,e,n){if(e.utf8seq===0){if(r<=127){n(r);return}for(let s=1;s<6;s+=1)if((r>>7-s&1)===0){e.utf8seq=s;break}if(e.utf8seq===2)e.codepoint=r&31;else if(e.utf8seq===3)e.codepoint=r&15;else if(e.utf8seq===4)e.codepoint=r&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1}else if(e.utf8seq>0){if(r<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|r&63,e.utf8seq-=1,e.utf8seq===0&&n(e.codepoint)}}function Ht(r){const e=[],n={queue:0,queuedBits:0},s=i=>{e.push(i)};for(let i=0;i<r.length;i+=1)fi(r.charCodeAt(i),n,s);return new Uint8Array(e)}function nl(r){const e=[];
36return tl(r,n=>e.push(n)),new Uint8Array(e)}function jt(r){const e=[],n={queue:0,queuedBits:0},s=i=>{e.push(i)};return r.forEach(i=>Ss(i,n,s)),Ss(null,n,s),e.join("")}function sl(r){return Math.round(Date.now()/1e3)+r}function il(){return Symbol("auth-callback")}const je=()=>typeof window<"u"&&typeof document<"u",pt={tested:!1,writable:!1},pi=()=>{if(!je())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(pt.tested)return pt.writable;const r=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(r,r),globalThis.localStorage.removeItem(r),pt.tested=!0,pt.writable=!0}catch{pt.tested=!0,pt.writable=!1}return pt.writable};function ol(r){const e={},n=new URL(r);if(n.hash&&n.hash[0]==="#")try{new URLSearchParams(n.hash.substring(1)).forEach((i,o)=>{e[o]=i})}catch{}return n.searchParams.forEach((s,i)=>{e[i]=s}),e}const gi=r=>r?(...e)=>r(...e):(...e)=>fetch(...e),al=r=>typeof r=="object"&&r!==null&&"status"in r&&"ok"in r&&"json"in r&&typeof r.json=="function",$t=async(r,e,n)=>{await r.setItem(e,JSON.stringify(n))},gt=async(r,e)=>{const n=await r.getItem(e);if(!n)return null;try{return JSON.parse(n)}catch{return n}},we=async(r,e)=>{await r.removeItem(e)};class Yr{constructor(){this.promise=new Yr.promiseConstructor((e,n)=>{this.resolve=e,this.reject=n})}}Yr.promiseConstructor=Promise;function Tr(r){const e=r.split(".");if(e.length!==3)throw new Ln("Invalid JWT structure");for(let s=0;s<e.length;s++)if(!Ka.test(e[s]))throw new Ln("JWT not in base64url format");return{header:JSON.parse(ks(e[0])),payload:JSON.parse(ks(e[1])),signature:Ht(e[2]),raw:{header:e[0],payload:e[1]}}}async function ll(r){return await new Promise(e=>{setTimeout(()=>e(null),r)})}function cl(r,e){return new Promise((s,i)=>{(async()=>{for(let o=0;o<1/0;o++)try{const a=await r(o);if(!e(o,null,a)){s(a);return}}catch(a){if(!e(o,a)){i(a);return}}})()})}function dl(r){return("0"+r.toString(16)).substr(-2)}function ul(){const e=new Uint32Array(56);if(typeof crypto>"u"){const n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",s=n.length;let i="";for(let o=0;o<56;o++)i+=n.charAt(Math.floor(Math.random()*s));return i}return crypto.getRandomValues(e),Array.from(e,dl).join("")}async function hl(r){const n=new TextEncoder().encode(r),s=await crypto.subtle.digest("SHA-256",n),i=new Uint8Array(s);return Array.from(i).map(o=>String.fromCharCode(o)).join("")}async function fl(r){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."),r;const n=await hl(r);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Tt(r,e,n=!1){const s=ul();let i=s;n&&(i+="/PASSWORD_RECOVERY"),await $t(r,`${e}-code-verifier`,i);const o=await fl(s);return[o,s===o?"plain":"s256"]}const pl=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function gl(r){const e=r.headers.get(Pn);if(!e||!e.match(pl))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function ml(r){if(!r)throw new Error("Missing exp claim");const e=Math.floor(Date.now()/1e3);if(r<=e)throw new Error("JWT has expired")}function yl(r){switch(r){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 xl=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function It(r){if(!xl.test(r))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function hn(){const r={};return new Proxy(r,{get:(e,n)=>{if(n==="__isUserNotAvailableProxy")return!0;if(typeof n=="symbol"){const s=n.toString();if(s==="Symbol(Symbol.toPrimitive)"||s==="Symbol(Symbol.toStringTag)"||s==="Symbol(util.inspect.custom)")return}throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${n}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,n)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${n}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,n)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${n}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function bl(r,e){return new Proxy(r,{get:(n,s,i)=>{if(s==="__isInsecureUserWarningProxy")return!0;
36if(typeof s=="symbol"){const o=s.toString();if(o==="Symbol(Symbol.toPrimitive)"||o==="Symbol(Symbol.toStringTag)"||o==="Symbol(util.inspect.custom)"||o==="Symbol(nodejs.util.inspect.custom)")return Reflect.get(n,s,i)}return!e.value&&typeof s=="string"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),e.value=!0),Reflect.get(n,s,i)}})}function Es(r){return JSON.parse(JSON.stringify(r))}const vt=r=>r.msg||r.message||r.error_description||r.error||JSON.stringify(r),vl=[502,503,504];async function Cs(r){var e;if(!al(r))throw new On(vt(r),0);if(vl.includes(r.status))throw new On(vt(r),r.status);let n;try{n=await r.json()}catch(o){throw new _t(vt(o),o)}let s;const i=gl(r);if(i&&i.getTime()>=hi["2024-01-01"].timestamp&&typeof n=="object"&&n&&typeof n.code=="string"?s=n.code:typeof n=="object"&&n&&typeof n.error_code=="string"&&(s=n.error_code),s){if(s==="weak_password")throw new _s(vt(n),r.status,((e=n.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(s==="session_not_found")throw new Oe}else if(typeof n=="object"&&n&&typeof n.weak_password=="object"&&n.weak_password&&Array.isArray(n.weak_password.reasons)&&n.weak_password.reasons.length&&n.weak_password.reasons.reduce((o,a)=>o&&typeof a=="string",!0))throw new _s(vt(n),r.status,n.weak_password.reasons);throw new Ga(vt(n),r.status||500,s)}const wl=(r,e,n,s)=>{const i={method:r,headers:(e==null?void 0:e.headers)||{}};return r==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e==null?void 0:e.headers),i.body=JSON.stringify(s),Object.assign(Object.assign({},i),n))};async function B(r,e,n,s){var i;const o=Object.assign({},s==null?void 0:s.headers);o[Pn]||(o[Pn]=hi["2024-01-01"].name),s!=null&&s.jwt&&(o.Authorization=`Bearer ${s.jwt}`);const a=(i=s==null?void 0:s.query)!==null&&i!==void 0?i:{};s!=null&&s.redirectTo&&(a.redirect_to=s.redirectTo);const l=Object.keys(a).length?"?"+new URLSearchParams(a).toString():"",c=await _l(r,e,n+l,{headers:o,noResolveJson:s==null?void 0:s.noResolveJson},{},s==null?void 0:s.body);return s!=null&&s.xform?s==null?void 0:s.xform(c):{data:Object.assign({},c),error:null}}async function _l(r,e,n,s,i,o){const a=wl(e,s,i,o);let l;try{l=await r(n,Object.assign({},a))}catch(c){throw console.error(c),new On(vt(c),0)}if(l.ok||await Cs(l),s!=null&&s.noResolveJson)return l;try{return await l.json()}catch(c){await Cs(c)}}function We(r){var e;let n=null;kl(r)&&(n=Object.assign({},r),r.expires_at||(n.expires_at=sl(r.expires_in)));const s=(e=r.user)!==null&&e!==void 0?e:r;return{data:{session:n,user:s},error:null}}function As(r){const e=We(r);return!e.error&&r.weak_password&&typeof r.weak_password=="object"&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.message&&typeof r.weak_password.message=="string"&&r.weak_password.reasons.reduce((n,s)=>n&&typeof s=="string",!0)&&(e.data.weak_password=r.weak_password),e}function ct(r){var e;return{data:{user:(e=r.user)!==null&&e!==void 0?e:r},error:null}}function jl(r){return{data:r,error:null}}function Sl(r){const{action_link:e,email_otp:n,hashed_token:s,redirect_to:i,verification_type:o}=r,a=Jr(r,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),l={action_link:e,email_otp:n,hashed_token:s,redirect_to:i,verification_type:o},c=Object.assign({},a);return{data:{properties:l,user:c},error:null}}function Rs(r){return r}function kl(r){return r.access_token&&r.refresh_token&&r.expires_in}const fn=["global","local","others"];class El{constructor({url:e="",headers:n={},fetch:s}){this.url=e,this.headers=n,this.fetch=gi(s),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)},this.customProviders={listProviders:this._listCustomProviders.bind(this),createProvider:this._createCustomProvider.bind(this),getProvider:this._getCustomProvider.bind(this),updateProvider:this._updateCustomProvider.bind(this),deleteProvider:this._deleteCustomProvider.bind(this)}}
vendor: 4,751 bytes, line 36
36async signOut(e,n=fn[0]){if(fn.indexOf(n)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${fn.join(", ")}`);try{return await B(this.fetch,"POST",`${this.url}/logout?scope=${n}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(s){if(L(s))return{data:null,error:s};throw s}}async inviteUserByEmail(e,n={}){try{return await B(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:n.data},headers:this.headers,redirectTo:n.redirectTo,xform:ct})}catch(s){if(L(s))return{data:{user:null},error:s};throw s}}async generateLink(e){try{const{options:n}=e,s=Jr(e,["options"]),i=Object.assign(Object.assign({},s),n);return"newEmail"in s&&(i.new_email=s==null?void 0:s.newEmail,delete i.newEmail),await B(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:i,headers:this.headers,xform:Sl,redirectTo:n==null?void 0:n.redirectTo})}catch(n){if(L(n))return{data:{properties:null,user:null},error:n};throw n}}async createUser(e){try{return await B(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:ct})}catch(n){if(L(n))return{data:{user:null},error:n};throw n}}async listUsers(e){var n,s,i,o,a,l,c;try{const d={nextPage:null,lastPage:0,total:0},u=await B(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(s=(n=e==null?void 0:e.page)===null||n===void 0?void 0:n.toString())!==null&&s!==void 0?s:"",per_page:(o=(i=e==null?void 0:e.perPage)===null||i===void 0?void 0:i.toString())!==null&&o!==void 0?o:""},xform:Rs});if(u.error)throw u.error;const f=await u.json(),p=(a=u.headers.get("x-total-count"))!==null&&a!==void 0?a:0,x=(c=(l=u.headers.get("link"))===null||l===void 0?void 0:l.split(","))!==null&&c!==void 0?c:[];return x.length>0&&(x.forEach(g=>{const v=parseInt(g.split(";")[0].split("=")[1].substring(0,1)),m=JSON.parse(g.split(";")[1].split("=")[1]);d[`${m}Page`]=v}),d.total=parseInt(p)),{data:Object.assign(Object.assign({},f),d),error:null}}catch(d){if(L(d))return{data:{users:[]},error:d};throw d}}async getUserById(e){It(e);try{return await B(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:ct})}catch(n){if(L(n))return{data:{user:null},error:n};throw n}}async updateUserById(e,n){It(e);try{return await B(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:n,headers:this.headers,xform:ct})}catch(s){if(L(s))return{data:{user:null},error:s};throw s}}async deleteUser(e,n=!1){It(e);try{return await B(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:n},xform:ct})}catch(s){if(L(s))return{data:{user:null},error:s};throw s}}async _listFactors(e){It(e.userId);try{const{data:n,error:s}=await B(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:i=>({data:{factors:i},error:null})});return{data:n,error:s}}catch(n){if(L(n))return{data:null,error:n};throw n}}async _deleteFactor(e){It(e.userId),It(e.id);try{return{data:await B(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(n){if(L(n))return{data:null,error:n};throw n}}async _listOAuthClients(e){var n,s,i,o,a,l,c;try{const d={nextPage:null,lastPage:0,total:0},u=await B(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(s=(n=e==null?void 0:e.page)===null||n===void 0?void 0:n.toString())!==null&&s!==void 0?s:"",per_page:(o=(i=e==null?void 0:e.perPage)===null||i===void 0?void 0:i.toString())!==null&&o!==void 0?o:""},xform:Rs});if(u.error)throw u.error;const f=await u.json(),p=(a=u.headers.get("x-total-count"))!==null&&a!==void 0?a:0,x=(c=(l=u.headers.get("link"))===null||l===void 0?void 0:l.split(","))!==null&&c!==void 0?c:[];return x.length>0&&(x.forEach(g=>{const v=parseInt(g.split(";")[0].split("=")[1].substring(0,1)),m=JSON.parse(g.split(";")[1].split("=")[1]);d[`${m}Page`]=v}),d.total=parseInt(p)),{data:Object.assign(Object.assign({},f),d),error:null}}catch(d){if(L(d))return{data:{clients:[]},error:d};throw d}}async _createOAuthClient(e){try{return await B(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if(L(n))return{data:null,error:n};throw n}}async _getOAuthClient(e){try{return await B(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if(L(n))return{data:null,error:n};throw n}}async _updateOAuthClient(e,n){try{return await B(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:n,headers:this.headers,xform:s=>({data:s,error:null})})}catch(s){if(L(s))return{data:null,error:s};throw s}}async _deleteOAuthClient(e){try{return await B(this.fetch,"DELET
36E",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(n){if(L(n))return{data:null,error:n};throw n}}async _regenerateOAuthClientSecret(e){try{return await B(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if(L(n))return{data:null,error:n};throw n}}async _listCustomProviders(e){try{const n={};return e!=null&&e.type&&(n.type=e.type),await B(this.fetch,"GET",`${this.url}/admin/custom-providers`,{headers:this.headers,query:n,xform:s=>{var i;return{data:{providers:(i=s==null?void 0:s.providers)!==null&&i!==void 0?i:[]},error:null}}})}catch(n){if(L(n))return{data:{providers:[]},error:n};throw n}}async _createCustomProvider(e){try{return await B(this.fetch,"POST",`${this.url}/admin/custom-providers`,{body:e,headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if(L(n))return{data:null,error:n};throw n}}async _getCustomProvider(e){try{return await B(this.fetch,"GET",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if(L(n))return{data:null,error:n};throw n}}async _updateCustomProvider(e,n){try{return await B(this.fetch,"PUT",`${this.url}/admin/custom-providers/${e}`,{body:n,headers:this.headers,xform:s=>({data:s,error:null})})}catch(s){if(L(s))return{data:null,error:s};throw s}}async _deleteCustomProvider(e){try{return await B(this.fetch,"DELETE",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(n){if(L(n))return{data:null,error:n};throw n}}}function Ts(r={}){return{getItem:e=>r[e]||null,setItem:(e,n)=>{r[e]=n},removeItem:e=>{delete r[e]}}}const Ze={debug:!!(globalThis&&pi()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class mi extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class Cl extends mi{}async function Al(r,e,n){Ze.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",r,e);const s=new globalThis.AbortController;e>0&&setTimeout(()=>{s.abort(),Ze.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",r)},e),await Promise.resolve();try{return await globalThis.navigator.locks.request(r,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:s.signal},async i=>{if(i){Ze.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",r,i.name);try{return await n()}finally{Ze.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",r,i.name)}}else{if(e===0)throw Ze.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",r),new Cl(`Acquiring an exclusive Navigator LockManager lock "${r}" immediately failed`);if(Ze.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"),await n()}})}catch(i){if((i==null?void 0:i.name)==="AbortError"&&e>0)return Ze.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire timeout, recovering by stealing lock",r),console.warn(`@supabase/gotrue-js: Lock "${r}" was not released within ${e}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(r,{mode:"exclusive",steal:!0},async o=>{if(o){Ze.debug&&console.log("@supabase/gotrue-js: navigatorLock: recovered (stolen)",r,o.name);try{return await n()}finally{Ze.debug&&console.log("@supabase/gotrue-js: navigatorLock: released (stolen)",r,o.name)}}else return console.warn("@supabase/gotrue-js: Navigator LockManager returned null lock even with steal: true"),await n()}));throw i}}function Rl(){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 yi(r){if(!/^0x[a-fA-F0-9]{40}$/.test(r))throw new Error(`@supabase/auth-js: Address "${r}
36" is invalid.`);return r.toLowerCase()}function Tl(r){return parseInt(r,16)}function Il(r){const e=new TextEncoder().encode(r);return"0x"+Array.from(e,s=>s.toString(16).padStart(2,"0")).join("")}function Pl(r){var e;const{chainId:n,domain:s,expirationTime:i,issuedAt:o=new Date,nonce:a,notBefore:l,requestId:c,resources:d,scheme:u,uri:f,version:p}=r;{if(!Number.isInteger(n))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${n}`);if(!s)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(a&&a.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${a}`);if(!f)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(!((e=r.statement)===null||e===void 0)&&e.includes(` 37`))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${r.statement}`)}const x=yi(r.address),g=u?`${u}://${s}`:s,v=r.statement?`${r.statement} 38`:"",m=`${g} wants you to sign in with your Ethereum account: 39${x} 40 41${v}`;let w=`URI: ${f} 42Version: ${p} 43Chain ID: ${n}${a?` 44Nonce: ${a}`:""} 45Issued At: ${o.toISOString()}`;if(i&&(w+=` 46Expiration Time: ${i.toISOString()}`),l&&(w+=` 47Not Before: ${l.toISOString()}`),c&&(w+=` 48Request ID: ${c}`),d){let _=` 49Resources:`;for(const b of d){if(!b||typeof b!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${b}`);_+=` 50- ${b}`}w+=_}return`${m} 51${w}`}class pe extends Error{constructor({message:e,code:n,cause:s,name:i}){var o;super(e,{cause:s}),this.__isWebAuthnError=!0,this.name=(o=i??(s instanceof Error?s.name:void 0))!==null&&o!==void 0?o:"Unknown Error",this.code=n}}class Mr extends pe{constructor(e,n){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n,message:e}),this.name="WebAuthnUnknownError",this.originalError=n}}function Ol({error:r,options:e}){var n,s,i;const{publicKey:o}=e;if(!o)throw Error("options was missing required publicKey property");if(r.name==="AbortError"){if(e.signal instanceof AbortSignal)return new pe({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:r})}else if(r.name==="ConstraintError"){if(((n=o.authenticatorSelection)===null||n===void 0?void 0:n.requireResidentKey)===!0)return new pe({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:r});if(e.mediation==="conditional"&&((s=o.authenticatorSelection)===null||s===void 0?void 0:s.userVerification)==="required")return new pe({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:r});if(((i=o.authenticatorSelection)===null||i===void 0?void 0:i.userVerification)==="required")return new pe({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:r})}else{if(r.name==="InvalidStateError")return new pe({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:r});if(r.name==="NotAllowedError")return new pe({message:r.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r});if(r.name==="NotSupportedError")return o.pubKeyCredParams.filter(l=>l.type==="public-key").length===0?new pe({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:r}):new pe({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:r});if(r.name==="SecurityError"){const a=window.location.hostname;if(xi(a)){if(o.rp.id!==a)return new pe({message:`The RP ID "${o.rp.id}
51" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:r})}else return new pe({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:r})}else if(r.name==="TypeError"){if(o.user.id.byteLength<1||o.user.id.byteLength>64)return new pe({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:r})}else if(r.name==="UnknownError")return new pe({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:r})}return new pe({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r})}function Ll({error:r,options:e}){const{publicKey:n}=e;if(!n)throw Error("options was missing required publicKey property");if(r.name==="AbortError"){if(e.signal instanceof AbortSignal)return new pe({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:r})}else{if(r.name==="NotAllowedError")return new pe({message:r.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r});if(r.name==="SecurityError"){const s=window.location.hostname;if(xi(s)){if(n.rpId!==s)return new pe({message:`The RP ID "${n.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:r})}else return new pe({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:r})}else if(r.name==="UnknownError")return new pe({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:r})}return new pe({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r})}class zl{createNewAbortSignal(){if(this.controller){const n=new Error("Cancelling existing WebAuthn API call for new one");n.name="AbortError",this.controller.abort(n)}const e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){const e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}}const Bl=new zl;function $l(r){if(!r)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(r);const{challenge:e,user:n,excludeCredentials:s}=r,i=Jr(r,["challenge","user","excludeCredentials"]),o=Ht(e).buffer,a=Object.assign(Object.assign({},n),{id:Ht(n.id).buffer}),l=Object.assign(Object.assign({},i),{challenge:o,user:a});if(s&&s.length>0){l.excludeCredentials=new Array(s.length);for(let c=0;c<s.length;c++){const d=s[c];l.excludeCredentials[c]=Object.assign(Object.assign({},d),{id:Ht(d.id).buffer,type:d.type||"public-key",transports:d.transports})}}return l}function Dl(r){if(!r)throw new Error("Credential request options are required");if(typeof PublicKeyCredential<"u"&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseRequestOptionsFromJSON=="function")return PublicKeyCredential.parseRequestOptionsFromJSON(r);const{challenge:e,allowCredentials:n}=r,s=Jr(r,["challenge","allowCredentials"]),i=Ht(e).buffer,o=Object.assign(Object.assign({},s),{challenge:i});if(n&&n.length>0){o.allowCredentials=new Array(n.length);for(let a=0;a<n.length;a++){const l=n[a];o.allowCredentials[a]=Object.assign(Object.assign({},l),{id:Ht(l.id).buffer,type:l.type||"public-key",transports:l.transports})}}return o}function Ul(r){var e;if("toJSON"in r&&typeof r.toJSON=="function")return r.toJSON();const n=r;return{id:r.id,rawId:r.id,response:{attestationObject:jt(new Uint8Array(r.response.attestationObject)),clientDataJSON:jt(new Uint8Array(r.response.clientDataJSON))},type:"public-key",clientExtensionResults:r.getClientExtensionResults(),authenticatorAttachment:(e=n.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function Ml(r){var e;if("toJSON"in r&&typeof r.toJSON=="function")return r.toJSON();const n=r,s=r.getClientExtensionResults(),i=r.response;return{id:r.id,rawId:r.id,response:{authenticatorData:jt(new Uint8Array(i.authenticatorData)),clientDataJSON:jt(new Uint8Array(i.clientDataJSON)),signature:jt(new Uint8Array(i.signature)),userHandle:i.userHandle?jt(new
51Uint8Array(i.userHandle)):void 0},type:"public-key",clientExtensionResults:s,authenticatorAttachment:(e=n.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function xi(r){return r==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(r)}function Is(){var r,e;return!!(je()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&typeof((r=navigator==null?void 0:navigator.credentials)===null||r===void 0?void 0:r.create)=="function"&&typeof((e=navigator==null?void 0:navigator.credentials)===null||e===void 0?void 0:e.get)=="function")}async function Wl(r){try{const e=await navigator.credentials.create(r);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Mr("Browser returned unexpected credential type",e)}:{data:null,error:new Mr("Empty credential response",e)}}catch(e){return{data:null,error:Ol({error:e,options:r})}}}async function Nl(r){try{const e=await navigator.credentials.get(r);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Mr("Browser returned unexpected credential type",e)}:{data:null,error:new Mr("Empty credential response",e)}}catch(e){return{data:null,error:Ll({error:e,options:r})}}}const Fl={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},Hl={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function Wr(...r){const e=i=>i!==null&&typeof i=="object"&&!Array.isArray(i),n=i=>i instanceof ArrayBuffer||ArrayBuffer.isView(i),s={};for(const i of r)if(i)for(const o in i){const a=i[o];if(a!==void 0)if(Array.isArray(a))s[o]=a;else if(n(a))s[o]=a;else if(e(a)){const l=s[o];e(l)?s[o]=Wr(l,a):s[o]=Wr(a)}else s[o]=a}return s}function Vl(r,e){return Wr(Fl,r,e||{})}function ql(r,e){return Wr(Hl,r,e||{})}class Kl{constructor(e){this.client=e,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(e){return this.client.mfa.enroll(Object.assign(Object.assign({},e),{factorType:"webauthn"}))}async _challenge({factorId:e,webauthn:n,friendlyName:s,signal:i},o){var a;try{const{data:l,error:c}=await this.client.mfa.challenge({factorId:e,webauthn:n});if(!l)return{data:null,error:c};const d=i??Bl.createNewAbortSignal();if(l.webauthn.type==="create"){const{user:u}=l.webauthn.credential_options.publicKey;if(!u.name){const f=s;if(f)u.name=`${u.id}:${f}`;else{const x=(await this.client.getUser()).data.user,g=((a=x==null?void 0:x.user_metadata)===null||a===void 0?void 0:a.name)||(x==null?void 0:x.email)||(x==null?void 0:x.id)||"User";u.name=`${u.id}:${g}`}}u.displayName||(u.displayName=u.name)}switch(l.webauthn.type){case"create":{const u=Vl(l.webauthn.credential_options.publicKey,o==null?void 0:o.create),{data:f,error:p}=await Wl({publicKey:u,signal:d});return f?{data:{factorId:e,challengeId:l.id,webauthn:{type:l.webauthn.type,credential_response:f}},error:null}:{data:null,error:p}}case"request":{const u=ql(l.webauthn.credential_options.publicKey,o==null?void 0:o.request),{data:f,error:p}=await Nl(Object.assign(Object.assign({},l.webauthn.credential_options),{publicKey:u,signal:d}));return f?{data:{factorId:e,challengeId:l.id,webauthn:{type:l.webauthn.type,credential_response:f}},error:null}:{data:null,error:p}}}}catch(l){return L(l)?{data:null,error:l}:{data:null,error:new _t("Unexpected error in challenge",l)}}}async _verify({challengeId:e,factorId:n,webauthn:s}){return this.client.mfa.verify({factorId:n,challengeId:e,webauthn:s})}async _authenticate({factorId:e,webauthn:{rpId:n=typeof window<"u"?window.location.hostname:void 0,rpOrigins:s=typeof window<"u"?[window.location.origin]:void 0,signal:i}={}},o){if(!n)return{data:null,error:new br("rpId is required for WebAuthn authentication")};try{if(!Is())return{data:null,error:new _t("Browser does not support WebAuthn",null)};const{data:a,error:l}=await this.challenge({factorId:e,webauthn:{rpId:n,rpOrigins:s},signal:i},{request:o});if(!a)return{data:null,error:l};const{webauthn:c}=a;return this._verify({factorId:e,challengeId:a.challengeId,webauthn:{type:c.type,rpId:n,rpOrigins:s,credential_response:c.credential_response}})}catch(a){return L(a)?{data:null,error:a}:{data:null,error:new _t("Unexpected error in authenticate",a)}}}async _register({friendlyName:e,webauthn:{rpId:n=typeof window<"u"?window.location.hostname:void 0,rpOrigins:s=typeof window<"u"?[window.location.origin]:void 0,signal:i}={}},o){if(!n)return{data:null,error:new br("rpId is required for WebAuthn registration")};try{if(!Is())return{data:null,error:new _t("Browser does not support WebAuthn",null)};const{data:a,error:l}=await this._enroll({friendlyName:e});if(!a)return await this.client.mfa.listFactors().then(u=>{var f;return(f=u.data)===null||f===void 0?void 0:f.all.find(p=>p.factor_type==="webauthn"&&p.friendly_name===e&&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:a.id,friendlyName:a.friendly_name,webauthn:{rpId:n,rpOrigins:s},signal:i},{create:o});return c?this._verify({factorId:a.id,challengeId:c.challengeId,webauthn:{rpId:n,rpOrigins:s,type:c.webauthn.type,credential_response:c.webauthn.credential_response}}):{data:null,error:d}}catch(a){return L(a)?{data:null,error:a}:{data:null,error:new _t("Unexpected error in register",a)}}}}Rl();const Jl={url:Ha,storageKey:Va,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:qa,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1};async function Ps(r,e,n){return await n()}const Pt={};class vr{get jwks(){var e,n;return(n=(e=Pt[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&n!==void 0?n:{keys:[]}}set jwks(e){Pt[this.storageKey]=Object.assign(Object.assign({},Pt[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,n;return(n=(e=Pt[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&n!==void 0?n:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){Pt[this.storageKey]=Object.assign(Object.assign({},Pt[this.storageKey]),{cachedAt:e})}constructor(e){var n,s,i;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;const o=Object.assign(Object.assign({},Jl),e);if(this.storageKey=o.storageKey,this.instanceID=(n=vr.nextInstanceID[this.storageKey])!==null&&n!==void 0?n:0,vr.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!o.debug,typeof o.debug=="function"&&(this.logger=o.debug),this.instanceID>0&&je()){const a=`${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`;console.warn(a),this.logDebugMessages&&console.trace(a)}if(this.persistSession=o.persistSession,this.autoRefreshToken=o.autoRefreshToken,this.admin=new El({url:o.url,headers:o.headers,fetch:o.fetch}),this.url=o.url,this.headers=o.headers,this.fetch=gi(o.fetch),this.lock=o.lock||Ps,this.detectSessionInUrl=o.detectSessionInUrl,this.flowType=o.flowType,this.hasCustomAuthorizationHeader=o.hasCustomAuthorizationHeader,this.throwOnError=o.throwOnError,this.lockAcquireTimeout=o.lockAcquireTimeout,o.lock?this.lock=o.lock:this.persistSession&&je()&&(!((s=globalThis==null?void 0:globalThis.navigator)===null||s===void 0)&&s.locks)?this.lock=Al:this.lock=Ps,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 Kl(this)}
51,this.oauth={getAuthorizationDetails:this._getAuthorizationDetails.bind(this),approveAuthorization:this._approveAuthorization.bind(this),denyAuthorization:this._denyAuthorization.bind(this),listGrants:this._listOAuthGrants.bind(this),revokeGrant:this._revokeOAuthGrant.bind(this)},this.persistSession?(o.storage?this.storage=o.storage:pi()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=Ts(this.memoryStorage)),o.userStorage&&(this.userStorage=o.userStorage)):(this.memoryStorage={},this.storage=Ts(this.memoryStorage)),je()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(a){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",a)}(i=this.broadcastChannel)===null||i===void 0||i.addEventListener("message",async a=>{this._debug("received broadcast notification from other tab or client",a);try{await this._notifyAllSubscribers(a.data.event,a.data.session,!1)}catch(l){this._debug("#broadcastChannel","error",l)}})}o.skipAutoInitialize||this.initialize().catch(a=>{this._debug("#initialize()","error",a)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${ui}) ${new Date().toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),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 e;try{let n={},s="none";if(je()&&(n=ol(window.location.href),this._isImplicitGrantCallback(n)?s="implicit":await this._isPKCECallback(n)&&(s="pkce")),je()&&this.detectSessionInUrl&&s!=="none"){const{data:i,error:o}=await this._getSessionFromURL(n,s);if(o){if(this._debug("#_initialize()","error detecting session from URL",o),Ya(o)){const c=(e=o.details)===null||e===void 0?void 0:e.code;if(c==="identity_already_exists"||c==="identity_not_found"||c==="single_identity_not_deletable")return{error:o}}return{error:o}}const{session:a,redirectType:l}=i;return this._debug("#_initialize()","detected session in URL",a,"redirect type",l),await this._saveSession(a),setTimeout(async()=>{l==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",a):await this._notifyAllSubscribers("SIGNED_IN",a)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(n){return L(n)?this._returnResult({error:n}):this._returnResult({error:new _t("Unexpected error during initialization",n)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var n,s,i;try{const o=await B(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(s=(n=e==null?void 0:e.options)===null||n===void 0?void 0:n.data)!==null&&s!==void 0?s:{},gotrue_meta_security:{captcha_token:(i=e==null?void 0:e.options)===null||i===void 0?void 0:i.captchaToken}},xform:We}),{data:a,error:l}=o;if(l||!a)return this._returnResult({data:{user:null,session:null},error:l});const c=a.session,d=a.user;return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",c)),this._returnResult({data:{user:d,session:c},error:null})}catch(o){if(L(o))return this._returnResult({data:{user:null,session:null},error:o});throw o}}async signUp(e){var n,s,i;try{let o;if("email"in e){const{email:u,password:f,options:p}=e;let x=null,g=null;this.flowType==="pkce"&&([x,g]=await Tt(this.storage,this.storageKey)),o=await B(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:p==null?void 0:p.emailRedirectTo,body:{email:u,password:f,data:(n=p==null?void 0:p.data)!==null&&n!==void 0?n:{},gotrue_meta_security:{captcha_token:p==null?void 0:p.captchaToken},code_challenge:x,code_challenge_method:g},xform:We})}else if("phone"in e){const{phone:u,password:f,options:p}=e;o=await B(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:u,password:f,data:(s=p==null?void 0:p.data)!==null&&s!==void 0?s:{},channel:(i=p==null?void 0:p.channel)!==null&&i!==void 0?i:"sms",gotrue_meta_security:{captcha_token:p==null?void 0:p.captchaToken}},xform:We})}else throw new Ar("You must provide either an email or phone number and a password");const{data:a,error:l}=o;if(l||!a)return await we(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:l});const c=a.session,d=a.user;return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",c)),this._returnResult({data:{user:d,session:c},error:null})}catch(o){if(await we(this.storage,`${this.storageKey}-code-verifier`),L(o))return this._returnResult({data:{user:null,session:null},error:o});throw o}}async signInWithPassword(e){try{let n;if("email"in e){const{email:o,password:a,options:l}=e;n=await B(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:o,password:a,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken}},xform:As})}else if("phone"in e){const{phone:o,password:a,options:l}=e;n=await B(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:o,password:a,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken}},xform:As})}else throw new Ar("You must provide either an email or phone number and a password");const{data:s,error:i}=n;if(i)return this._returnResult({data:{user:null,session:null},error:i});if(!s||!s.session||!s.user){const o=new Rt;return this._returnResult({data:{user:null,session:null},error:o})}return s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),this._returnResult({data:Object.assign({user:s.user,session:s.session},s.weak_password?{weakPassword:s.weak_password}:null),error:i})}catch(n){if(L(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async signInWithOAuth(e){var n,s,i,o;return await this._handleProviderSignIn(e.provider,{redirectTo:(n=e.options)===null||n===void 0?void 0:n.redirectTo,scopes:(s=e.options)===null||s===void 0?void 0:s.scopes,queryParams:(i=e.options)===null||i===void 0?void 0:i.queryParams,skipBrowserRedirect:(o=e.options)===null||o===void 0?void 0:o.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){const{chain:n}=e;switch(n){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw new Error(`@supabase/auth-js: Unsupported chain "${n}"`)}}async signInWithEthereum(e){var n,s,i,o,a,l,c,d,u,f,p;let x,g;if("message"in e)x=e.message,g=e.signature;else{const{chain:v,wallet:m,statement:w,options:_}=e;let b;if(je())if(typeof m=="object")b=m;else{const C=window;if("ethereum"in C&&typeof C.ethereum=="object"&&"request"in C.ethereum&&typeof C.ethereum.request=="function")b=C.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 m!="object"||!(_!=null&&_.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");b=m}const y=new URL((n=_==null?void 0:_.url)!==null&&n!==void 0?n:window.location.href),k=await b.request({method:"eth_requestAccounts"}).then(C=>C).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!k||k.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");const S=yi(k[0]);let T=(s=_==null?void 0:_.signInWithEthereum)===null||s===void 0?void 0:s.chainId;if(!T){const C=await b.request({method:"eth_chainId"});T=Tl(C)}const V={domain:y.host,address:S,statement:w,uri:y.href,version:"1",chainId:T,nonce:(i=_==null?void 0:_.signInWithEthereum)===null||i===void 0?void 0:i.nonce,issuedAt:(a=(o=_==null?void 0:_.signInWithEthereum)===null||o===void 0?void 0:o.issuedAt)!==null&&a!==void 0?a:new Date,expirationTime:(l=_==null?void 0:_.signInWithEthereum)===null||l===void 0?void 0:l.expirationTime,notBefore:(c=_==null?void 0:_.signInWithEthereum)===null||c===void 0?void 0:c.notBefore,requestId:(d=_==null?void 0:_.signInWithEthereum)===null||d===void 0?void 0:d.requestId,resources:(u=_==null?void 0:_.signInWithEthereum)===null||u===void 0?void 0:u.resources};x=Pl(V),g=await b.request({method:"personal_sign",params:[Il(x),S]})}try{const{data:v,error:m}=await B(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:x,signature:g},!((f=e.options)===null||f===void 0)&&f.captchaToken?{gotrue_meta_security:{captcha_token:(p=e.options)===null||p===void 0?void 0:p.captchaToken}}:null),xform:We});if(m)throw m;if(!v||!v.session||!v.user){const w=new Rt;return this._returnResult({data:{user:null,session:null},error:w})}return v.session&&(await this._saveSession(v.session),await this._notifyAllSubscribers("SIGNED_IN",v.session)),this._returnResult({data:Object.assign({},v),error:m})}catch(v){if(L(v))return this._returnResult({data:{user:null,session:null},error:v});throw v}}async signInWithSolana(e){var n,s,i,o,a,l,c,d,u,f,p,x;let g,v;if("message"in e)g=e.message,v=e.signature;else{const{chain:m,wallet:w,statement:_,options:b}=e;let y;if(je())if(typeof w=="object")y=w;else{const S=window;if("solana"in S&&typeof S.solana=="object"&&("signIn"in S.solana&&typeof S.solana.signIn=="function"||"signMessage"in S.solana&&typeof S.solana.signMessage=="function"))y=S.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 w!="object"||!(b!=null&&b.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");y=w}const k=new URL((n=b==null?void 0:b.url)!==null&&n!==void 0?n:window.location.href);if("signIn"in y&&y.signIn){const S=await y.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},b==null?void 0:b.signInWithSolana),{version:"1",domain:k.host,uri:k.href}),_?{statement:_}:null));let T;if(Array.isArray(S)&&S[0]&&typeof S[0]=="object")T=S[0];else if(S&&typeof S=="object"&&"signedMessage"in S&&"signature"in S)T=S;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in T&&"signature"in T&&(typeof T.signedMessage=="string"||T.signedMessage instanceof Uint8Array)&&T.signature instanceof Uint8Array)g=typeof T.signedMessage=="string"?T.signedMessage:new TextDecoder().decode(T.signedMessage),v=T.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in y)||typeof y.signMessage!="function"||!("publicKey"in y)||typeof y!="object"||!y.publicKey||!("toBase58"in y.publicKey)||typeof y.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");g=[`${k.host} wants you to sign in with your Solana account:`,y.publicKey.toBase58(),..._?["",_,""]:[""],"Version: 1",`URI: ${k.href}`,`Issued At: ${(i=(s=b==null?void 0:b.signInWithSolana)===null||s===void 0?void 0:s.issuedAt)!==null&&i!==void 0?i:new Date().toISOString()}`,...!((o=b==null?void 0:b.signInWithSolana)===null||o===void 0)&&o.notBefore?[`Not Before: ${b.signInWithSolana.notBefore}`]:[],...!((a=b==null?void 0:b.signInWithSolana)===null||a===void 0)&&a.expirationTime?[`Expiration Time: ${b.signInWithSolana.expirationTime}`]:[],...!((l=b==null?void 0:b.signInWithSolana)===null||l===void 0)&&l.chainId?[`Chain ID: ${b.signInWithSolana.chainId}`]:[],...!((c=b==null?void 0:b.signInWithSolana)===null||c===void 0)&&c.nonce?[`Nonce: ${b.signInWithSolana.nonce}`]:[],...!((d=b==null?void 0:b.signInWithSolana)===null||d===void 0)&&d.requestId?[`Request ID: ${b.signInWithSolana.requestId}`]:[],...!((f=(u=b==null?void 0:b.signInWithSolana)===null||u===void 0?void 0:u.resources)===null||f===void 0)&&f.length?["Resources",...b.signInWithSolana.resources.map(T=>`- ${T}`)]:[]].join(` 52`);const S=await y.signMessage(new TextEncoder().encode(g),"utf8");if(!S||!(S instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");v=S}}try{const{data:m,error:w}=await B(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:g,signature:jt(v)},!((p=e.options)===null||p===void 0)&&p.captchaToken?{gotrue_meta_security:{captcha_token:(x=e.options)===null||x===void 0?void 0:x.captchaToken}}:null),xform:We});if(w)throw w;if(!m||!m.session||!m.user){const _=new Rt;return this._returnResult({data:{user:null,session:null},error:_})}return m.session&&(await this._saveSession(m.session),await this._notifyAllSubscribers("SIGNED_IN",m.session)),this._returnResult({data:Object.assign({},m),error:w})}catch(m){if(L(m))return this._returnResult({data:{user:null,session:null},error:m});throw m}}async _exchangeCodeForSession(e){const n=await gt(this.storage,`${this.storageKey}-code-verifier`),[s,i]=(n??"").split("/");try{if(!s&&this.flowType==="pkce")throw new Xa;const{data:o,error:a}=await B(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:s},xform:We});if(await we(this.storage,`${this.storageKey}-code-verifier`),a)throw a;if(!o||!o.session||!o.user){const l=new Rt;return this._returnResult({data:{user:null,session:null,redirectType:null},error:l})}return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",o.session)),this._returnResult({data:Object.assign(Object.assign({},o),{redirectType:i??null}),error:a})}catch(o){if(await we(this.storage,`${this.storageKey}-code-verifier`),L(o))return this._returnResult({data:{user:null,session:null,redirectType:null},error:o});throw o}}async signInWithIdToken(e){try{const{options:n,provider:s,token:i,access_token:o,nonce:a}=e,l=await B(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:s,id_token:i,access_token:o,nonce:a,gotrue_meta_security:{captcha_token:n==null?void 0:n.captchaToken}},xform:We}),{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 Rt;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(n){if(L(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async signInWithOtp(e){var n,s,i,o,a;try{if("email"in e){const{email:l,options:c}=e;let d=null,u=null;this.flowType==="pkce"&&([d,u]=await Tt(this.storage,this.storageKey));const{error:f}=await B(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:l,data:(n=c==null?void 0:c.data)!==null&&n!==void 0?n:{},create_user:(s=c==null?void 0:c.shouldCreateUser)!==null&&s!==void 0?s:!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:f})}if("phone"in e){const{phone:l,options:c}=e,{data:d,error:u}=await B(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:l,data:(i=c==null?void 0:c.data)!==null&&i!==void 0?i:{},create_user:(o=c==null?void 0:c.shouldCreateUser)!==null&&o!==void 0?o:!0,gotrue_meta_security:{captcha_token:c==null?void
520:c.captchaToken},channel:(a=c==null?void 0:c.channel)!==null&&a!==void 0?a:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:d==null?void 0:d.message_id},error:u})}throw new Ar("You must provide either an email or phone number.")}catch(l){if(await we(this.storage,`${this.storageKey}-code-verifier`),L(l))return this._returnResult({data:{user:null,session:null},error:l});throw l}}async verifyOtp(e){var n,s;try{let i,o;"options"in e&&(i=(n=e.options)===null||n===void 0?void 0:n.redirectTo,o=(s=e.options)===null||s===void 0?void 0:s.captchaToken);const{data:a,error:l}=await B(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:o}}),redirectTo:i,xform:We});if(l)throw l;if(!a)throw new Error("An error occurred on token verification.");const c=a.session,d=a.user;return c!=null&&c.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),this._returnResult({data:{user:d,session:c},error:null})}catch(i){if(L(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signInWithSSO(e){var n,s,i,o,a;try{let l=null,c=null;this.flowType==="pkce"&&([l,c]=await Tt(this.storage,this.storageKey));const d=await B(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(s=(n=e.options)===null||n===void 0?void 0:n.redirectTo)!==null&&s!==void 0?s:void 0}),!((i=e==null?void 0:e.options)===null||i===void 0)&&i.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:l,code_challenge_method:c}),headers:this.headers,xform:jl});return!((o=d.data)===null||o===void 0)&&o.url&&je()&&!(!((a=e.options)===null||a===void 0)&&a.skipBrowserRedirect)&&window.location.assign(d.data.url),this._returnResult(d)}catch(l){if(await we(this.storage,`${this.storageKey}-code-verifier`),L(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 e=>{const{data:{session:n},error:s}=e;if(s)throw s;if(!n)throw new Oe;const{error:i}=await B(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:n.access_token});return this._returnResult({data:{user:null,session:null},error:i})})}catch(e){if(L(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{const n=`${this.url}/resend`;if("email"in e){const{email:s,type:i,options:o}=e,{error:a}=await B(this.fetch,"POST",n,{headers:this.headers,body:{email:s,type:i,gotrue_meta_security:{captcha_token:o==null?void 0:o.captchaToken}},redirectTo:o==null?void 0:o.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:a})}else if("phone"in e){const{phone:s,type:i,options:o}=e,{data:a,error:l}=await B(this.fetch,"POST",n,{headers:this.headers,body:{phone:s,type:i,gotrue_meta_security:{captcha_token:o==null?void 0:o.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:a==null?void 0:a.message_id},error:l})}throw new Ar("You must provide either an email or phone number and a type")}catch(n){if(L(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async getSession(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async n=>n))}async _acquireLock(e,n){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){const s=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),i=(async()=>(await s,await n()))();return this.pendingInLock.push((async()=>{try{await i}catch{}})()),i}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const s=n();for(this.pendingInLock.push((async()=>{try{await s}catch{}})()),await s;this.pendingInLock.length;){const i=[...this.pendingInLock];await Promise.all(i),this.pendingInLock.splice(0,i.length)}return await s}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{const n=await this.__loadSession();return await e(n)}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 e=null;const n=await gt(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",n),n!==null&&(this._isValidSession(n)?e=n:(this._debug("#getSession()","session from storage is not val
52id"),await this._removeSession())),!e)return{data:{session:null},error:null};const s=e.expires_at?e.expires_at*1e3-Date.now()<cn:!1;if(this._debug("#__loadSession()",`session has${s?"":" not"} expired`,"expires_at",e.expires_at),!s){if(this.userStorage){const a=await gt(this.userStorage,this.storageKey+"-user");a!=null&&a.user?e.user=a.user:e.user=hn()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){const a={value:this.suppressGetSessionWarning};e.user=bl(e.user,a),a.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}const{data:i,error:o}=await this._callRefreshToken(e.refresh_token);return o?this._returnResult({data:{session:null},error:o}):this._returnResult({data:{session:i},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;const n=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser());return n.data.user&&(this.suppressGetSessionWarning=!0),n}async _getUser(e){try{return e?await B(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:ct}):await this._useSession(async n=>{var s,i,o;const{data:a,error:l}=n;if(l)throw l;return!(!((s=a.session)===null||s===void 0)&&s.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new Oe}:await B(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(o=(i=a.session)===null||i===void 0?void 0:i.access_token)!==null&&o!==void 0?o:void 0,xform:ct})})}catch(n){if(L(n))return dn(n)&&(await this._removeSession(),await we(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:n});throw n}}async updateUser(e,n={}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,n))}async _updateUser(e,n={}){try{return await this._useSession(async s=>{const{data:i,error:o}=s;if(o)throw o;if(!i.session)throw new Oe;const a=i.session;let l=null,c=null;this.flowType==="pkce"&&e.email!=null&&([l,c]=await Tt(this.storage,this.storageKey));const{data:d,error:u}=await B(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:n==null?void 0:n.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:l,code_challenge_method:c}),jwt:a.access_token,xform:ct});if(u)throw u;return a.user=d.user,await this._saveSession(a),await this._notifyAllSubscribers("USER_UPDATED",a),this._returnResult({data:{user:a.user},error:null})})}catch(s){if(await we(this.storage,`${this.storageKey}-code-verifier`),L(s))return this._returnResult({data:{user:null},error:s});throw s}}async setSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new Oe;const n=Date.now()/1e3;let s=n,i=!0,o=null;const{payload:a}=Tr(e.access_token);if(a.exp&&(s=a.exp,i=s<=n),i){const{data:l,error:c}=await this._callRefreshToken(e.refresh_token);if(c)return this._returnResult({data:{user:null,session:null},error:c});if(!l)return{data:{user:null,session:null},error:null};o=l}else{const{data:l,error:c}=await this._getUser(e.access_token);if(c)return this._returnResult({data:{user:null,session:null},error:c});o={access_token:e.access_token,refresh_token:e.refresh_token,user:l.user,token_type:"bearer",expires_in:s-n,expires_at:s},await this._saveSession(o),await this._notifyAllSubscribers("SIGNED_IN",o)}return this._returnResult({data:{user:o.user,session:o},error:null})}catch(n){if(L(n))return this._returnResult({data:{session:null,user:null},error:n});throw n}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async n=>{var s;if(!e){const{data:a,error:l}=n;if(l)throw l;e=(s=a.session)!==null&&s!==void 0?s:void 0}if(!(e!=null&&e.refresh_token))throw new Oe;const{data:i,error:o}=await this._callRefreshToken(e.refresh_token);return o?this._returnResult({data:{user:null,session:null},error:o}):i?this._returnResult({data:{user:i.user,session:i},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(n){if(L(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async _getSessionFromURL(e,n){try{if(!je())throw new Rr("No browser detected.");
52if(e.error||e.error_description||e.error_code)throw new Rr(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(n){case"implicit":if(this.flowType==="pkce")throw new ws("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new Rr("Not a valid implicit grant flow url.");break;default:}if(n==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new ws("No code detected.");const{data:_,error:b}=await this._exchangeCodeForSession(e.code);if(b)throw b;const y=new URL(window.location.href);return y.searchParams.delete("code"),window.history.replaceState(window.history.state,"",y.toString()),{data:{session:_.session,redirectType:null},error:null}}const{provider_token:s,provider_refresh_token:i,access_token:o,refresh_token:a,expires_in:l,expires_at:c,token_type:d}=e;if(!o||!l||!a||!d)throw new Rr("No session defined in URL");const u=Math.round(Date.now()/1e3),f=parseInt(l);let p=u+f;c&&(p=parseInt(c));const x=p-u;x*1e3<=Bt&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${x}s, should have been closer to ${f}s`);const g=p-f;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:v,error:m}=await this._getUser(o);if(m)throw m;const w={provider_token:s,provider_refresh_token:i,access_token:o,expires_in:f,expires_at:p,refresh_token:a,token_type:d,user:v.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:w,redirectType:e.type},error:null})}catch(s){if(L(s))return this._returnResult({data:{session:null,redirectType:null},error:s});throw s}}_isImplicitGrantCallback(e){return typeof this.detectSessionInUrl=="function"?this.detectSessionInUrl(new URL(window.location.href),e):!!(e.access_token||e.error_description)}async _isPKCECallback(e){const n=await gt(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&n)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async n=>{var s;const{data:i,error:o}=n;if(o&&!dn(o))return this._returnResult({error:o});const a=(s=i.session)===null||s===void 0?void 0:s.access_token;if(a){const{error:l}=await this.admin.signOut(a,e);if(l&&!(Za(l)&&(l.status===404||l.status===401||l.status===403)||dn(l)))return this._returnResult({error:l})}return e!=="others"&&(await this._removeSession(),await we(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){const n=il(),s={id:n,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",n),this.stateChangeEmitters.delete(n)}};return this._debug("#onAuthStateChange()","registered callback with id",n),this.stateChangeEmitters.set(n,s),(async()=>(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(n)})))(),{data:{subscription:s}}}async _emitInitialSession(e){return await this._useSession(async n=>{var s,i;try{const{data:{session:o},error:a}=n;if(a)throw a;await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",o)),this._debug("INITIAL_SESSION","callback id",e,"session",o)}catch(o){await((i=this.stateChangeEmitters.get(e))===null||i===void 0?void 0:i.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",o),console.error(o)}})}async resetPasswordForEmail(e,n={}){let s=null,i=null;this.flowType==="pkce"&&([s,i]=await Tt(this.storage,this.storageKey,!0));try{return await B(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:s,code_challenge_method:i,gotrue_meta_security:{captcha_token:n.captchaToken}},headers:this.headers,redirectTo:n.redirectTo})}catch(o){if(await we(this.storage,`${this.storageKey}-code-verifier`),L(o))return this._returnResult({data:null,error:o});throw o}}async getUserIdentities(){var e;try{const{data:n,error:s}=await this.getUser();if(s)throw s;return this._returnResult({data:{identities:(e=n.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(n){if(L(n))return this._returnResult({data:null,error:n});throw n}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var n;try{const{data:s,error:i}=await this._useSession(async o=>{var a,l,c,d,u;const{data:f,error:p}=o;if(p)throw p;const x=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(a=e.options)===null||a===void 0?void 0:a.redirectTo,scopes:(l=e.options)===null||l===void 0?void 0:l.scopes,queryParams:(c=e.options)===null||c===void 0?void 0:c.queryParams,skipBrowserRedirect:!0});return await B(this.fetch,"GET",x,{headers:this.headers,jwt:(u=(d=f.session)===null||d===void 0?void 0:d.access_token)!==null&&u!==void 0?u:void 0})});if(i)throw i;return je()&&!(!((n=e.options)===null||n===void 0)&&n.skipBrowserRedirect)&&window.location.assign(s==null?void 0:s.url),this._returnResult({data:{provider:e.provider,url:s==null?void 0:s.url},error:null})}catch(s){if(L(s))return this._returnResult({data:{provider:e.provider,url:null},error:s});throw s}}async linkIdentityIdToken(e){return await this._useSession(async n=>{var s;try{const{error:i,data:{session:o}}=n;if(i)throw i;const{options:a,provider:l,token:c,access_token:d,nonce:u}=e,f=await B(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(s=o==null?void 0:o.access_token)!==null&&s!==void 0?s:void 0,body:{provider:l,id_token:c,access_token:d,nonce:u,link_identity:!0,gotrue_meta_security:{captcha_token:a==null?void 0:a.captchaToken}},xform:We}),{data:p,error:x}=f;return x?this._returnResult({data:{user:null,session:null},error:x}):!p||!p.session||!p.user?this._returnResult({data:{user:null,session:null},error:new Rt}):(p.session&&(await this._saveSession(p.session),await this._notifyAllSubscribers("USER_UPDATED",p.session)),this._returnResult({data:p,error:x}
52))}catch(i){if(await we(this.storage,`${this.storageKey}-code-verifier`),L(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}})}async unlinkIdentity(e){try{return await this._useSession(async n=>{var s,i;const{data:o,error:a}=n;if(a)throw a;return await B(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(i=(s=o.session)===null||s===void 0?void 0:s.access_token)!==null&&i!==void 0?i:void 0})})}catch(n){if(L(n))return this._returnResult({data:null,error:n});throw n}}async _refreshAccessToken(e){const n=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(n,"begin");try{const s=Date.now();return await cl(async i=>(i>0&&await ll(200*Math.pow(2,i-1)),this._debug(n,"refreshing attempt",i),await B(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:We})),(i,o)=>{const a=200*Math.pow(2,i);return o&&un(o)&&Date.now()+a-s<Bt})}catch(s){if(this._debug(n,"error",s),L(s))return this._returnResult({data:{session:null,user:null},error:s});throw s}finally{this._debug(n,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,n){const s=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:n.redirectTo,scopes:n.scopes,queryParams:n.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",n,"url",s),je()&&!n.skipBrowserRedirect&&window.location.assign(s),{data:{provider:e,url:s},error:null}}async _recoverAndRefresh(){var e,n;const s="#_recoverAndRefresh()";this._debug(s,"begin");try{const i=await gt(this.storage,this.storageKey);if(i&&this.userStorage){let a=await gt(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!a&&(a={user:i.user},await $t(this.userStorage,this.storageKey+"-user",a)),i.user=(e=a==null?void 0:a.user)!==null&&e!==void 0?e:hn()}else if(i&&!i.user&&!i.user){const a=await gt(this.storage,this.storageKey+"-user");a&&(a!=null&&a.user)?(i.user=a.user,await we(this.storage,this.storageKey+"-user"),await $t(this.storage,this.storageKey,i)):i.user=hn()}if(this._debug(s,"session from storage",i),!this._isValidSession(i)){this._debug(s,"session is not valid"),i!==null&&await this._removeSession();return}const o=((n=i.expires_at)!==null&&n!==void 0?n:1/0)*1e3-Date.now()<cn;if(this._debug(s,`session has${o?"":" not"} expired with margin of ${cn}s`),o){if(this.autoRefreshToken&&i.refresh_token){const{error:a}=await this._callRefreshToken(i.refresh_token);a&&(console.error(a),un(a)||(this._debug(s,"refresh failed with a non-retryable error, removing the session",a),await this._removeSession()))}}else if(i.user&&i.user.__isUserNotAvailableProxy===!0)try{const{data:a,error:l}=await this._getUser(i.access_token);!l&&(a!=null&&a.user)?(i.user=a.user,await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)):this._debug(s,"could not get user data, skipping SIGNED_IN notification")}catch(a){console.error("Error getting user data:",a),this._debug(s,"error getting user data, skipping SIGNED_IN notification",a)}else await this._notifyAllSubscribers("SIGNED_IN",i)}catch(i){this._debug(s,"error",i),console.error(i);return}finally{this._debug(s,"end")}}async _callRefreshToken(e){var n,s;if(!e)throw new Oe;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const i=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(i,"begin");try{this.refreshingDeferred=new Yr;const{data:o,error:a}=await this._refreshAccessToken(e);if(a)throw a;if(!o.session)throw new Oe;await this._saveSession(o.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",o.session);const l={data:o.session,error:null};return this.refreshingDeferred.resolve(l),l}catch(o){if(this._debug(i,"error",o),L(o)){const a={data:null,error:o};return un(o)||await this._removeSession(),(n=this.refreshingDeferred)===null||n===void 0||n.resolve(a),a}throw(s=this.refreshingDeferred)===null||s===void 0||s.reject(o),o}finally{this.refreshingDeferred=null,this._debug(i,"end")}}async _notifyAllSubscribers(e,n,s=!0){const i=`#_notifyAllSubscribers(${e})`;this._debug(i,"begin",n,`broadcast = ${s}`);try{this.broadcastChannel&&s&&this.broadcastChannel.postMessage({event:e,session:n});const o=[],a=Array.from(this.stateChangeEmitters.values()).map(async l=>{try{await l.callback(e,n)}catch(c){o.push(c)}});if(await Promise.all(a),o.length>0){for(let l=0;l<o.length;l+=1)console.error(o[l]);throw o[0]}}finally{this._debug(i,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await we(this.storage,`${this.storageKey}-code-verifier`);const n=Object.assign({},e),s=n.user&&n.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!s&&n.user&&await $t(this.userStorage,this.storageKey+"-user",{user:n.user});const i=Object.assign({},n);delete i.user;const o=Es(i);await $t(this.storage,this.storageKey,o)}else{const i=Es(n);await $t(this.storage,this.storageKey,i)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await we(this.storage,this.storageKey),await we(this.storage,this.storageKey+"-code-verifier"),await we(this.storage,this.storageKey+"-user"),this.userStorage&&await we(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&je()&&(window!=null&&window.removeEventListener)&&window.removeEventListener("visibilitychange",e)}
52catch(n){console.error("removing visibilitychange callback failed",n)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const e=setInterval(()=>this._autoRefreshTokenTick(),Bt);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e);const n=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=n,n&&typeof n=="object"&&typeof n.unref=="function"?n.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(n)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);const n=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,n&&clearTimeout(n)}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 e=Date.now();try{return await this._useSession(async n=>{const{data:{session:s}}=n;if(!s||!s.refresh_token||!s.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const i=Math.floor((s.expires_at*1e3-e)/Bt);this._debug("#_autoRefreshTokenTick()",`access token expires in ${i} ticks, a tick lasts ${Bt}ms, refresh threshold is ${In} ticks`),i<=In&&await this._callRefreshToken(s.refresh_token)})}catch(n){console.error("Auto refresh tick failed with error. This is likely a transient error.",n)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof mi)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!je()||!(window!=null&&window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(e){this._debug("#visibilityChangedCallback","error",e)}},window==null||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){const n=`#_onVisibilityChanged(${e})`;this._debug(n,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{if(document.visibilityState!=="visible"){this._debug(n,"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(e,n,s){const i=[`provider=${encodeURIComponent(n)}`];if(s!=null&&s.redirectTo&&i.push(`redirect_to=${encodeURIComponent(s.redirectTo)}`),s!=null&&s.scopes&&i.push(`scopes=${encodeURIComponent(s.scopes)}`),this.flowType==="pkce"){const[o,a]=await Tt(this.storage,this.storageKey),l=new URLSearchParams({code_challenge:`${encodeURIComponent(o)}`,code_challenge_method:`${encodeURIComponent(a)}`});i.push(l.toString())}if(s!=null&&s.queryParams){const o=new URLSearchParams(s.queryParams);i.push(o.toString())}return s!=null&&s.skipBrowserRedirect&&i.push(`skip_http_redirect=${s.skipBrowserRedirect}`),`${e}?${i.join("&")}`}async _unenroll(e){try{return await this._useSession(async n=>{var s;const{data:i,error:o}=n;return o?this._returnResult({data:null,error:o}):await B(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(s=i==null?void 0:i.session)===null||s===void 0?void 0:s.access_token})})}catch(n){if(L(n))return this._returnResult({data:null,error:n});throw n}}async _enroll(e){try{return await this._useSession(async n=>{var s,i;const{data:o,error:a}=n;if(a)return this._returnResult({data:null,error:a});const l=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:c,error:d}=await B(this.fetch,"POST",`${this.url}/factors`,{body:l,headers:this.headers,jwt:(s=o==null?void 0:o.session)===null||s===void 0?void 0:s.access_token});return d?this._returnResult({data:null,error:d}):(e.factorType==="totp"&&c.type==="totp"&&(!((i=c==null?void 0:c.totp)===null||i===void 0)&&i.qr_code)&&(c.totp.qr_code=`data:image/svg+xml;utf-8,${c.totp.qr_code}`),this._returnResult({data:c,error:null}))})}catch(n){if(L(n))return this._returnResult({data:null,error:n});throw n}}async _verify(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async n=>{var s;const{data:i,error:o}=n;
52if(o)return this._returnResult({data:null,error:o});const a=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?Ul(e.webauthn.credential_response):Ml(e.webauthn.credential_response)})}:{code:e.code}),{data:l,error:c}=await B(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:a,headers:this.headers,jwt:(s=i==null?void 0:i.session)===null||s===void 0?void 0:s.access_token});return 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(n){if(L(n))return this._returnResult({data:null,error:n});throw n}})}async _challenge(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async n=>{var s;const{data:i,error:o}=n;if(o)return this._returnResult({data:null,error:o});const a=await B(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(s=i==null?void 0:i.session)===null||s===void 0?void 0:s.access_token});if(a.error)return a;const{data:l}=a;if(l.type!=="webauthn")return{data:l,error:null};switch(l.webauthn.type){case"create":return{data:Object.assign(Object.assign({},l),{webauthn:Object.assign(Object.assign({},l.webauthn),{credential_options:Object.assign(Object.assign({},l.webauthn.credential_options),{publicKey:$l(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:Dl(l.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(n){if(L(n))return this._returnResult({data:null,error:n});throw n}})}async _challengeAndVerify(e){const{data:n,error:s}=await this._challenge({factorId:e.factorId});return s?this._returnResult({data:null,error:s}):await this._verify({factorId:e.factorId,challengeId:n.id,code:e.code})}async _listFactors(){var e;const{data:{user:n},error:s}=await this.getUser();if(s)return{data:null,error:s};const i={all:[],phone:[],totp:[],webauthn:[]};for(const o of(e=n==null?void 0:n.factors)!==null&&e!==void 0?e:[])i.all.push(o),o.status==="verified"&&i[o.factor_type].push(o);return{data:i,error:null}}async _getAuthenticatorAssuranceLevel(e){var n,s,i,o;if(e)try{const{payload:x}=Tr(e);let g=null;x.aal&&(g=x.aal);let v=g;const{data:{user:m},error:w}=await this.getUser(e);if(w)return this._returnResult({data:null,error:w});((s=(n=m==null?void 0:m.factors)===null||n===void 0?void 0:n.filter(y=>y.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(v="aal2");const b=x.amr||[];return{data:{currentLevel:g,nextLevel:v,currentAuthenticationMethods:b},error:null}}catch(x){if(L(x))return this._returnResult({data:null,error:x});throw x}const{data:{session:a},error:l}
52=await this.getSession();if(l)return this._returnResult({data:null,error:l});if(!a)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:c}=Tr(a.access_token);let d=null;c.aal&&(d=c.aal);let u=d;((o=(i=a.user.factors)===null||i===void 0?void 0:i.filter(x=>x.status==="verified"))!==null&&o!==void 0?o:[]).length>0&&(u="aal2");const p=c.amr||[];return{data:{currentLevel:d,nextLevel:u,currentAuthenticationMethods:p},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async n=>{const{data:{session:s},error:i}=n;return i?this._returnResult({data:null,error:i}):s?await B(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:s.access_token,xform:o=>({data:o,error:null})}):this._returnResult({data:null,error:new Oe})})}catch(n){if(L(n))return this._returnResult({data:null,error:n});throw n}}async _approveAuthorization(e,n){try{return await this._useSession(async s=>{const{data:{session:i},error:o}=s;if(o)return this._returnResult({data:null,error:o});if(!i)return this._returnResult({data:null,error:new Oe});const a=await B(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:i.access_token,body:{action:"approve"},xform:l=>({data:l,error:null})});return a.data&&a.data.redirect_url&&je()&&!(n!=null&&n.skipBrowserRedirect)&&window.location.assign(a.data.redirect_url),a})}catch(s){if(L(s))return this._returnResult({data:null,error:s});throw s}}async _denyAuthorization(e,n){try{return await this._useSession(async s=>{const{data:{session:i},error:o}=s;if(o)return this._returnResult({data:null,error:o});if(!i)return this._returnResult({data:null,error:new Oe});const a=await B(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:i.access_token,body:{action:"deny"},xform:l=>({data:l,error:null})});return a.data&&a.data.redirect_url&&je()&&!(n!=null&&n.skipBrowserRedirect)&&window.location.assign(a.data.redirect_url),a})}catch(s){if(L(s))return this._returnResult({data:null,error:s});throw s}}async _listOAuthGrants(){try{return await this._useSession(async e=>{const{data:{session:n},error:s}=e;return s?this._returnResult({data:null,error:s}):n?await B(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:n.access_token,xform:i=>({data:i,error:null})}):this._returnResult({data:null,error:new Oe})})}catch(e){if(L(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async n=>{const{data:{session:s},error:i}=n;return i?this._returnResult({data:null,error:i}):s?(await B(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:s.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new Oe})})}catch(n){if(L(n))return this._returnResult({data:null,error:n});throw n}}async fetchJwk(e,n={keys:[]}){let s=n.keys.find(l=>l.kid===e);if(s)return s;const i=Date.now();if(s=this.jwks.keys.find(l=>l.kid===e),s&&this.jwks_cached_at+Ja>i)return s;const{data:o,error:a}=await B(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(a)throw a;return!o.keys||o.keys.length===0||(this.jwks=o,this.jwks_cached_at=i,s=o.keys.find(l=>l.kid===e),!s)?null:s}async getClaims(e,n={}){try{let s=e;if(!s){const{data:x,error:g}
52=await this.getSession();if(g||!x.session)return this._returnResult({data:null,error:g});s=x.session.access_token}const{header:i,payload:o,signature:a,raw:{header:l,payload:c}}=Tr(s);n!=null&&n.allowExpired||ml(o.exp);const d=!i.alg||i.alg.startsWith("HS")||!i.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(i.kid,n!=null&&n.keys?{keys:n.keys}:n==null?void 0:n.jwks);if(!d){const{error:x}=await this.getUser(s);if(x)throw x;return{data:{claims:o,header:i,signature:a},error:null}}const u=yl(i.alg),f=await crypto.subtle.importKey("jwk",d,u,!0,["verify"]);if(!await crypto.subtle.verify(u,f,a,nl(`${l}.${c}`)))throw new Ln("Invalid JWT signature");return{data:{claims:o,header:i,signature:a},error:null}}catch(s){if(L(s))return this._returnResult({data:null,error:s});throw s}}}vr.nextInstanceID={};const Gl=vr,Zl="2.99.0";let ar="";typeof Deno<"u"?ar="deno":typeof document<"u"?ar="web":typeof navigator<"u"&&navigator.product==="ReactNative"?ar="react-native":ar="node";const Yl={"X-Client-Info":`supabase-js-${ar}/${Zl}`},Xl={headers:Yl},Ql={schema:"public"},ec={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},tc={};function wr(r){"@babel/helpers - typeof";return wr=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},wr(r)}function rc(r,e){if(wr(r)!="object"||!r)return r;var n=r[Symbol.toPrimitive];if(n!==void 0){var s=n.call(r,e);if(wr(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(r)}function nc(r){var e=rc(r,"string");return wr(e)=="symbol"?e:e+""}function sc(r,e,n){return(e=nc(e))in r?Object.defineProperty(r,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):r[e]=n,r}function Os(r,e){var n=Object.keys(r);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(r);e&&(s=s.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),n.push.apply(n,s)}return n}function de(r){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?Os(Object(n),!0).forEach(function(s){sc(r,s,n[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(n)):Os(Object(n)).forEach(function(s){Object.defineProperty(r,s,Object.getOwnPropertyDescriptor(n,s))})}return r}const ic=r=>r?(...e)=>r(...e):(...e)=>fetch(...e),oc=()=>Headers,ac=(r,e,n)=>{const s=ic(n),i=oc();return async(o,a)=>{var l;const c=(l=await e())!==null&&l!==void 0?l:r;let d=new i(a==null?void 0:a.headers);return d.has("apikey")||d.set("apikey",r),d.has("Authorization")||d.set("Authorization",`Bearer ${c}`),s(o,de(de({},a),{},{headers:d}))}};function lc(r){return r.endsWith("/")?r:r+"/"}function cc(r,e){var n,s;const{db:i,auth:o,realtime:a,global:l}=r,{db:c,auth:d,realtime:u,global:f}=e,p={db:de(de({},c),i),auth:de(de({},d),o),realtime:de(de({},u),a),storage:{},global:de(de(de({},f),l),{},{headers:de(de({},(n=f==null?void 0:f.headers)!==null&&n!==void 0?n:{}),(s=l==null?void 0:l.headers)!==null&&s!==void 0?s:{})}),accessToken:async()=>""};return r.accessToken?p.accessToken=r.accessToken:delete p.accessToken,p}function dc(r){const e=r==null?void 0:r.trim();if(!e)throw new Error("supabaseUrl is required.");if(!e.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(lc(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var uc=class extends Gl{constructor(r){super(r)}},hc=class{constructor(r,e,n){var s,i;this.supabaseUrl=r,this.supabaseKey=e;const o=dc(r);if(!e)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",o),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",o),this.storageUrl=new URL("storage/v1",o),this.functionsUrl=new URL("functions/v1",o);const a=`sb-${o.hostname.split(".")[0]}-auth-token`,l={db:Ql,realtime:tc,auth:de(de({},ec),{},{storageKey:a}),global:Xl},c=cc(n??{},l);if(this.storageKey=(s=c.auth.storageKey)!==null&&s!==void 0?s:"",this.headers=(i=c.global.headers)!==null&&i!==void 0?i:{},c.accessToken)this.accessToken=c.accessToken,this.auth=new Proxy({},{get:(u,f)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(f)} 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=ac(e,this._getAccessToken.bind(this),c.global.fetch),this.realtime=this._initRealtimeClient(de({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 Zo(new URL("rest/v1",o).href,{headers:this.headers,schema:c.db.schema,fetch:this.fetch,timeout:c.db.timeout,urlLengthLimit:c.db.urlLengthLimit}),this.storage=new Fa(this.storageUrl.href,this.headers,this.fetch,n==null?void 0:n.storage),c.accessToken||this._listenForAuthEvents()}get functions(){return new No(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(r){return this.rest.from(r)}schema(r){return this.rest.schema(r)}rpc(r,e={},n={head:!1,get:!1,count:void 0}){return this.rest.rpc(r,e,n)}channel(r,e={config:{}}){return this.realtime.channel(r,e)}getChannels(){return this.realtime.getChannels()}removeChannel(r){return this.realtime.removeChannel(r)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var r=this,e,n;if(r.accessToken)return await r.accessToken();const{data:s}=await r.auth.getSession();return(e=(n=s.session)===null||n===void 0?void 0:n.access_token)!==null&&e!==void 0?e:r.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:r,persistSession:e,detectSessionInUrl:n,storage:s,userStorage:i,storageKey:o,flowType:a,lock:l,debug:c,throwOnError:d},u,f){const p={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new uc({url:this.authUrl.href,headers:de(de({},p),u),storageKey:o,autoRefreshToken:r,persistSession:e,detectSessionInUrl:n,storage:s,userStorage:i,flowType:a,lock:l,debug:c,throwOnError:d,fetch:f,hasCustomAuthorizationHeader:Object.keys(this.headers).some(x=>x.toLowerCase()==="authorization")})}_initRealtimeClient(r){return new fa(this.realtimeUrl.href,de(de({},r),{},{params:de(de({},{apikey:this.supabaseKey}),r==null?void 0:r.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((r,e)=>{this._handleTokenChanged(r,"CLIENT",e==null?void 0:e.access_token)})}_handleTokenChanged(r,e,n){(r==="TOKEN_REFRESHED"||r==="SIGNED_IN")&&this.changedAccessToken!==n?(this.changedAccessToken=n,this.realtime.setAuth(n)):r==="SIGNED_OUT"&&(this.realtime.setAuth(),e=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};const bi=(r,e,n)=>new hc(r,e,n);function fc(){if(typeof window<"u")return!1;const r=globalThis.process;if(!r)return!1;const e=r.version;if(e==null)return!1;const n=e.match(/^v(\d+)\./);return n?parseInt(n[1],10)<=18:!1}fc()&&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 N
52ode.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217");const ie=bi("https://vhadhtsblncdelbisrho.supabase.co","eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InZoYWRodHNibG5jZGVsYmlzcmhvIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzMxNTE3MTUsImV4cCI6MjA4ODcyNzcxNX0.VAPxFF05LqvGAihym5EuSigeiRyYHfNaAA0VCLZcgmg"),pc="https://review-scraper-production-9324.up.railway.app/user";async function gc(){const{data:{session:r}}=await ie.auth.getSession();if(!r)throw new Error("Nicht eingeloggt");return{Authorization:`Bearer ${r.access_token}`,"Content-Type":"application/json"}}async function mt(r,e={}){const n=await gc(),s=await fetch(`${pc}${r}`,{...e,headers:{...n,...e.headers}}),i=await s.json();if(!s.ok)throw new Error(i.error||`Fehler ${s.status}`);return i}const qt={getProfile:()=>mt("/profile"),updateProfile:r=>mt("/profile",{method:"PATCH",body:JSON.stringify(r)}),updateEmail:r=>mt("/email",{method:"PATCH",body:JSON.stringify({email:r})}),getPlatforms:()=>mt("/platforms"),connectPlatform:(r,e)=>mt("/platforms/connect",{method:"POST",body:JSON.stringify({platform_name:r,profile_url:e})}),disconnectPlatform:r=>mt("/platforms/disconnect",{method:"POST",body:JSON.stringify({platform_id:r})}),createCompany:(r,e,n)=>mt("/onboarding/company",{method:"POST",body:JSON.stringify({name:r,industry:e,website_url:n})})},vi=h.createContext({});function Ls(){sessionStorage.removeItem("trial_banner_dismissed"),sessionStorage.removeItem("just_upgraded")}async function mc(r){try{const{count:e}=await ie.from("platforms").select("id",{count:"exact",head:!0}).eq("company_id",r).eq("is_active",!0).not("profile_url","is",null);return e>0}catch{return!1}}const yc=({children:r})=>{const[e,n]=h.useState(void 0),[s,i]=h.useState(null),[o,a]=h.useState(null),[l,c]=h.useState(null),[d,u]=h.useState(!1),[f,p]=h.useState(!1),x=h.useRef(null),g=async w=>{u(!1);const _=x.current;_&&_!==w&&Ls(),x.current=w;let b=null;try{b=await qt.getProfile()}catch(y){console.warn("[AuthContext] Backend profile failed:",y.message);const{data:k}=await ie.from("profiles").select("*, companies(*)").eq("id",w).single();b=k}if(b){i(b);const y=b.companies||null;if(a(y),y!=null&&y.id)try{const{data:k}=await ie.from("subscriptions").select("*").eq("company_id",y.id).single();if(c(k||null),k&&(k.plan==="erstanalyse"||k.plan==="monitoring")){const S=await mc(y.id);p(S)}}catch{c(null)}}else i(null),a(null),c(null),p(!1);u(!0)};h.useEffect(()=>{ie.auth.getSession().then(({data:{session:_}})=>{n(_),_?g(_.user.id):u(!0)});const{data:{subscription:w}}=ie.auth.onAuthStateChange((_,b)=>{n(b),b?g(b.user.id):(i(null),a(null),c(null),p(!1),u(!0),Ls())});return()=>w.unsubscribe()},[]);const v=()=>e?g(e.user.id):Promise.resolve(),m=e===void 0||!d;return t.jsx(vi.Provider,{value:{session:e,profile:s,company:o,subscription:l,hasActivePlatforms:f,refreshProfile:v,loading:m,profileLoaded:d},children:r})},$e=()=>h.useContext(vi);var Nr={},xc=()=>{window.si||(window.si=function(...e){window.siq=window.siq||[],window.siq.push(e)})},bc="@vercel/speed-insights",vc="2.0.0";function wc(){return typeof window<"u"}function _c(){try{const r="production"}catch{}return"production"}function wi(){return _c()==="development"}function jc(r){return r.scriptSrc?Fr(r.scriptSrc):wi()?"https://va.vercel-scripts.com/v1/speed-insights/script.debug.js":r.dsn?"https://va.vercel-scripts.com/v1/speed-insights/script.js":r.basePath?Fr(`${r.basePath}/speed-insights/script.js`):"/_vercel/speed-insights/script.js"}function Sc(r,e){var n;let s=r;if(e)try{s={...(n=JSON.parse(e))==null?void 0:n.speedInsights,...r}}catch{}const i={sdkn:bc+(s.framework?`/${s.framework}`:""),sdkv:vc};return s.sampleRate&&(i.sampleRate=s.sampleRate.toString()),s.route&&(i.route=s.route),wi()&&s.debug===!1&&(i.debug="false"),s.dsn&&(i.dsn=s.dsn),s.endpoint?i.endpoint=Fr(s.endpoint):s.basePath&&(i.endpoint=Fr(`${s.basePath}/speed-insights/vitals`)),{src:jc(s),beforeSend:s.beforeSend,dataset:i}}function Fr(r){return r.startsWith("http://")||r.startsWith("https://")||r.startsWith("/")?r:`/${r}`}function kc(r={},e){var n;if(!wc()||r.route===null)return null;xc();const{beforeSend:s,src:i,dataset:o}=Sc(r,e);if(document.head.querySelector(`script[src*="${i}"]`))return null;s&&((n=window.si)==null||n.call(window,"beforeSend",s));const a=document.createElement("script");a.src=i,a.defer=!0;for(const[l,c]of Object.entries(o))a.dataset[l]=c;return a.onerror=()=>{console.log(`[Vercel Speed Insights] Failed to load script from ${i}. Please check if any content blockers are enabled and try again.`)},document.head.appendChild(a),{setRoute:l=>{a.dataset.route=l??void 0}}}function Ec(){if(!(typeof process>"u"||typeof Nr>"u"))return Nr.REACT_APP_VERCEL_OBSERVABILITY_BASEPATH}function Cc(){if(!(typeof process>"u"||typeof Nr>"u"))return Nr.REACT_APP_VERCEL_OBSERVABILITY_CLIENT_CONFIG}function Ac(r){h.useEffect(()=>{var n;r.beforeSend&&((n=window.si)==null||n.call(window,"beforeSend",r.beforeSend))},[r.beforeSend]);const e=h.useRef(null);return h.useEffect(()=>{if(!e.current){const n=kc({framework:r.framework??"react",basePath:r.basePath??Ec(),...r}
52,r.configString??Cc());n&&(e.current=n.setRoute)}},[r]),h.useEffect(()=>{e.current&&r.route&&e.current(r.route)},[r.route]),null}var Hr={},Rc=()=>{window.va||(window.va=function(...e){window.vaq||(window.vaq=[]),window.vaq.push(e)})},Tc="@vercel/analytics",Ic="2.0.1";function _i(){return typeof window<"u"}function ji(){try{const r="production"}catch{}return"production"}function Pc(r="auto"){if(r==="auto"){window.vam=ji();return}window.vam=r}function Oc(){return(_i()?window.vam:ji())||"production"}function Vn(){return Oc()==="development"}function Lc(r){return r.scriptSrc?Nt(r.scriptSrc):Vn()?"https://va.vercel-scripts.com/v1/script.debug.js":r.basePath?Nt(`${r.basePath}/insights/script.js`):"/_vercel/insights/script.js"}function zc(r,e){var n;let s=r;if(e)try{s={...(n=JSON.parse(e))==null?void 0:n.analytics,...r}}catch{}Pc(s.mode);const i={sdkn:Tc+(s.framework?`/${s.framework}`:""),sdkv:Ic};return s.disableAutoTrack&&(i.disableAutoTrack="1"),s.viewEndpoint&&(i.viewEndpoint=Nt(s.viewEndpoint)),s.eventEndpoint&&(i.eventEndpoint=Nt(s.eventEndpoint)),s.sessionEndpoint&&(i.sessionEndpoint=Nt(s.sessionEndpoint)),Vn()&&s.debug===!1&&(i.debug="false"),s.dsn&&(i.dsn=s.dsn),s.endpoint?i.endpoint=s.endpoint:s.basePath&&(i.endpoint=Nt(`${s.basePath}/insights`)),{beforeSend:s.beforeSend,src:Lc(s),dataset:i}}function Nt(r){return r.startsWith("http://")||r.startsWith("https://")||r.startsWith("/")?r:`/${r}`}function Bc(r={debug:!0},e){var n;if(!_i())return;const{beforeSend:s,src:i,dataset:o}=zc(r,e);if(Rc(),s&&((n=window.va)==null||n.call(window,"beforeSend",s)),document.head.querySelector(`script[src*="${i}"]`))return;const a=document.createElement("script");a.src=i;for(const[l,c]of Object.entries(o))a.dataset[l]=c;a.defer=!0,a.onerror=()=>{const l=Vn()?"Please check if any ad blockers are enabled and try again.":"Be sure to enable Web Analytics for your project and deploy again. See https://vercel.com/docs/analytics/quickstart for more information.";console.log(`[Vercel Web Analytics] Failed to load script from ${i}. ${l}`)},document.head.appendChild(a)}function $c({route:r,path:e}){var n;(n=window.va)==null||n.call(window,"pageview",{route:r,path:e})}function Dc(){if(!(typeof process>"u"||typeof Hr>"u"))return Hr.REACT_APP_VERCEL_OBSERVABILITY_BASEPATH}function Uc(){if(!(typeof process>"u"||typeof Hr>"u"))return Hr.REACT_APP_VERCEL_OBSERVABILITY_CLIENT_CONFIG}function Mc(r){return h.useEffect(()=>{var e;r.beforeSend&&((e=window.va)==null||e.call(window,"beforeSend",r.beforeSend))},[r.beforeSend]),h.useEffect(()=>{Bc({framework:r.framework||"react",basePath:r.basePath??Dc(),...r.route!==void 0&&{disableAutoTrack:!0},...r},r.configString??Uc())},[]),h.useEffect(()=>{r.route&&r.path&&$c({route:r.route,path:r.path})},[r.route,r.path]),null}const Wc="modulepreload",Nc=function(r){return"/"+r},zs={},Ee=function(e,n,s){let i=Promise.resolve();if(n&&n.length>0){let a=function(d){return Promise.all(d.map(u=>Promise.resolve(u).then(f=>({status:"fulfilled",value:f}),f=>({status:"rejected",reason:f}))))};document.getElementsByTagName("link");const l=document.querySelector("meta[property=csp-nonce]"),c=(l==null?void 0:l.nonce)||(l==null?void 0:l.getAttribute("nonce"));i=a(n.map(d=>{if(d=Nc(d),d in zs)return;zs[d]=!0;const u=d.endsWith(".css"),f=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${f}`))return;const p=document.createElement("link");if(p.rel=u?"stylesheet":Wc,u||(p.as="script"),p.crossOrigin="",p.href=d,c&&p.setAttribute("nonce",c),document.head.appendChild(p),u)return new Promise((x,g)=>{p.addEventListener("load",x),p.addEventListener("error",()=>g(new Error(`Unable to preload CSS for ${d}`)))})}))}function o(a){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=a,window.dispatchEvent(l),!l.defaultPrevented)throw a}return i.then(a=>{for(const l of a||[])l.status==="rejected"&&o(l.reason);return e().catch(o)})},Fc='-apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif';function Si(){return t.jsx("div",{style:{minHeight:"100vh",display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:"#f6f8fa",fontFamily:Fc},children:t.jsxs("div",{style:{textAlign:"center"},children:[t.jsx("div",{style:{width:32,height:32,border:"3px solid #d0d7de",borderTopColor:"#0969da",borderRadius:"50%",animation:"spin 0.8s linear infinite",margin:"0 auto 12px"}}),t.jsx("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"}),t.jsx("p",{style:{fontSize:13,color:"#656d76",margin:0},children:"Wird geladenâ¦"})]})})}const Bs=({children:r})=>{const{session:e,profile:n,loading:s}=$e();return s?t.jsx(Si,{}):e?n!=null&&n.onboarding_done?t.jsx(ee,{to:"/dashboard",replace:!0}):r:t.jsx(ee,{to:"/login",replace:!0})},Hc=({children:r})=>{const{session:e,profile:n,loading:s}=$e();return s?t.jsx(Si,{}):e?!n||!n.onboarding_done?n!=null&&n.company_id&&(n==null?void 0:n.role)!=="owner"?t.jsx(ee,{to:"/invite-onboarding",replace:!0}):t.jsx(ee,{to:"/onboarding",replace:!0}):t.jsx(ee,{to:"/dashboard",replace:!0}):r},Dt='-apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif',pn={width:"100%",padding:"10px 12px",border:"1px solid #e2e8f0",borderRadius:8,fontSize:14,fontFamily:Dt,outline:"none",boxSizing:"border-box",backgroundColor:"#fff",color:"#0f172a",transition:"border-color 0.15s"},Vc=[["Invalid login credentials","E-Mail oder Passwort ist falsch."],["Email not confirmed","Bitte bestätigen Sie zuerst Ihre E-Mail-Adresse."],["Too many requests","Zu viele Anmeldever
52suche. Bitte warten Sie kurz."],["over_email_send_rate_limit","Zu viele Versuche. Bitte warten Sie einige Minuten."],["For security purposes","Aus Sicherheitsgründen bitte kurz warten."],["Network request failed","Keine Verbindung. Bitte Internetverbindung prüfen."],["Unable to validate email address","Ungültige E-Mail-Adresse."],["User not found","Kein Konto mit dieser E-Mail-Adresse gefunden."]];function $s(r){if(!r)return"Ein unbekannter Fehler ist aufgetreten.";for(const[e,n]of Vc)if(r.includes(e))return n;return r}function qc(){var C,z,H;const[r,e]=h.useState(""),[n,s]=h.useState(""),[i,o]=h.useState(""),[a,l]=h.useState(!1),[c,d]=h.useState(!1),[u,f]=h.useState(""),[p,x]=h.useState(!1),[g,v]=h.useState(""),[m,w]=h.useState(""),_=Se(),b=$n(),y=((z=(C=b.state)==null?void 0:C.from)==null?void 0:z.pathname)||"/dashboard",k=((H=b.state)==null?void 0:H.message)||null,S=async G=>{if(G.preventDefault(),w(""),v(""),!u.trim()){w("Bitte geben Sie Ihre E-Mail-Adresse ein.");return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(u)){w("Bitte geben Sie eine gültige E-Mail-Adresse ein.");return}x(!0);const{error:O}=await ie.auth.resetPasswordForEmail(u,{redirectTo:"https://dashboard.optimavo.de/reset-password"});if(x(!1),O){w($s(O.message));return}v("Falls ein Konto mit dieser E-Mail existiert, wurde ein Link zum Zurücksetzen gesendet. Bitte prüfen Sie Ihr Postfach.")};h.useEffect(()=>{var G;if(!((G=window.UnicornStudio)!=null&&G.isInitialized)&&(window.UnicornStudio||(window.UnicornStudio={isInitialized:!1}),!document.querySelector("script[data-unicorn-loader]"))){const O=document.createElement("script");O.src="https://cdn.jsdelivr.net/gh/hiunicornstudio/[email protected]/dist/unicornStudio.umd.js",O.setAttribute("data-unicorn-loader","true"),O.onload=()=>{window.UnicornStudio.isInitialized||(window.UnicornStudio.init(),window.UnicornStudio.isInitialized=!0)},document.head.appendChild(O)}},[]);const T=async(G,O)=>{if(o(""),!G.trim()){o("Bitte geben Sie Ihre E-Mail-Adresse ein.");return}if(!O){o("Bitte geben Sie Ihr Passwort ein.");return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(G)){o("Bitte geben Sie eine gültige E-Mail-Adresse ein.");return}l(!0);const{error:F}=await ie.auth.signInWithPassword({email:G,password:O});if(l(!1),F){o($s(F.message));return}_(y,{replace:!0})},V=G=>{G.preventDefault(),T(r,n)};return t.jsxs("div",{style:{minHeight:"100vh",maxHeight:"100vh",display:"flex",fontFamily:Dt,backgroundColor:"#f8fafc",overflow:"hidden"},children:[t.jsx("style",{children:` 53 @media (max-width: 860px) { .auth-right { display: none !important; } .auth-left { padding: 24px 20px !important; overflow-y: auto !important; } } 54 .auth-input:focus { border-color: #0969da !important; box-shadow: 0 0 0 3px rgba(9,105,218,0.1); } 55 `}),t.jsxs("div",{className:"auth-left",style:{width:"100%",maxWidth:480,display:"flex",flexDirection:"column",justifyContent:"center",padding:"48px 56px",backgroundColor:"#fff",borderRight:"1px solid #f1f5f9"},children:[t.jsx("img",{src:"/OptimavoLogo.webp",alt:"Optimavo",style:{maxWidth:140,height:"auto",marginBottom:52}}),t.jsx("h1",{style:{fontSize:26,fontWeight:700,color:"#0f172a",margin:"0 0 10px",letterSpacing:"-0.4px"},children:"Willkommen zurück"}),t.jsx("p",{style:{fontSize:14,color:"#64748b",margin:"0 0 36px",lineHeight:1.65},children:"Melden Sie sich an, um Ihre Kundenbewertungen zu analysieren und Verbesserungen zu erkennen."}),k&&t.jsxs("div",{style:{marginBottom:20,padding:"12px 14px",backgroundColor:"#f0fdf4",border:"1px solid #bbf7d0",borderRadius:10,fontSize:13,color:"#15803d",display:"flex",gap:8},children:[t.jsx("span",{children:"â"}),t.jsx("span",{children:k})]}),t.jsxs("form",{onSubmit:V,noValidate:!0,style:{display:"flex",flexDirection:"column",gap:16},children:[t.jsxs("div",{children:[t.jsx("label",{style:{display:"block",fontSize:13,fontWeight:600,color:"#374151",marginBottom:6},children:"E-Mail-Adresse"}),t.jsx("input",{className:"auth-input",type:"email",value:r,onChange:G=>e(G.target.value),autoFocus:!0,placeholder:"[email protected]",style:pn})]}),t.jsxs("div",{children:[t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:6},children:[t.jsx("label",{style:{fontSize:13,fontWeight:600,color:"#374151"},children:"Passwort"}),t.jsx("span",{onClick:()=>{d(!0),f(r),w(""),v("")},style:{fontSize:12,color:"#0969da",cursor:"pointer"},children:"Passwort vergessen?"})]}),t.jsx("input",{className:"auth-input",type:"password",value:n,onChange:G=>s(G.target.value),placeholder:"â¢â¢â¢â¢â¢â¢â¢â¢",style:pn})]}),i&&t.jsx("div",{style:{padding:"10px 14px",backgroundColor:"#fff1f2",border:"1px solid #fecdd3",borderRadius:8,fontSize:13,color:"#be123c"},children:i}),t.jsx("button",{type:"submit",disabled:a,style:{padding:"11px 0",backgroundColor:a?"#93c5fd":"#0969da",color:"#fff",border:"none",borderRadius:8,fontSize:14,fontWeight:600,cursor:a?"default":"pointer",fontFamily:Dt,marginTop:4,transition:"background-color 0.15s"},children:a?"Anmeldenâ¦":"Anmelden"})]}),c&&t.jsx("div",{style:{position:"fixed",top:0,left:0,right:0,bottom:0,backgroundColor:"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:9999},onClick:()=>d(!1),children:t.jsxs("div",{onClick:G=>G.stopPropagation(),style:{backgroundColor:"#fff",borderRadius:12,padding:"36px 32px",width:"100%",maxWidth:420,boxShadow:"0 20px 60px rgba(0,0,0,0.15)",fontFamily:Dt},children:[t.jsx("h2",{style:{fontSize:20,fontWeight:700,color:"#0f172a",margin:"0 0 8px"},children:"Passwort zurücksetzen"}),t.jsx("p",{style:{fontSize:14,color:"#64748b",margin:"0 0 24px",lineHeight:1.6},children:"Geben Sie Ihre E-Mail-Adresse ein. Wir senden Ihnen einen Link zum Zurücksetzen Ihres Passworts."}),g&&t.jsx("div",{style:{marginBottom:16,padding:"12px 14px",backgroundColor:"#f0fdf4",border:"1px solid #bbf7d0",borderRadius:8,fontSize:13,color:"#15803d",lineHeight:1.5},children:g}),m&&t.jsx("div",{style:{marginBottom:16,padding:"10px 14px",backgroundColor:"#fff1f2",border:"1px solid #fecdd3",borderRadius:8,fontSize:13,color:"#be123c"},children:m}),!g&&t.jsxs("form",{onSubmit:S,noValidate:!0,style:{display:"flex",flexDirection:"column",gap:16},children:[t.jsxs("div",{children:[t.jsx("label",{style:{display:"block",fontSize:13,fontWeight:600,color:"#374151",marginBottom:6},children:"E-Mail-Adresse"}),t.jsx("input",{className:"auth-input",type:"email",value:u,onChange:G=>f(G.target.value),autoFocus:!0,placeholder:"[email protected]",style:pn})]}),t.jsx("button",{type:"submit",disabled:p,style:{padding:"11px 0",backgroundColor:p?"#93c5fd":"#0969da",color:"#fff",border:"none",borderRadius:8,fontSize:14,fontWeight:600,cursor:p?"default":"pointer",fontFamily:Dt,transition:"background-color 0.15s"},children:p?"Wird gesendetâ¦":"Link senden"})]}),t.jsx("button",{onClick:()=>d(!1),style:{marginTop:16,padding:"8px 0",width:"100%",backgroundColor:"transparent",border:"none",fontSize:13,color:"#64748b",cursor:"pointer",fontFamily:Dt},children:"Zurück zur Anmeldung"})]})})]}),t.jsxs("div",{className:"auth-right",style:{flex:1,backgroundColor:"#fff",display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",padding:"64px 56px",position:"relative",overflow:"hidden"},children:[t.jsx("div",{style:{position:"absolute",top:0,left:0,width:"100%",height:"100%",zIndex:0,overflow:"hidden",pointerEvents:"none"},children:t.jsx("div",{style:{position:"absolute",top:0,left:0,width:"100%",height:"100%",opacity:.6,mixBlendMode:"screen"},children:t.jsx("div",{"data-us-project":"WdVna2EGJHojbGLRHA52","data-us-dpi":"1.5","data-us-fps":"60","data-us-lazyload":"true","data-us-production":"true",style:{position:"absolute",top:0,left:0,width:"100%",height:"100%"}})})}),t.jsx("div",{style:{maxWidth:720,textAlign:"center",position:"relative",zIndex:1},children:t.jsx("div",{style:{borderRadius:14,overflow:"hidden",boxShadow:"0 32px 80px rgba(15,23,42,0.14), 0 4px 24px rgba(15,23,42,0.08)",transform:"perspective(1200
55px) rotateX(2deg)",transformOrigin:"center top",maxWidth:800},children:t.jsx("img",{src:"/Dashboard.png",alt:"Optimavo Dashboard",style:{width:"100%",display:"block"}})})})]})]})}const Kc='-apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif';function Jc(){const r=Se();return h.useEffect(()=>{ie.auth.signOut().then(()=>{r("/login",{replace:!0,state:{message:"Sie wurden erfolgreich abgemeldet."}})})},[]),t.jsx("div",{style:{minHeight:"100vh",backgroundColor:"#f6f8fa",display:"flex",alignItems:"center",justifyContent:"center",fontFamily:Kc},children:t.jsxs("div",{style:{textAlign:"center"},children:[t.jsx("div",{style:{width:32,height:32,border:"3px solid #d0d7de",borderTopColor:"#0969da",borderRadius:"50%",animation:"spin 0.8s linear infinite",margin:"0 auto 12px"}}),t.jsx("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"}),t.jsx("p",{style:{fontSize:13,color:"#656d76",margin:0},children:"Abmeldenâ¦"})]})})}const lr='-apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif',Ds={width:"100%",padding:"10px 12px",border:"1px solid #e2e8f0",borderRadius:8,fontSize:14,fontFamily:lr,outline:"none",boxSizing:"border-box",backgroundColor:"#fff",color:"#0f172a",transition:"border-color 0.15s"};function Gc(){const[r,e]=h.useState(""),[n,s]=h.useState(""),[i,o]=h.useState(!1),[a,l]=h.useState(""),[c,d]=h.useState(!1),[u,f]=h.useState(!1),[p,x]=h.useState(!1);Se(),h.useEffect(()=>{const{data:{subscription:v}}=ie.auth.onAuthStateChange(w=>{w==="PASSWORD_RECOVERY"&&f(!0)});ie.auth.getSession().then(({data:{session:w}})=>{w&&f(!0)});const m=setTimeout(()=>{f(w=>(w||x(!0),w))},5e3);return()=>{v.unsubscribe(),clearTimeout(m)}},[]);const g=async v=>{if(v.preventDefault(),l(""),!r){l("Bitte geben Sie ein neues Passwort ein.");return}if(r.length<6){l("Das Passwort muss mindestens 6 Zeichen lang sein.");return}if(r!==n){l("Die Passwörter stimmen nicht überein.");return}o(!0);const{error:m}=await ie.auth.updateUser({password:r});if(o(!1),m){l(m.message||"Fehler beim Ãndern des Passworts.");return}await ie.auth.signOut(),d(!0)};return t.jsxs("div",{style:{minHeight:"100vh",display:"flex",alignItems:"center",justifyContent:"center",fontFamily:lr,backgroundColor:"#f8fafc",padding:20},children:[t.jsx("style",{children:` 56 .reset-input:focus { border-color: #0969da !important; box-shadow: 0 0 0 3px rgba(9,105,218,0.1); } 57 `}),t.jsxs("div",{style:{width:"100%",maxWidth:420,backgroundColor:"#fff",borderRadius:12,padding:"40px 36px",boxShadow:"0 1px 3px rgba(0,0,0,0.06), 0 6px 16px rgba(0,0,0,0.06)",border:"1px solid #e2e8f0"},children:[t.jsx("img",{src:"/OptimavoLogo.webp",alt:"Optimavo",style:{maxWidth:120,height:"auto",marginBottom:32}}),c?t.jsxs(t.Fragment,{children:[t.jsxs("div",{style:{padding:"14px 16px",backgroundColor:"#f0fdf4",border:"1px solid #bbf7d0",borderRadius:10,fontSize:14,color:"#15803d",lineHeight:1.6,marginBottom:24,display:"flex",gap:8,alignItems:"flex-start"},children:[t.jsx("span",{style:{flexShrink:0,marginTop:1},children:"â"}),t.jsx("span",{children:"Passwort wurde erfolgreich geändert. Sie können sich jetzt mit Ihrem neuen Passwort anmelden."})]}),t.jsx(nn,{to:"/login",style:{display:"block",textAlign:"center",padding:"11px 0",backgroundColor:"#0969da",color:"#fff",border:"none",borderRadius:8,fontSize:14,fontWeight:600,textDecoration:"none",fontFamily:lr},children:"Zur Anmeldung"})]}):p?t.jsxs(t.Fragment,{children:[t.jsx("h1",{style:{fontSize:22,fontWeight:700,color:"#0f172a",margin:"0 0 12px",letterSpacing:"-0.3px"},children:"Link ungültig oder abgelaufen"}),t.jsx("p",{style:{fontSize:14,color:"#64748b",margin:"0 0 24px",lineHeight:1.6},children:"Der Link zum Zurücksetzen des Passworts ist ungültig oder abgelaufen. Bitte fordern Sie einen neuen Link an."}),t.jsx(nn,{to:"/login",style:{display:"block",textAlign:"center",padding:"11px 0",backgroundColor:"#0969da",color:"#fff",border:"none",borderRadius:8,fontSize:14,fontWeight:600,textDecoration:"none",fontFamily:lr},children:"Zurück zur Anmeldung"})]}):u?t.jsxs(t.Fragment,{children:[t.jsx("h1",{style:{fontSize:22,fontWeight:700,color:"#0f172a",margin:"0 0 8px",letterSpacing:"-0.3px"},children:"Neues Passwort festlegen"}),t.jsx("p",{style:{fontSize:14,color:"#64748b",margin:"0 0 28px",lineHeight:1.6},children:"Geben Sie Ihr neues Passwort ein."}),t.jsxs("form",{onSubmit:g,noValidate:!0,style:{display:"flex",flexDirection:"column",gap:16},children:[t.jsxs("div",{children:[t.jsx("label",{style:{display:"block",fontSize:13,fontWeight:600,color:"#374151",marginBottom:6},children:"Neues Passwort"}),t.jsx("input",{className:"reset-input",type:"password",value:r,onChange:v=>e(v.target.value),autoFocus:!0,placeholder:"Mindestens 6 Zeichen",style:Ds})]}),t.jsxs("div",{children:[t.jsx("label",{style:{display:"block",fontSize:13,fontWeight:600,color:"#374151",marginBottom:6},children:"Passwort bestätigen"}),t.jsx("input",{className:"reset-input",type:"password",value:n,onChange:v=>s(v.target.value),placeholder:"Passwort wiederholen",style:Ds})]}),a&&t.jsx("div",{style:{padding:"10px 14px",backgroundColor:"#fff1f2",border:"1px solid #fecdd3",borderRadius:8,fontSize:13,color:"#be123c"},children:a}),t.jsx("button",{type:"submit",disabled:i,style:{padding:"11px 0",backgroundColor:i?"#93c5fd":"#0969da",color:"#fff",border:"none",borderRadius:8,fontSize:14,fontWeight:600,cursor:i?"default":"pointer",fontFamily:lr,marginTop:4,transition:"background-color 0.15s"},children:i?"Wird geändertâ¦":"Passwort ändern"})]}),t.jsx("div",{style:{textAlign:"center",marginTop:20},children:t.jsx(nn,{to:"/login",style:{fontSize:13,color:"#64748b",textDecoration:"none"},children:"Zurück zur Anmeldung"})})]}):t.jsx("div",{style:{textAlign:"center",padding:"20px 0"},children:t.jsx("p",{style:{fontSize:14,color:"#64748b"},children:"Link wird überprüft..."})})]})]})}const ki='-apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif',Zc={backgroundColor:"#ffffff",border:"1px solid #d0d7de",borderRadius:6,boxShadow:"0 1px 0 rgba(27,31,36,0.04)"},gn={width:"100%",padding:"8px 10px",border:"1px solid #d0d7de",borderRadius:6,fontSize:13,fontFamily:ki,outline:"none",boxSizing:"border-box"},Yc=["Gastronomie & Hotel","Handel & E-Commerce","Dienstleistungen","Gesundheit & Beauty","Handwerk & Bau","Immobilien","Bildung & Training","Sonstige"];function Xc(){var v,m;const{session:r,refreshProfile:e}=$e(),n=((m=(v=r==null?void 0:r.user)==null?void 0:v.user_metadata)==null?void 0:m.company_name)||"",[s,i]=h.useState(n),[o,a]=h.useState(""),[l,c]=h.useState(""),[d,u]=h.useState(""),[f,p]=h.useState(!1),x=Se(),g=async w=>{if(w.preventDefault(),u(""),!s.trim()){u("Bitte geben Sie einen Unternehmensnamen ein.");return}if(!o){u("Bitte wählen Sie eine Branche.");return}p(!0);try{let _=l.trim();_&&!/^https?:\/\//i.test(_)&&(_="https://"+_.replace(/^www\./i,"www.")),await qt.createCompany(s.trim(),o,_||null),e(),x("/onboarding/plattformen")}catch(_){u(_.message),p(!1)}};return t.jsxs("div",{style:{...Zc,padding:32},children:[t.jsxs("div",{style:{marginBottom:24},children:[t.jsx("h2",{style:{fontSize:18,fontWeight:700,color:"#24292f",margin:"0 0 8px"},children:"Ihr Unternehmen"}),t.jsx("p",{style:{fontSize:13,color:"#656d76",margin:0},children:"Wie heiÃt Ihr Unternehmen und in welcher Branche sind Sie tätig?"})]}),t.jsxs("form",{onSubmit:g,children:[t.jsxs("div",{style:{marginBottom:16},children:[t.jsx("label",{style:{display:"block",fontSize:13,fontWeight:600,color:"#24292f",marginBottom:6},children:"Unternehmensname *"}),t.jsx("input",{type:"text",value:s,onChange:w=>i(w.target.value),required:!0,autoFocus:!0,placeholder:"z.B. Muster GmbH",style:gn,onFocus:w=>w.target.style.borderColor="#0969da",onBlur:w=>w.target.style.borderColor="#d0d7de"})]}),t.jsxs("div",{style:{marginBottom:16},children:[t.jsx("label",{style:{display:"block",fontSize:13,fontWeight:600,color:"#24292f",marginBottom:6},children:"Branche *"}),t.jsxs("select",{value:o,onChange:w=>a(w.target.value),required:!0,style:{...gn,backgroundColor:"#fff",cursor:"pointer"},onFocus:w=>w.target.style.borderColor="#0969da",onBlur:w=>w.target.style.borderColor="#d0d7de",children:[t.jsx("option",{value:"",children:"Bitte wählenâ¦"}),Yc.map(w=>t.jsx("option",{value:w,children:w}
57,w))]})]}),t.jsxs("div",{style:{marginBottom:24},children:[t.jsxs("label",{style:{display:"block",fontSize:13,fontWeight:600,color:"#24292f",marginBottom:6},children:["Website ",t.jsx("span",{style:{fontWeight:400,color:"#656d76"},children:"(optional)"})]}),t.jsx("input",{type:"text",value:l,onChange:w=>c(w.target.value),placeholder:"www.beispiel.de",style:gn,onFocus:w=>w.target.style.borderColor="#0969da",onBlur:w=>w.target.style.borderColor="#d0d7de"})]}),d&&t.jsx("div",{style:{marginBottom:16,padding:"8px 12px",backgroundColor:"#ffebe9",border:"1px solid #ffcecb",borderRadius:6,fontSize:12,color:"#cf222e"},children:d}),t.jsx("button",{type:"submit",disabled:f,style:{width:"100%",padding:"10px 0",backgroundColor:f?"#9ab8e0":"#0969da",color:"#fff",border:"none",borderRadius:6,fontSize:14,fontWeight:600,cursor:f?"default":"pointer",fontFamily:ki},children:f?"Speichernâ¦":"Weiter â"})]})]})}const Us='-apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif',Qc={backgroundColor:"#ffffff",border:"1px solid #d0d7de",borderRadius:6,boxShadow:"0 1px 0 rgba(27,31,36,0.04)"},yt=r=>`https://www.google.com/s2/favicons?domain=${r}&sz=64`,ed=[{id:"google",label:"Google",logo:yt("google.com"),desc:"Google Maps & Search Bewertungen"},{id:"tripadvisor",label:"TripAdvisor",logo:yt("tripadvisor.com"),desc:"Reise- und Restaurantbewertungen"},{id:"trustpilot",label:"Trustpilot",logo:yt("trustpilot.com"),desc:"Unabhängige Kundenbewertungen"},{id:"trusted_shops",label:"Trusted Shops",logo:yt("trustedshops.de"),desc:"Gütesiegel & Kundenbewertungen"},{id:"amazon",label:"Amazon",logo:yt("amazon.de"),desc:"Verkäufer- und Produktbewertungen"},{id:"yelp",label:"Yelp",logo:yt("yelp.com"),desc:"Lokale Unternehmensbewertungen"},{id:"provenexpert",label:"ProvenExpert",logo:yt("provenexpert.com"),desc:"Professionelle Kundenbewertungen"}];function td(){const[r,e]=h.useState([]),[n,s]=h.useState(""),[i,o]=h.useState(!1),a=Se(),{profile:l,refreshProfile:c}=$e(),d=f=>{e(p=>p.includes(f)?p.filter(x=>x!==f):[...p,f])},u=async f=>{if(f.preventDefault(),r.length===0){s("Bitte wählen Sie mindestens eine Plattform.");return}if(s(""),o(!0),!(l==null?void 0:l.company_id)){s("Unternehmens-ID nicht gefunden. Bitte gehen Sie zurück."),o(!1);return}try{for(const x of r)await qt.connectPlatform(x,"");await qt.updateProfile({onboarding_step:3}),c(),a("/onboarding/setup")}catch(x){s(x.message),o(!1)}};return t.jsxs("div",{style:{...Qc,padding:32},children:[t.jsxs("div",{style:{marginBottom:24},children:[t.jsx("h2",{style:{fontSize:18,fontWeight:700,color:"#24292f",margin:"0 0 8px"},children:"Bewertungsplattformen"}),t.jsx("p",{style:{fontSize:13,color:"#656d76",margin:0},children:"Auf welchen Plattformen erhalten Sie Kundenbewertungen?"})]}),t.jsxs("form",{onSubmit:u,children:[t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:10,marginBottom:24},children:ed.map(f=>{const p=r.includes(f.id);return t.jsxs("div",{onClick:()=>d(f.id),style:{display:"flex",alignItems:"center",gap:12,padding:"12px 14px",border:`1px solid ${p?"#0969da":"#d0d7de"}`,borderRadius:6,cursor:"pointer",backgroundColor:p?"#dbeafe":"#fff",transition:"all 0.15s"},children:[t.jsx("div",{style:{width:18,height:18,borderRadius:3,border:`2px solid ${p?"#0969da":"#d0d7de"}`,backgroundColor:p?"#0969da":"#fff",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:p&&t.jsx("span",{style:{color:"#fff",fontSize:11,fontWeight:700},children:"â"})}),t.jsx("img",{src:f.logo,alt:f.label,style:{width:24,height:24,objectFit:"contain",borderRadius:4,flexShrink:0}}),t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:13,fontWeight:600,color:"#24292f"},children:f.label}),t.jsx("div",{style:{fontSize:12,color:"#656d76"},children:f.desc})]})]},f.id)})}),n&&t.jsx("div",{style:{marginBottom:16,padding:"8px 12px",backgroundColor:"#ffebe9",border:"1px solid #ffcecb",borderRadius:6,fontSize:12,color:"#cf222e"},children:n}),t.jsxs("div",{style:{display:"flex",gap:10},children:[t.jsx("button",{type:"button",onClick:()=>a("/onboarding/unternehmen"),style:{flex:1,padding:"10px 0",backgroundColor:"#fff",color:"#24292f",border:"1px solid #d0d7de",borderRadius:6,fontSize:14,fontWeight:600,cursor:"pointer",fontFamily:Us},children:"â Zurück"}),t.jsx("button",{type:"submit",disabled:i,style:{flex:2,padding:"10px 0",backgroundColor:i?"#9ab8e0":"#0969da",color:"#fff",border:"none",borderRadius:6,fontSize:14,fontWeight:600,cursor:i?"default":"pointer",fontFamily:Us},children:i?"Speichernâ¦":"Weiter â"})]})]})]})}function rd(r){return{ratingHistory:[{company_id:r,month:"2024-04-01",avg_rating:3.4,new_reviews:42},{company_id:r,month:"2024-05-01",avg_rating:3.5,new_reviews:38},{company_id:r,month:"2024-06-01",avg_rating:3.6,new_reviews:51},{company_id:r,month:"2024-07-01",avg_rating:3.5,new_reviews:47},{company_id:r,month:"2024-08-01",avg_rating:3.7,new_reviews:63},{company_id:r,month:"2024-09-01",avg_rating:3.6,new_reviews:58},{company_id:r,month:"2024-10-01",avg_rating:3.8,new_reviews:72},{company_id:r,month:"2024-11-01",avg_rating:3.7,new_reviews:69},{company_id:r,month:"2024-12-01",avg_rating:3.9,new_reviews:84},{company_id:r,month:"2025-01-01",avg_rating:3.8,new_reviews:77},{company_id:r,month:"2025-02-01",avg_rating:3.9,new_reviews:91},{company_id:r,month:"2025-03-01",avg_rating:3.8,new_reviews:88}],problemfelder:[{company_id:r,name:"Lieferzeiten",slug:"lieferzeiten",severity:"HOCH",prozent:42,avg_sterne:2.3,trend_value:"+23%",trend_direction:"steigend",sort_order:1},{company_id:r,name:"Produktqualität",slug:"produktqualitaet",severity:"HOCH",prozent:31,avg_sterne:2.8,trend_value:"
570%",trend_direction:"neutral",sort_order:2},{company_id:r,name:"Kundenservice",slug:"kundenservice",severity:"MITTEL",prozent:22,avg_sterne:3.1,trend_value:"-8%",trend_direction:"fallend",sort_order:3},{company_id:r,name:"Preis-Leistung",slug:"preis-leistung",severity:"MITTEL",prozent:15,avg_sterne:3.4,trend_value:"+2%",trend_direction:"neutral",sort_order:4}],alerts:[{company_id:r,type:"critical",title:"Kritischer Bewertungsrückgang",text:"3 Bewertungen mit 1 Stern in 7 Tagen, sofortiger Handlungsbedarf.",is_read:!1},{company_id:r,type:"warning",title:"Lieferzeiten: Neue Erwähnungen",text:"12 neue Bewertungen erwähnen Lieferprobleme. Trend: +23% Vorwoche.",is_read:!1},{company_id:r,type:"success",title:"Kundenservice verbessert",text:"Ihr Kundenservice-Score stieg um 0,3 Punkte auf 3,9/5.",is_read:!1},{company_id:r,type:"info",title:"Monatsbericht verfügbar",text:"Bewertungsbericht März 2025: 88 neue Bewertungen analysiert.",is_read:!1}],massnahmen:[{company_id:r,_problemName:"Lieferzeiten",titel:"Express-Versandoption einführen",prioritaet:"HOCH",status:"In Bearbeitung",fortschritt:65,warum:"Express-Lieferung (1-2 Werktage) für Bestandskunden reduziert Beschwerden direkt."},{company_id:r,_problemName:"Lieferzeiten",titel:"Echtzeit-Tracking implementieren",prioritaet:"HOCH",status:"In Bearbeitung",fortschritt:40,warum:"Kunden erwarten heute Sendungsverfolgung in Echtzeit."},{company_id:r,_problemName:"Produktqualität",titel:"Qualitätskontrolle verschärfen",prioritaet:"HOCH",status:"Offen",fortschritt:10,warum:"3-stufiger Qualitätscheck vor dem Versand eliminiert fehlerhafte Ware."},{company_id:r,_problemName:"Kundenservice",titel:"Support-Reaktionszeit < 4h",prioritaet:"MITTEL",status:"In Bearbeitung",fortschritt:75,warum:"SLA-Ziel: Erstreaktion innerhalb von 4 Stunden während Geschäftszeiten."},{company_id:r,_problemName:"Preis-Leistung",titel:"Treueprogramm einführen",prioritaet:"MITTEL",status:"Offen",fortschritt:5,warum:"Punkteprogramm steigert wahrgenommene Wertigkeit für Stammkunden."}]}}const Ms='-apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif',mn={backgroundColor:"#ffffff",border:"1px solid #d0d7de",borderRadius:6,boxShadow:"0 1px 0 rgba(27,31,36,0.04)"},yn=["Unternehmensprofil wird vorbereitetâ¦","Demo-Bewertungsdaten werden eingespieltâ¦","Kundenthemen werden analysiertâ¦","MaÃnahmen werden angelegtâ¦","Dashboard wird finalisiertâ¦"];function nd(){const[r,e]=h.useState(0),[n,s]=h.useState(!1),[i,o]=h.useState(""),a=Se(),{session:l,profile:c,refreshProfile:d}=$e();h.useEffect(()=>{u()},[]);const u=async()=>{try{const f=c==null?void 0:c.company_id;if(!f)throw new Error("Unternehmens-ID fehlt.");const p=rd(f);e(0),await sr(600),e(1);const{error:x}=await ie.from("rating_history").insert(p.ratingHistory);if(x)throw new Error("Bewertungsverlauf: "+x.message);await sr(600),e(2);const{data:g,error:v}=await ie.from("problemfelder").insert(p.problemfelder).select();if(v)throw new Error("Problemfelder: "+v.message);await sr(600),e(3);const m=p.massnahmen.map(({_problemName:y,...k})=>{var S;return{...k,problem_id:((S=g==null?void 0:g.find(T=>T.name===y))==null?void 0:S.id)??null}}),{error:w}=await ie.from("massnahmen").insert(m);if(w)throw new Error("MaÃnahmen: "+w.message);await sr(500),e(4);const{error:_}=await ie.from("alerts").insert(p.alerts);if(_)throw new Error("Alerts: "+_.message);const{error:b}=await ie.from("profiles").update({onboarding_done:!0,onboarding_step:4}).eq("id",l.user.id);if(b)throw new Error("Profil-Update: "+b.message);await sr(600),await d(),s(!0)}catch(f){o(f.message||"Ein Fehler ist aufgetreten.")}};return i?t.jsxs("div",{style:{...mn,padding:32,textAlign:"center"},children:[t.jsx("div",{style:{fontSize:40,marginBottom:16},children:"â ï¸"}),t.jsx("h2",{style:{fontSize:18,fontWeight:700,color:"#24292f",marginBottom:8},children:"Setup fehlgeschlagen"}),t.jsx("p",{style:{fontSize:13,color:"#656d76",marginBottom:20},children:i}),t.jsx("button",{onClick:u,style:{padding:"10px 24px",backgroundColor:"#0969da",color:"#fff",border:"none",borderRadius:6,fontSize:14,fontWeight:600,cursor:"pointer",fontFamily:Ms},children:"Erneut versuchen"})]}):n?t.jsxs("div",{style:{...mn,padding:40,textAlign:"center"},children:[t.jsx("div",{style:{width:64,height:64,borderRadius:"50%",backgroundColor:"#dafbe1",display:"flex",alignItems:"center",justifyContent:"center",margin:"0 auto 20px",fontSize:28},children:"â"}),t.jsx("h2",{style:{fontSize:20,fontWeight:700,color:"#24292f",margin:"0 0 10px"},children:"Alles bereit!"}),t.jsxs("p",{style:{fontSize:14,color:"#656d76",margin:"0 0 28px",lineHeight:1.6}
57,children:["Ihr Dashboard wurde eingerichtet und mit Demo-Daten befüllt.",t.jsx("br",{}),"Sie können jetzt loslegen."]}),t.jsx("button",{onClick:()=>a("/dashboard"),style:{padding:"12px 32px",backgroundColor:"#1a7f37",color:"#fff",border:"none",borderRadius:6,fontSize:15,fontWeight:700,cursor:"pointer",fontFamily:Ms},children:"Zum Dashboard â"})]}):t.jsxs("div",{style:{...mn,padding:40,textAlign:"center"},children:[t.jsxs("div",{style:{marginBottom:24},children:[t.jsx("div",{style:{display:"inline-block",width:48,height:48,borderRadius:"50%",border:"3px solid #eaecef",borderTopColor:"#0969da",animation:"spin 0.8s linear infinite"}}),t.jsx("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),t.jsx("h2",{style:{fontSize:18,fontWeight:700,color:"#24292f",margin:"0 0 8px"},children:"Dashboard wird eingerichtetâ¦"}),t.jsx("p",{style:{fontSize:13,color:"#656d76",margin:"0 0 28px",minHeight:20},children:yn[r]}),t.jsx("div",{style:{backgroundColor:"#eaecef",borderRadius:4,height:6,overflow:"hidden",maxWidth:320,margin:"0 auto"},children:t.jsx("div",{style:{height:"100%",borderRadius:4,backgroundColor:"#0969da",width:`${(r+1)/yn.length*100}%`,transition:"width 0.4s ease"}})}),t.jsx("div",{style:{marginTop:24,textAlign:"left",maxWidth:280,margin:"24px auto 0"},children:yn.map((f,p)=>t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,marginBottom:8},children:[t.jsx("div",{style:{width:20,height:20,borderRadius:"50%",flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",fontSize:11,fontWeight:700,backgroundColor:p<r?"#1a7f37":p===r?"#0969da":"#eaecef",color:p<=r?"#fff":"#656d76"},children:p<r?"â":p+1}),t.jsx("span",{style:{fontSize:12,color:p<=r?"#24292f":"#8c959f",fontWeight:p===r?600:400},children:f.replace("â¦","")})]},p))})]})}function sr(r){return new Promise(e=>setTimeout(e,r))}const sd='-apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif',xn=[{path:"unternehmen",label:"Unternehmen"},{path:"plattformen",label:"Plattformen"},{path:"setup",label:"Einrichten"}];function id(){const r=$n(),e=xn.findIndex(s=>r.pathname.includes(s.path)),n=e>=0?e:0;return t.jsxs("div",{style:{minHeight:"100vh",backgroundColor:"#f6f8fa",fontFamily:sd},children:[t.jsxs("div",{style:{backgroundColor:"#fff",borderBottom:"1px solid #d0d7de",padding:"12px 24px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[t.jsx("img",{src:"/OptimavoLogo.webp",alt:"Optimavo",style:{maxWidth:140,height:"auto"}}),t.jsx("div",{style:{display:"flex",alignItems:"center",gap:8},children:xn.map((s,i)=>t.jsxs(Dn.Fragment,{children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[t.jsx("div",{style:{width:24,height:24,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",fontSize:12,fontWeight:700,backgroundColor:i<n?"#1a7f37":i===n?"#0969da":"#eaecef",color:i<=n?"#fff":"#656d76"},children:i<n?"â":i+1}),t.jsx("span",{style:{fontSize:12,color:i===n?"#24292f":"#656d76",fontWeight:i===n?600:400,display:window.innerWidth>600?"inline":"none"},children:s.label})]}),i<xn.length-1&&t.jsx("div",{style:{width:24,height:1,backgroundColor:i<n?"#1a7f37":"#d0d7de"}})]},s.path))}),t.jsx("div",{style:{width:140}})]}),t.jsx("div",{style:{maxWidth:600,margin:"48px auto",padding:"0 16px"},children:t.jsxs(pr,{children:[t.jsx(K,{index:!0,element:t.jsx(ee,{to:"unternehmen",replace:!0})}),t.jsx(K,{path:"unternehmen",element:t.jsx(Xc,{})}),t.jsx(K,{path:"plattformen",element:t.jsx(td,{})}),t.jsx(K,{path:"wettbewerber",element:t.jsx(ee,{to:"../setup",replace:!0})}),t.jsx(K,{path:"setup",element:t.jsx(nd,{})})]})})]})}const zn='-apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif',bn={width:"100%",fontSize:14,border:"1px solid #d0d7de",borderRadius:10,padding:"11px 14px",fontFamily:zn,outline:"none",boxSizing:"border-box",transition:"border-color 0.15s"},od={admin:"Administrator",manager:"Manager",viewer:"Betrachter"};function ad(){const r=Se(),{session:e,profile:n,refreshProfile:s}=$e(),[i,o]=h.useState(""),[a,l]=h.useState(""),[c,d]=h.useState(""),[u,f]=h.useState(""),[p,x]=h.useState(!1),[g,v]=h.useState(""),[m,w]=h.useState(!0);h.useEffect(()=>{e&&(async()=>{var y,k;try{const S=await fetch("https://review-scraper-production-9324.up.railway.app/user/profile",{headers:{Authorization:`Bearer ${e.access_token}`}});if(S.ok){const T=await S.json();o(((y=T.companies)==null?void 0:y.name)||((k=T.company)==null?void 0:k.name)||"")}}catch{}finally{w(!1)}})()},[e]);const _=async y=>{if(y.preventDefault(),v(""),!a.trim()){v("Bitte geben Sie Ihren vollständigen Namen ein.");return}if(c.length<8){v("Passwort muss mindestens 8 Zeichen lang sein.");return}if(c!==u){v("Passwörter stimmen nicht überein.");return}x(!0);try{const{error:k}=await ie.auth.updateUser({password:c});if(k)throw new Error(k.message);const{error:S}=await ie.from("profiles").update({full_name:a.trim(),onboarding_done:!0,onboarding_step:5}).eq("id",e.user.id);if(S)throw new Error(S.message);s&&await s(),r("/dashboard",{replace:!0})}catch(k){v(k.message||"Ein Fehler ist aufgetreten.")}finally{x(!1)}};if(m)return t.jsx("div",{style:{minHeight:"100vh",display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:"#f8fafc"},children:t.jsx("div",{style:{width:48,height:64,overflow:"hidden"},children:t.jsx("img",{src:"/loading-animation.gif",alt:"Ladenâ¦",style:{width:64,height:64,objectFit:"contain",marginLeft:-2}})})});const b=od[n==null?void 0:n.role]||(n==null?void 0:n.role)||"Mitglied";return t.jsxs("div",{style:{minHeight:"100vh",display:"flex",alignItems:"center",justifyContent:"center",fontFamily:zn,backgroundColor:"#f8fafc",padding:20},children:[t.jsx("style",{children:` 58 .invite-input:focus { border-color: #0969da !important; box-shadow: 0 0 0 3px rgba(9,105,218,0.1); } 59 `}),t.jsxs("div",{style:{width:"100%",maxWidth:440},children:[t.jsx("div",{style:{textAlign:"center",marginBottom:32},children:t.jsx("img",{src:"/OptimavoLogo.webp",alt:"Optimavo",style:{maxWidth:140,height:"auto"}})}),t.jsxs("div",{style:{backgroundColor:"#fff",borderRadius:16,boxShadow:"0 4px 24px rgba(15,23,42,0.08)",padding:"40px 36px",border:"1px solid #e2e8f0"},children:[t.jsxs("div",{style:{textAlign:"center",marginBottom:28},children:[t.jsx("div",{style:{width:56,height:56,borderRadius:"50%",background:"linear-gradient(135deg, #ddf4ff, #b6d9fc)",display:"flex",alignItems:"center",justifyContent:"center",margin:"0 auto 16px",fontSize:24},children:"ð"}),t.jsxs("h1",{style:{fontSize:22,fontWeight:700,color:"#0f172a",margin:"0 0 6px",letterSpacing:"-0.3px"}
59,children:["Willkommen",i?` bei ${i}`:"","!"]}),t.jsxs("p",{style:{fontSize:14,color:"#64748b",margin:0,lineHeight:1.5},children:["Sie wurden als ",t.jsx("strong",{style:{color:"#0969da"},children:b})," eingeladen.",` 60`,"Vervollständigen Sie Ihr Konto, um loszulegen."]})]}),t.jsxs("form",{onSubmit:_,noValidate:!0,style:{display:"flex",flexDirection:"column",gap:16},children:[t.jsxs("div",{children:[t.jsx("label",{style:{display:"block",fontSize:13,fontWeight:600,color:"#374151",marginBottom:6},children:"Vollständiger Name"}),t.jsx("input",{className:"invite-input",type:"text",value:a,onChange:y=>l(y.target.value),autoFocus:!0,placeholder:"Max Mustermann",style:bn})]}),t.jsxs("div",{children:[t.jsx("label",{style:{display:"block",fontSize:13,fontWeight:600,color:"#374151",marginBottom:6},children:"Passwort festlegen"}),t.jsx("input",{className:"invite-input",type:"password",value:c,onChange:y=>d(y.target.value),placeholder:"Mindestens 8 Zeichen",style:bn})]}),t.jsxs("div",{children:[t.jsx("label",{style:{display:"block",fontSize:13,fontWeight:600,color:"#374151",marginBottom:6},children:"Passwort bestätigen"}),t.jsx("input",{className:"invite-input",type:"password",value:u,onChange:y=>f(y.target.value),placeholder:"Passwort wiederholen",style:bn})]}),g&&t.jsx("div",{style:{padding:"10px 14px",backgroundColor:"#fef2f2",border:"1px solid #fecaca",borderRadius:10,fontSize:13,color:"#dc2626"},children:g}),t.jsx("button",{type:"submit",disabled:p,style:{width:"100%",padding:"12px 20px",fontSize:15,fontWeight:700,color:"#fff",backgroundColor:p?"#8c959f":"#0969da",border:"none",borderRadius:10,cursor:p?"wait":"pointer",fontFamily:zn,marginTop:4,transition:"background-color 0.15s"},children:p?"Wird eingerichtetâ¦":"Einladung annehmen"})]})]}),t.jsx("p",{style:{textAlign:"center",fontSize:12,color:"#94a3b8",marginTop:20},children:"Powered by Optimavo · Bewertungsanalyse & Reputationsmanagement"})]})]})}const ld="https://review-scraper-production-9324.up.railway.app",Ei=h.createContext(null),cd=120*1e3,fr="optimavo_dashboard_cache",dd=300*1e3;function ud(r){try{const e=localStorage.getItem(fr);if(!e)return null;const{data:n,timestamp:s,id:i}=JSON.parse(e);return i!==r||Date.now()-s>dd?null:n}catch{return null}}function Ws(r,e){try{localStorage.setItem(fr,JSON.stringify({data:e,timestamp:Date.now(),id:r}))}catch{}}const Jt=()=>h.useContext(Ei)||{data:null,loading:!1,error:null,isLive:!1,analysisReady:!1,reviewsOnly:!1,liveMode:!1,hasExistingReport:!1};async function hd(){const{data:{session:r}}=await ie.auth.getSession();if(r!=null&&r.access_token){const e={Authorization:`Bearer ${r.access_token}`};return window.__optimavoAuthHeaders=e,e}return{}}function Ir(){try{if(typeof window>"u")return null;const e=new URLSearchParams(window.location.search).get("preview");if(e){try{sessionStorage.setItem("optimavo_preview_company_id",e)}catch{}return e}try{return sessionStorage.getItem("optimavo_preview_company_id")||null}catch{return null}}catch{return null}}function fd({children:r}){const[e]=h.useState(()=>Ir()),[n,s]=h.useState(()=>{const D=Ir();if(D)return D;try{return localStorage.getItem("optimavo_company_id")||null}catch{return null}}),[i]=h.useState(()=>{try{const D=localStorage.getItem("optimavo_company_id");return D?ud(D):null}catch{return null}}),[o,a]=h.useState(i),[l,c]=h.useState(!1),[d,u]=h.useState(null),f=h.useRef(!1),[p,x]=h.useState(()=>{if(Ir())return!1;try{return!!localStorage.getItem("optimavo_live_mode")}catch{return!1}}),[g,v]=h.useState(()=>{if(Ir())return null;try{return i!=null&&i.hasAnalysis||localStorage.getItem("optimavo_has_report")==="true"?!0:null}catch{return null}});h.useEffect(()=>{if(e)return;(async()=>{var Y;try{const{data:{session:te}}=await ie.auth.getSession();if(!((Y=te==null?void 0:te.user)!=null&&Y.id))return;const{data:X}=await ie.from("profiles").select("company_id").eq("id",te.user.id).single();if(X!=null&&X.company_id&&X.company_id!==n){console.log("[DashboardData] User switch detected, updating companyId:",X.company_id),s(X.company_id);try{localStorage.setItem("optimavo_company_id",X.company_id),localStorage.removeItem(fr),localStorage.removeItem("optimavo_has_report")}catch{}v(null),a(null),u(null),f.current=!1}if(X!=null&&X.company_id){const{count:Ce}=await ie.from("platforms").select("id",{count:"exact",head:!0}).eq("company_id",X.company_id).eq("is_active",!0).not("profile_url","is",null);if(Ce>0&&!p){try{X.company_id&&localStorage.setItem("optimavo_company_id",X.company_id),localStorage.setItem("optimavo_live_mode","1")}catch{}X.company_id&&s(X.company_id),x(!0)}}}catch(te){console.warn("[DashboardData] Profile check failed:",te.message)}})()},[]);const[m,w]=h.useState(()=>{try{const D=sessionStorage.getItem("optimavo_reconnect_until");return D?parseInt(D,10):0}catch{return 0}}),[_,b]=h.useState(()=>{try{const D=sessionStorage.getItem("optimavo_reconnect_until");return D?Date.now()<parseInt(D,10):!1}catch{return!1}});h.useEffect(()=>{if(!m||Date.now()>=m){b(!1);return}b(!0);const D=m-Date.now(),Y=setTimeout(()=>{b(!1),sessionStorage.removeItem("optimavo_reconnect_until")},D);return()=>clearTimeout(Y)},[m]);const y=h.useCallback(D=>{try{D&&localStorage.setItem("optimavo_company_id",D),localStorage.setItem("optimavo_live_mode","1"),localStorage.removeItem(fr)}catch{}D&&s(D),x(!0),a(null);const Y=Date.now()+cd;try{sessionStorage.setItem("optimavo_reconnect_until",String(Y))}catch{}w(Y),b(!0)},[]),k=h.useCallback(()=>{try{localStorage.removeItem("optimavo_company_id"),localStorage.removeItem("optimavo_live_mode"),localStorage.removeItem(fr),sessionStorage.removeItem("optimavo_reconnect_until")}catch{}s(null),x(!1),a(null),w(0),b(!1),v(!1)},[]),[S,T]=h.useState(()=>{try{return sessionStorage.getItem("optimavo_time_range")||"all"}catch{return"all"}}
60),[V,C]=h.useState(!1),z=h.useRef(S),H=h.useRef(0),G=h.useCallback(D=>{D!==z.current&&(C(!0),H.current=Date.now(),z.current=D),T(D);try{sessionStorage.setItem("optimavo_time_range",D)}catch{}},[]),O=h.useRef(o);O.current=o;const F=h.useRef(S);F.current=S;const ne=h.useCallback(async({background:D=!1}={})=>{if(n&&!(D&&document.hidden))try{!D&&!O.current&&c(!0);const Y=await hd(),te=F.current,X=[];te!=="all"&&X.push(`timeRange=${te}`),e&&X.push("preview=1");const Ce=`${ld}/dashboard/${n}${X.length?`?${X.join("&")}`:""}`,N=await fetch(Ce,{headers:Y});if(N.status===401||N.status===403){console.warn(`[DashboardData] ${N.status}, waiting for auth/company sync`);return}if(!N.ok)throw new Error(`API error: ${N.status}`);const ze=await N.json();if(a(ze),e||Ws(n,ze),u(null),ze.totalReviews>0&&x(!0),ze.hasAnalysis){if(v(!0),!e)try{localStorage.setItem("optimavo_has_report","true")}catch{}}else if(g===null&&(v(!1),!e))try{localStorage.removeItem("optimavo_has_report")}catch{}}catch(Y){D||u(Y.message)}finally{c(!1);const Y=Date.now()-H.current,te=500;Y<te?setTimeout(()=>C(!1),te-Y):C(!1)}},[n]);h.useEffect(()=>{n&&(f.current=!1,ne())},[n,ne]),h.useEffect(()=>{const{data:{subscription:D}}=ie.auth.onAuthStateChange((Y,te)=>{var X;(Y==="SIGNED_IN"||Y==="TOKEN_REFRESHED"||Y==="INITIAL_SESSION")&&te&&n&&(!((X=O.current)!=null&&X.hasAnalysis)||d)&&(f.current||(f.current=!0,console.log("[DashboardData] Auth session ready, re-fetching data"),ne()))});return()=>D==null?void 0:D.unsubscribe()},[n,ne,d]);const re=h.useRef(S);h.useEffect(()=>{re.current!==S&&n&&p&&(re.current=S,setTimeout(()=>ne(),50))},[S]);const J=o==null?void 0:o.hasAnalysis;h.useEffect(()=>{J&&v(!0)},[J]),h.useEffect(()=>{if(!n||!p)return;const D=setInterval(()=>ne({background:!0}),_?15e3:12e4);return()=>clearInterval(D)},[n,p,J,_,ne]);const ke=h.useRef(0);return h.useEffect(()=>{const D=()=>{if(!document.hidden&&n){const Y=Date.now();if(Y-ke.current<6e4)return;ke.current=Y,ne({background:!0})}};return document.addEventListener("visibilitychange",D),()=>document.removeEventListener("visibilitychange",D)},[n,ne]),t.jsx(Ei.Provider,{value:{data:o,loading:l,error:d,companyId:n,previewMode:!!e,isLive:!!e&&!!o||(!_||(o==null?void 0:o.debugMode))&&!!o&&o.totalReviews>0&&(o.hasAnalysis||o.analyzedReviews>=o.totalReviewsAll&&o.totalReviewsAll>=5)&&!(o!=null&&o.visibleAfter&&new Date(o.visibleAfter)>new Date),analysisReady:(!_||(o==null?void 0:o.debugMode))&&!!o&&(o.hasAnalysis||o.analyzedReviews>=o.totalReviewsAll&&o.totalReviewsAll>=5)&&!(o!=null&&o.visibleAfter&&new Date(o.visibleAfter)>new Date),analysisProcessing:!!(o!=null&&o.visibleAfter)&&new Date(o.visibleAfter)>new Date,reviewsOnly:(!_||(o==null?void 0:o.debugMode))&&!!o&&o.totalReviews>0&&!o.hasAnalysis&&!(o.analyzedReviews>=o.totalReviewsAll&&o.totalReviewsAll>=5),dataLoaded:!!o,liveMode:p,hasExistingReport:g,cooldownActive:_,timeRange:S,setTimeRange:G,timeRangeLoading:V,activateLiveMode:y,deactivateLiveMode:k,refetch:ne,patchMeasureProgress:(D,Y)=>{a(te=>{var Ce;if(!te)return te;const X={...te,measureProgress:{...te.measureProgress,[D]:{...((Ce=te.measureProgress)==null?void 0:Ce[D])||{},...Y}}};try{const N=n||localStorage.getItem("optimavo_company_id");N&&Ws(N,X)}catch{}return X})}},children:r})}const Ye='-apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif',pd=()=>t.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:t.jsx("path",{d:"M8 0a8.2 8.2 0 0 1 .701.031C9.444.095 9.99.645 10.16 1.29l.288 1.107c.018.066.079.158.212.224.231.114.454.243.668.386.123.082.233.09.299.071l1.103-.303c.644-.176 1.392.021 1.82.63.27.385.506.792.704 1.218.315.675.111 1.422-.364 1.891l-.814.806c-.049.048-.098.147-.088.294.016.257.016.515 0 .772-.01.147.039.246.088.294l.814.806c.475.469.679 1.216.364 1.891a7.977 7.977 0 0 1-.704 1.217c-.428.61-1.176.807-1.82.63l-1.102-.302c-.067-.019-.177-.011-.3.071a5.909 5.909 0 0 1-.668.386c-.133.066-.194.158-.211.224l-.29 1.106c-.168.646-.715 1.196-1.458 1.26a8.006 8.006 0 0 1-1.402 0c-.743-.064-1.289-.614-1.458-1.26l-.289-1.106c-.018-.066-.079-.158-.212-.224a5.738 5.738 0 0 1-.668-.386c-.123-.082-.233-.09-.299-.071l-1.103.303c-.644.176-1.392-.021-1.82-.63a8.12 8.12 0 0 1-.704-1.218c-.315-.675-.111-1.422.363-1.891l.815-.806c.05-.048.098-.147.088-.294a6.214 6.214 0 0 1 0-.772c.01-.147-.038-.246-.088-.294l-.815-.806C.635 6.045.431 5.298.746 4.623a7.92 7.92 0 0 1 .704-1.217c.428-.61 1.176-.807 1.82-.63l
601.102.302c.067.019.177.011.3-.071.214-.143.437-.272.668-.386.133-.066.194-.158.211-.224l.29-1.106C6.009.645 6.556.095 7.299.03 7.53.01 7.764 0 8 0Zm-.571 1.525c-.036.003-.108.036-.137.146l-.289 1.105c-.147.561-.549.967-.998 1.189-.173.086-.34.183-.5.29-.417.278-.97.423-1.529.27l-1.103-.303c-.109-.03-.175.016-.195.045-.22.312-.412.644-.573.99-.014.031-.021.11.059.19l.815.806c.411.406.562.957.53 1.456a4.709 4.709 0 0 0 0 .582c.032.499-.119 1.05-.53 1.456l-.815.806c-.081.08-.073.159-.059.19.162.346.353.677.573.989.02.03.085.076.195.046l1.102-.303c.56-.153 1.113-.008 1.53.27.161.107.328.204.501.29.447.222.85.629.997 1.189l.289 1.105c.029.109.101.143.137.146a6.6 6.6 0 0 0 1.142 0c.036-.003.108-.036.137-.146l.289-1.105c.147-.561.549-.967.998-1.189.173-.086.34-.183.5-.29.417-.278.97-.423 1.529-.27l1.103.303c.109.029.175-.016.195-.045.22-.313.411-.644.573-.99.014-.031.021-.11-.059-.19l-.815-.806c-.411-.406-.562-.957-.53-1.456a4.709 4.709 0 0 0 0-.582c-.032-.499.119-1.05.53-1.456l.815-.806c.081-.08.073-.159.059-.19a6.464 6.464 0 0 0-.573-.989c-.02-.03-.085-.076-.195-.046l-1.102.303c-.56.153-1.113.008-1.53-.27a4.44 4.44 0 0 0-.501-.29c-.447-.222-.85-.629-.997-1.189l-.289-1.105c-.029-.11-.101-.143-.137-.146a6.6 6.6 0 0 0-1.142 0ZM8 5.5a2.5 2.5 0 1 1 0 5 2.5 2.5 0 0 1 0-5Z"})}),gd=()=>t.jsx("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"currentColor",children:t.jsx("path",{fillRule:"evenodd",d:"M2 2.75C2 1.784 2.784 1 3.75 1h2.5a.75.75 0 0 1 0 1.5h-2.5a.25.25 0 0 0-.25.25v10.5c0 .138.112.25.25.25h2.5a.75.75 0 0 1 0 1.5h-2.5A1.75 1.75 0 0 1 2 13.25Zm10.44 4.5-1.97-1.97a.749.749 0 0 1 .326-1.275.749.749 0 0 1 .734.215l3.25 3.25a.75.75 0 0 1 0 1.06l-3.25 3.25a.749.749 0 0 1-1.275-.326.749.749 0 0 1 .215-.734l1.97-1.97H6.75a.75.75 0 0 1 0-1.5Z"})}),md=()=>t.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:t.jsx("path",{d:"M4 4a4 4 0 0 1 8 0v2h.25c.966 0 1.75.784 1.75 1.75v5.5A1.75 1.75 0 0 1 12.25 15h-8.5A1.75 1.75 0 0 1 2 13.25v-5.5C2 6.784 2.784 6 3.75 6H4Zm8.25 3.5h-8.5a.25.25 0 0 0-.25.25v5.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-5.5a.25.25 0 0 0-.25-.25ZM10.5 6V4a2.5 2.5 0 1 0-5 0v2Z"})}),Bn={"/dashboard":["owner","admin","manager","viewer"],"/monitoring":["owner","admin","manager","viewer"],"/themen":["owner","admin","manager"],"/massnahmen":["owner","admin","manager"],"/insights":["owner","admin","manager"],"/wettbewerb":["owner","admin","manager"],"/einstellungen":["owner","admin"]},yd=[{to:"/dashboard",label:"Dashboard",tourId:"nav-dashboard",icon:t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[t.jsx("path",{d:"M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"}),t.jsx("polyline",{points:"9 22 9 12 15 12 15 22"})]})},{to:"/monitoring",label:"Monitoring",tourId:"nav-monitoring",icon:t.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:t.jsx("path",{d:"M22 12h-4l-3 9L9 3l-3 9H2"})})},{to:"/themen",label:"Themen",tourId:"nav-probleme",icon:t.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:t.jsx("path",{d:"M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"})}),matchPaths:["/themen"]},{to:"/massnahmen",label:"MaÃnahmen",tourId:"nav-massnahmen",icon:t.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:t.jsx("path",{d:"M2.5 1.75v11.5c0 .138.112.25.25.25h3.17a.75.75 0 0 1 0 1.5H2.75A1.75 1.75 0 0 1 1 13.25V1.75C1 .784 1.784 0 2.75 0h8.5C12.216 0 13 .784 13 1.75v7.736a.75.75 0 0 1-1.5 0V1.75a.25.25 0 0 0-.25-.25h-8.5a.25.25 0 0 0-.25.25Zm3.5 6.25a.75.75 0 0 1 .75-.75h4a.75.75 0 0 1 0 1.5h-4a.75.75 0 0 1-.75-.75ZM6.75 4a.75.75 0 0 0 0 1.5h4a.75.75 0 0 0 0-1.5h-4Zm3.74 9.22a.75.75 0 0 1 1.06 0l.97.97.97-.97a.75.75 0 1 1 1.06 1.06l-.97.97.97.97a.75.75 0 1 1-1.06 1.06l-.97-.97-.97.97a.75.75 0 0 1-1.06-1.06l.97-.97-.97-.97a.75.75 0 0 1 0-1.06Z"})}),matchPaths:["/massnahmen"]},{to:"/insights",label:"Insights",tourId:"nav-insights",icon:t.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:t.jsx("path",{d:"M8 1.5a6.5 6.5 0 1 0 0 13 6.5 6.5 0 0 0 0-13ZM0 8a8 8 0 1 1 16 0A8 8 0 0 1 0 8Zm9 3a1 1 0 1 1-2 0 1 1 0 0 1 2 0Zm-.25-6.25a.75.75 0 0 0-1.5 0v3.5a.75.75 0 0 0 1.5 0v-3.5Z"})})},{to:"/wettbewerb",label:"Wettbewerb",tourId:"nav-wettbewerb",icon:t.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:t.jsx("path",{d:"M1.5 1.75a.75.75 0 0 0-1.5 0v12.5c0 .414.336.75.75.75h14.5a.75.75 0 0 0 0-1.5H1.5V1.75ZM14 10.04a.75.75 0 0 1-1.158.635L9.75 8.882l-2.36 2.836
60a.75.75 0 0 1-1.05.1L3.25 9.26a.75.75 0 1 1 .96-1.152l2.59 2.158 2.391-2.876a.75.75 0 0 1 1.074-.098l3.25 2.35A.75.75 0 0 1 14 10.04Z"})})}];function xd({collapsed:r=!1,onToggle:e,locked:n=!1}){var k;const{profile:s,company:i}=$e(),{previewMode:o,data:a}=Jt(),l=Se(),[c,d]=h.useState(!1),[u,f]=h.useState(!1),[p,x]=h.useState(!0);h.useEffect(()=>{const S=setTimeout(()=>x(!1),4e3);return()=>clearTimeout(S)},[]);const g=p||u,m=o&&((k=a==null?void 0:a.company)==null?void 0:k.name)||null||(s==null?void 0:s.full_name)||"Nutzer",w=m.charAt(0).toUpperCase(),_=o?"Vorschau":(s==null?void 0:s.role)==="admin"?"Admin":"Inhaber",b=async()=>{await ie.auth.signOut(),l("/login")},y=r?56:240;return t.jsxs("aside",{style:{width:y,flexShrink:0,backgroundColor:"#ffffff",borderRight:"1px solid #e5e7eb",height:"100vh",position:"fixed",top:0,left:0,zIndex:50,display:"flex",flexDirection:"column",fontFamily:Ye,transition:"width 0.2s ease",overflow:"hidden"},children:[t.jsx("div",{style:{padding:r?"10px 0":"12px 12px",borderBottom:"1px solid #eaecef",display:"flex",alignItems:"center",justifyContent:r?"center":"space-between",gap:8,minHeight:52,flexWrap:"nowrap",flexDirection:r?"column":"row"},children:r?t.jsxs(t.Fragment,{children:[t.jsx("div",{onMouseEnter:()=>f(!0),onMouseLeave:()=>f(!1),style:{width:32,height:32,cursor:"pointer",flexShrink:0,position:"relative"},onClick:()=>window.location.href="https://optimavo.de",children:t.jsx("img",{src:g?"/loading-animation.gif":"/Icon.png",alt:"Optimavo",style:{width:32,height:32,objectFit:"contain",position:"absolute",top:0,left:0}})}),t.jsx("button",{onClick:()=>e(),style:{width:32,height:22,borderRadius:4,border:"1px solid #d0d7de",backgroundColor:"#f6f8fa",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",color:"#656d76",padding:0},children:t.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:t.jsx("path",{d:"M8.22 2.97a.75.75 0 0 1 1.06 0l4.25 4.25a.75.75 0 0 1 0 1.06l-4.25 4.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l2.97-2.97H3.75a.75.75 0 0 1 0-1.5h7.44L8.22 4.03a.75.75 0 0 1 0-1.06Z"})})})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{style:{flex:1,minWidth:0,maxWidth:160,cursor:"pointer",position:"relative"},onClick:()=>window.location.href="https://optimavo.de",onMouseEnter:()=>f(!0),onMouseLeave:()=>f(!1),children:[t.jsx("img",{src:"/OptimavoLogo.webp",alt:"Optimavo",style:{width:"100%",height:"auto",display:"block",opacity:g?0:1,transition:"opacity 0.2s"}}),t.jsx("img",{src:"/LogoAnimiert.gif",alt:"",style:{position:"absolute",top:0,left:0,width:"100%",height:"auto",display:"block",opacity:g?1:0,transition:"opacity 0.2s",pointerEvents:"none"}})]}),t.jsx("button",{onClick:()=>e(),style:{flexShrink:0,width:28,height:28,borderRadius:6,border:"1px solid #d0d7de",backgroundColor:"#f6f8fa",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",color:"#656d76"},children:t.jsx("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"currentColor",children:t.jsx("path",{d:"M7.78 12.53a.75.75 0 0 1-1.06 0L2.47 8.28a.75.75 0 0 1 0-1.06l4.25-4.25a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042L4.81 7h7.44a.75.75 0 0 1 0 1.5H4.81l2.97 2.97a.75.75 0 0 1 0 1.06Z"})})})]})}),t.jsxs("nav",{style:{flex:1,padding:"8px"},children:[!r&&t.jsx("p",{style:{fontSize:11,fontWeight:600,color:"#656d76",textTransform:"uppercase",letterSpacing:"0.04em",padding:"6px 8px 4px",margin:0},children:"Navigation"}),yd.filter(({to:S})=>{if(o)return!0;const T=(s==null?void 0:s.role)||"viewer",V=Bn[S];return!V||V.includes(T)}).map(({to:S,label:T,icon:V,matchPaths:C,tourId:z})=>n&&!(S==="/dashboard")?t.jsxs("div",{title:r?`${T} (Plan erforderlich)`:void 0,style:{display:"flex",alignItems:"center",gap:r?0:8,justifyContent:r?"center":"flex-start",width:"100%",padding:r?"10px 0":"7px 10px",borderRadius:8,marginBottom:2,fontSize:13,fontWeight:400,color:"#c0c5cc",cursor:"default",backgroundColor:"transparent",fontFamily:Ye,borderLeft:"3px solid transparent"},children:[t.jsx("span",{style:{display:"flex",flexShrink:0,transform:r?"scale(1.25)":"none",opacity:.4},children:V}),!r&&t.jsx("span",{style:{flex:1},children:T}),!r&&t.jsx(md,{})]},S):t.jsxs(Zs,{to:S,title:r?T:void 0,"data-tour":z,style:({isActive:O})=>{const F=O||(C==null?void 0:C.some(ne=>location.pathname.startsWith(ne)));return{display:"flex",alignItems:"center",gap:r?0:8,justifyContent:r?"center":"flex-start",width:"100%",textDecoration:"none",padding:r?"10px 0":"7px 10px",borderRadius:8,marginBottom:2,fontSize:13,fontWeight:F?600:400,color:F?"#0969da":"#656d76",backgroundColor:F?"#eff6ff":"transparent",fontFamily:Ye,transition:"all 0.15s",borderLeft:F&&!r?"3px solid #0969da":"3px solid transparent"}},children:[t.jsx("span",{style:{display:"flex",flexShrink:0,transform:r?"scale(1.25)":"none"},children:V}),!r&&T]},S)),n&&!r&&t.jsxs("div",{style:{margin:"12px 6px 0",padding:"14px 12px",borderRadius:10,background:"linear-gradient(135deg, #eff6ff, #f0fdf4)",border:"1px solid #bfdbfe"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,marginBottom:6},children:[t.jsx("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"#0969da",children:t.jsx("path",{d:"M8.22 2.97a.75.75 0 0 1 1.06 0l4.25 4.25a.75.75 0 0 1 0 1.06l-4.25 4.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l2.97-2.97H3.75a.75.75 0 0 1 0-1.5h7.44L8.22 4.03a.75.75 0 0 1 0-1.06Z"})}),t.jsx("span",{style:{fontSize:11,fontWeight:700,color:"#0969da"},children:"Plan wählen"})]}),t.jsx("p",{style:{fontSize:11,color:"#475569",margin:"0 0 10px",lineHeight:1.5},children:"Alle Features freischalten und Ihre Bewertungen analysieren."}),t.jsx("a",{href:"/kontakt",target:"_blank",rel:"noopener noreferrer",style:{display:"block",width:"100%",padding:"8px 0",borderRadius:6,border:"none",background:"#0969da",color:"#fff",fontSize:12,fontWeight:700,cursor:"pointer",fontFamily:Ye,textAlign:"center",textDecoration:"none",boxSizing:"border-box"},children:"Kontakt aufnehmen"})]})]}),t.jsx("div",{style:{padding:r?"12px 8px":"12px 16px",borderTop:"1px solid #eaecef",position:"relative"},children:n&&!s?!r&&t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[t.jsx("a",{href:"/kontakt",target:"_blank",rel:"noopener noreferrer",style:{display:"block",width:"100%",padding:"8px 10px",borderRadius:6,border:"none",background:"#0969da",color:"#fff",cursor:"pointer",fontSize:12,fontWeight:600,fontFamily:Ye,textAlign:"center",textDecoration:"none",boxSizing:"border-box"},children:"Kontakt aufnehmen"}),t.jsx("button",{onClick:()=>l("/login"),style:{width:"100%",padding:"6px 10px",borderRadius:6,border:"1px solid #d0d7de",background:"#f6f8fa",color:"#656d76",cursor:"pointer",fontSize:12,fontFamily:Ye},children:"Anmelden"})]}):t.jsxs(t.Fragment,{children:[c&&t.jsxs(t.Fragment,{children:[t.jsx("div",{onClick:()=>d(!1),style:{position:"fixed",inset:0,zIndex:98}}),t.jsxs("div",{style:{position:"absolute",bottom:"100%",left:r?4:12,right:r?4:12,marginBottom:8,backgroundColor:"#fff",border:"1px solid #e5e7eb",borderRadius:10,boxShadow:"0 8px 24px rgba(0,0,0,0.12)",zIndex:99,overflow:"hidden"},children:[t.jsxs("div",{style:{padding:"12px 14px",borderBottom:"1px solid #f3f4f6"},children:[t.jsx("div",{style:{fontSize:13,fontWeight:600,color:"#24292f"},children:m}),t.jsx("div",{style:{fontSize:11,color:"#656d76",marginTop:2},children:o?"Admin-Vorschau":(i==null?void 0:i.name)||""})]}),t.jsxs("div",{style:{padding:"4px 0"},children:[t.jsxs("button",{onClick:()=>{d(!1),l("/einstellungen")},style:{display:"flex",alignItems:"center",gap:10,width:"100%",padding:"9px 14px",border:"none",backgroundColor:"transparent",curs
60or:"pointer",fontSize:13,color:"#24292f",fontFamily:Ye,textAlign:"left"},onMouseEnter:S=>S.currentTarget.style.backgroundColor="#f6f8fa",onMouseLeave:S=>S.currentTarget.style.backgroundColor="transparent",children:[t.jsx(pd,{})," Einstellungen"]}),t.jsx("div",{style:{height:1,backgroundColor:"#f3f4f6",margin:"2px 0"}}),t.jsxs("button",{onClick:()=>{d(!1),b()},style:{display:"flex",alignItems:"center",gap:10,width:"100%",padding:"9px 14px",border:"none",backgroundColor:"transparent",cursor:"pointer",fontSize:13,color:"#B91C1C",fontFamily:Ye,textAlign:"left"},onMouseEnter:S=>S.currentTarget.style.backgroundColor="#fef2f2",onMouseLeave:S=>S.currentTarget.style.backgroundColor="transparent",children:[t.jsx(gd,{})," Abmelden"]})]})]})]}),t.jsxs("button",{onClick:()=>d(!c),style:{display:"flex",alignItems:"center",gap:10,width:"100%",padding:r?"6px 0":"8px 10px",borderRadius:8,border:"1px solid transparent",backgroundColor:c?"#f6f8fa":"transparent",cursor:"pointer",fontFamily:Ye,transition:"all 0.15s",justifyContent:r?"center":"flex-start"},onMouseEnter:S=>{c||(S.currentTarget.style.backgroundColor="#f6f8fa")},onMouseLeave:S=>{c||(S.currentTarget.style.backgroundColor="transparent")},children:[t.jsx("div",{style:{width:34,height:34,borderRadius:"50%",background:"linear-gradient(135deg, #ddf4ff, #b6d9fc)",display:"flex",alignItems:"center",justifyContent:"center",fontSize:14,fontWeight:700,color:"#0969da",flexShrink:0,border:"1px solid #b6d9fc"},children:w}),!r&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{style:{minWidth:0,flex:1,textAlign:"left"},children:[t.jsx("div",{style:{fontSize:13,fontWeight:600,color:"#24292f",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:m}),t.jsx("div",{style:{fontSize:11,color:"#656d76",marginTop:1},children:_})]}),t.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"#656d76",style:{flexShrink:0,transform:c?"rotate(180deg)":"none",transition:"transform 0.2s"},children:t.jsx("path",{d:"M4.427 7.427l3.396 3.396a.25.25 0 0 0 .354 0l3.396-3.396A.25.25 0 0 0 11.396 7H4.604a.25.25 0 0 0-.177.427Z"})})]})]})]})})]})}const Pr='-apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif',Ot=[{id:"welcome",title:"Willkommen bei Optimavo!",text:"In wenigen Schritten zeigen wir Ihnen die wichtigsten Funktionen Ihres Review-Dashboards.",anchor:null,position:"center"},{id:"sidebar-dashboard",title:"Dashboard",text:"Hier sehen Sie auf einen Blick alle wichtigen KPIs: Ihre Durchschnittsbewertung, neue Reviews und erkannte Kundenthemen.",anchor:'[data-tour="nav-dashboard"]',position:"right"},{id:"sidebar-probleme",title:"Kundenfeedback",text:"KI-gestützte Analyse: Welche Themen sprechen Kunden am häufigsten an? Sortiert nach Häufigkeit und Priorität.",anchor:'[data-tour="nav-probleme"]',position:"right"},{id:"sidebar-massnahmen",title:"Aktionsplan",text:"Zu jedem Kundenthema gibt es konkrete MaÃnahmen mit Status, Priorität und Fortschrittsanzeige.",anchor:'[data-tour="nav-massnahmen"]',position:"right"},{id:"sidebar-insights",title:"KI-Insights",text:"Prognosen, Szenarien und datenbasierte Handlungsempfehlungen, automatisch aus Ihren Bewertungen generiert.",anchor:'[data-tour="nav-insights"]',position:"right"},{id:"sidebar-wettbewerb",title:"Wettbewerb",text:"Vergleichen Sie Ihre Bewertungen mit denen Ihrer Konkurrenten und sehen Sie wo Sie stärker oder schwächer sind.",anchor:'[data-tour="nav-wettbewerb"]',position:"right"},{id:"done",title:"Plattformen verbinden",text:t.jsxs(t.Fragment,{children:["Verbinden Sie jetzt Ihre Bewertungsplattformen unter ",t.jsx("strong",{children:"Einstellungen â Integrationen"}),". Fügen Sie einfach den Link zu Ihrem Google-, Trustpilot- oder anderen Profil ein, die KI-Analyse startet automatisch.",t.jsx("br",{}),t.jsx("br",{}),t.jsx("span",{style:{fontSize:12,color:"#8c959f"},children:"Sie können diese Tour jederzeit über Einstellungen â Hilfe erneut starten."})]}),anchor:null,position:"center"}];function bd({onDone:r}){const[e,n]=h.useState(0),[s,i]=h.useState(null),o=h.useRef(null),a=Ot[e];h.useEffect(()=>{if(!a.anchor){i(null);return}const g=document.querySelector(a.anchor);if(!g){i(null);return}const v=g.getBoundingClientRect();
60i({top:v.top,left:v.left,width:v.width,height:v.height}),g.scrollIntoView({behavior:"smooth",block:"center"})},[e]);const l=()=>{e<Ot.length-1?n(g=>g+1):r()},c=()=>n(g=>g-1),d=()=>r(),u=!a.anchor||!s,f=(e+1)/Ot.length*100,p=typeof window<"u"&&window.innerWidth<768,x=()=>{if(u)return{position:"fixed",top:"50%",left:"50%",transform:"translate(-50%, -50%)",width:p?"calc(100vw - 32px)":420,maxWidth:p?"calc(100vw - 32px)":420};const g=14;return a.position==="right"&&!p?{position:"fixed",top:Math.max(8,s.top+s.height/2-80),left:s.left+s.width+g,width:340}:p?{position:"fixed",top:s.top+s.height+g,left:16,right:16,width:"auto",maxWidth:"calc(100vw - 32px)"}:{position:"fixed",top:s.top+s.height+g,left:Math.max(8,s.left),width:340}};return t.jsxs(t.Fragment,{children:[t.jsx("div",{style:{position:"fixed",inset:0,backgroundColor:"rgba(27,31,36,0.5)",zIndex:9998},onClick:d}),s&&t.jsx("div",{style:{position:"fixed",top:s.top-6,left:s.left-6,width:s.width+12,height:s.height+12,borderRadius:10,border:"3px solid #0969da",boxShadow:"0 0 0 9999px rgba(27,31,36,0.5), 0 0 12px rgba(9,105,218,0.3)",zIndex:9999,pointerEvents:"none",transition:"all 0.25s ease"}}),t.jsxs("div",{ref:o,style:{...x(),zIndex:1e4,backgroundColor:"#fff",border:"1px solid #d0d7de",borderRadius:14,boxShadow:"0 12px 32px rgba(27,31,36,0.18)",padding:"28px 28px 24px",fontFamily:Pr,transition:"top 0.25s ease, left 0.25s ease"},onClick:g=>g.stopPropagation(),children:[t.jsx("div",{style:{height:3,backgroundColor:"#eaecef",borderRadius:2,marginBottom:16,overflow:"hidden"},children:t.jsx("div",{style:{height:"100%",width:`${f}%`,backgroundColor:"#0969da",borderRadius:2,transition:"width 0.3s ease"}})}),t.jsxs("div",{style:{fontSize:11,color:"#8c959f",marginBottom:8,fontWeight:500},children:["Schritt ",e+1," von ",Ot.length]}),t.jsx("h3",{style:{fontSize:15,fontWeight:700,color:"#24292f",margin:"0 0 10px"},children:a.title}),t.jsx("p",{style:{fontSize:13,color:"#656d76",margin:"0 0 20px",lineHeight:1.6},children:a.text}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[e>0&&t.jsx("button",{onClick:c,style:{padding:"7px 14px",border:"1px solid #d0d7de",borderRadius:6,backgroundColor:"#fff",color:"#24292f",fontSize:13,fontWeight:500,cursor:"pointer",fontFamily:Pr},children:"â Zurück"}),t.jsx("button",{onClick:l,style:{flex:1,padding:"8px 14px",border:"none",borderRadius:6,backgroundColor:"#0969da",color:"#fff",fontSize:13,fontWeight:600,cursor:"pointer",fontFamily:Pr},children:e===Ot.length-1?"Integrationen öffnen":"Weiter â"}),e<Ot.length-1&&t.jsx("button",{onClick:d,style:{padding:"7px 10px",border:"none",backgroundColor:"transparent",color:"#8c959f",fontSize:12,cursor:"pointer",fontFamily:Pr},children:"Ãberspringen"})]})]})]})}class vd extends h.Component{constructor(e){super(e),this.state={hasError:!1,errorMsg:"",errorStack:""}}static getDerivedStateFromError(e){return{hasError:!0,errorMsg:(e==null?void 0:e.message)||"Unknown error"}}componentDidCatch(e,n){var a;const s=((a=n==null?void 0:n.componentStack)==null?void 0:a.slice(0,800))||"",i=(e==null?void 0:e.message)||"";if(console.error("[DashboardErrorBoundary] ERROR:",i,` 61Component Stack:`,s),i.includes("Failed to fetch dynamically imported module")||i.includes("Importing a module script failed")||i.includes("error loading dynamically imported module")||/Loading (?:CSS )?chunk [\d]+ failed/.test(i)){const l=parseInt(sessionStorage.getItem("_chunk_reload_attempts")||"0",10);if(l<2){sessionStorage.setItem("_chunk_reload_attempts",String(l+1)),(async()=>{try{if("caches"in window){const d=await caches.keys();await Promise.all(d.map(u=>caches.delete(u)))}if(navigator.serviceWorker){const d=await navigator.serviceWorker.getRegistrations();await Promise.all(d.map(u=>u.unregister()))}}catch{}const c=new URL(window.location.href);c.searchParams.set("_v",String(Date.now())),window.location.replace(c.toString())})();return}}this.setState({errorStack:s})}componentDidMount(){this._resetTimer=setTimeout(()=>{try{sessionStorage.removeItem("_chunk_reload_attempts")}catch{}},1e4)}componentWillUnmount(){this._resetTimer&&clearTimeout(this._resetTimer)}componentDidUpdate(e){this.state.hasError&&this.props.children!==e.children&&this.setState({hasError:!1,errorMsg:"",errorStack:""})}render(){return this.state.hasError?t.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",minHeight:"60vh",gap:12,fontFamily:"-apple-system, sans-serif"},children:[t.jsx("div",{style:{fontSize:14,color:"#656d76"},children:"Seite konnte nicht geladen werden."}),this.state.errorMsg&&t.jsx("div",{style:{fontSize:11,color:"#9ca3af",maxWidth:500,textAlign:"center"},children:this.state.errorMsg}),this.state.errorStack&&t.jsx("pre",{style:{fontSize:9,color:"#b0b8c1",maxWidth:500,maxHeight:120,overflow:"auto",textAlign:"left",background:"#f6f8fa",padding:8,borderRadius:6,margin:"8px 0 0",whiteSpace:"pre-wrap",wordBreak:"break-all"},children:this.state.errorStack}),t.jsx("button",{onClick:()=>{try{sessionStorage.removeItem("_chunk_reload_attempts")}catch{}window.location.reload()},style:{padding:"8px 16px",borderRadius:8,border:"1px solid #d0d7de",background:"#fff",cursor:"pointer",fontSize:13},children:"Erneut versuchen"}),t.jsx("button",{onClick:()=>{window.location.href="/dashboard"},style:{padding:"8px 16px",borderRadius:8,border:"none",background:"none",cursor:"pointer",fontSize:13,color:"#0969da"},children:"Zum Dashboard"})]}):this.props.children}}const wd=h.lazy(()=>Ee(()=>import("./UpgradePage-CZ8BaBrH.js"),__vite__mapDeps([0,1])).then(r=>({default:r.UpgradePage}))),_d=h.lazy(()=>Ee(()=>import("./EinstellungenPage-CvIYgqKZ.js"),__vite__mapDeps([2,1])
61).then(r=>({default:r.EinstellungenPage}))),jd=h.lazy(()=>Ee(()=>import("./ReviewDashboard_v2-CeH0FaaE.js"),__vite__mapDeps([3,1,4,5,6,7])).then(r=>({default:r.DashboardPage}))),Sd=h.lazy(()=>Ee(()=>import("./ReviewDashboard_v2-CeH0FaaE.js"),__vite__mapDeps([3,1,4,5,6,7])).then(r=>({default:r.ProblemeOverviewPage}))),kd=h.lazy(()=>Ee(()=>import("./ReviewDashboard_v2-CeH0FaaE.js"),__vite__mapDeps([3,1,4,5,6,7])).then(r=>({default:r.ProblemDetailPage}))),Ed=h.lazy(()=>Ee(()=>import("./ReviewDashboard_v2-CeH0FaaE.js"),__vite__mapDeps([3,1,4,5,6,7])).then(r=>({default:r.MassnahmenOverviewPage}))),Cd=h.lazy(()=>Ee(()=>import("./ReviewDashboard_v2-CeH0FaaE.js"),__vite__mapDeps([3,1,4,5,6,7])).then(r=>({default:r.MassnahmeDetailPage}))),Ad=h.lazy(()=>Ee(()=>import("./InsightsPage-DHL-O1fO.js").then(r=>r.I),__vite__mapDeps([8,1,7,4,5])).then(r=>({default:r.InsightsPage}))),Rd=h.lazy(()=>Ee(()=>import("./MonitoringPage-D9SPIw0E.js"),__vite__mapDeps([9,1,4,5,6])).then(r=>({default:r.MonitoringPage}))),Td=h.lazy(()=>Ee(()=>import("./ReviewDashboard_v2-CeH0FaaE.js"),__vite__mapDeps([3,1,4,5,6,7])).then(r=>({default:r.WettbewerbPage}))),Ke='-apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif';function Id(){const{slug:r}=qr(),e=Se();return t.jsx(kd,{problemName:decodeURIComponent(r),onBack:()=>e("/themen"),onNavigateMassnahme:n=>e(`/massnahmen/${encodeURIComponent(n.titel)}`,{state:{massnahme:n}})})}function Pd(){var o;const{id:r}=qr(),e=Se(),n=((o=window.history.state)==null?void 0:o.usr)||{},{previewMode:s}=Jt(),i=n.massnahme||null;return i?s?t.jsx(Od,{massnahme:i,onBack:()=>e("/massnahmen")}):t.jsx(Cd,{massnahme:i,onBack:()=>{i._origin?e(`/themen/${encodeURIComponent(i._origin)}`):e("/massnahmen")},onNavigateProblem:a=>e(`/themen/${encodeURIComponent(a)}`)}):t.jsx(ee,{to:"/massnahmen",replace:!0})}function Od({massnahme:r,onBack:e}){return t.jsxs("div",{style:{maxWidth:720,margin:"40px auto",padding:"0 20px",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif'},children:[t.jsxs("button",{onClick:e,style:{background:"none",border:"none",color:"#656d76",fontSize:13,cursor:"pointer",padding:"0 0 16px",display:"inline-flex",alignItems:"center",gap:6},children:[t.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:t.jsx("path",{d:"m15 18-6-6 6-6"})}),"Zur MaÃnahmen-Ãbersicht"]}),t.jsxs("div",{style:{background:"#fff",border:"1px solid #e5e7eb",borderRadius:16,padding:"48px 40px",textAlign:"center",boxShadow:"0 1px 3px rgba(0,0,0,0.04)"},children:[t.jsx("div",{style:{width:64,height:64,borderRadius:16,background:"linear-gradient(135deg, #eff6ff, #f5f3ff)",border:"1px solid #bfdbfe",display:"inline-flex",alignItems:"center",justifyContent:"center",marginBottom:20},children:t.jsxs("svg",{width:"28",height:"28",viewBox:"0 0 24 24",fill:"none",stroke:"#0969da",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[t.jsx("rect",{x:"3",y:"11",width:"18",height:"11",rx:"2"}),t.jsx("path",{d:"M7 11V7a5 5 0 0 1 10 0v4"})]})}),t.jsx("div",{style:{fontSize:11,fontWeight:700,color:"#7c3aed",textTransform:"uppercase",letterSpacing:"0.08em",marginBottom:10},children:"Bestandteil der Vollanalyse"}),t.jsx("h1",{style:{fontSize:24,fontWeight:700,color:"#0f172a",margin:"0 0 12px",lineHeight:1.25,letterSpacing:"-0.02em"},children:r.titel||"Diese MaÃnahme"}),t.jsx("p",{style:{fontSize:15,color:"#475569",lineHeight:1.6,margin:"0 auto 28px",maxWidth:540},children:"Die Vorschau-Analyse zeigt Ihnen die wichtigsten Probleme und welche MaÃnahmen wir empfehlen. Den ausführlichen Schritt-für-Schritt-Plan, den geschätzten Zeitaufwand und die erwarteten Effekte bekommen Sie mit der Vollanalyse."}),t.jsxs("div",{style:{background:"#f8fafc",border:"1px solid #e5e7eb",borderRadius:12,padding:"20px 22px",textAlign:"left",maxWidth:520,margin:"0 auto 28px"},children:[t.jsx("div",{style:{fontSize:12,fontWeight:700,color:"#0f172a",marginBottom:12,textTransform:"uppercase",letterSpacing:"0.06em"},children:"In der Vollanalyse enthalten:"}),["Konkreter Aktionsplan in 5â7 Schritten","Geschätzter Zeitaufwand und Priorisierung","Erwartete Effekte auf Bewertung und Umsatz","90-Tage-Roadmap mit Fortschritts-Tracking","Persönliches Gespräch zur Umsetzung"].map((s,i)=>
61t.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:10,marginBottom:i<4?8:0,fontSize:14,color:"#0f172a"},children:[t.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"#16a34a",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,marginTop:2},children:t.jsx("polyline",{points:"20 6 9 17 4 12"})}),s]},i))]}),t.jsxs("a",{href:"https://optimavo.de/#kontakt",style:{display:"inline-flex",alignItems:"center",gap:8,padding:"12px 28px",borderRadius:10,background:"linear-gradient(135deg, #0969da, #3758f9)",color:"#fff",fontSize:14,fontWeight:600,textDecoration:"none",boxShadow:"0 4px 14px rgba(9,105,218,0.25)"},children:["Vollanalyse freischalten",t.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[t.jsx("path",{d:"M5 12h14"}),t.jsx("path",{d:"m12 5 7 7-7 7"})]})]})]})]})}function at({children:r,variant:e="default"}){var nt,De,st;const{liveMode:n,isLive:s,reviewsOnly:i,loading:o,companyId:a,error:l,data:c,cooldownActive:d,refetch:u,hasExistingReport:f,analysisProcessing:p}=Jt(),x=d&&!(c!=null&&c.debugMode),g=(c==null?void 0:c.totalReviewsAll)||0,v=(c==null?void 0:c.analyzedReviews)||0,m=g>0?Math.min(100,Math.round(v/g*100)):0,w={analyzed:v};(nt=c==null?void 0:c.lastScrapeJob)!=null&&nt.status;const _=m>=100&&!(c!=null&&c.hasAnalysis)&&g>=5,b=["Bewertungen werden überprüft...","Ergebnisse werden zusammengeführt...","Bericht wird vorbereitet..."],[y,k]=h.useState(!1),[S,T]=h.useState(0),V=h.useRef(!1),C=h.useRef(!1),z=s&&!x&&(f||(c==null?void 0:c.hasAnalysis))||(c==null?void 0:c.totalReviews)>0&&!x&&!_&&(c==null?void 0:c.hasAnalysis)||!!l&&!o&&!x&&!_;!z&&n&&a&&console.warn("[LiveModeGate] NOT complete:",{isLive:s,cooldownActive:x,hasExistingReport:f,hasAnalysis:c==null?void 0:c.hasAnalysis,totalReviews:c==null?void 0:c.totalReviews,loading:o,error:!!l,reportGenerating:_,dataExists:!!c,liveMode:n});const H=h.useRef(!1);h.useEffect(()=>{if(!z&&!H.current&&(V.current=!0,C.current=!1),z&&V.current&&!C.current){if(C.current=!0,V.current=!1,f||c!=null&&c.hasAnalysis)return;u&&!H.current&&(H.current=!0,u()),k(!0),T(0),b.forEach((oe,Ae)=>setTimeout(()=>T(Ae),Ae*800)),setTimeout(()=>k(!1),b.length*800+400)}},[z]);const G=h.useRef(Date.now()),[O,F]=h.useState(0);if(h.useEffect(()=>{const oe=setInterval(()=>F(Math.floor((Date.now()-G.current)/1e3)),1e3);return()=>clearInterval(oe)},[]),!n&&!p||!a)return r;if(!p){if(z&&!y)return r;if(c!=null&&c.hasAnalysis&&(c==null?void 0:c.totalReviews)>0)return r}if((f===null||f===!0||(()=>{try{return localStorage.getItem("optimavo_has_report")==="true"}catch{return!1}})())&&!z){const oe='-apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif',Ae={backgroundColor:"#fff",border:"1px solid #eaecef",borderRadius:14,boxShadow:"0 1px 3px rgba(0,0,0,0.04)"},be=({width:Re="100%",height:it=20,radius:ut=8,style:Ie={}})=>t.jsx("div",{className:"shimmer",style:{width:Re,height:it,borderRadius:ut,...Ie}});return t.jsxs("div",{style:{fontFamily:oe,backgroundColor:"#f6f8fa",minHeight:"100vh",padding:28},children:[t.jsx("style",{children:` 62 .shimmer { background: linear-gradient(90deg, #f1f3f5 25%, #e9ecef 37%, #f1f3f5 63%); background-size: 400% 100%; animation: shimmer 1.4s ease infinite; } 63 @keyframes shimmer { 0% { background-position: 100% 0 } 100% { background-position: -100% 0 } } 64 @keyframes pulse-bar { 0%, 100% { opacity: 0.7; } 50% { opacity: 1; } } 65 @keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } } 66 `}),t.jsxs("div",{style:{maxWidth:1280,margin:"0 auto"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,marginBottom:28},children:[t.jsx(be,{width:220,height:28,radius:8}),t.jsx(be,{width:90,height:24,radius:20})]}),t.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(200px, 1fr))",gap:16,marginBottom:24},children:["Bewertung","Neue Reviews","Reputationsrisiko","Sentiment"].map((Re,it)=>t.jsxs("div",{style:{...Ae,padding:"20px 22px"},children:[t.jsx("div",{style:{fontSize:11,fontWeight:500,color:"#8c959f",marginBottom:10},children:Re}),t.jsx("div",{style:{fontSize:28,fontWeight:700,color:"#d0d7de",lineHeight:1,marginBottom:6},children:", "}),t.jsx("div",{style:{fontSize:11,color:"#b0b8c1"},children:"wird geladen"})]},it))}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"2fr 1fr",gap:16,marginBottom:24},children:[t.jsxs("div",{style:{...Ae,padding:"22px 24px"},children:[t.jsx(be,{width:180,height:16,style:{marginBottom:18}}),t.jsx(be,{height:200,radius:10})]}),t.jsxs("div",{style:{...Ae,padding:"22px 24px"},children:[t.jsx(be,{width:150,height:16,style:{marginBottom:18}}),[1,2,3,4].map(Re=>t.jsx(be,{height:32,style:{marginBottom:10}},Re))]})]}),t.jsxs("div",{style:{...Ae,padding:"22px 24px"},children:[t.jsx(be,{width:200,height:16,style:{marginBottom:18}}),[1,2,3].map(Re=>t.jsx(be,{height:52,style:{marginBottom:12},radius:10},Re))]}),t.jsx("div",{style:{position:"fixed",bottom:28,left:"50%",transform:"translateX(-50%)",zIndex:10,maxWidth:480,width:"100%",padding:"0 16px"},children:t.jsxs("div",{style:{background:"#fff",border:"1px solid #e5e7eb",borderRadius:14,padding:"16px 20px",boxShadow:"0 8px 24px rgba(0,0,0,0.06)"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:6},children:[t.jsx("span",{style:{fontSize:11,fontWeight:600,color:"#656d76"},children:"Dashboard"}),t.jsx("span",{style:{fontSize:11,fontWeight:700,color:"#0969da"},children:"wird geladen..."})]}),t.jsx("div",{style:{height:5,background:"#e5e7eb",borderRadius:99,marginBottom:12,overflow:"hidden"},children:t.jsx("div",{style:{height:"100%",width:"60%",borderRadius:99,background:"linear-gradient(90deg, #0969da 0%, #54aeff 50%, #0969da 100%)",backgroundSize:"200% 100%",animation:"pulse-bar 1.5s ease infinite"}})}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[t.jsx("img",{src:"/loading-animation.gif",alt:"",width:"18",height:"18",style:{objectFit:"contain"}}),t.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#24292f"},children:"Daten werden geladen..."})]}),t.jsx("div",{style:{fontSize:11,color:"#8c959f",marginTop:6},children:"Ihre Bewertungen und Analysen werden abgerufen."})]})})]})]})}const re=((De=c==null?void 0:c.lastScrapeJob)==null?void 0:De.providerIssue)&&((st=c==null?void 0:c.lastScrapeJob)==null?void 0:st.status)==="failed",J=({width:oe="100%",height:Ae=20,radius:be=8,style:Re={}})=>t.jsx("div",{className:"shimmer",style:{width:oe,height:Ae,borderRadius:be,...Re}}),ke={provenexpert:{scrapeSecs:480,reviewsPerMin:40},google:{scrapeSecs:150,reviewsPerMin:100},trustpilot:{scrapeSecs:200,reviewsPerMin:80},tripadvisor:{scrapeSecs:200,reviewsPerMin:80},trusted_shops:{scrapeSecs:180,reviewsPerMin:80},yelp:{scrapeSecs:200,reviewsPerMin:80}},D=(()=>{try{return sessionStorage.getItem("optimavo_scraping_platform")||""}catch{return""}})(),Y=ke[D]||{scrapeSecs:300,reviewsPerMin:60},te=[{day:0,label:"Ihre Bewertungen werden gesammelt...",pct:15},{day:1,label:"Bewertungen werden analysiert...",pct:35},{day:2,label:"KI-Analyse wird erstellt...",pct:55},{day:3,label:"Bericht wird vorbereitet...",pct:75},{day:4,label:"Qualitätsprüfung läuft...",pct:90}],X=c!=null&&c.lastAnalyzedAt?Math.floor((Date.now()-new Date(c.lastAnalyzedAt).getTime())/864e5):0,Ce=[...te].reverse().find(oe=>X>=oe.day)||te[0],N=[{fromSec:0,label:"Ihre Analyse wird vorbereitet..."},{fromSec:8,label:"Bewertungen werden gesammelt..."},{fromSec:20,label:"Daten werden aufbereitet..."},{fromSec:90,label:"Analyse in Bearbeitung..."}],ze=g===0?([...N].reverse().find(oe=>O>=oe.fromSec)||N[0]).label:null;g===0&&O>20&&Math.min(999,Math.round((O-20)*(Y.reviewsPerMin/60)));let Ge;if(g===0){const oe=O<20?O/20*.05:.05+Math.min(.4,(O-20)/Math.max(1,Y.scrapeSecs-20)*.4);Ge=Math.round(oe*100)}else _?Ge=93:Ge=Math.round(45+m/100*45);function rt(){return _?"Abschlussbericht wird erstellt...":g===0?ze:m<30?"Bewertungen werden analysiert...":m<60?"Sentiment & Themen werden erkannt...":m<90?"Risiken & Stärken werden bewertet...":m<100?"Aktionsplan wird erstellt...":"Abschlussbericht wird erstellt..."}const He=()=>t.jsx("img",{src:"/loading-animation.gif",alt:"",style:{width:20,height:20,objectFit:"contain"}});return c!=null&&c.totalReviews,t.jsxs("div",{style:{fontFamily:Ke,backgroundColor:"#f6f8fa",minHeight:"100vh",padding:28},children:[t.jsx("style",{children:` 67 .shimmer { 68 background: linear-gradient(90deg, #f1f3f5 25%, #e9ecef 37%, #f1f3f5 63%); 69 background-size: 400% 100%; 70 animation: shimmer 1.4s ease infinite; 71 } 72 @keyframes shimmer { 0% { background-position: 100% 0 } 100% { background-position: -100% 0 } } 73 @keyframes fadeIn { from { opacity: 0; transform: translateY(4px); } to { opacity: 1; transform: translateY(0); } } 74 .stage-text { animation: fadeIn 0.4s ease; } 75 `}),t.jsxs("div",{style:{maxWidth:1280,margin:"0 auto"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,marginBottom:28},children:[t.jsx(J,{width:220,height:28,radius:8}
75),t.jsx(J,{width:90,height:24,radius:20})]}),e==="dashboard"?t.jsxs(t.Fragment,{children:[t.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(4, 1fr)",gap:16,marginBottom:24},children:[1,2,3,4].map(oe=>t.jsx(J,{height:90,radius:12},oe))}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"2fr 1fr",gap:16,marginBottom:24},children:[t.jsx(J,{height:220,radius:12}),t.jsx(J,{height:220,radius:12})]}),t.jsx(J,{height:160,radius:12,style:{marginBottom:80}})]}):e==="themen"?t.jsxs(t.Fragment,{children:[t.jsx(J,{height:100,radius:12,style:{marginBottom:20}}),[1,2,3,4].map(oe=>t.jsx(J,{height:80,radius:12,style:{marginBottom:10}},oe))]}):e==="massnahmen"?t.jsxs(t.Fragment,{children:[t.jsx(J,{height:80,radius:12,style:{marginBottom:20}}),t.jsx(J,{height:50,radius:12,style:{marginBottom:16}}),t.jsx("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:16,marginBottom:80},children:[1,2,3,4].map(oe=>t.jsx(J,{height:100,radius:12},oe))})]}):e==="insights"?t.jsxs(t.Fragment,{children:[t.jsx(J,{height:60,radius:12,style:{marginBottom:20}}),t.jsx(J,{height:200,radius:12,style:{marginBottom:20}}),t.jsx("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:16,marginBottom:80},children:[1,2,3].map(oe=>t.jsx(J,{height:120,radius:12},oe))})]}):e==="monitoring"?t.jsxs(t.Fragment,{children:[t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:16,marginBottom:20},children:[t.jsx(J,{height:80,radius:12}),t.jsx(J,{height:80,radius:12})]}),[1,2,3,4].map(oe=>t.jsx(J,{height:60,radius:12,style:{marginBottom:10}},oe))]}):e==="wettbewerb"?t.jsxs(t.Fragment,{children:[t.jsx(J,{height:180,radius:12,style:{marginBottom:20}}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:16,marginBottom:80},children:[t.jsx(J,{height:200,radius:12}),t.jsx(J,{height:200,radius:12})]})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:16,marginBottom:24},children:[t.jsx(J,{height:120,radius:12}),t.jsx(J,{height:120,radius:12})]}),t.jsx(J,{height:180,radius:12,style:{marginBottom:16}}),t.jsx(J,{height:100,radius:12,style:{marginBottom:80}})]}),t.jsx("div",{style:{position:"fixed",bottom:28,left:"50%",transform:"translateX(-50%)",zIndex:10,maxWidth:480,width:"100%",padding:"0 16px"},children:re?t.jsxs("div",{style:{background:"#fff",border:"1px solid #e5e7eb",borderRadius:14,padding:"20px 24px",boxShadow:"0 8px 24px rgba(0,0,0,0.08)"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:8,justifyContent:"center"},children:[t.jsx("svg",{width:"18",height:"18",viewBox:"0 0 16 16",fill:"#d97706",children:t.jsx("path",{d:"M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575ZM8 5a.75.75 0 0 0-.75.75v2.5a.75.75 0 0 0 1.5 0v-2.5A.75.75 0 0 0 8 5Zm0 9a1 1 0 1 0 0-2 1 1 0 0 0 0 2Z"})}),t.jsx("span",{style:{fontWeight:600,color:"#92400e",fontSize:14},children:"Vorübergehendes Problem"})]}),t.jsx("p",{style:{fontSize:13,color:"#656d76",lineHeight:1.6,margin:0,textAlign:"center"},children:"Die Bewertungsplattform antwortet nicht. Bitte versuchen Sie es in einer Stunde erneut."})]}):_?t.jsxs("div",{style:{background:"#fff",border:"1px solid #e5e7eb",borderRadius:14,padding:"16px 20px",boxShadow:"0 8px 24px rgba(0,0,0,0.06)"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:6},children:[t.jsx("span",{style:{fontSize:11,fontWeight:600,color:"#656d76"},children:"Bericht"}),t.jsx("span",{style:{fontSize:11,fontWeight:700,color:"#9a6700"},children:"wird erstellt..."})]}),t.jsx("div",{style:{height:5,background:"#e5e7eb",borderRadius:99,marginBottom:12,overflow:"hidden"},children:t.jsx("div",{style:{height:"100%",width:"100%",borderRadius:99,background:"linear-gradient(90deg, #d97706 0%, #f59e0b 50%, #d97706 100%)",backgroundSize:"200% 100%",animation:"shimmer 2s infinite linear"}})}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:8},children:[t.jsx(He,{}),t.jsx("span",{style:{fontSize:13,fontWeight:500,color:"#24292f"}
75,children:"Abschlussbericht wird erstellt..."})]}),t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:6},children:[t.jsxs("span",{style:{fontSize:11,color:"#8c959f"},children:[w.analyzed," Bewertungen analysiert â KI erstellt den Bericht"]}),t.jsx("span",{style:{fontSize:11,color:"#8c959f",fontWeight:500},children:"â± Ca. 4â5 Tage"})]}),t.jsx("div",{style:{fontSize:11,color:"#8c959f"},children:"Sie können die Seite schlieÃen und später zurückkommen."}),t.jsx("div",{style:{fontSize:11,color:"#8c959f",marginTop:2},children:"Sie werden per E-Mail informiert, sobald Ihre Analyse bereit ist."})]}):p?t.jsxs("div",{style:{background:"#fff",border:"1px solid #eaecef",borderRadius:14,padding:"16px 20px",boxShadow:"0 8px 24px rgba(0,0,0,0.06)"},children:[t.jsx("div",{style:{height:5,background:"#e5e7eb",borderRadius:99,marginBottom:12,overflow:"hidden"},children:t.jsx("div",{style:{height:"100%",width:`${Ce.pct}%`,borderRadius:99,transition:"width 1s ease",background:"linear-gradient(90deg, #0969da 0%, #388bfd 50%, #0969da 100%)",backgroundSize:"200% 100%",animation:"shimmer 2s infinite linear"}})}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:10},children:[t.jsx(He,{}),t.jsx("span",{style:{fontSize:13,fontWeight:500,color:"#24292f"},children:Ce.label})]}),t.jsx("div",{style:{fontSize:11,color:"#8c959f",fontWeight:500,marginBottom:4},children:"â± Ca. 4â5 Tage"}),t.jsx("div",{style:{fontSize:11,color:"#8c959f"},children:"Sie können die Seite schlieÃen und später zurückkommen."}),t.jsx("div",{style:{fontSize:11,color:"#8c959f",marginTop:2},children:"Sie werden per E-Mail informiert, sobald Ihre Analyse bereit ist."})]}):t.jsxs("div",{style:{background:"#fff",border:"1px solid #eaecef",borderRadius:14,padding:"16px 20px",boxShadow:"0 8px 24px rgba(0,0,0,0.06)"},children:[t.jsx("div",{style:{height:5,background:"#e5e7eb",borderRadius:99,marginBottom:12,overflow:"hidden"},children:t.jsx("div",{style:{height:"100%",width:`${y?95:Ge}%`,borderRadius:99,transition:"width 1s ease",background:"linear-gradient(90deg, #0969da 0%, #388bfd 50%, #0969da 100%)",backgroundSize:"200% 100%",animation:"shimmer 2s infinite linear"}})}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:10},children:[t.jsx(He,{}),t.jsx("span",{className:"stage-text",style:{fontSize:13,fontWeight:500,color:"#24292f"},children:y?b[S]:rt()},y?b[S]:rt())]}),t.jsx("div",{style:{fontSize:11,color:"#8c959f",fontWeight:500,marginBottom:4},children:"â± Ca. 4â5 Tage"}),t.jsx("div",{style:{fontSize:11,color:"#8c959f"},children:"Sie können die Seite schlieÃen und später zurückkommen."}),t.jsx("div",{style:{fontSize:11,color:"#8c959f",marginTop:2},children:"Sie werden per E-Mail informiert, sobald Ihre Analyse bereit ist."})]})})]})]})}const Ns=720*60*60*1e3;function Ld(r){try{const e=r!=null&&r.created_at?new Date(r.created_at).getTime():0;if(!e)return{active:!1,expired:!1,daysLeft:0};const n=Date.now()-e;return n>=Ns?{active:!1,expired:!0,daysLeft:0}:{active:!0,expired:!1,daysLeft:Math.ceil((Ns-n)/(1440*60*1e3))}}catch{return{active:!1,expired:!1,daysLeft:0}}}function zd(){const r=Se(),{liveMode:e,isLive:n,previewMode:s}=Jt(),[i,o]=h.useState(()=>{try{return!!sessionStorage.getItem("trial_banner_dismissed")}catch{return!1}}),{subscription:a,session:l,company:c}
75=$e(),[d,u]=h.useState(null);if(s)return null;h.useEffect(()=>{l!=null&&l.access_token&&(async()=>{try{const y=await fetch("https://review-scraper-production-9324.up.railway.app/billing/pricing",{headers:{Authorization:`Bearer ${l.access_token}`}});if(y.ok){const k=await y.json();k.erstanalyse_cents&&u(k.erstanalyse_cents/100)}}catch{}})()},[l==null?void 0:l.access_token]);const p=(()=>{try{return!!sessionStorage.getItem("just_upgraded")}catch{return!1}})()||!!a&&(a.plan==="erstanalyse"||a.plan==="monitoring"),x=!!a&&a.plan==="monitoring"&&a.status==="active",g=(a==null?void 0:a.status)==="unpaid",[v,m]=h.useState(()=>{try{return!!sessionStorage.getItem("unpaid_banner_dismissed")}catch{return!1}}),w=g&&e&&!v,_=Ld(a);if(h.useEffect(()=>{if(!e&&i){try{sessionStorage.removeItem("trial_banner_dismissed")}catch{}o(!1)}},[e]),w)return t.jsxs("div",{style:{position:"sticky",top:0,zIndex:1e3,background:"linear-gradient(135deg, rgba(217,119,6,0.7) 0%, rgba(180,83,9,0.7) 100%)",backdropFilter:"blur(8px)",color:"#fff",padding:"10px 24px",display:"flex",alignItems:"center",justifyContent:"space-between",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',fontSize:13,gap:16},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[t.jsx("svg",{width:"15",height:"15",viewBox:"0 0 16 16",fill:"currentColor",children:t.jsx("path",{d:"M1.75 0h12.5C15.216 0 16 .784 16 1.75v12.5A1.75 1.75 0 0 1 14.25 16H1.75A1.75 1.75 0 0 1 0 14.25V1.75C0 .784.784 0 1.75 0ZM1.5 1.75v12.5c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25V1.75a.25.25 0 0 0-.25-.25H1.75a.25.25 0 0 0-.25.25ZM3.5 4h9v1.5h-9V4Zm0 3h9v1.5h-9V7Zm0 3h5v1.5h-5V10Z"})}),t.jsxs("span",{children:[t.jsx("strong",{children:"Offene Rechnung"}),", Erstanalyse",d?` (${d} â¬)`:""," noch nicht bezahlt."]})]}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[t.jsx("button",{onClick:()=>r("/einstellungen?tab=abonnement"),style:{flexShrink:0,padding:"7px 18px",backgroundColor:"#fff",color:"#b45309",border:"none",borderRadius:8,fontSize:13,fontWeight:700,cursor:"pointer",fontFamily:"inherit"},children:"Jetzt bezahlen"}),t.jsx("button",{onClick:()=>{m(!0);try{sessionStorage.setItem("unpaid_banner_dismissed","1")}catch{}},style:{background:"none",border:"none",color:"rgba(255,255,255,0.7)",cursor:"pointer",padding:4,display:"flex"},title:"SchlieÃen",children:t.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:t.jsx("path",{d:"M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 0 1 1.275.326.749.749 0 0 1-.215.734L9.06 8l3.22 3.22a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L8 9.06l-3.22 3.22a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z"})})})]})]});if(p&&_.expired&&!x&&e){const y=typeof window<"u"&&window.innerWidth<768;return t.jsxs("div",{style:{position:"sticky",top:0,zIndex:1e3,background:"linear-gradient(135deg, #dc2626 0%, #b91c1c 100%)",color:"#fff",padding:y?"8px 12px":"12px 24px",display:"flex",alignItems:"center",justifyContent:"space-between",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',fontSize:y?12:13,gap:y?8:16},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flex:1,minWidth:0},children:[!y&&t.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",style:{flexShrink:0},children:t.jsx("path",{d:"M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575ZM8 5a.75.75 0 0 0-.75.75v2.5a.75.75 0 0 0 1.5 0v-2.5A.75.75 0 0 0 8 5Zm0 9a1 1 0 1 0 0-2 1 1 0 0 0 0 2Z"})}),t.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis"},children:y?t.jsxs(t.Fragment,{children:[t.jsx("strong",{children:"Abo abgelaufen"}),", Monitoring aktivieren"]}):t.jsxs(t.Fragment,{children:[t.jsx("strong",{children:"Monitoring deaktiviert"}),", Ihr Probeabo ist abgelaufen. Aktivieren Sie das Monitoring, um weiterhin Updates zu erhalten."]})})]}),t.jsxs("button",{onClick:()=>r("/einstellungen?tab=abonnement"),style:{flexShrink:0,padding:y?"5px 10px":"7px 18px",backgroundColor:"#fff",color:"#dc2626",border:"none",borderRadius:8,fontSize:y?11:13,fontWeight:700,cursor:"pointer",fontFamily:"inherit",whiteSpace:"nowrap",display:"flex",alignItems:"center",gap:4},children:[t.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"#dc2626",children:t.jsx("path",{d:"M8.22 2.97a.75.75 0 0 1 1.06 0l4.25 4.25a.75.75 0 0 1 0 1.06l-4.25 4.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l2.97-2.97H3.75a.75.75 0 0 1 0-1.5h7.44L8.22 4.03a.75.75 0 0 1 0-1.06Z"})}),y?"Aktivieren":"Monitoring aktivieren"]})]})}const b=typeof window<"u"&&window.innerWidth<768;return p&&_.active&&!x&&e&&!i?t.jsxs("div",{style:{position:"sticky",top:0,zIndex:1e3,background:"linear-gradient(135deg, rgba(26,127,55,0.85) 0%, rgba(9,105,218,0.85) 100%)",color:"#fff",padding:b?"8px 12px":"12px 24px",display:"flex",alignItems:"center",justifyContent:"space-between",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',fontSize:b?12:13,gap:b?8:16},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flex:1,minWidth:0},children:[!b&&t.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",style:{flexShrink:0},children:t.jsx("path",{d:"M8 1.5a6.5 6.5 0 1 0 0 13 6.5 6.5 0 0 0 0-13ZM0 8a8 8 0 1 1 16 0A8 8 0 0 1 0 8Zm9 3a1 1 0 1 1-2 0 1 1 0 0 1 2 0Zm-.25-6.25a.75.75 0 0 0-1.5 0v3.5a.75.75 0 0 0 1.5 0v-3.5Z"})}),t.jsxs("span",{style:{overflow:"hidden",textOverflow:"ellipsis"},children:[t.jsx("strong",{children:"Probeabo"}),", Noch ",_.daysLeft," ",_.daysLeft===1?"Tag":"Tage",b?"":" kostenloses Monitoring.",d||b?"":" Danach zum vereinbarten Preis."]})]}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0},children:[t.jsxs("button",{onClick:()=>r("/einstellungen?tab=abonnement"),style:{flexShrink:0,padding:b?"5px 10px":"7px 18px",backgroundColor:"#fff",color:"#0969da",border:"none",borderRadius:8,fontSize:b?11:13,fontWeight:700,cursor:"pointer",fontFamily:"inherit",whiteSpace:"nowrap",display:"flex",alignItems:"center",gap:4},children:[t.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"#0969da",children:t.jsx("path",{d:"M8.22 2.97a.75.75 0 0 1 1.06 0l4.25 4.25a.75.75 0 0 1 0 1.06l-4.25 4.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l2.97-2.97H3.75a.75.75 0 0 1 0-1.5h7.44L8.22 4.03a.75.75 0 0 1 0-1.06Z"})}),"Jetzt Abo abschlieÃen"]}),t.jsx("button",{onClick:()=>{o(!0);try{sessionStorage.setItem("trial_banner_dismissed","1")}catch{}},style:{flexShrink:0,background:"none",border:"none",color:"#fff",cursor:"pointer",padding:"4px",display:"flex",alignItems:"center",justifyContent:"center",opacity:.8},onMouseEnter:y=>y.currentTarget.style.opacity="1",onMouseLeave:y=>y.currentTarget.style.opacity="0.8",title:"SchlieÃen",children:t.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:t.jsx("path",{d:"M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 0 1 1.275.326.749.749 0 0 1-.215.734L9.06 8l3.22 3.22a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L8 9.06l-3.22 3.22a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z"})})})]})]}):i||e?null:t.jsxs("div",{style:{position:"sticky",top:0,zIndex:1e3,background:p?"linear-gradient(135deg, rgba(26,127,55,0.85) 0%, rgba(9,105,218,0.85) 100%)":"linear-gradient(135deg, rgba(9,105,218,0.85) 0%, rgba(26,127,55,0.85) 100%)",color:"#fff",padding:"12px 24px",display:"flex",alignItems:"center",justifyContent:"space-between",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',fontSize:13,gap:16},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[t.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:t.jsx("path",{d:"M8 1.5a6.5 6.5 0 1 0 0 13 6.5 6.5 0 0 0 0-13ZM0 8a8 8 0 1 1 16 0A8 8 0 0 1 0 8Zm9 3a1 1 0 1 1-2 0 1 1 0 0 1 2 0Zm-.25-6.25a.75.75 0 0 0-1.5 0v3.5a.75.75 0 0 0 1.5 0v-3.5Z"})}),t.jsx("span",{children:p?t.jsxs(t.Fragment,{children:[t.jsx("strong",{children:"Fast geschafft!"}),", Verbinden Sie Ihre Bewertungsplattformen, um die KI-Analyse zu starten."]}):t.jsxs(t.Fragment,{children:[t.jsx("strong",{children:"Demo-Modus"}),", Sie sehen Beispieldaten. Analysieren Sie Ihre eigenen Bewertungen in wenigen Minuten."]})})]}),t.jsxs("button",{onClick:()=>p?r("/einstellungen?tab=integrationen"):window.open("/kontakt","_blank"),style:{flexShrink:0,padding:"7px 18px",backgroundColor:"#fff",color:"#0969da",border:"none",borderRadius:8,fontSize:13,fontWeight:700,cursor:"pointer",fontFamily:"inherit",whiteSpace:"nowrap",display:"flex",alignItems:"center",gap:6},children:[t.jsx("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"#0969da",children:t.jsx("path",{d:"M8.22 2.97a.75.75 0 0 1 1.06 0l4.25 4.25a.75.75 0 0 1 0 1.06l-4.25 4.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l2.97-2.97H3.75a.75.75 0 0 1 0-1.5h7.44L8.22 4.03a.75.75 0 0 1 0-1.06Z"})}),p?"Plattformen verbinden":"Eigene Bewertungen analysieren"]})]})}const vn="https://review-scraper-production-9324.up.railway.app";function Bd(){const{data:r,companyId:e,liveMode:n}=Jt(),{session:s}=$e(),[i,o]=h.useState(!1),[a,l]=h.useState(!1),[c,d]=h.useState(0),[u,f]=h.useState(0),[p,x]=h.useState(!1),[g,v]=h.useState(""),[m,w]=h.useState(!1),[_,b]=h.useState(!1),y=h.useRef(!1);h.useEffect(()=>{if(!e||!n||!(r!=null&&r.lastAnalyzedAt)||!(s!=null&&s.access_token)||y.current)return;y.current=!0;try{if(localStorage.getItem("optimavo_feedback_done"))return}catch{}const T=new Date(r.lastAnalyzedAt).getTime(),V=10080*60*1e3;Date.now()-T<V||fetch(`${vn}/dashboard/${e}/feedback-dismissed`,{headers:{Authorization:`Bearer ${s.access_token}`}}).then(C=>C.json()).then(C=>{C.dismissed||o(!0)}).catch(()=>{})},[e,n,r==null?void 0:r.lastAnalyzedAt,s==null?void 0:s.access_token]);const k=async()=>{o(!1),l(!0);try{localStorage.setItem("optimavo_feedback_done","1")}catch{}try{await fetch(`${vn}/dashboard/${e}/feedback-dismiss`,{method:"POST",headers:{Authorization:`Bearer ${s.access_token}`,"Content-Type":"application/json"}})}catch{}},S=async()=>
75{if(c){b(!0);try{await fetch(`${vn}/dashboard/${e}/feedback`,{method:"POST",headers:{Authorization:`Bearer ${s.access_token}`,"Content-Type":"application/json"},body:JSON.stringify({type:"nps_rating",data:{rating:c,comment:g.trim()||null}})}),w(!0),setTimeout(()=>k(),2e3)}catch{}finally{b(!1)}}};return!i||a?null:t.jsxs("div",{style:{position:"fixed",bottom:24,right:24,zIndex:9999,width:320,background:"#fff",borderRadius:14,border:"1px solid #e5e7eb",boxShadow:"0 8px 30px rgba(0,0,0,0.12)",padding:"20px 22px",fontFamily:Ke,animation:"feedbackSlideIn 0.3s ease"},children:[t.jsx("style",{children:"@keyframes feedbackSlideIn { from { opacity: 0; transform: translateY(16px); } to { opacity: 1; transform: translateY(0); } }"}),t.jsx("button",{onClick:k,style:{position:"absolute",top:10,right:10,background:"none",border:"none",cursor:"pointer",color:"#656d76",padding:4,display:"flex"},title:"Schliessen",children:t.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:t.jsx("path",{d:"M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 0 1 1.275.326.749.749 0 0 1-.215.734L9.06 8l3.22 3.22a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L8 9.06l-3.22 3.22a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z"})})}),m?t.jsxs("div",{style:{textAlign:"center",padding:"12px 0"},children:[t.jsx("div",{style:{fontSize:24,marginBottom:8},children:"Vielen Dank!"}),t.jsx("p",{style:{color:"#656d76",fontSize:13,margin:0},children:"Ihr Feedback hilft uns, Optimavo zu verbessern."})]}):t.jsxs(t.Fragment,{children:[t.jsx("p",{style:{fontSize:15,fontWeight:600,color:"#1f2328",margin:"0 0 14px",paddingRight:20},children:"Wie gefällt Ihnen Optimavo?"}),t.jsx("div",{style:{display:"flex",gap:6,marginBottom:p?14:0},children:[1,2,3,4,5].map(T=>t.jsx("button",{onClick:()=>{d(T),x(!0)},onMouseEnter:()=>f(T),onMouseLeave:()=>f(0),style:{background:"none",border:"none",cursor:"pointer",padding:2,fontSize:28,lineHeight:1,transition:"transform 0.1s",transform:(u||c)>=T?"scale(1.15)":"scale(1)",color:(u||c)>=T?"#f59e0b":"#d0d7de"},children:"â
"},T))}),p&&t.jsxs("div",{style:{animation:"feedbackSlideIn 0.2s ease"},children:[t.jsx("textarea",{value:g,onChange:T=>v(T.target.value),placeholder:"Was können wir verbessern? (optional)",style:{width:"100%",minHeight:60,padding:"8px 10px",border:"1px solid #e5e7eb",borderRadius:8,fontSize:13,fontFamily:Ke,color:"#1f2328",resize:"vertical",boxSizing:"border-box",background:"#f6f8fa"}}),t.jsx("button",{onClick:S,disabled:_,style:{marginTop:10,width:"100%",padding:"9px 16px",background:"#0969da",color:"#fff",border:"none",borderRadius:8,fontSize:13,fontWeight:600,cursor:"pointer",opacity:_?.6:1},children:_?"Wird gesendet...":"Absenden"})]})]})]})}function $d({profile:r,company:e,navigate:n}){const[s,i]=h.useState(!1),[o,a]=h.useState(!0),l=(r==null?void 0:r.full_name)||"Nutzer",c=l.charAt(0).toUpperCase();return h.useEffect(()=>{const d=setTimeout(()=>a(!1),2400);return()=>clearTimeout(d)},[]),t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 14px",borderBottom:"1px solid #e5e7eb",backgroundColor:"#fff",position:"relative",fontFamily:Ke},children:[t.jsxs("div",{style:{position:"relative",height:28,width:140},children:[t.jsx("img",{src:"/OptimavoLogo.webp",alt:"Optimavo",style:{height:28,objectFit:"contain",opacity:o?0:1,transition:"opacity 0.4s ease"}}),t.jsx("img",{src:"/LogoAnimiert.gif",alt:"",style:{position:"absolute",top:0,left:0,height:28,objectFit:"contain",opacity:o?1:0,transition:"opacity 0.4s ease",pointerEvents:"none"}})]}),t.jsx("button",{onClick:()=>i(!s),style:{width:30,height:30,borderRadius:"50%",border:s?"2px solid #0969da":"1px solid #b6d9fc",background:"linear-gradient(135deg, #ddf4ff, #b6d9fc)",display:"flex",alignItems:"center",justifyContent:"center",fontSize:13,fontWeight:700,color:"#0969da",cursor:"pointer",padding:0,flexShrink:0},children:c}),s&&t.jsxs(t.Fragment,{children:[t.jsx("div",{onClick:()=>i(!1),style:{position:"fixed",inset:0,zIndex:198}}),t.jsxs("div",{style:{position:"absolute",top:46,right:14,backgroundColor:"#fff",border:"1px solid #e5e7eb",borderRadius:10,boxShadow:"0 8px 24px rgba(0,0,0,0.12)",zIndex:199,minWidth:190,padding:"4px 0",fontFamily:Ke},children:[t.jsxs("div",{style:{padding:"10px 16px",borderBottom:"1px solid #f3f4f6"},children:[t.jsx("div",{style:{fontSize:13,fontWeight:600,color:"#24292f"},children:l}),t.jsx("div",{style:{fontSize:11,color:"#656d76",marginTop:2},children:(e==null?void 0:e.name)||""})]}),t.jsxs("button",{onClick:()=>{i(!1),n("/einstellungen")},style:{display:"flex",alignItems:"center",gap:10,width:"100%",padding:"10px 16px",fontSize:13,fontWeight:500,color:"#24292f",background:"none",border:"none",cursor:"pointer",fontFamily:Ke,textAlign:"left"},children:[t.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"#656d76",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[t.jsx("circle",{cx:"12",cy:"12",r:"3"}),t.jsx("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"})]}),"Einstellungen"]}),t.jsx("div",{style:{borderTop:"1px solid #f3f4f6",margin:"2px 0"}}),t.jsxs("button",{onClick:async()=>{i(!1),await ie.auth.signOut(),window.location.href="/login"},style:{display:"flex",alignItems:"center",gap:10,width:"100%",padding:"10px 16px",fontSize:13,fontWeight:500,color:"#B91C1C",background:"none",border:"none",cursor:"pointer",fontFamily:Ke,textAlign:"left"},children:[t.jsx("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"currentColor",style:{color:"#B91C1C"},children:t.jsx("path",{fillRule:"evenodd",d:"M2 2.75C2 1.784 2.784 1 3.75 1h2.5a.75.75 0 0 1 0 1.5h-2.5a.25.25 0 0 0-.25.25v10.5c0 .138.112.25.25.25h2.5a.75.75 0 0 1 0 1.5h-2.5A1.75 1.75 0 0 1 2 13.25Zm10.44 4.5-1.97-1.97a.749.749 0 0 1 .326-1.275.749.749 0 0 1 .734.215l3.25 3.25a.75.75 0 0 1 0 1.06l-3.25 3.25a.749.749 0 0 1-1.275-.326.749.749 0 0 1 .215-.734l1.97-1.97H6.75a.75.75 0 0 1 0-1.5Z"})}),"Abmelden"]})]})]})]})}function ir(){const r=Se(),e=$n(),[n]=Zi(),{profile:s,profileLoaded:i,subscription:o,refreshProfile:a,company:l}=$e(),c=(()=>{try{return new URLSearchParams(window.location.search).get("preview")?!0:!!sessionStorage.getItem("optimavo_preview_company_id")}catch{return!1}})(),d=c?"admin":(s==null?void 0:s.role)||"viewer",u=O=>
75{if(c)return O!=="/einstellungen";const F=Bn[O];return!F||F.includes(d)},[f,p]=h.useState(!1),g=(()=>{try{return!!sessionStorage.getItem("just_upgraded")}catch{return!1}})()||!!o&&(o.plan==="erstanalyse"||o.plan==="monitoring");h.useEffect(()=>{const O=n.get("session_id");if(!O)return;try{sessionStorage.setItem("just_upgraded","1")}catch{}const F=fetch("https://review-scraper-production-9324.up.railway.app/billing/verify-checkout",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:O})}).then(re=>re.json()).catch(()=>({})),ne=fetch(`https://review-scraper-production-9324.up.railway.app/billing/checkout-session?sessionId=${O}`).then(re=>re.json()).catch(()=>({}));Promise.all([F,ne]).then(async([,re])=>{await a();const J=re.subscriptionId?"abonnement":"integrationen";r(`/einstellungen?tab=${J}`,{replace:!0})}).catch(()=>{r("/einstellungen?tab=integrationen",{replace:!0})})},[n,r]);const{liveMode:v,loading:m,data:w}=Jt(),_=(()=>{try{return!!sessionStorage.getItem("just_upgraded")}catch{return!1}})(),[b,y]=h.useState(!1);h.useEffect(()=>{const O=["/","/dashboard","/themen","/massnahmen","/insights","/monitoring","/wettbewerb"];if(_&&!v&&!m&&!n.get("session_id")&&O.includes(e.pathname)){y(!0);const F=setTimeout(()=>{y(!1),r("/einstellungen?tab=integrationen",{replace:!0})},2e3);return()=>clearTimeout(F)}else y(!1)},[g,_,v,e.pathname]);const[k,S]=h.useState(!1);h.useEffect(()=>{if(i&&s&&!s.tour_seen&&(w!=null&&w.hasAnalysis)){try{if(localStorage.getItem("optimavo_tour_seen")){qt.updateProfile({tour_seen:!0}).catch(()=>{});return}}catch{}S(!0)}},[i,s,w==null?void 0:w.hasAnalysis]);const T=()=>{try{localStorage.setItem("optimavo_tour_seen","1")}catch{}S(!1),qt.updateProfile({tour_seen:!0}).catch(()=>{}),v||r("/einstellungen?tab=integrationen",{replace:!0})},V=(()=>{try{return new URLSearchParams(window.location.search).get("preview")?!0:!!sessionStorage.getItem("optimavo_preview_company_id")}catch{return!1}})();if(!V&&i&&s===null)return t.jsx(ee,{to:"/onboarding",replace:!0});if(!V&&i&&s&&s.onboarding_done===!1)return t.jsx(ee,{to:"/onboarding",replace:!0});const C=(O,F=null)=>{O==="dashboard"?r("/dashboard"):O==="probleme"?r("/themen"):O==="massnahmen"?r("/massnahmen"):O==="insights"?r("/insights"):O==="monitoring"?r("/monitoring"):O==="wettbewerb"?r("/wettbewerb"):O==="einstellungen"?r("/einstellungen"):O==="problem"?r(`/themen/${encodeURIComponent(F)}`):O==="massnahme"&&r(`/massnahmen/${encodeURIComponent((F==null?void 0:F.titel)||"")}`,{state:{massnahme:F}})},z=e.pathname==="/upgrade",[H,G]=h.useState(window.innerWidth<768);return h.useEffect(()=>{const O=()=>{const F=window.innerWidth<768;G(F),F&&!f&&p(!0)};return window.addEventListener("resize",O),O(),()=>window.removeEventListener("resize",O)},[]),t.jsx(fd,{children:t.jsxs("div",{style:{display:"flex",minHeight:"100vh",fontFamily:Ke,backgroundColor:"#f6f8fa"},children:[t.jsx("style",{children:` 76 @media (max-width: 767px) { 77 .optimavo-sidebar { display: none !important; } 78 .optimavo-main { margin-left: 0 !important; padding-bottom: 64px !important; overflow-x: hidden !important; } 79 div[style*="grid-template-columns: 2fr 1fr"], 80 div[style*="grid-template-columns: 1fr 2fr"], 81 div[style*="grid-template-columns: 1fr 280px"], 82 div[style*="repeat(2, 1fr)"], 83 div[style*="repeat(3, 1fr)"], 84 div[style*="repeat(4, minmax"], 85 div[style*="repeat(auto-fit"] { 86 grid-template-columns: 1fr !important; 87 } 88 .kpi-pipeline { grid-template-columns: 1fr 1fr !important; } 89 .optimavo-page { padding: 14px !important; } 90 .mobile-bottom-nav { display: flex !important; } 91 } 92 .mobile-bottom-nav { display: none; } 93 `}),k&&t.jsx(bd,{onDone:T}),!z&&!H&&t.jsx(xd,{collapsed:f,onToggle:()=>p(O=>!O)}),t.jsxs("main",{className:"optimavo-main",style:{flex:1,marginLeft:z||H?0:f?56:240,transition:"margin-left 0.2s ease",display:"flex",flexDirection:"column"},children:[!z&&t.jsx(zd,{}),H&&!z&&t.jsx($d,{profile:s,company:l,navigate:r}),!z&&t.jsx(Bd,{}),t.jsx("div",{style:{flex:1,overflow:"auto",paddingBottom:H?64:0},children:b?t.jsxs("div",{style:{padding:H?"16px 14px 80px":28},children:[t.jsx("style",{children:"@keyframes shimmer{0%{background-position:-400px 0}100%{background-position:400px 0}}"}),[180,60,60,300].map((O,F)=>t.jsx("div",{style:{height:O,borderRadius:12,marginBottom:16,background:"linear-gradient(90deg,#f0f
930f0 25%,#e8e8e8 50%,#f0f0f0 75%)",backgroundSize:"400px 100%",animation:"shimmer 1.5s infinite linear"}},F))]}):t.jsx(vd,{children:t.jsx(h.Suspense,{fallback:t.jsxs("div",{style:{padding:H?"16px 14px 80px":28},children:[t.jsx("style",{children:"@keyframes shimmer{0%{background-position:-400px 0}100%{background-position:400px 0}}"}),[180,60,60,300].map((O,F)=>t.jsx("div",{style:{height:O,borderRadius:12,marginBottom:16,background:"linear-gradient(90deg,#f0f0f0 25%,#e8e8e8 50%,#f0f0f0 75%)",backgroundSize:"400px 100%",animation:"shimmer 1.5s infinite linear"}},F))]}),children:t.jsxs(pr,{children:[t.jsx(K,{path:"/",element:t.jsx(ee,{to:"/dashboard",replace:!0})}),t.jsx(K,{path:"/dashboard",element:t.jsx(at,{variant:"dashboard",children:t.jsx(jd,{onNavigate:C})})}),t.jsx(K,{path:"/themen",element:u("/themen")?t.jsx(at,{variant:"themen",children:t.jsx(Sd,{onNavigate:C})}):t.jsx(ee,{to:"/dashboard",replace:!0})}),t.jsx(K,{path:"/themen/:slug",element:u("/themen")?t.jsx(at,{variant:"themen",children:t.jsx(Id,{})}):t.jsx(ee,{to:"/dashboard",replace:!0})}),t.jsx(K,{path:"/probleme",element:t.jsx(ee,{to:"/themen",replace:!0})}),t.jsx(K,{path:"/probleme/:slug",element:t.jsx(ee,{to:`/themen/${window.location.pathname.split("/").pop()}`,replace:!0})}),t.jsx(K,{path:"/massnahmen",element:u("/massnahmen")?t.jsx(at,{variant:"massnahmen",children:t.jsx(Ed,{onNavigate:C})}):t.jsx(ee,{to:"/dashboard",replace:!0})}),t.jsx(K,{path:"/massnahmen/:id",element:u("/massnahmen")?t.jsx(at,{variant:"massnahmen",children:t.jsx(Pd,{})}):t.jsx(ee,{to:"/dashboard",replace:!0})}),t.jsx(K,{path:"/insights",element:u("/insights")?t.jsx(at,{variant:"insights",children:t.jsx(Ad,{})}):t.jsx(ee,{to:"/dashboard",replace:!0})}),t.jsx(K,{path:"/monitoring",element:t.jsx(at,{variant:"monitoring",children:t.jsx(Rd,{})})}),t.jsx(K,{path:"/wettbewerb",element:u("/wettbewerb")?t.jsx(at,{variant:"wettbewerb",children:t.jsx(Td,{onNavigate:C})}):t.jsx(ee,{to:"/dashboard",replace:!0})}),t.jsx(K,{path:"/einstellungen",element:u("/einstellungen")?t.jsx(_d,{}):t.jsx(ee,{to:"/dashboard",replace:!0})}),t.jsx(K,{path:"/upgrade",element:t.jsx(wd,{})}),t.jsx(K,{path:"*",element:t.jsx(ee,{to:"/dashboard",replace:!0})})]})})})})]}),H&&!z&&t.jsx("nav",{style:{position:"fixed",bottom:0,left:0,right:0,zIndex:9999,backgroundColor:"#fff",borderTop:"1px solid #e5e7eb",display:"flex",justifyContent:"space-around",padding:"4px 0 env(safe-area-inset-bottom, 4px)",fontFamily:Ke},children:[{to:"/dashboard",label:"Home",icon:t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[t.jsx("path",{d:"M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"}),t.jsx("polyline",{points:"9 22 9 12 15 12 15 22"})]})},{to:"/monitoring",label:"Monitor",icon:t.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:t.jsx("path",{d:"M22 12h-4l-3 9L9 3l-3 9H2"})})},{to:"/themen",label:"Themen",icon:t.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:t.jsx("path",{d:"M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"})})},{to:"/massnahmen",label:"Aktionen",icon:t.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:t.jsx("path",{d:"M2.5 1.75v11.5c0 .138.112.25.25.25h3.17a.75.75 0 0 1 0 1.5H2.75A1.75 1.75 0 0 1 1 13.25V1.75C1 .784 1.784 0 2.75 0h8.5C12.216 0 13 .784 13 1.75v7.736a.75.75 0 0 1-1.5 0V1.75a.25.25 0 0 0-.25-.25h-8.5a.25.25 0 0 0-.25.25Zm3.5 6.25a.75.75 0 0 1 .75-.75h4a.75.75 0 0 1 0 1.5h-4a.75.75 0 0 1-.75-.75ZM6.75 4a.75.75 0 0 0 0 1.5h4a.75.75 0 0 0 0-1.5h-4Z"})})},{to:"/insights",label:"Analyse",icon:t.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:t.jsx("path",{d:"M8 1.5a6.5 6.5 0 1 0 0 13 6.5 6.5 0 0 0 0-13ZM0 8a8 8 0 1 1 16 0A8 8 0 0 1 0 8Zm9 3a1 1 0 1 1-2 0 1 1 0 0 1 2 0Zm-.25-6.25a.75.75 0 0 0-1.5 0v3.5a.75.75 0 0 0 1.5 0v-3.5Z"})})}
93,{to:"/wettbewerb",label:"Vergleich",icon:t.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:t.jsx("path",{d:"M1.5 1.75a.75.75 0 0 0-1.5 0v12.5c0 .414.336.75.75.75h14.5a.75.75 0 0 0 0-1.5H1.5V1.75ZM14 10.04a.75.75 0 0 1-1.158.635L9.75 8.882l-2.36 2.836a.75.75 0 0 1-1.05.1L3.25 9.26a.75.75 0 1 1 .96-1.152l2.59 2.158 2.391-2.876a.75.75 0 0 1 1.074-.098l3.25 2.35A.75.75 0 0 1 14 10.04Z"})})}].filter(O=>{const F=(s==null?void 0:s.role)||"viewer",ne=Bn[O.to];return!ne||ne.includes(F)}).map(O=>{const F=e.pathname===O.to||e.pathname.startsWith(O.to+"/");return t.jsxs("button",{onClick:()=>r(O.to),style:{display:"flex",flexDirection:"column",alignItems:"center",gap:1,background:"none",border:"none",cursor:"pointer",padding:"3px 4px",minWidth:0,color:F?"#0969da":"#8c959f",fontSize:9,fontWeight:F?600:400,fontFamily:Ke},children:[O.icon,O.label]},O.to)})})]})})}const qe='-apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif';function Dd(){const r=Se(),[e,n]=h.useState({name:"",email:"",firma:"",telefon:"",message:""}),[s,i]=h.useState(""),o=async l=>{if(l.preventDefault(),!(!e.name||!e.email||!e.firma||!e.telefon||!e.message)){i("sending");try{(await fetch("https://review-scraper-production-9324.up.railway.app/billing/contact",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e.name,email:e.email,firma:e.firma,telefon:e.telefon,nachricht:e.message})})).ok?(i("sent"),n({name:"",email:"",firma:"",telefon:"",message:""})):i("error")}catch{i("error")}}},a={width:"100%",padding:"10px 14px",borderRadius:8,border:"1px solid #e5e7eb",fontSize:14,fontFamily:qe,color:"#0f172a",background:"#f9fafb",boxSizing:"border-box",outline:"none"};return t.jsxs("div",{style:{minHeight:"100vh",fontFamily:qe,backgroundColor:"#f6f8fa"},children:[t.jsxs("header",{style:{position:"sticky",top:0,zIndex:1e3,backgroundColor:"#fff",borderBottom:"1px solid #e5e7eb",padding:"0 32px",display:"flex",alignItems:"center",justifyContent:"space-between",height:56},children:[t.jsx("img",{src:"/OptimavoLogo.webp",alt:"Optimavo",style:{maxWidth:140,height:"auto",cursor:"pointer"},onClick:()=>r("/")}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12},children:[t.jsx("button",{onClick:()=>r("/login"),style:{background:"none",border:"none",fontSize:13,fontWeight:500,color:"#334155",cursor:"pointer",fontFamily:qe},children:"Anmelden"}),t.jsx("button",{onClick:()=>r("/upgrade"),style:{padding:"8px 20px",borderRadius:8,border:"none",fontSize:13,fontWeight:700,backgroundColor:"#0f172a",color:"#fff",cursor:"pointer",fontFamily:qe},children:"Jetzt starten"})]})]}),t.jsxs("main",{style:{maxWidth:960,margin:"0 auto",padding:"48px 24px 32px"},children:[t.jsxs("div",{style:{textAlign:"center",marginBottom:48},children:[t.jsx("h1",{style:{fontSize:32,fontWeight:800,color:"#0f172a",margin:"0 0 8px",fontFamily:qe},children:"Kontakt"}),t.jsx("p",{style:{fontSize:15,color:"#6B7280",margin:0,fontFamily:qe},children:"Wir helfen Ihnen gerne weiter"})]}),t.jsxs("div",{style:{display:"flex",gap:28,flexWrap:"wrap",alignItems:"flex-start"},children:[t.jsxs("div",{style:{flex:"1 1 540px",minWidth:320,display:"flex",flexDirection:"column",gap:16},children:[t.jsxs("div",{style:{backgroundColor:"#fff",borderRadius:14,padding:24,border:"1px solid #E5E7EB"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,marginBottom:20},children:[t.jsx("div",{style:{width:48,height:48,borderRadius:12,backgroundColor:"#eff6ff",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:t.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"#0969da",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[t.jsx("rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}),t.jsx("path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"})]})}),t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:16,fontWeight:700,color:"#0f172a"},children:"Nachricht senden"}),t.jsx("div",{style:{fontSize:13,color:"#6B7280"},children:"Antwort innerhalb von 24 Stunden"})]})]}),s==="sent"?t.jsxs("div",{style:{padding:20,textAlign:"center",background:"#ecfdf5",borderRadius:10},children:[t.jsx("div",{style:{fontSize:28,marginBottom:8},children:"â"}),t.jsx("div",{style:{fontSize:15,fontWeight:600,color:"#059669"},children:"Nachricht gesendet!"}),t.jsx("div",{style:{fontSize:13,color:"#6B7280",marginTop:4},children:"Wir melden uns schnellstmöglich bei Ihnen."}),t.jsx("button",{onClick:()=>i(""),style:{marginTop:14,padding:"8px 20px",borderRadius:8,border:"1px solid #e5e7eb",background:"#fff",fontSize:13,fontWeight:600,cursor:"pointer",fontFamily:qe,color:"#334155"},children:"Weitere Nachricht senden"})]}):t.jsxs("form",{onSubmit:o,style:{display:"flex",flexDirection:"column",gap:14},children:[t.jsxs("div",{children:[t.jsx("label",{style:{fontSize:13,fontWeight:600,color:"#334155",display:"block",marginBottom:5},children:"Name"}),t.jsx("input",{style:a,placeholder:"Ihr Name",value:e.name,onChange:l=>n(c=>({...c,name:l.target.value})),required:!0})]}),t.jsxs("div",{children:[t.jsx("label",{style:{fontSize:13,fontWeight:600,color:"#334155",display:"block",marginBottom:5},children:"E-Mail"}),t.jsx("input",{style:a,type:"email",placeholder:"[email protected]",value:e.email,onChange:l=>n(c=>({...c,email:l.target.value})),required:!0})]}),t.jsxs("div",{children:[t.jsx("label",{style:{fontSize:13,fontWeight:600,color:"#334155",display:"block",marginBottom:5},children:"Firma"}),t.jsx("input",{style:a,placeholder:"Ihre Firma",value:e.firma,onChange:l=>n(c=>({...c,firma:l.target.value})),required:!0})]}),t.jsxs("div",{children:[t.jsx("label",{style:{fontSize:13,fontWeight:600,color:"#334155",display:"block",marginBottom:5},children:"Telefon"}),t.jsx("input",{style:a,type:"tel",placeholder:"+49 123 456789",value:e.telefon,onChange:l=>n(c=>({...c,telefon:l.target.value})),required:!0})]}),t.jsxs("div",{children:[t.jsx("label",{style:{fontSize:13,fontWeight:600,color:"#334155",display:"block",marginBottom:5},children:"Nachricht"}),t.jsx("textarea",{style:{...a,minHeight:110,resize:"vertical"},placeholder:"Wie können wir Ihnen helfen?",value:e.message,onChange:l=>n(c=>({...c,message:l.target.value})),required:!0})]}),s==="error"&&t.jsx("div",{style:{fontSize:13,color:"#cf222e"},children:"Fehler beim Senden. Bitte versuchen Sie es erneut."}),t.jsx("button",{type:"submit",disabled:s==="sending",style:{padding:"10px 24px",borderRadius:8,border:"none",fontSize:14,fontWeight:700,backgroundColor:"#0969da",color:"#fff",cursor:s==="sending"?"wait":"pointer",fontFamily:qe,opacity:s==="sending"?.6:1,alignSelf:"flex-start"},children:s==="sending"?"Wird gesendet...":"Nachricht senden"})]})]}),t.jsx("div",{style:{backgroundColor:"#fff",borderRadius:14,padding:24,border:"1px solid #E5E7EB",transition:"box-shadow 0.2s ease",cursor:"default"},onMouseEnter:l=>{l.currentTarget.style.boxShadow="0 8px 24px rgba(0,0,0,0.08)"},onMouseLeave:l=>{l.currentTarget.style.boxShadow="none"},children:t.jsxs("div",{style:{display:"flex",alignItems:"flex-start",ga
93p:16},children:[t.jsx("div",{style:{width:48,height:48,borderRadius:12,backgroundColor:"#ecfdf5",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:t.jsx("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"#059669",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:t.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}),t.jsxs("div",{style:{flex:1},children:[t.jsx("div",{style:{fontSize:16,fontWeight:700,color:"#0f172a",marginBottom:4},children:"Live-Chat"}),t.jsx("div",{style:{fontSize:14,color:"#334155"},children:"Sofort-Hilfe während der Geschäftszeiten"}),t.jsx("div",{style:{fontSize:13,color:"#6B7280",marginTop:4},children:"Mo-Fr, 9:00 - 18:00 Uhr"}),t.jsx("button",{onClick:()=>{window.$crisp?window.$crisp.push(["do","chat:open"]):window.open("mailto:[email protected]","_self")},style:{display:"inline-flex",alignItems:"center",gap:6,padding:"9px 20px",borderRadius:8,backgroundColor:"#059669",color:"#fff",fontSize:13,fontWeight:600,fontFamily:qe,border:"none",cursor:"pointer",marginTop:14},children:"Chat starten"})]})]})}),t.jsx("div",{style:{backgroundColor:"#fff",borderRadius:14,padding:24,border:"1px solid #E5E7EB",transition:"box-shadow 0.2s ease",cursor:"default"},onMouseEnter:l=>{l.currentTarget.style.boxShadow="0 8px 24px rgba(0,0,0,0.08)"},onMouseLeave:l=>{l.currentTarget.style.boxShadow="none"},children:t.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:16},children:[t.jsx("div",{style:{width:48,height:48,borderRadius:12,backgroundColor:"#f5f3ff",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:t.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"#7C3AED",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[t.jsx("rect",{x:"3",y:"4",width:"18",height:"18",rx:"2"}),t.jsx("line",{x1:"16",y1:"2",x2:"16",y2:"6"}),t.jsx("line",{x1:"8",y1:"2",x2:"8",y2:"6"}),t.jsx("line",{x1:"3",y1:"10",x2:"21",y2:"10"})]})}),t.jsxs("div",{style:{flex:1},children:[t.jsx("div",{style:{fontSize:16,fontWeight:700,color:"#0f172a",marginBottom:4},children:"Persönliches Gespräch"}),t.jsx("div",{style:{fontSize:14,color:"#334155"},children:"30-minütiges kostenloses Beratungsgespräch"}),t.jsx("a",{href:"https://kalender.optimavo.de",target:"_blank",rel:"noopener noreferrer",style:{display:"inline-flex",alignItems:"center",gap:6,padding:"9px 20px",borderRadius:8,backgroundColor:"#7C3AED",color:"#fff",fontSize:13,fontWeight:600,textDecoration:"none",fontFamily:qe,border:"none",cursor:"pointer",marginTop:14},children:"Termin buchen"})]})]})})]}),t.jsxs("div",{style:{flex:"0 1 360px",minWidth:280,display:"flex",flexDirection:"column",gap:16},children:[t.jsxs("div",{style:{backgroundColor:"#fff",borderRadius:14,padding:24,border:"1px solid #E5E7EB"},children:[t.jsx("div",{style:{display:"flex",alignItems:"center",gap:10,marginBottom:16},children:t.jsx("img",{src:"/OptimavoLogo.webp",alt:"Optimavo",style:{maxWidth:100,height:"auto"}})}),t.jsxs("div",{style:{fontSize:13,color:"#475569",lineHeight:1.8},children:[t.jsx("div",{style:{fontWeight:600,color:"#0f172a",marginBottom:4},children:"D.CRAMER ESOLUTIONS LTD"}),t.jsx("div",{children:"Istanbul 10, Athanasia Court, Office No.6"}),t.jsx("div",{children:"CY-6025 Larnaca, Zypern"}),t.jsxs("div",{style:{marginTop:8},children:[t.jsx("span",{style:{color:"#64748b"},children:"E-Mail: "}),t.jsx("a",{href:"mailto:[email protected]",style:{color:"#0969da",textDecoration:"none",fontWeight:500},children:"[email protected]"})]})]})]}),t.jsx("div",{style:{borderRadius:14,overflow:"hidden",border:"1px solid #E5E7EB",height:300},children:t.jsx("iframe",{title:"Optimavo Standort",src:"https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3261.5!2d33.6234!3d34.9186!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x14e082f9c0e5b2a1%3A0x6d97e2c7f8e2a5b3!2sLarnaca%2C%20Zypern!5e0!3m2!1sen!2s!4v1700000000000",width:"100%",height:"100%",style:{border:0,display:"block"},allowFullScreen:"",loading:"lazy",referrerPolicy:"no-referrer-when-downgrade"})})]})]}),t.jsx("footer",{style:{borderTop:"1px solid #e5e7eb",padding:"24px 0",marginTop:48,display:"flex",justifyContent:"space-between",alignItems:"center",flexWrap:"wrap",gap:12},children:t.jsx("span",{style:{fontSize:12,color:"#94a3b8"},children:"© 2026 Optimavo"})})]})]})}const Je=bi("https://vhadhtsblncdelbisrho.supabase.co","eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InZoYWRodHNibG5jZGVsYmlzcmhvIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzMxNTE3MTUsImV4cCI6MjA4ODcyNzcxNX0.VAPxFF05LqvGAihym5EuSigeiRyYHfNaAA0VCLZcgmg",{auth:{storageKey:"optimavo-admin-auth",autoRefreshToken:!0,persistSession:!0}}),Or=Object.freeze(Object.defineProperty({__proto__:null,supabaseAdmin:Je},Symbol.toStringTag,{value:"Module"}
93)),Ci="https://review-scraper-production-9324.up.railway.app/admin",Lt="https://review-scraper-production-9324.up.railway.app";async function Ut(){const{data:{session:r}}=await Je.auth.getSession();if(!r)throw new Error("Nicht eingeloggt");return{Authorization:`Bearer ${r.access_token}`,"Content-Type":"application/json"}}async function Z(r,e={}){const n=await Ut(),s=await fetch(`${Ci}${r}`,{...e,headers:{...n,...e.headers}}),i=await s.text();let o;try{o=JSON.parse(i)}catch{throw new Error(`Server-Fehler: Unerwartete Antwort (${s.status})`)}if(!s.ok)throw new Error(o.error||`Fehler ${s.status}`);return o}const M={getVersion:async()=>(await fetch(`${Lt}/version`)).json(),validateToken:async r=>(await(await fetch(`${Ci}/validate-token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:r})})).json()).valid,getDashboard:()=>Z("/dashboard"),getUsers:()=>Z("/users"),getUser:r=>Z(`/users/${r}`),updateUser:(r,e)=>Z(`/users/${r}`,{method:"PATCH",body:JSON.stringify(e)}),deleteUser:r=>Z(`/users/${r}`,{method:"DELETE"}),impersonate:(r,e)=>Z("/impersonate",{method:"POST",body:JSON.stringify({userId:r,companyId:e})}),getImpersonation:r=>Z(`/impersonate/${r}`),getErrors:(r={})=>{const e=new URLSearchParams(r).toString();return Z(`/errors${e?"?"+e:""}`)},resolveError:r=>Z(`/errors/${r}/resolve`,{method:"PATCH"}),getLogs:(r=100)=>Z(`/logs?limit=${r}`),getHealth:()=>Z("/health"),getServerHealth:()=>Z("/server-health"),getJobs:(r=50)=>Z(`/jobs?limit=${r}&noCache=1`),getAnalysisTasks:(r=25)=>Z(`/analysis-tasks?limit=${r}`),getSettings:()=>Z("/settings"),updateSetting:(r,e)=>Z("/settings",{method:"PATCH",body:JSON.stringify({key:r,value:e})}),testTelegram:()=>Z("/telegram/test",{method:"POST"}),updatePlatform:(r,e)=>Z(`/platforms/${r}`,{method:"PATCH",body:JSON.stringify(e)}),addPlatform:(r,e,n)=>Z("/platforms",{method:"POST",body:JSON.stringify({company_id:r,platform_name:e,profile_url:n||null})}),deletePlatform:r=>Z(`/platforms/${r}`,{method:"DELETE"}),triggerScrape:(r,e)=>Z(`/scrape/${r}`,{method:"POST",body:JSON.stringify({platform:e})}),regenerateReport:r=>Z(`/regenerate-report/${r}`,{method:"POST"}),getApiStatus:()=>Z("/api-status"),updateOAuthConfig:r=>Z("/oauth-config",{method:"POST",body:JSON.stringify(r)}),testConnection:()=>Z("/test-connection",{method:"POST"}),refreshOAuth:()=>Z("/oauth-refresh",{method:"POST"}),getApiCredits:()=>Z("/api-credits"),startOAuth:()=>Z("/oauth-start"),exchangeOAuth:r=>Z("/oauth-exchange",{method:"POST",body:JSON.stringify({code:r})}),pollOAuth:()=>Z("/oauth-poll"),getFeedback:()=>Z("/feedback"),onboardCustomer:r=>Z("/onboard",{method:"POST",body:JSON.stringify(r)}),generateMagicLink:r=>Z(`/magic-link/${r}`,{method:"POST"}),getConfiguredCompetitors:async r=>{const e=await Ut(),n=await fetch(`${Lt}/competitors/${r}/configured`,{headers:e}),s=await n.json();if(!n.ok)throw new Error(s.error||`Fehler ${n.status}`);return s},addConfiguredCompetitor:async(r,e)=>{const n=await Ut(),s=await fetch(`${Lt}/competitors/${r}/configured`,{method:"POST",headers:n,body:JSON.stringify(e)}),i=await s.json();if(!s.ok)throw new Error(i.error||`Fehler ${s.status}`);return i},deleteConfiguredCompetitor:async(r,e)=>{const n=await Ut(),s=await fetch(`${Lt}/competitors/${r}/configured/${encodeURIComponent(e)}`,{method:"DELETE",headers:n}),i=await s.json();if(!s.ok)throw new Error(i.error||`Fehler ${s.status}`);return i},triggerCompetitorAnalysis:async(r,e)=>{const n=await Ut(),s=await fetch(`${Lt}/competitors/${r}/analyze`,{method:"POST",headers:n,body:JSON.stringify({competitors:e})}),i=await s.json();if(!s.ok)throw new Error(i.error||`Fehler ${s.status}`);return i},deleteCompetitorAnalysis:async r=>{const e=await Ut(),n=await fetch(`${Lt}/competitors/${r}`,{method:"DELETE",headers:e});return n.ok?await n.json():Z("/settings",{method:"PATCH",body:JSON.stringify({key:`competitors:${r}`,value:null})})},getOnboarding:()=>Z("/onboarding"),getOnboardingDraft:(r,e)=>Z(`/onboarding/${r}/email/${e}/draft`,{method:"POST"}),sendOnboardingMail:(r,e,{subject:n,html:s})=>Z(`/onboarding/${r}/email/${e}/send`,{method:"POST",body:JSON.stringify({subject:n,html:s})}),toggleOnboardingMeeting:(r,e,n)=>Z(`/onboarding/${r}/meeting/${e}`,{method:"POST",body:JSON.stringify(n!=null?{done:n}
93:{})}),getOnboardingProfile:r=>Z(`/onboarding/${r}/profile`),saveOnboardingProfile:(r,e)=>Z(`/onboarding/${r}/profile`,{method:"POST",body:JSON.stringify(e)})},Be={page:{minHeight:"100vh",background:"#f6f8fa",display:"flex",alignItems:"center",justifyContent:"center",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif'},card:{background:"#ffffff",border:"1px solid #e5e7eb",borderRadius:12,padding:40,width:380,boxShadow:"0 4px 24px rgba(0,0,0,0.08)"},title:{color:"#1f2328",fontSize:22,fontWeight:600,margin:"0 0 6px",textAlign:"center"},subtitle:{color:"#656d76",fontSize:13,margin:"0 0 28px",textAlign:"center"},label:{color:"#656d76",fontSize:12,fontWeight:500,display:"block",marginBottom:6},input:{width:"100%",padding:"10px 12px",background:"#f6f8fa",border:"1px solid #e5e7eb",borderRadius:6,color:"#1f2328",fontSize:14,outline:"none",boxSizing:"border-box",marginBottom:16},btn:{width:"100%",padding:"10px 0",background:"#1f6feb",border:"none",borderRadius:6,color:"#fff",fontSize:14,fontWeight:600,cursor:"pointer"},btnDisabled:{opacity:.5,cursor:"not-allowed"},error:{color:"#cf222e",fontSize:13,textAlign:"center",marginBottom:16,padding:"8px 12px",background:"#ffebe9",borderRadius:6},logo:{color:"#1f6feb",fontSize:28,textAlign:"center",marginBottom:20,fontWeight:700}};function Ud({onLogin:r}){const[e,n]=h.useState(""),[s,i]=h.useState(""),[o,a]=h.useState(!1),[l,c]=h.useState(""),d=async u=>{u.preventDefault(),a(!0),c("");try{const{data:f,error:p}=await Je.auth.signInWithPassword({email:e,password:s});if(p)throw p;const{data:x,error:g}=await Je.from("profiles").select("id, role, full_name").eq("id",f.user.id).single();if(g)throw console.error("[Admin Login] Profile fetch error:",g),await Je.auth.signOut(),new Error("Profil konnte nicht geladen werden");if(!x||x.role!=="admin")throw await Je.auth.signOut(),new Error("Keine Admin-Berechtigung");r(f.session,x)}catch(f){c(f.message)}finally{a(!1)}};return t.jsx("div",{style:Be.page,children:t.jsxs("form",{onSubmit:d,style:Be.card,children:[t.jsx("div",{style:Be.logo,children:"Optimavo"}),t.jsx("h1",{style:Be.title,children:"Admin Panel"}),t.jsx("p",{style:Be.subtitle,children:"Nur für autorisierte Administratoren"}),l&&t.jsx("p",{style:Be.error,children:l}),t.jsx("label",{style:Be.label,children:"E-Mail"}),t.jsx("input",{style:Be.input,type:"email",value:e,onChange:u=>n(u.target.value),required:!0,autoFocus:!0}),t.jsx("label",{style:Be.label,children:"Passwort"}),t.jsx("input",{style:Be.input,type:"password",value:s,onChange:u=>i(u.target.value),required:!0}),t.jsx("button",{type:"submit",style:{...Be.btn,...o?Be.btnDisabled:{}},disabled:o,children:o?"Anmelden...":"Als Admin anmelden"})]})})}const R={h1:{fontSize:22,fontWeight:600,margin:"0 0 24px",color:"#1f2328"},grid:{display:"grid",gridTemplateColumns:"repeat(4, 1fr)",gap:16,marginBottom:32},card:{background:"#ffffff",border:"1px solid #e5e7eb",borderRadius:12,boxShadow:"0 1px 2px rgba(0,0,0,0.05)",padding:20},cardLabel:{color:"#656d76",fontSize:12,fontWeight:500,margin:"0 0 4px"},cardValue:{color:"#1f2328",fontSize:28,fontWeight:700,margin:0},section:{marginBottom:32},sectionHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:12},sectionTitle:{fontSize:15,fontWeight:600,color:"#1f2328",margin:0},table:{width:"100%",borderCollapse:"collapse"},th:{textAlign:"left",padding:"8px 12px",color:"#656d76",fontSize:11,fontWeight:600,textTransform:"uppercase",borderBottom:"1px solid #e5e7eb"},td:{padding:"10px 12px",color:"#1f2328",fontSize:13,borderBottom:"1px solid #f0f0f0"},badge:r=>({display:"inline-block",padding:"2px 8px",borderRadius:12,fontSize:11,fontWeight:600,background:r+"22",color:r}),healthDot:r=>({display:"inline-block",width:10,height:10,borderRadius:"50%",marginRight:8,flexShrink:0,background:r==="ok"?"#1a7f37":r==="warning"?"#9a6700":"#cf222e"}),btn:{padding:"6px 14px",border:"none",borderRadius:8,fontSize:12,fontWeight:600,cursor:"pointer",transition:"opacity 0.15s"},btnBlue:{background:"#0969da",color:"#fff"},loading:{color:"#656d76",fontSize:14},error:{color:"#cf222e",fontSize:14},statusCard:{display:"flex",alignItems:"center",gap:12,padding:"12px 16px",background:"#f6f8fa",borderRadius:8,border:"1px solid #e5e7eb"},statusLabel:{fontSize:12,color:"#656d76",margin:0},statusValue:{fontSize:13,fontWeight:600,margin:"2px 0 0"}},Md={google:{logo:"https://www.google.com/s2/favicons?domain=google.com&sz=64",name:"Google"},trustpilot:{logo:"https://www.google.com/s2/favicons?domain=trustpilot.com&sz=64",name:"Trustpilot"},tripadvisor:{logo:"https://www.google.com/s2/favicons?domain=tripadvisor.com&sz=64",name:"Tripadvisor"},trusted_shops:{logo:"https://www.google.com/s2/favicons?domain=trustedshops.de&sz=64",name:"Trusted Shops"},provenexpert:{logo:"https://www.google.com/s2/favicons?domain=provenexpert.com&sz=64",name:"ProvenExpert"}
93,yelp:{logo:"https://www.google.com/s2/favicons?domain=yelp.com&sz=64",name:"Yelp"}};function Wd(r){if(r.status==="failed")return{label:"Fehlgeschlagen",color:"#cf222e"};const e=r.reviews_total||0,n=r.reviews_analyzed||0,s=r.has_report,i=r.reviews_found||0;if(r.status==="completed"&&s)return{label:"Abgeschlossen",color:"#1a7f37"};if(r.status==="completed"&&e>0&&n>=e&&!s){const o=r.completed_at?new Date(r.completed_at).getTime():0;return(Date.now()-o)/6e4>10?{label:"Report ausstehend",color:"#9a6700"}:{label:"Report wird erstellt...",color:"#8250df"}}return r.status==="completed"&&e>0&&n<e?{label:`Analyse ${Math.round(n/e*100)}%`,color:"#0969da"}:r.status==="completed"?{label:"Fertig",color:"#1a7f37"}:i===0?{label:"Scraping...",color:"#9a6700"}:{label:`Scraping (${i})...`,color:"#9a6700"}}function Nd(){var D,Y,te,X,Ce,N,ze,Ge,rt,He,nt,De,st,oe,Ae,be,Re,it,ut,Ie,ht,ot,St,jr,Gt,ft,Zt,Yt,Xt,Qt;const[r,e]=h.useState(null),[n,s]=h.useState(!0),[i,o]=h.useState(""),[a,l]=h.useState(null),[c,d]=h.useState(!0),[u,f]=h.useState(!1),[p,x]=h.useState([]),[g,v]=h.useState(!1),[m,w]=h.useState(null),[_,b]=h.useState(!0),[y,k]=h.useState(!1),[S,T]=h.useState(null),[V,C]=h.useState(!0),[z,H]=h.useState(!1);h.useEffect(()=>{M.getDashboard().then(ve=>{e(ve),x(ve.health||[])}).catch(ve=>o(ve.message)).finally(()=>s(!1)),M.getApiStatus().then(l).catch(()=>l(null)).finally(()=>d(!1)),M.getServerHealth().then(T).catch(()=>T(null)).finally(()=>C(!1));const P=()=>{M.getApiCredits().then(ve=>{w(ve),localStorage.setItem("admin_credits_last_fetch",Date.now().toString())}).catch(ve=>{console.error("API Credits error:",ve),w(null)}).finally(()=>{b(!1),k(!1)})};parseInt(localStorage.getItem("admin_credits_last_fetch")||"0",10);const ue=1440*60*1e3;P();const Pe=setInterval(()=>{const ve=parseInt(localStorage.getItem("admin_credits_last_fetch")||"0",10);Date.now()-ve>ue&&P()},3600*1e3);return()=>clearInterval(Pe)},[]);const G=async()=>{v(!0);try{const P=await M.testConnection(),ue=await M.getApiStatus();l(ue),setOauthResult({success:P.connectionOk,authMode:P.authMode,message:P.connectionOk?"Verbindung erfolgreich":"Verbindung fehlgeschlagen"})}catch(P){setOauthResult({success:!1,error:P.message})}finally{v(!1)}},O=async()=>{k(!0);try{const P=await M.getApiCredits();w(P),localStorage.setItem("admin_credits_last_fetch",Date.now().toString())}catch(P){console.error("API Credits refresh error:",P)}finally{k(!1)}},F=async()=>{f(!0);try{const P=await M.getHealth();x(P)}finally{f(!1)}},ne=async()=>{H(!0);try{const P=await M.getServerHealth();T(P)}finally{H(!1)}};if(n)return t.jsx("p",{style:R.loading,children:"Lade Dashboard..."});if(i)return t.jsx("p",{style:R.error,children:i});if(!r)return null;const{stats:re,recentJobs:J,recentErrors:ke}=r;return t.jsxs("div",{children:[t.jsx("style",{children:"@keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }"}),t.jsx("h1",{style:R.h1,children:"System-Dashboard"}),t.jsxs("div",{style:R.grid,"data-sensitive":!0,children:[t.jsx(Lr,{label:"Benutzer",value:re.users}),t.jsx(Lr,{label:"Unternehmen",value:re.companies}),t.jsx(Lr,{label:"Reviews",value:(D=re.reviews)==null?void 0:D.toLocaleString("de-DE")}),t.jsx(Lr,{label:"Offene Fehler",value:re.unresolvedErrors,alert:re.unresolvedErrors>0})]}),t.jsxs("div",{style:R.section,"data-sensitive":!0,children:[t.jsx("h2",{style:{...R.sectionTitle,marginBottom:12},children:"API-Status"}),t.jsx("div",{style:R.card,children:c?t.jsx("p",{style:R.loading,children:"Prüfe API-Status..."}):a?t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:16},children:[t.jsxs("div",{style:{...R.statusCard,flex:1},children:[t.jsx(Fd,{ok:a.connectionOk}),t.jsxs("div",{children:[t.jsx("p",{style:R.statusLabel,children:"Claude AI"}),t.jsx("p",{style:{...R.statusValue,color:a.connectionOk?"#1a7f37":"#cf222e"},children:a.connectionOk?"Verbunden (API-Key)":"Nicht verbunden"})]})]}),t.jsx("button",{style:{...R.btn,padding:"6px 14px",fontSize:12,opacity:g?.5:1,background:"#f6f8fa",color:"#1f2328",border:"1px solid #d0d7de"}
93,onClick:G,disabled:g,children:g?"Teste...":"Verbindung testen"})]}):t.jsx("p",{style:{color:"#656d76",fontSize:13},children:"Status nicht verfügbar"})})]}),t.jsxs("div",{style:R.section,"data-sensitive":!0,children:[t.jsxs("div",{style:R.sectionHeader,children:[t.jsx("h2",{style:R.sectionTitle,children:"API-Guthaben & Verbrauch"}),t.jsxs("button",{style:{...R.btn,background:"none",border:"1px solid #d0d7de",color:"#1f2328",display:"inline-flex",alignItems:"center",gap:6,opacity:y?.5:1},onClick:O,disabled:y,children:[t.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",style:{animation:y?"spin 1s linear infinite":"none"},children:[t.jsx("path",{d:"M1 8a7 7 0 0 1 13.2-3.2M15 8a7 7 0 0 1-13.2 3.2"}),t.jsx("path",{d:"M14.2 1v3.8H10.4M1.8 15v-3.8h3.8"})]}),y?"Lädt...":"Aktualisieren"]})]}),t.jsx("div",{style:R.card,children:_?t.jsx("p",{style:R.loading,children:"Lade API-Daten..."}):m?t.jsxs(t.Fragment,{children:[t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(3, 1fr)",gap:12,marginBottom:16},children:[t.jsx(zr,{label:"Claude AI",sublabel:"API-Key",connected:(Y=m.claude)==null?void 0:Y.connected,value:(()=>{const P=m.claude;return P!=null&&P.connected?P.realCostUSD!=null&&P.balanceUSD!=null?`$${Math.max(0,P.balanceUSD-P.realCostUSD).toFixed(2)} übrig`:P.realCostUSD!=null?`$${P.realCostUSD.toFixed(2)} diesen Monat`:"Verbunden":"Getrennt"})(),detail:(()=>{var Pe;const P=m.claude;if(!(P!=null&&P.connected))return", ";const ue=[];return P.realCostUSD!=null&&P.balanceUSD!=null?ue.push(`$${P.realCostUSD.toFixed(2)} / $${P.balanceUSD.toFixed(2)} verbraucht`):P.realCostUSD!=null&&ue.push(`$${P.realCostUSD.toFixed(2)} Kosten`),ue.push(`${((Pe=P.tokenUsage)==null?void 0:Pe.totalCalls)||0} Aufrufe`),ue.join(" · ")})(),color:"#8b5cf6",link:"https://console.anthropic.com/settings/billing"}),t.jsx(zr,{label:"Outscraper",sublabel:"Google & Yelp",connected:((te=m.outscraper)==null?void 0:te.configured)&&!((X=m.outscraper)!=null&&X.error),value:((Ce=m.outscraper)==null?void 0:Ce.balance)!=null?`$${Number(m.outscraper.balance).toFixed(2)}`:(N=m.outscraper)!=null&&N.configured?"Fehler":"Nicht konfiguriert",detail:((ze=m.outscraper)==null?void 0:ze.plan)||((Ge=m.outscraper)==null?void 0:Ge.error)||", ",color:"#f97316",link:"https://app.outscraper.cloud/billing/payments?ln=de"}),t.jsx(zr,{label:"ScrapingBee",sublabel:"ProvenExpert",connected:((rt=m.scrapingbee)==null?void 0:rt.configured)&&!((He=m.scrapingbee)!=null&&He.error),value:((nt=m.scrapingbee)==null?void 0:nt.creditsRemaining)!=null?`${m.scrapingbee.creditsRemaining.toLocaleString("de-DE")} Credits`:(De=m.scrapingbee)!=null&&De.configured?"Fehler":"Nicht konfiguriert",detail:((st=m.scrapingbee)==null?void 0:st.creditsUsed)!=null?`Verbraucht: ${m.scrapingbee.creditsUsed.toLocaleString("de-DE")} / ${(m.scrapingbee.maxCredits||0).toLocaleString("de-DE")}`:((oe=m.scrapingbee)==null?void 0:oe.error)||", ",color:"#f59e0b",link:"https://dashboard.scrapingbee.com/dashboard"}),t.jsx(zr,{label:"Wextractor",sublabel:"Trustpilot, TripAdvisor, Trusted Shops",connected:((Ae=m.wextractor)==null?void 0:Ae.configured)&&!((be=m.wextractor)!=null&&be.error),value:((Re=m.wextractor)==null?void 0:Re.available)!=null?`${m.wextractor.available.toLocaleString("de-DE")} Credits`:(it=m.wextractor)!=null&&it.configured?"Verbunden":"Nicht konfiguriert",detail:((ut=m.wextractor)==null?void 0:ut.used)!=null?`Verbraucht: ${m.wextractor.used.toLocaleString("de-DE")} / ${(m.wextractor.total||0).toLocaleString("de-DE")} · ~$${(m.wextractor.used*.006).toFixed(2)} / $${((m.wextractor.total||0)*.006).toFixed(2)}`:((Ie=m.wextractor)==null?void 0:Ie.plan)||", ",color:"#6366f1",link:"https://wextractor.com/account/"})]}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(2, 1fr)",gap:12,marginBottom:12},children:[t.jsx("div",{style:{...R.statusCard,padding:"10px 14px"},children:t.jsxs("div",{children:[t.jsx("p",{style:R.statusLabel,children:"Analysen gesamt"}),t.jsxs("p",{style:{...R.statusValue,fontSize:15},children:[((ht=m.stats)==null?void 0:ht.totalAnalyses)||0," Berichte · ",((ot=m.stats)==null?void 0:ot.analyzedReviews)||0," Reviews"]})]})}),t.jsx("div",{style:{...R.statusCard,padding:"10px 14px"},children:t.jsxs("div",{children:[t.jsx("p",{style:R.statusLabel,children:"Claude Token-Detail
93s"}),t.jsxs("p",{style:{...R.statusValue,fontSize:15},children:["In: ",(((jr=(St=m.claude)==null?void 0:St.tokenUsage)==null?void 0:jr.inputTokens)||0).toLocaleString("de-DE")," · Out: ",(((ft=(Gt=m.claude)==null?void 0:Gt.tokenUsage)==null?void 0:ft.outputTokens)||0).toLocaleString("de-DE")]})]})})]}),t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",fontSize:11,color:"#656d76"},children:[t.jsxs("span",{children:["Tracking seit: ",(Yt=(Zt=m.claude)==null?void 0:Zt.tokenUsage)!=null&&Yt.trackedSince?new Date(m.claude.tokenUsage.trackedSince).toLocaleString("de-DE"):", ",((Qt=(Xt=m.claude)==null?void 0:Xt.tokenUsage)==null?void 0:Qt.lastCallAt)&&` · Letzter Aufruf: ${new Date(m.claude.tokenUsage.lastCallAt).toLocaleString("de-DE")}`]}),t.jsxs("span",{children:["Aktualisiert: ",m.lastUpdated?new Date(m.lastUpdated).toLocaleString("de-DE"):", "," · Auto-Refresh: täglich"]})]})]}):t.jsx("p",{style:{color:"#656d76",fontSize:13},children:"Nicht verfügbar"})})]}),t.jsxs("div",{style:R.section,"data-sensitive":!0,children:[t.jsxs("div",{style:R.sectionHeader,children:[t.jsx("h2",{style:R.sectionTitle,children:"Server-Status"}),t.jsxs("button",{style:{...R.btn,background:"none",border:"1px solid #d0d7de",color:"#1f2328",display:"inline-flex",alignItems:"center",gap:6,opacity:z?.5:1},onClick:ne,disabled:z,children:[t.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",style:{animation:z?"spin 1s linear infinite":"none"},children:[t.jsx("path",{d:"M1 8a7 7 0 0 1 13.2-3.2M15 8a7 7 0 0 1-13.2 3.2"}),t.jsx("path",{d:"M14.2 1v3.8H10.4M1.8 15v-3.8h3.8"})]}),z?"Lade...":"Aktualisieren"]})]}),t.jsx("div",{style:R.card,children:V?t.jsx("p",{style:R.loading,children:"Lade Server-Status..."}):S?t.jsx(Hd,{health:S}):t.jsx("p",{style:{color:"#656d76",fontSize:13},children:"Nicht verfügbar"})})]}),t.jsxs("div",{style:R.section,"data-sensitive":!0,children:[t.jsxs("div",{style:R.sectionHeader,children:[t.jsx("h2",{style:R.sectionTitle,children:"System-Monitoring"}),t.jsx("button",{style:{...R.btn,...R.btnBlue,opacity:u?.5:1},onClick:F,disabled:u,children:u?"Prüfe...":"Aktualisieren"})]}),t.jsx("div",{style:{...R.card,display:"flex",gap:12,flexWrap:"wrap"},children:p.length>0?p.map(P=>t.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8,padding:"10px 14px",background:"#f6f8fa",borderRadius:8,border:`1px solid ${P.status==="ok"?"#1a7f3733":P.status==="warning"?"#9a670033":"#cf222e33"}`},children:[t.jsx("span",{style:R.healthDot(P.status)}),t.jsxs("div",{children:[t.jsx("span",{style:{color:"#1f2328",fontSize:13,fontWeight:500},children:Vd(P.check_name)}),P.details&&t.jsx("div",{style:{fontSize:11,color:"#656d76",marginTop:2},children:Object.entries(P.details).slice(0,2).map(([ue,Pe])=>t.jsxs("span",{style:{marginRight:8},children:[ue,": ",t.jsx("strong",{children:(Pe==null?void 0:Pe.toString())??"--"})]},ue))})]})]},P.check_name)):t.jsx("p",{style:{color:"#656d76",fontSize:13},children:"Keine Health-Checks"})})]}),t.jsxs("div",{style:R.section,children:[t.jsx("h2",{style:{...R.sectionTitle,marginBottom:12},children:"Letzte Scrape-Jobs"}),t.jsx("div",{style:R.card,children:t.jsxs("table",{style:R.table,children:[t.jsx("thead",{children:t.jsxs("tr",{children:[t.jsx("th",{style:R.th,children:"Status"}),t.jsx("th",{style:R.th,children:"Unternehmen"}),t.jsx("th",{style:R.th,children:"Plattform"}),t.jsx("th",{style:R.th,children:"Gefunden"}),t.jsx("th",{style:R.th,children:"Neu"}),t.jsx("th",{style:R.th,children:"Fortschritt"}),t.jsx("th",{style:R.th,children:"Fehler"}),t.jsx("th",{style:R.th,children:"Datum"})]})}),t.jsxs("tbody",{children:[(J||[]).slice(0,10).map(P=>{var Et,tr;const ue=Md[P.platform]||{logo:null,name:P.platform},Pe=((Et=P.companies)==null?void 0:Et.name)||"",ve=P.profile_url||null,er=Wd(P),kt=P.status==="running"||P.status==="pending",Ue=t.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:6},children:[ue.logo&&t.jsx("img",{src:ue.logo,alt:ue.name,style:{width:16,height:16,borderRadius:3,flexShrink:0}}),t.jsx("span",{style:{fontSize:13},children:ue.name})]});return t.jsxs("tr",{children:[t.jsx("td",{style:R.td,children:t.jsx("span",{style:R.badge(P.status==="completed"?"#1a7f37":P.status==="failed"?"#cf222e":"#9a6700"),children:P.status==="completed"?"Fertig":P.status==="failed"?"Fehler":"Läuft"})}),t.jsx("td",{style:R.td,children:Pe||((tr=P.company_id)==null?void 0:tr.slice(0,8))+"..."}),t.jsx("td",{style:R.td,children:ve?t.jsx("a",{href:ve,target:"_blank",rel:"noopener noreferrer",style:{textDecoration:"none",color:"#1f2328"},children:Ue}):Ue}),t.jsx("td",{style:R.td,children:kt&&!P.reviews_found?"":P.reviews_found??""}),t.jsx("td",{style:R.td,children:kt&&!P.reviews_new?"":P.reviews_new??""}),t.jsx("td",{style:R.td,children:t.jsx("span",{style:{fontSize:12,fontWeight:500,color:er.color},children:er.label})}),t.jsx("td",{style:{...R.td,color:"#cf222e",maxWidth:200,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:P.error_message||""}),t.jsx("td",{style:{...R.td,color:"#656d76",whiteSpace:"nowrap"}
93,children:P.started_at?new Date(P.started_at).toLocaleString("de-DE"):new Date(P.created_at).toLocaleString("de-DE")})]},P.id)}),(!J||J.length===0)&&t.jsx("tr",{children:t.jsx("td",{colSpan:8,style:{...R.td,color:"#656d76",textAlign:"center"},children:"Keine Jobs"})})]})]})})]}),t.jsxs("div",{style:R.section,children:[t.jsx("h2",{style:{...R.sectionTitle,marginBottom:12},children:"Letzte Fehler"}),t.jsx("div",{style:R.card,children:t.jsxs("table",{style:R.table,children:[t.jsx("thead",{children:t.jsxs("tr",{children:[t.jsx("th",{style:R.th,children:"Schwere"}),t.jsx("th",{style:R.th,children:"Typ"}),t.jsx("th",{style:R.th,children:"Nachricht"}),t.jsx("th",{style:R.th,children:"Datum"})]})}),t.jsxs("tbody",{children:[(ke||[]).map(P=>t.jsxs("tr",{children:[t.jsx("td",{style:R.td,children:t.jsx("span",{style:R.badge(P.severity==="critical"?"#cf222e":P.severity==="error"?"#9a6700":"#656d76"),children:P.severity})}),t.jsx("td",{style:R.td,children:P.error_type}),t.jsx("td",{style:{...R.td,maxWidth:300,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:P.message}),t.jsx("td",{style:R.td,children:new Date(P.created_at).toLocaleString("de-DE")})]},P.id)),(!ke||ke.length===0)&&t.jsx("tr",{children:t.jsx("td",{colSpan:4,style:{...R.td,color:"#656d76",textAlign:"center"},children:"Keine Fehler"})})]})]})})]})]})}function Lr({label:r,value:e,alert:n}){return t.jsxs("div",{style:{...R.card,borderColor:n?"#cf222e33":"#e5e7eb"},children:[t.jsx("p",{style:R.cardLabel,children:r}),t.jsx("p",{style:{...R.cardValue,color:n?"#cf222e":"#1f2328"},children:e??"--"})]})}function Fd({ok:r}){return t.jsx("div",{style:{width:10,height:10,borderRadius:"50%",background:r?"#1a7f37":"#cf222e",flexShrink:0}})}function zr({label:r,sublabel:e,connected:n,value:s,detail:i,color:o,link:a}){const l=n?"#1a7f37":n===!1?"#cf222e":"#656d76";return t.jsxs("div",{style:{...R.statusCard,flexDirection:"column",alignItems:"flex-start",gap:8,padding:"14px 16px"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,width:"100%"},children:[t.jsx("div",{style:{width:10,height:10,borderRadius:"50%",background:l,flexShrink:0}}),t.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#1f2328"},children:r}),t.jsx("span",{style:{fontSize:11,color:"#656d76",marginLeft:"auto"},children:e})]}),t.jsxs("div",{children:[t.jsx("p",{style:{fontSize:20,fontWeight:700,color:n?"#1f2328":"#cf222e",margin:"0 0 2px"},children:s}),t.jsx("p",{style:{fontSize:11,color:"#656d76",margin:0},children:i})]}),a&&t.jsx("a",{href:a,target:"_blank",rel:"noopener noreferrer",style:{fontSize:11,color:"#0969da",textDecoration:"none"},children:"Guthaben & Billing ansehen"})]})}function Hd({health:r}){var c,d,u,f,p,x,g,v,m;const e=w=>{const _=Math.floor(w/86400),b=Math.floor(w%86400/3600),y=Math.floor(w%3600/60);return _>0?`${_}d ${b}h ${y}m`:b>0?`${b}h ${y}m`:`${y}m`},n=w=>w?w<1048576?`${(w/1024).toFixed(0)} KB`:`${(w/1048576).toFixed(1)} MB`:"--",s=w=>w?new Date(w).toLocaleString("de-DE"):"--",i=r.memory?Math.round(r.memory.heapUsed/r.memory.heapTotal*100):0,o=((c=r.database)==null?void 0:c.status)==="ok",l=[{label:"Server",ok:r.status==="ok",detail:`Uptime: ${e(r.uptime)}`},{label:"Datenbank",ok:o,detail:o?`${r.database.latencyMs}ms Latenz`:((d=r.database)==null?void 0:d.error)||"Fehler"},{label:"Queue",ok:r.queueSize===0,detail:r.queueSize>0?`${r.queueSize} Jobs ausstehend`:"Leer"},{label:"Wextractor",ok:r.wextractorCredits!=null&&r.wextractorCredits>100,detail:r.wextractorCredits!=null?`${r.wextractorCredits.toLocaleString("de-DE")} Credits`:"Unbekannt"}];return t.jsxs("div",{children:[t.jsx("div",{style:{display:"flex",gap:16,flexWrap:"wrap",marginBottom:16},children:l.map(w=>t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"8px 14px",background:"#f6f8fa",borderRadius:8,border:`1px solid ${w.ok?"#1a7f3733":"#cf222e33"}`},children:[t.jsx("div",{style:{width:10,height:10,borderRadius:"50%",background:w.ok?"#1a7f37":"#cf222e",flexShrink:0}}),t.jsxs("div",{children:[t.jsx("span",{style:{fontSize:13,fontWeight:500,color:"#1f2328"},children:w.label}),t.jsx("p",{style:{fontSize:11,color:"#656d76",margin:"2px 0 0"},children:w.detail})]})]},w.label))}),t.jsxs("div",{style:{marginBottom:16},children:[t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",fontSize:12,color:"#656d76",marginBottom:4},children:[t.jsx("span",{children:"Speicher (Heap)"}),t.jsxs("span",{children:[n((u=r.memory)==null?void 0:u.heapUsed)," / ",n((f=r.memory)==null?void 0:f.heapTotal)," (",i,"%)"]})]}),t.jsx("div",{style:{height:8,background:"#e5e7eb",borderRadius:4,overflow:"hidden"},children:t.jsx("div",{style:{height:"100%",width:`${i}%`,background:i>85?"#cf222e":i>60?"#9a6700":"#1a7f37",borderRadius:4,transition:"width 0.3s ease"}})}),t.jsxs("div",{style:{fontSize:11,color:"#656d76",marginTop:4},children:["RSS: ",n((p=r.memory)==null?void 0:p.rss)]})]}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(3, 1fr)",gap:12},children:[t.jsxs("div",{style:{...R.statusCard,padding:"10px 14px",flexDirection:"column",alignItems:"flex-start",ga
93p:4},children:[t.jsx("p",{style:R.statusLabel,children:"Letzter Scrape (OK)"}),t.jsx("p",{style:{...R.statusValue,fontSize:12},children:s((x=r.lastSuccessfulScrape)==null?void 0:x.timestamp)}),r.lastSuccessfulScrape&&t.jsxs("p",{style:{fontSize:11,color:"#656d76",margin:0},children:[r.lastSuccessfulScrape.company," (",r.lastSuccessfulScrape.platform,")"]})]}),t.jsxs("div",{style:{...R.statusCard,padding:"10px 14px",flexDirection:"column",alignItems:"flex-start",gap:4},children:[t.jsx("p",{style:R.statusLabel,children:"Letzter Scrape (Fehler)"}),t.jsx("p",{style:{...R.statusValue,fontSize:12,color:r.lastFailedScrape?"#cf222e":"#1f2328"},children:s((g=r.lastFailedScrape)==null?void 0:g.timestamp)}),r.lastFailedScrape&&t.jsxs("p",{style:{fontSize:11,color:"#656d76",margin:0,maxWidth:220,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:r.lastFailedScrape.error,children:[r.lastFailedScrape.company,": ",r.lastFailedScrape.error]})]}),t.jsxs("div",{style:{...R.statusCard,padding:"10px 14px",flexDirection:"column",alignItems:"flex-start",gap:4},children:[t.jsx("p",{style:R.statusLabel,children:"Letztes Backup"}),t.jsx("p",{style:{...R.statusValue,fontSize:12,color:((v=r.lastBackup)==null?void 0:v.success)===!1?"#cf222e":"#1f2328"},children:s((m=r.lastBackup)==null?void 0:m.timestamp)}),r.lastBackup&&t.jsx("p",{style:{fontSize:11,color:r.lastBackup.success?"#1a7f37":"#cf222e",margin:0},children:r.lastBackup.success?"Erfolgreich":"Fehlgeschlagen"})]})]}),t.jsxs("div",{style:{fontSize:11,color:"#656d76",marginTop:12,textAlign:"right"},children:["Health-Check Antwortzeit: ",r.responseTimeMs,"ms"]})]})}function Vd(r){return r.split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}const fe={h1:{fontSize:22,fontWeight:600,margin:"0 0 24px",color:"#1f2328"},card:{background:"#ffffff",border:"1px solid #e5e7eb",borderRadius:12,boxShadow:"0 1px 2px rgba(0,0,0,0.05)",padding:0,overflow:"hidden"},table:{width:"100%",borderCollapse:"collapse"},th:{textAlign:"left",padding:"10px 16px",color:"#656d76",fontSize:11,fontWeight:600,textTransform:"uppercase",borderBottom:"1px solid #e5e7eb",background:"#ffffff"},td:{padding:"12px 16px",color:"#1f2328",fontSize:13,borderBottom:"1px solid #f0f0f0"},row:{cursor:"pointer",transition:"background 0.15s"},badge:r=>({display:"inline-block",padding:"2px 8px",borderRadius:12,fontSize:11,fontWeight:600,background:r+"22",color:r}),loading:{color:"#656d76",fontSize:14}};function Fs(r){if(!r)return", ";const e=new Date(r);return e.toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"})+", "+e.toLocaleTimeString("de-DE",{hour:"2-digit",minute:"2-digit"})}function qd(r){if(!r)return t.jsx("span",{style:fe.badge("#656d76"),children:"Kein Plan"});const n={erstanalyse:"Erstanalyse",monitoring:"Monitoring",free:"Free"}[r.plan]||r.plan;return r.status==="unpaid"?t.jsxs("span",{style:fe.badge("#d97706"),children:[n," (unbezahlt)"]}):r.status==="active"?t.jsx("span",{style:fe.badge("#1a7f37"),children:n}):r.status==="canceled"?t.jsxs("span",{style:fe.badge("#cf222e"),children:[n," (gekündigt)"]}):t.jsx("span",{style:fe.badge("#656d76"),children:n})}function Kd({basePath:r}){const[e,n]=h.useState([]),[s,i]=h.useState(!0),o=Se();return h.useEffect(()=>{M.getUsers().then(n).finally(()=>i(!1))},[]),s?t.jsx("p",{style:fe.loading,children:"Lade Benutzer..."}):t.jsxs("div",{children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:24},children:[t.jsxs("h1",{style:{...fe.h1,margin:0},children:["Benutzer (",e.length,")"]}),t.jsxs("button",{onClick:()=>o(`${r}/onboard`),style:{padding:"8px 16px",borderRadius:8,border:"none",backgroundColor:"#1a7f37",color:"#fff",fontSize:13,fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",gap:6,fontFamily:"-apple-system, sans-serif"},children:[t.jsx("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"#fff",children:t.jsx("path",{d:"M7.75 2a.75.75 0 0 1 .75.75V7h4.25a.75.75 0 0 1 0 1.5H8.5v4.25a.75.75 0 0 1-1.5 0V8.5H2.75a.75.75 0 0 1 0-1.5H7V2.75A.75.75 0 0 1 7.75 2Z"})}),"Kunde anlegen"]})]}),t.jsx("div",{style:fe.card,children:t.jsxs("table",{style:fe.table,children:[t.jsx("thead",{children:t.jsxs("tr",{children:[t.jsx("th",{style:fe.th,children:"Name"}),t.jsx("th",{style:fe.th,children:"Unternehmen"}),t.jsx("th",{style:fe.th,children:"Plan"}),t.jsx("th",{style:fe.th,children:"Letzter Login"}),t.jsx("th",{style:fe.th,children:"Erstellt"})]})}),t.jsx("tbody",{children:e.map(a=>{var l;return t.jsxs("tr",{style:fe.row,onClick:()=>o(`${r}/users/${a.id}`),onMouseEnter:c=>c.currentTarget.style.background="#f3f4f6",onMouseLeave:c=>c.currentTarget.style.background="transparent",children:[t.jsxs("td",{style:fe.td,children:[t.jsx("div",{style:{fontWeight:500},children:a.full_name||", "}),t.jsx("div",{style:{fontSize:11,color:"#8c959f",marginTop:1},children:a.role==="owner"?"Inhaber":a.role==="admin"?"Admin":a.role})]}),t.jsx("td",{style:fe.td,children:((l=a.companies)==null?void 0:l.name)||", "}),t.jsx("td",{style:fe.td,children:qd(a.subscription)}),t.jsx("td",{style:{...fe.td,color:a.last_sign_in_at?"#1f2328":"#b0b8c1",fontSize:12},children:Fs(a.last_sign_in_at)}),t.jsx("td",{style:{...fe.td,color:"#656d76",fontSize:12},children:Fs(a.created_at)})]},a.id)})})]})})]})}const E={h1:{fontSize:22,fontWeight:600,margin:"0 0 8px",color:"#1f2328"},back:{color:"#0969da",fontSize:13,cursor:"pointer",background:"none",border:"none",padding:0,marginBottom:20,display:"flex",alignItems:"center",gap:6},grid:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:24,marginBottom:24},card:{background:"#ffffff",border:"1px solid #e5e7eb",borderRadius:12,boxShadow:"0 1px 2px rgba(0,0,0,0.05)",padding:20,marginBottom:24},cardTitle:{fontSize:14,fontWeight:600,color:"#1f2328",margin:"0 0 16px",display:"flex",alignItems:"center",gap:8},row:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"8px 0",borderBottom:"1px solid #f0f
930f0"},label:{color:"#656d76",fontSize:13,flex:"0 0 120px"},value:{color:"#1f2328",fontSize:13,fontWeight:500},btn:{padding:"8px 16px",borderRadius:8,border:"none",fontSize:13,fontWeight:600,cursor:"pointer",marginRight:8,transition:"opacity 0.15s"},btnPrimary:{background:"#0969da",color:"#fff"},btnDanger:{background:"#cf222e",color:"#fff"},btnSuccess:{background:"#1a7f37",color:"#fff"},badge:r=>({display:"inline-block",padding:"2px 8px",borderRadius:12,fontSize:11,fontWeight:600,background:r+"22",color:r}),table:{width:"100%",borderCollapse:"collapse"},th:{textAlign:"left",padding:"8px 12px",color:"#656d76",fontSize:11,fontWeight:600,textTransform:"uppercase",borderBottom:"1px solid #e5e7eb"},td:{padding:"10px 12px",color:"#1f2328",fontSize:13,borderBottom:"1px solid #f0f0f0"},input:{padding:"6px 10px",background:"#f6f8fa",border:"1px solid #e5e7eb",borderRadius:6,color:"#1f2328",fontSize:13,boxSizing:"border-box"},saveBtn:{padding:"5px 12px",background:"#1a7f37",border:"none",borderRadius:6,color:"#fff",fontSize:11,fontWeight:600,cursor:"pointer",whiteSpace:"nowrap",display:"inline-flex",alignItems:"center",gap:4},loading:{color:"#656d76",fontSize:14},success:{color:"#1a7f37",fontSize:12},logPanel:{background:"#0d1117",borderRadius:8,padding:16,maxHeight:300,overflowY:"auto",fontFamily:"ui-monospace, SFMono-Regular, monospace",fontSize:12,lineHeight:1.6},logLine:r=>({color:r==="error"?"#f85149":r==="success"?"#3fb950":r==="info"?"#58a6ff":"#8b949e",margin:0,whiteSpace:"pre-wrap"})},Dr={google:{label:"Google",color:"#4285f4",icon:t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",children:[t.jsx("path",{d:"M15.68 8.18c0-.57-.05-1.11-.15-1.64H8v3.1h4.31a3.68 3.68 0 01-1.6 2.42v2.01h2.58c1.51-1.39 2.39-3.44 2.39-5.89z",fill:"#4285F4"}),t.jsx("path",{d:"M8 16c2.16 0 3.97-.72 5.29-1.93l-2.58-2.01c-.72.48-1.63.76-2.71.76-2.08 0-3.85-1.41-4.48-3.3H.85v2.07A8 8 0 008 16z",fill:"#34A853"}),t.jsx("path",{d:"M3.52 9.52A4.8 4.8 0 013.27 8c0-.53.09-1.04.25-1.52V4.41H.85A8 8 0 000 8c0 1.29.31 2.51.85 3.59l2.67-2.07z",fill:"#FBBC05"}),t.jsx("path",{d:"M8 3.18c1.17 0 2.23.4 3.06 1.2l2.29-2.29A7.96 7.96 0 008 0 8 8 0 00.85 4.41l2.67 2.07C4.15 4.59 5.92 3.18 8 3.18z",fill:"#EA4335"})]})},trustpilot:{label:"Trustpilot",color:"#00b67a",icon:t.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",children:t.jsx("path",{d:"M8 0l2.47 5.01L16 5.81l-4 3.9.94 5.49L8 12.49l-4.94 2.7.94-5.49-4-3.9 5.53-.8z",fill:"#00B67A"})})},trusted_shops:{label:"Trusted Shops",color:"#ffdc0f",icon:t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:[t.jsx("path",{d:"M8 1L2 4v4c0 3.5 2.6 6.4 6 7 3.4-.6 6-3.5 6-7V4L8 1z",fill:"#FFDC0F",stroke:"#E8C900",strokeWidth:".5"}),t.jsx("path",{d:"M5.5 8l2 2 3.5-3.5",stroke:"#333",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})]})},tripadvisor:{label:"TripAdvisor",color:"#34e0a1",icon:t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:[t.jsx("circle",{cx:"8",cy:"8",r:"7",fill:"#34E0A1"}),t.jsx("circle",{cx:"5.5",cy:"8",r:"2",stroke:"#333",strokeWidth:"1",fill:"white"}),t.jsx("circle",{cx:"10.5",cy:"8",r:"2",stroke:"#333",strokeWidth:"1",fill:"white"}),t.jsx("circle",{cx:"5.5",cy:"8",r:".8",fill:"#333"}),t.jsx("circle",{cx:"10.5",cy:"8",r:".8",fill:"#333"})]})},amazon:{label:"Amazon",color:"#ff9900",icon:t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:[t.jsx("path",{d:"M2 10c3 2 6 3 10 1",stroke:"#FF9900",strokeWidth:"1.5",strokeLinecap:"round"}),t.jsx("path",{d:"M11 9l1.5 2",stroke:"#FF9900",strokeWidth:"1.5",strokeLinecap:"round"}),t.jsx("text",{x:"4",y:"8",fontSize:"8",fontWeight:"bold",fill:"#333",children:"a"})]})},yelp:{label:"Yelp",color:"#d32323",icon:t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",children:[t.jsx("circle",{cx:"8",cy:"8",r:"7",fill:"#D32323"}),t.jsx("text",{x:"8",y:"11",textAnchor:"middle",fontSize:"9",fontWeight:"bold",fill:"white",children:"y"})]})},provenexpert:{label:"ProvenExpert",color:"#1a1a2e",icon:t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",children:[t.jsx("circle",{cx:"8",cy:"8",r:"7",fill:"#1a1a2e"}),t.jsx("path",{d:"M5 8l2 2 4-4",stroke:"white",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})]})}},Hs={completed:"Abgeschlossen",failed:"Fehlgeschlagen",running:"Läuft",pending:"Wartend",in_progress:"In Bearbeitung"},Vs=()=>t.jsx("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:t.jsx("path",{d:"M3.5 8.5l3 3 6-7"})}),Jd=()=>t.jsx("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:t.jsx("path",{d:"M10 3L5 8l5 5"})});function qs({name:r}){const e=Dr[r]||{label:r,color:"#656d76",icon:null};return t.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:6},children:[e.icon||t.jsx("span",{style:{width:16,height:16,borderRadius:4,background:e.color,display:"inline-block"}}),t.jsx("span",{style:{fontWeight:500},children:e.label})]})}function Gd({basePath:r}){var Jn,Gn,Zn,Yn,Xn,Qn;const{id:e}=qr(),n=Se(),[s,i]=h.useState(null),[o,a]=h.useState(!0),[l,c]=h.useState(!1),[d,u]=
93h.useState({}),[f,p]=h.useState({}),[x,g]=h.useState({}),[v,m]=h.useState({}),[w,_]=h.useState(!1),[b,y]=h.useState(!1),[k,S]=h.useState(!1),[T,V]=h.useState([]),[C,z]=h.useState(!1),H=h.useRef(null),[G,O]=h.useState(!1),[F,ne]=h.useState(null),re=h.useRef(null),J=h.useRef(new Set),[ke,D]=h.useState(!1),[Y,te]=h.useState(""),[X,Ce]=h.useState(""),[N,ze]=h.useState(null),[Ge,rt]=h.useState(!1),[He,nt]=h.useState(""),[De,st]=h.useState(""),[oe,Ae]=h.useState(!1),[be,Re]=h.useState(!1),[it,ut]=h.useState(!1),[Ie,ht]=h.useState([]),[ot,St]=h.useState([]),[jr,Gt]=h.useState(!1),[ft,Zt]=h.useState(""),[Yt,Xt]=h.useState(""),[Qt,P]=h.useState("google"),[ue,Pe]=h.useState(!1),[ve,er]=h.useState(!1),[kt,Ue]=h.useState(null),[Et,tr]=h.useState(!1),[Xr,Kn]=h.useState({});h.useEffect(()=>{M.getUser(e).then(j=>{var I,q,se;i(j);const A={};(j.platforms||[]).forEach(he=>{A[he.id]=he.profile_url||""}),u(A),m({full_name:j.profile.full_name||"",email:j.profile.email||"",company_name:((I=j.profile.companies)==null?void 0:I.name)||"",industry:((q=j.profile.companies)==null?void 0:q.industry)||"",website_url:((se=j.profile.companies)==null?void 0:se.website_url)||""}),J.current=new Set((j.jobs||[]).map(he=>he.id))}).finally(()=>a(!1))},[e]),h.useEffect(()=>{var j;if(!((j=s==null?void 0:s.profile)!=null&&j.email)){console.log("[Billing] Keine Email vorhanden, überspringe Billing-Fetch");return}console.log("[Billing] Lade Billing für:",s.profile.email),rt(!0),fetch(`https://review-scraper-production-9324.up.railway.app/billing/admin-billing?email=${encodeURIComponent(s.profile.email)}`).then(A=>(console.log("[Billing] Response Status:",A.status),A.json())).then(A=>{console.log("[Billing] Daten:",A),ze(A)}).catch(A=>{console.error("[Billing] Fehler:",A),ze(null)}).finally(()=>rt(!1))},[(Jn=s==null?void 0:s.profile)==null?void 0:Jn.email]),h.useEffect(()=>{var j;(j=s==null?void 0:s.profile)!=null&&j.company_id&&(Ae(!0),(async()=>{try{const{data:{session:A}}=await(await Ee(async()=>{const{supabaseAdmin:se}=await Promise.resolve().then(()=>Or);return{supabaseAdmin:se}},void 0)).supabaseAdmin.auth.getSession();if(!A)return;const q=await(await fetch(`https://review-scraper-production-9324.up.railway.app/billing/admin-pricing?companyId=${s.profile.company_id}`,{headers:{Authorization:`Bearer ${A.access_token}`}})).json();q.erstanalyse_cents&&nt(String(q.erstanalyse_cents/100)),q.monthly_cents&&st(String(q.monthly_cents/100))}catch(A){console.error("[Pricing] Fehler:",A)}finally{Ae(!1)}})())},[(Gn=s==null?void 0:s.profile)==null?void 0:Gn.company_id]),h.useEffect(()=>{var q;if(!((q=s==null?void 0:s.profile)!=null&&q.company_id))return;const j=s.profile.company_id;Gt(!0);const A=M.getConfiguredCompetitors(j).then(se=>ht(se.competitors||[])).catch(()=>ht([])),I=(async()=>{var se,he;try{const ye=await(async()=>{const{data:{session:Ve}}=await(await Ee(async()=>{const{supabaseAdmin:rn}=await Promise.resolve().then(()=>Or);return{supabaseAdmin:rn}},void 0)).supabaseAdmin.auth.getSession();return{Authorization:`Bearer ${Ve==null?void 0:Ve.access_token}`,"Content-Type":"application/json"}})(),le=await fetch(`https://review-scraper-production-9324.up.railway.app/competitors/${j}`,{headers:ye});if(le.ok){const Ve=await le.json(),rn=((se=Ve.results)==null?void 0:se.ranking)||((he=Ve.results)==null?void 0:he.competitors)||[];St(rn.filter(qi=>!qi.isOwn))}}catch{St([])}})();Promise.all([A,I]).finally(()=>Gt(!1))},[(Zn=s==null?void 0:s.profile)==null?void 0:Zn.company_id]);const Qr=async()=>{var j;if(!(!ft.trim()||!((j=s==null?void 0:s.profile)!=null&&j.company_id))){Pe(!0);try{const A=await M.addConfiguredCompetitor(s.profile.company_id,{name:ft.trim(),platform:Qt,url:Yt.trim()||null});ht(A.competitors||[]),Zt(""),Xt(""),P("google")}catch(A){alert("Fehler: "+A.message)}finally{Pe(!1)}}},Pi=async j=>{var A;if((A=s==null?void 0:s.profile)!=null&&A.company_id)try{const I=await M.deleteConfiguredCompetitor(s.profile.company_id,j);ht(I.competitors||[])}catch(I){alert("Fehler: "+I.message)}},Oi=async()=>{var j;if(!(!((j=s==null?void 0:s.profile)!=null&&j.company_id)||Ie.length===0)){er(!0),Ue(null);try{const A=Ie.map(I=>({name:I.name,placeId:"",mapsUrl:I.url||"",rating:null,reviewsCount:0,website:I.platform==="trustpilot"?I.url:null,trustpilotUrl:I.platform==="trustpilot"?I.url:void 0}));await M.triggerCompetitorAnalysis(s.profile.company_id,A),Ue({ok:!0,text:"Analyse gestartet â Ergebnis in wenigen Minuten verfügbar"})}catch(A){Ue({ok:!1,text:`Fehler: ${A.message}`})}finally{er(!1)}}},Li=async()=>{var j;if((j=s==null?void 0:s.profile)!=null&&j.company_id){tr(!0),Ue(null);try{await M.deleteCompetitorAnalysis(s.profile.company_id);const A=Ie.map(I=>({name:I.name,placeId:"",mapsUrl:I.url||"",rating:null,reviewsCount:0,website:I.platform==="trustpilot"?I.url:null,trustpilotUrl:I.platform==="trustpilot"?I.url:void 0}));await M.triggerCompetitorAnalysis(s.profile.company_id,A),Ue({ok:!0,text:"Cache gelöscht, Analyse neu gestartet"})}catch(A){Ue({ok:!1,text:`Fehler: ${A.message}`})}finally{tr(!1)}}},zi=async j=>{var A;if((A=s==null?void 0:s.profile)!=null&&A.company_id){Kn(I=>({...I,[j.name]:!0}));try{const I=[{name:j.name,placeId:"",mapsUrl:j.url||"",rating:null,reviewsCount:0,website:j.platform==="trustpilot"?j.url:null,trustpilotUrl:j.platform==="trustpilot"?j.url:void 0}];await M.triggerCompetitorAnalysis(s.profile.company_id,I),Ue({ok:!0,text:`Scrape für "${j.name}" gestartet`})}catch(I){Ue({ok:!1,text:`Fehler: ${I.message}`})}finally{Kn(I=>({...I,[j.name]:!1}))}}},Me=h.useCallback((j,A="default")=>{const I=new Date().toLocaleTimeString("de-DE",{hour:"2-digit",minute:"2-digit",second:"2-digit"});V(q=>[...q,{text:`[${I}] ${j}`,type:A}]),setTimeout(()=>{var q;return(q=H.current)==null?void 0:q.scrollTo(0,H.current.scrollHeight)},50)},[]),Bi=async()=>{var A,I,q;if(!((A=s==null?void 0:s.profile)!=null&&A.company_id))return;S(!0),z(!0),V([]),Me("Scrape gestartet für alle Plattformen...","info"),Me(`Unternehmen: ${((I=s.profile.companies)==null?void 0:I.name)||s.profile.company_id}`,"default");const j=new Set;re.current=setInterval(async()=>{var se;try{const he=await M.getUser(e),ye=(he.jobs||[]).filter(le=>!J.current.has(le.id)&&!j.has(le.id));for(const le of ye){j.add(le.id);const Ve=((se=Dr[le.platform])==null?void 0:se.label)||le.platform;le.status==="completed"?Me(`${Ve}: ${le.reviews_found||0} Reviews gefunden, ${le.reviews_new||0} neu`,"success"):le.status==="failed"?Me(`${Ve}: Fehler â ${le.error_message||"Unbekannt"}`,"error"):Me(`${Ve}: ${Hs[le.status]||le.status}...`,"info")}i(le=>le&&{...le,jobs:he.jobs})}catch{}},2500);try{const se=await M.triggerScrape(s.profile.company_id);if(clearInterval(re.current),se.error)Me(`Fehler: ${se.error}`,"error");else if(Array.isArray(se)){for(const ye of se){const le=((q=Dr[ye.platform])==null?void 0:q.label)||ye.platform;ye.error?Me(`${le}: Fehler â ${ye.error}`,"error"):Me(`${le}: ${ye.reviewsFound||0} Reviews, ${ye.reviewsNew||0} neu`,"success")}Me("Scrape abgeschlossen.","success")}else Me("Scrape abgeschlossen.","success");const he=await M.getUser(e);
93i(he),J.current=new Set((he.jobs||[]).map(ye=>ye.id))}catch(se){clearInterval(re.current),Me(`Fehler: ${se.message}`,"error")}finally{S(!1)}};h.useEffect(()=>()=>{re.current&&clearInterval(re.current)},[]);const $i=async()=>{var j;if((j=s==null?void 0:s.profile)!=null&&j.company_id){O(!0),ne(null);try{const A=await M.regenerateReport(s.profile.company_id);ne({ok:!0,text:`Bericht neu erstellt (${A.analyzed} analysierte Reviews)`})}catch(A){ne({ok:!1,text:`Fehler: ${A.message}`})}finally{O(!1)}}},Di=async()=>{var j;if((j=s==null?void 0:s.profile)!=null&&j.company_id){Re(!0);try{const{data:{session:A}}=await(await Ee(async()=>{const{supabaseAdmin:he}=await Promise.resolve().then(()=>Or);return{supabaseAdmin:he}},void 0)).supabaseAdmin.auth.getSession();if(!A)throw new Error("Nicht eingeloggt");const I=He?Math.round(parseFloat(He)*100):null,q=De?Math.round(parseFloat(De)*100):null,se=await fetch(`https://review-scraper-production-9324.up.railway.app/billing/admin-pricing?companyId=${s.profile.company_id}`,{method:"PUT",headers:{Authorization:`Bearer ${A.access_token}`,"Content-Type":"application/json"},body:JSON.stringify({erstanalyse_cents:I,monthly_cents:q})});if(!se.ok)throw new Error((await se.json()).error||"Fehler");ut(!0),setTimeout(()=>ut(!1),2e3)}catch(A){alert("Fehler: "+A.message)}finally{Re(!1)}}},Ui=async j=>{p(A=>({...A,[j]:!0}));try{await M.updatePlatform(j,{profile_url:d[j]}),g(A=>({...A,[j]:!0})),setTimeout(()=>g(A=>({...A,[j]:!1})),2e3),i(A=>({...A,platforms:A.platforms.map(I=>I.id===j?{...I,profile_url:d[j]}:I)}))}catch(A){alert("Fehler: "+A.message)}finally{p(A=>({...A,[j]:!1}))}},Mi=async(j,A)=>{try{await M.updatePlatform(j,{is_active:!A}),i(I=>({...I,platforms:I.platforms.map(q=>q.id===j?{...q,is_active:!A}:q)}))}catch(I){alert("Fehler: "+I.message)}},Wi=async j=>{if(me.company_id){D(!0),te(j);try{const A=Y===j?X:"",I=await M.addPlatform(me.company_id,j,A||null);i(q=>({...q,platforms:[...q.platforms,{...I,reviews_count:0}]})),u(q=>({...q,[I.id]:I.profile_url||""})),te(""),Ce("")}catch(A){alert("Fehler: "+A.message)}finally{D(!1)}}},Ni=async j=>{if(confirm("Plattform wirklich löschen?"))try{await M.deletePlatform(j),i(A=>({...A,platforms:A.platforms.filter(I=>I.id!==j)}))}catch(A){alert("Fehler: "+A.message)}},Fi=async()=>{_(!0);try{await M.updateUser(e,{full_name:v.full_name,email:v.email,company_name:v.company_name}),y(!0),setTimeout(()=>y(!1),2e3),i(j=>({...j,profile:{...j.profile,full_name:v.full_name,email:v.email,companies:{...j.profile.companies,name:v.company_name}}}))}catch(j){alert("Fehler: "+j.message)}finally{_(!1)}};if(o)return t.jsx("p",{style:E.loading,children:"Lade Benutzer..."});if(!s)return t.jsx("p",{style:{color:"#cf222e"},children:"Benutzer nicht gefunden"});const{profile:me,platforms:en,reviews:tn}=s,Hi=en.reduce((j,A)=>j+(A.reviews_count||0),0),Vi=en.filter(j=>j.is_active&&j.profile_url).length;return t.jsxs("div",{children:[t.jsxs("button",{style:E.back,onClick:()=>n(`${r}/users`),children:[t.jsx(Jd,{})," Zurück zu Benutzer"]}),t.jsx("h1",{style:E.h1,children:me.full_name||"Unbenannt"}),t.jsxs("p",{style:{color:"#656d76",fontSize:13,margin:"0 0 24px"},"data-sensitive":!0,children:[me.email||"",me.email?" · ":"","ID: ",me.id]}),t.jsxs("div",{style:E.grid,children:[t.jsxs("div",{style:{...E.card,marginBottom:0},"data-sensitive":!0,children:[t.jsxs("h3",{style:E.cardTitle,children:[t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"#656d76",strokeWidth:"1.5",strokeLinecap:"round",children:[t.jsx("circle",{cx:"8",cy:"5",r:"3"}),t.jsx("path",{d:"M2 15c0-3.31 2.69-6 6-6s6 2.69 6 6"})]}),"Profil bearbeiten"]}),t.jsxs("div",{style:E.row,children:[t.jsx("span",{style:E.label,children:"Name"}),t.jsx("input",{style:{...E.input,flex:1},value:v.full_name,onChange:j=>m(A=>({...A,full_name:j.target.value}))})]}),t.jsxs("div",{style:E.row,children:[t.jsx("span",{style:E.label,children:"E-Mail"}),t.jsx("input",{style:{...E.input,flex:1},value:v.email,onChange:j=>m(A=>({...A,email:j.target.value}))})]}),t.jsxs("div",{style:E.row,children:[t.jsx("span",{style:E.label,children:"Unternehmen"}),t.jsx("input",{style:{...E.input,flex:1},value:v.company_name,onChange:j=>m(A=>({...A,company_name:j.target.value}))})]}),t.jsxs("div",{style:E.row,children:[t.jsx("span",{style:E.label,children:"Branche"}),t.jsx("span",{style:E.value,children:v.industry||"Nicht gesetzt"})]}),t.jsxs("div",{style:E.row,children:[t.jsx("span",{style:E.label,children:"Website"}),t.jsx("span",{style:E.value,children:v.website_url||"Nicht gesetzt"})]}),t.jsxs("div",{style:E.row,children:[t.jsx("span",{style:E.label,children:"Rolle"}),t.jsx("span",{style:E.badge(me.role==="admin"?"#0969da":"#1a7f37"),children:me.role==="admin"?"Admin":"Kunde"})]}),t.jsxs("div",{style:E.row,children:[t.jsx("span",{style:E.label,children:"Onboarding"}),t.jsx("span",{style:E.value,children:me.onboarding_done?"Abgeschlossen":`Schritt ${me.onboarding_step}`})]}),t.jsxs("div",{style:E.row,children:[t.jsx("span",{style:E.label,children:"Erstellt"}),t.jsx("span",{style:E.value,children:new Date(me.created_at).toLocaleStr
93ing("de-DE")})]}),t.jsxs("div",{style:{marginTop:12,display:"flex",alignItems:"center",gap:8},children:[t.jsx("button",{style:{...E.btn,...E.btnPrimary,opacity:w?.5:1},onClick:Fi,disabled:w,children:w?"Speichert...":"Profil speichern"}),b&&t.jsx("span",{style:E.success,children:"Gespeichert"})]})]}),t.jsxs("div",{style:{...E.card,marginBottom:0},children:[t.jsxs("h3",{style:E.cardTitle,children:[t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"#656d76",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[t.jsx("path",{d:"M6 2H3.5A1.5 1.5 0 002 3.5v9A1.5 1.5 0 003.5 14H6"}),t.jsx("path",{d:"M11 11l3-3-3-3"}),t.jsx("path",{d:"M14 8H6"})]}),"Schnellzugriff"]}),t.jsx("p",{style:{color:"#656d76",fontSize:13,margin:"0 0 16px"},children:"Direkt als dieser Kunde einloggen (Magic Link)."}),t.jsxs("button",{style:{...E.btn,...E.btnPrimary,display:"inline-flex",alignItems:"center",gap:6},disabled:!me.email||l,onClick:async()=>{c(!0);try{const{data:{session:j}}=await(await Ee(async()=>{const{supabaseAdmin:q}=await Promise.resolve().then(()=>Or);return{supabaseAdmin:q}},void 0)).supabaseAdmin.auth.getSession(),I=await(await fetch(`https://review-scraper-production-9324.up.railway.app/admin/magic-link/${me.id}`,{method:"POST",headers:{Authorization:`Bearer ${j==null?void 0:j.access_token}`,"Content-Type":"application/json"}})).json();I.url?window.open(I.url,"_blank"):alert(I.error||"Magic Link konnte nicht erstellt werden.")}catch(j){alert("Fehler: "+j.message)}finally{c(!1)}},children:[t.jsx("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"currentColor",children:t.jsx("path",{d:"M8.22 2.97a.75.75 0 0 1 1.06 0l4.25 4.25a.75.75 0 0 1 0 1.06l-4.25 4.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l2.97-2.97H3.75a.75.75 0 0 1 0-1.5h7.44L8.22 4.03a.75.75 0 0 1 0-1.06Z"})}),l?"Wird erstellt...":"Als Kunde einloggen"]}),me.email&&t.jsxs("div",{style:{marginTop:12,padding:12,background:"#f6f8fa",borderRadius:6,border:"1px solid #e5e7eb"},children:[t.jsx("p",{style:{color:"#656d76",fontSize:11,margin:"0 0 4px"},children:"Login-Daten:"}),t.jsxs("div",{style:{fontSize:13,color:"#24292f"},children:[t.jsxs("div",{children:["E-Mail: ",t.jsx("strong",{children:me.email})]}),t.jsx("div",{style:{fontSize:11,color:"#8c959f",marginTop:4},children:"Passwort wurde beim Onboarding per E-Mail versendet."})]})]})]}),me.role!=="admin"&&t.jsxs("div",{style:{...E.card,marginBottom:0,borderColor:"#ffcecb"},children:[t.jsxs("h3",{style:{...E.cardTitle,color:"#cf222e"},children:[t.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"#cf222e",strokeWidth:"1.5",strokeLinecap:"round",children:t.jsx("path",{d:"M2 4h12M5.33 4V2.67a1.33 1.33 0 011.34-1.34h2.66a1.33 1.33 0 011.34 1.34V4m2 0v9.33a1.33 1.33 0 01-1.34 1.34H4.67a1.33 1.33 0 01-1.34-1.34V4"})}),"Benutzer löschen"]}),t.jsx("p",{style:{color:"#656d76",fontSize:13,margin:"0 0 16px"},children:"Löscht den Benutzer und alle zugehörigen Daten (Unternehmen, Plattformen, Reviews, Jobs)."}),t.jsx("button",{style:{...E.btn,...E.btnDanger},onClick:async()=>{if(confirm("Benutzer wirklich löschen? Alle Daten werden unwiderruflich gelöscht."))try{await M.deleteUser(e),n(r+"/users")}catch(j){alert("Fehler: "+j.message)}},children:"Benutzer endgültig löschen"})]})]}),t.jsxs("div",{style:E.card,"data-sensitive":!0,children:[t.jsxs("h3",{style:E.cardTitle,children:[t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"#656d76",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[t.jsx("rect",{x:"1",y:"3",width:"14",height:"10",rx:"1.5"}),t.jsx("path",{d:"M1 6.5h14"}),t.jsx("path",{d:"M4 10h3",strokeWidth:"1.2"})]}),"Abonnement & Zahlung"]}),Ge?t.jsx("p",{style:E.loading,children:"Lade Billing-Daten..."}):!N||!N.customer?t.jsx("p",{style:{color:"#656d76",fontSize:13},children:"Kein Stripe-Kunde gefunden â Benutzer hat noch kein Abo abgeschlossen."}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(3, 1fr)",gap:12,marginBottom:16},children:[t.jsxs("div",{style:{padding:12,background:"#f6f8fa",borderRadius:8,border:"1px solid #e5e7eb"},children:[t.jsx("p",{style:{color:"#656d76",fontSize:11,margin:"0 0 4px"},children:"Stripe-Kunde"}),t.jsx("p",{style:{color:"#1f2328",fontSize:13,fontWeight:600,margin:0},children:N.customer.name||N.customer.email}),t.jsx("p",{style:{color:"#656d76",fontSize:11,margin:"2px 0 0"},children:N.customer.id})]}),N.customer.phone&&t.jsxs("div",{style:{padding:12,background:"#f6f8fa",borderRadius:8,border:"1px solid #e5e7eb"},children:[t.jsx("p",{style:{color:"#656d76",fontSize:11,margin:"0 0 4px"},children:"Telefon"}),t.jsx("p",{style:{color:"#1f2328",fontSize:13,fontWeight:600,margin:0},children:N.customer.phone})]}),N.customer.address&&(N.customer.address.line1||N.customer.address.city)&&t.jsxs("div",{style:{padding:12,background:"#f6f8fa",borderRadius:8,border:"1px solid #e5e7eb"},children:[t.jsx("p",{style:{color:"#656d76",fontSize:11,margin:"0 0 4px"},children:"Rechnungsadresse"}),t.jsxs("p",{style:{color:"#1f2328",fontSize:13,fontWeight:500,margin:0,lineHeight:1.4},children:[[N.customer.address.line1,N.customer.address.line2].filter(
93Boolean).join(", "),t.jsx("br",{}),[N.customer.address.postal_code,N.customer.address.city].filter(Boolean).join(" "),N.customer.address.country?`, ${N.customer.address.country}`:""]})]})]}),N.subscription?t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(4, 1fr)",gap:12,marginBottom:16},children:[t.jsxs("div",{style:{padding:12,background:"#f6f8fa",borderRadius:8,border:"1px solid #e5e7eb"},children:[t.jsx("p",{style:{color:"#656d76",fontSize:11,margin:"0 0 4px"},children:"Plan"}),t.jsx("p",{style:{color:"#1f2328",fontSize:15,fontWeight:600,margin:"0 0 4px"},children:N.subscription.planName}),t.jsx("span",{style:E.badge(N.subscription.status==="active"?"#1a7f37":"#cf222e"),children:N.subscription.status==="active"&&!N.subscription.cancelAtPeriodEnd?"Aktiv":N.subscription.cancelAtPeriodEnd?"Gekündigt":N.subscription.status})]}),t.jsxs("div",{style:{padding:12,background:"#f6f8fa",borderRadius:8,border:"1px solid #e5e7eb"},children:[t.jsx("p",{style:{color:"#656d76",fontSize:11,margin:"0 0 4px"},children:"Betrag"}),t.jsxs("p",{style:{color:"#1f2328",fontSize:15,fontWeight:600,margin:0},children:[N.subscription.amount.toLocaleString("de-DE",{style:"currency",currency:"EUR"}),t.jsxs("span",{style:{fontSize:11,fontWeight:400,color:"#656d76"},children:["/",N.subscription.interval==="year"?"Jahr":"Monat"]})]})]}),t.jsxs("div",{style:{padding:12,background:"#f6f8fa",borderRadius:8,border:"1px solid #e5e7eb"},children:[t.jsx("p",{style:{color:"#656d76",fontSize:11,margin:"0 0 4px"},children:"Nächste Abrechnung"}),t.jsx("p",{style:{color:"#1f2328",fontSize:13,fontWeight:600,margin:0},children:N.subscription.cancelAtPeriodEnd?`Endet ${new Date(N.subscription.currentPeriodEnd).toLocaleDateString("de-DE")}`:new Date(N.subscription.currentPeriodEnd).toLocaleDateString("de-DE",{day:"numeric",month:"long",year:"numeric"})})]}),t.jsxs("div",{style:{padding:12,background:"#f6f8fa",borderRadius:8,border:"1px solid #e5e7eb"},children:[t.jsx("p",{style:{color:"#656d76",fontSize:11,margin:"0 0 4px"},children:"Zahlungsmethode"}),N.subscription.paymentMethod?t.jsxs("p",{style:{color:"#1f2328",fontSize:13,fontWeight:600,margin:0},children:[(Yn=N.subscription.paymentMethod.brand)==null?void 0:Yn.toUpperCase()," ···· ",N.subscription.paymentMethod.last4]}):t.jsx("p",{style:{color:"#656d76",fontSize:13,margin:0},children:"Nicht hinterlegt"})]})]}):t.jsx("p",{style:{color:"#9a6700",fontSize:13,marginBottom:16},children:"Stripe-Kunde vorhanden, aber kein aktives Abo."}),((Xn=N.invoices)==null?void 0:Xn.length)>0&&t.jsxs(t.Fragment,{children:[t.jsx("h4",{style:{fontSize:13,fontWeight:600,color:"#1f2328",margin:"0 0 8px"},children:"Rechnungen"}),t.jsxs("table",{style:E.table,children:[t.jsx("thead",{children:t.jsxs("tr",{children:[t.jsx("th",{style:E.th,children:"Nr."}),t.jsx("th",{style:E.th,children:"Datum"}),t.jsx("th",{style:E.th,children:"Betrag"}),t.jsx("th",{style:E.th,children:"Status"}),t.jsx("th",{style:E.th})]})}),t.jsx("tbody",{children:N.invoices.map(j=>t.jsxs("tr",{children:[t.jsx("td",{style:E.td,children:j.number}),t.jsx("td",{style:E.td,children:j.date}),t.jsx("td",{style:E.td,children:j.amount}),t.jsx("td",{style:E.td,children:t.jsx("span",{style:E.badge(j.status==="Bezahlt"?"#1a7f37":"#cf222e"),children:j.status})}),t.jsx("td",{style:E.td,children:j.pdfUrl&&t.jsx("a",{href:j.pdfUrl,target:"_blank",rel:"noopener noreferrer",style:{color:"#0969da",fontSize:12,textDecoration:"none"},children:"PDF"})})]},j.id))})]})]})]})]}),t.jsxs("div",{style:E.card,"data-sensitive":!0,children:[t.jsxs("h3",{style:E.cardTitle,children:[t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"#656d76",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[t.jsx("circle",{cx:"8",cy:"8",r:"6.5"}),t.jsx("path",{d:"M8 4v8M5.5 6.5c0-.83.9-1.5 2.5-1.5s2.5.67 2.5 1.5S10.1 8 8 8 5.5 8.67 5.5 9.5s.9 1.5 2.5 1.5 2.5-.67 2.5-1.5"})]}),"Preise"]}),oe?t.jsx("p",{style:E.loading,children:"Lade Preise..."}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:16,marginBottom:16},children:[t.jsxs("div",{children:[t.jsx("label",{style:{display:"block",color:"#656d76",fontSize:12,fontWeight:600,marginBottom:6},children:"Erstanalyse-Preis (EUR)"}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[t.jsx("input",{style:{...E.input,width:"100%",maxWidth:160}
93,type:"number",step:"1",min:"0",placeholder:"349",value:He,onChange:j=>nt(j.target.value)}),t.jsx("span",{style:{color:"#656d76",fontSize:13},children:"EUR"})]})]}),t.jsxs("div",{children:[t.jsx("label",{style:{display:"block",color:"#656d76",fontSize:12,fontWeight:600,marginBottom:6},children:"Monitoring-Monatspreis (EUR)"}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[t.jsx("input",{style:{...E.input,width:"100%",maxWidth:160},type:"number",step:"1",min:"0",placeholder:"49",value:De,onChange:j=>st(j.target.value)}),t.jsx("span",{style:{color:"#656d76",fontSize:13},children:"EUR / Monat"})]})]})]}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[t.jsx("button",{style:{...E.btn,...E.btnPrimary,opacity:be?.5:1},onClick:Di,disabled:be,children:be?"Speichert...":"Speichern"}),it&&t.jsxs("span",{style:E.success,children:[t.jsx(Vs,{})," Gespeichert"]})]}),De&&t.jsxs("p",{style:{color:"#656d76",fontSize:11,marginTop:8,margin:"8px 0 0"},children:["Jahrespreis (10% Rabatt): ",(parseFloat(De)*12*.9).toFixed(0)," EUR / Jahr"]})]})]}),t.jsxs("div",{style:E.card,children:[t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:16},children:[t.jsxs("h3",{style:{...E.cardTitle,margin:0},children:[t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"#656d76",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[t.jsx("circle",{cx:"8",cy:"8",r:"6.5"}),t.jsx("path",{d:"M1.5 8h13M8 1.5c-2 2-3 4-3 6.5s1 4.5 3 6.5c2-2 3-4 3-6.5s-1-4.5-3-6.5"})]}),"Plattformen (",Vi," verbunden) · ",Hi," Rezensionen gesamt"]}),me.company_id&&t.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center",flexWrap:"wrap"},children:[t.jsx("button",{style:{...E.btn,...E.btnSuccess,opacity:k?.5:1,display:"inline-flex",alignItems:"center",gap:6},onClick:Bi,disabled:k,children:k?"Scraping läuft...":"Alle Plattformen scrapen"}),t.jsx("button",{style:{...E.btn,...E.btnPrimary,opacity:G?.5:1,display:"inline-flex",alignItems:"center",gap:6},onClick:$i,disabled:G,children:G?"Erstellt...":"Bericht neu erstellen"}),F&&t.jsx("span",{style:{fontSize:12,color:F.ok?"#1a7f37":"#cf222e",fontWeight:500},children:F.text})]})]}),C&&t.jsxs("div",{style:{marginBottom:16},children:[t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:8},children:[t.jsx("span",{style:{color:"#656d76",fontSize:12,fontWeight:600},children:"Scrape-Log"}),!k&&t.jsx("button",{style:{background:"none",border:"none",color:"#656d76",fontSize:11,cursor:"pointer"},onClick:()=>z(!1),children:"SchlieÃen"})]}),t.jsx("div",{ref:H,style:E.logPanel,children:T.length===0?t.jsx("p",{style:{color:"#8b949e",margin:0},children:"Warte auf Logs..."}):T.map((j,A)=>t.jsx("p",{style:E.logLine(j.type),children:j.text},A))})]}),t.jsx("div",{style:{display:"grid",gap:12},children:Object.entries(Dr).map(([j,A])=>{const I=en.find(ye=>ye.platform_name===j),q=!!I,se=!!(I&&I.is_active&&I.profile_url),he=q&&!I.profile_url;return t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:16,padding:"14px 16px",background:se?"#f6f8fa":"#fafafa",borderRadius:10,border:`1px solid ${se?"#e5e7eb":he?"#f5a62388":"#e5e7eb88"}`,opacity:q&&!I.is_active?.6:1},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,flex:"0 0 150px"},children:[t.jsx("div",{style:{width:28,height:28,borderRadius:6,background:"#fff",border:"1px solid #e5e7eb",display:"flex",alignItems:"center",justifyContent:"center"},children:A.icon}),t.jsxs("div",{children:[t.jsx("p",{style:{margin:0,fontSize:13,fontWeight:600,color:se||q?"#1f2328":"#656d76"},children:A.label}),t.jsx("p",{style:{margin:0,fontSize:11,color:he?"#9a6700":"#656d76"},children:se?`${I.reviews_count||0} Rezensionen`:he?"URL fehlt":"Nicht verbunden"})]})]}),t.jsx("div",{style:{flex:1},children:q?t.jsx("input",{style:{...E.input,width:"100%",fontSize:12,borderColor:he?"#f5a623":void 0},value:d[I.id]??"",onChange:ye=>u(le=>({...le,[I.id]:ye.target.value})),placeholder:he?"Profil-URL eingeben (fehlt noch!)...":"Profil-URL eingeben..."}):t.jsx("input",{style:{...E.input,width:"100%",fontSize:12,borderStyle:"dashed"}
93,value:X&&Y===j?X:"",onChange:ye=>{te(j),Ce(ye.target.value)},placeholder:"Profil-URL eingeben zum Verbinden..."})}),q?t.jsxs(t.Fragment,{children:[t.jsx("button",{style:{padding:"4px 12px",borderRadius:20,border:"none",fontSize:11,fontWeight:600,cursor:"pointer",background:I.is_active?"#1a7f3722":"#cf222e22",color:I.is_active?"#1a7f37":"#cf222e"},onClick:()=>Mi(I.id,I.is_active),children:I.is_active?"Aktiv":"Inaktiv"}),t.jsx("button",{style:{...E.saveBtn,opacity:f[I.id]?.5:1,flexShrink:0},onClick:()=>Ui(I.id),disabled:f[I.id],children:x[I.id]?t.jsxs(t.Fragment,{children:[t.jsx(Vs,{})," OK"]}):"Speichern"}),t.jsx("button",{style:{background:"none",border:"none",cursor:"pointer",padding:4,color:"#cf222e",opacity:.6,flexShrink:0},onClick:()=>Ni(I.id),title:"Plattform entfernen",children:t.jsx("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",children:t.jsx("path",{d:"M3 4h10M5.5 4V3a1 1 0 011-1h3a1 1 0 011 1v1M6 7v5M10 7v5M4 4l.8 9a1.5 1.5 0 001.5 1.4h3.4a1.5 1.5 0 001.5-1.4L12 4"})})})]}):t.jsx("button",{style:{...E.btn,...E.btnPrimary,whiteSpace:"nowrap",opacity:ke?.5:1},onClick:()=>{te(j),Wi(j)},disabled:ke,children:ke&&Y===j?"Wird verbunden...":"Verbinden"})]},j)})})]}),((Qn=s.jobs)==null?void 0:Qn.length)>0&&t.jsxs("div",{style:E.card,children:[t.jsxs("h3",{style:E.cardTitle,children:[t.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"#656d76",strokeWidth:"1.5",strokeLinejoin:"round",children:t.jsx("path",{d:"M8.5 1L3 9h4.5l-1 6L12 7H7.5l1-6z"})}),"Letzte Scrape-Jobs"]}),t.jsxs("table",{style:E.table,children:[t.jsx("thead",{children:t.jsxs("tr",{children:[t.jsx("th",{style:E.th,children:"Status"}),t.jsx("th",{style:E.th,children:"Plattform"}),t.jsx("th",{style:E.th,children:"Reviews"}),t.jsx("th",{style:E.th,children:"Datum"})]})}),t.jsx("tbody",{children:s.jobs.map(j=>t.jsxs("tr",{children:[t.jsx("td",{style:E.td,children:t.jsx("span",{style:E.badge(j.status==="completed"?"#1a7f37":j.status==="failed"?"#cf222e":"#9a6700"),children:Hs[j.status]||j.status})}),t.jsx("td",{style:E.td,children:t.jsx(qs,{name:j.platform})}),t.jsxs("td",{style:E.td,children:[j.reviews_found||0," / ",j.reviews_new||0," neu"]}),t.jsx("td",{style:E.td,children:new Date(j.created_at).toLocaleString("de-DE")})]},j.id))})]})]}),me.company_id&&t.jsxs("div",{style:E.card,children:[t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:16},children:[t.jsxs("div",{children:[t.jsxs("h3",{style:{...E.cardTitle,margin:0},children:[t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"#656d76",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[t.jsx("path",{d:"M5.5 3.5a2.5 2.5 0 105 0 2.5 2.5 0 00-5 0z"}),t.jsx("path",{d:"M2 13c0-2.76 2.24-5 5-5h2c2.76 0 5 2.24 5 5"}),t.jsx("path",{d:"M12.5 1.5l1.5 1.5-1.5 1.5"}),t.jsx("path",{d:"M14 3H10"})]}),"Wettbewerber (",Ie.length+ot.length,")"]}),t.jsx("p",{style:{color:"#656d76",fontSize:12,margin:"4px 0 0 24px"},children:"Wettbewerber für die Analyse"})]}),(Ie.length>0||ot.length>0)&&t.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center",flexWrap:"wrap"},children:[t.jsxs("button",{style:{...E.btn,...E.btnSuccess,opacity:ve?.5:1,display:"inline-flex",alignItems:"center",gap:6},onClick:Oi,disabled:ve||Ie.length===0,children:[t.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",children:[t.jsx("path",{d:"M1 8a7 7 0 0 1 13.2-3.2M15 8a7 7 0 0 1-13.2 3.2"}),t.jsx("path",{d:"M14.2 1v3.8H10.4M1.8 15v-3.8h3.8"})]}),ve?"Analyse läuft...":"Alle aktualisieren"]}),t.jsx("button",{style:{...E.btn,...E.btnPrimary,opacity:Et?.5:1,display:"inline-flex",alignItems:"center",gap:6},onClick:Li,disabled:Et||Ie.length===0,children:Et?"Erstellt...":"Bericht neu erstellen"}),kt&&t.jsx("span",{style:{fontSize:12,color:kt.ok?"#1a7f37":"#cf222e",fontWeight:500},children:kt.text})]})]}),jr?t.jsx("p",{style:E.loading,children:"Lade Wettbewerber..."}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{style:{display:"grid",gap:12,marginBottom:16},children:[Ie.length===0&&t.jsx("p",{style:{color:"#656d76",fontSize:13},children:"Noch keine Wettbewerber konfiguriert."}),Ie.map((j,A)=>{const I=j.platform==="trustpilot"?"trustpilot.com":"google.com",q=j.platform==="trustpilot"?{label:"Trustpilot",color:"#00b67a"}:j.platform==="manual"?{label:"Manuell",color:"#656d76"}:{label:"Google",color:"#4285f4"};return t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:16,padding:"14px 16px",background:"#f6f8fa",borderRadius:10,border:"1px solid #e5e7eb"},children:[t.jsx("div",{style:{width:28,height:28,borderRadius:6,background:"#fff",border:"1px solid #e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:t.jsx("img",{src:`https://www.google.com/s2/favicons?domain=${I}&sz=32`,width:"16",height:"16",alt:"",style:{borderRadius:2}})}),t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsx("p",{style:{margin:0,fontSize:13,fontWeight:600,color:"#1f2328"},children:j.name}),j.url&&t.jsx("a",{href:j.url,target:"_blank",rel:"noopener noreferrer",style:{display:"block",margin:"2px 0 0",fontSize:11,color:"#656d76",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",textDecoration:"none"},children:j.url})]}),t.jsx("span",{style:{display:"inline-flex",alignItems:"center",gap:4,padding:"2px 8px",borderRadius:12,fontSize:11,fontWeight:600,background:q.color+"22",color:q.color,flexShrink:0},children:q.label}),j.addedAt&&t.jsx("span",{style:{color:"#656d76",fontSize:11,flexShrink:0},children:new Date(j.addedAt).toLocaleDateString("de-DE")}),t.jsxs("button",{style:{padding:"4px 10px",borderRadius:6,border:"1px solid #d0d7de",background:"#f6f8fa",color:"#1f2328",fontSize:11,fontWeight:600,cursor:"pointer",flexShrink:0,display:"inline-flex",alignItems:"center",gap:4,opacity:Xr[j.name]?.5:1},onClick:()=>zi(j),disabled:Xr[j.name],title:"Neu scrappen",children:[t.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",children:[t.jsx("path",{d:"M1 8a7 7 0 0 1 13.2-3.2M15 8a7 7 0 0 1-13.2 3.2"}),t.jsx("path",{d:"M14.2 1v3.8H10.4M1.8 15v-3.8h3.8"})]}),Xr[j.name]?"Läuft...":"Neu scrappen"]}),t.jsxs("button",{style:{padding:"4px 10px",borderRadius:6,border:"1px solid #ffcecb",background:"#fff",color:"#cf222e",fontSize:11,fontWeight:600,cursor:"pointer",flexShrink:0,display:"inline-flex",alignItems:"center",gap:4},onClick:()=>Pi(j.name),title:"Entfernen",children:[t.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",children:t.jsx("path",{d:"M3 4h10M5.5 4V3a1 1 0 011-1h3a1 1 0 011 1v1M6 7v5M10 7v5M4 4l.8 9a1.5 1.5 0 001.5 1.4h3.4a1.5 1.5 0 001.5-1.4L12 4"})}),"Entfernen"]})]},A)})]}),ot.length>0&&t.jsxs("div",{style:{marginTop:16,marginBottom:16},children:[t.jsxs("p",{style:{color:"#656d76",fontSize:12,fontWeight:600,marginBottom:8,display:"flex",alignItems:"center",gap:6},children:[t.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"#656d76",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[t.jsx("circle",{cx:"8",cy:"8",r:"6"}),t.jsx("path",{d:"M8 5v3l2 1.5"})]}),"Aus der Analyse (",ot.length,")"]}),t.jsx("div",{style:{display:"grid",gap:8},children:ot.map((j,A)=>t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:16,padding:"12px 16px",background:"#f0f7ff",borderRadius:10,border:"1px solid #bfdbfe"},children:[t.jsx("div",{style:{width:28,height:28,borderRadius:6,background:"#fff",border:"1px solid #e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:t.jsx("img",{src:"https://www.google.com/s2/favicons?domain=google.com&sz=32",width:"16",height:"16",alt:"",style:{borderRadius:2}})}),t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsx("p",{style:{margin:0,fontSize:13,fontWeight:600,color:"#1f2328"},children:j.name||j.businessName||"Unbekannt"}),(j.rating!=null||j.reviewCount!=null)&&t.jsxs("p",{style:{margin:"2px 0 0",fontSize:11,color:"#656d76"},children:[j.rating!=null&&`â
${j.rating}`,j.rating!=null&&j.reviewCount!=null&&" · ",j.reviewCount!=null&&`${j.reviewCount} Bewertungen`]})]}),t.jsx("span",{style:{display:"inline-flex",alignItems:"center",gap:4,padding:"2px 8px",borderRadius:12,fontSize:11,fontWeight:600,background:"#0969da22",color:"#0969da",flexShrink:0},children:"Analyse"}),t.jsxs("button",{style:{padding:"4px 10px",borderRadius:6,border:"1px solid #ffcecb",background:"#fff",color:"#cf222e",fontSize:11,fontWeight:600,cursor:"pointer",flexShrink:0,display:"inline-flex",alignItems:"center",gap:4},onClick:async()=>
93{if(confirm(`Wettbewerber "${j.name}" aus der Analyse entfernen?`))try{const I=await M.getHeaders();await fetch(`https://review-scraper-production-9324.up.railway.app/competitors/${s.profile.company_id}/configured/${encodeURIComponent(j.name)}`,{method:"DELETE",headers:I}),St(q=>q.filter(se=>se.name!==j.name))}catch(I){alert("Fehler: "+I.message)}},title:"Aus Analyse entfernen",children:[t.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",children:t.jsx("path",{d:"M3 4h10M5.5 4V3a1 1 0 011-1h3a1 1 0 011 1v1M6 7v5M10 7v5M4 4l.8 9a1.5 1.5 0 001.5 1.4h3.4a1.5 1.5 0 001.5-1.4L12 4"})}),"Entfernen"]})]},`analyzed-${A}`))})]}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"14px 16px",background:"#fafafa",borderRadius:10,border:"1px dashed #e5e7eb"},children:[t.jsx("input",{style:{...E.input,flex:1,minWidth:140},placeholder:"Firmenname oder Google Maps URL...",value:ft,onChange:j=>Zt(j.target.value),onKeyDown:j=>j.key==="Enter"&&Qr()}),t.jsx("input",{style:{...E.input,flex:1,minWidth:140},placeholder:"Profil-URL (optional)...",value:Yt,onChange:j=>Xt(j.target.value),onKeyDown:j=>j.key==="Enter"&&Qr()}),t.jsxs("select",{style:{...E.input,width:140,cursor:"pointer"},value:Qt,onChange:j=>P(j.target.value),children:[t.jsx("option",{value:"google",children:"Google Maps"}),t.jsx("option",{value:"trustpilot",children:"Trustpilot"}),t.jsx("option",{value:"manual",children:"Manuell"})]}),t.jsx("button",{style:{...E.btn,...E.btnPrimary,whiteSpace:"nowrap",opacity:ue?.5:1},onClick:Qr,disabled:ue||!ft.trim(),children:ue?"Wird hinzugefügt...":"Hinzufügen"})]})]})]}),t.jsxs("div",{style:E.card,children:[t.jsxs("h3",{style:E.cardTitle,children:[t.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"#656d76",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:t.jsx("path",{d:"M8 1l2.1 4.3 4.7.7-3.4 3.3.8 4.7L8 11.8 3.8 14l.8-4.7L1.2 6l4.7-.7z"})}),"Letzte Reviews (",tn.length,")"]}),tn.length>0?t.jsxs("table",{style:E.table,children:[t.jsx("thead",{children:t.jsxs("tr",{children:[t.jsx("th",{style:E.th,children:"Plattform"}),t.jsx("th",{style:E.th,children:"Bewertung"}),t.jsx("th",{style:E.th,children:"Autor"}),t.jsx("th",{style:E.th,children:"Text"}),t.jsx("th",{style:E.th,children:"Datum"})]})}),t.jsx("tbody",{children:tn.slice(0,15).map(j=>t.jsxs("tr",{children:[t.jsx("td",{style:E.td,children:t.jsx(qs,{name:j.platform})}),t.jsxs("td",{style:{...E.td,color:j.rating>=4?"#1a7f37":j.rating<=2?"#cf222e":"#9a6700",fontWeight:600},children:[j.rating,"/5"]}),t.jsx("td",{style:E.td,children:j.reviewer_name||"â"}),t.jsx("td",{style:{...E.td,maxWidth:250,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"#656d76"},children:j.review_text||j.title||"â"}),t.jsx("td",{style:{...E.td,color:"#656d76"},children:j.published_at?new Date(j.published_at).toLocaleDateString("de-DE"):"â"})]},j.id))})]}):t.jsx("p",{style:{color:"#656d76",fontSize:13},children:"Keine Reviews"})]})]})}const ce={h1:{fontSize:22,fontWeight:600,margin:"0 0 24px",color:"#1f2328"},card:{background:"#ffffff",border:"1px solid #e5e7eb",borderRadius:12,boxShadow:"0 1px 2px rgba(0,0,0,0.05)",overflow:"hidden"},filters:{display:"flex",gap:8,marginBottom:16},filterBtn:r=>({padding:"6px 14px",borderRadius:20,border:r?"none":"1px solid #e5e7eb",background:r?"#0969da":"transparent",color:r?"#fff":"#656d76",fontSize:12,fontWeight:500,cursor:"pointer"}),table:{width:"100%",borderCollapse:"collapse"},th:{textAlign:"left",padding:"10px 16px",color:"#656d76",fontSize:11,fontWeight:600,textTransform:"uppercase",borderBottom:"1px solid #e5e7eb"},td:{padding:"12px 16px",color:"#1f2328",fontSize:13,borderBottom:"1px solid #f0f0f0"},badge:r=>({display:"inline-block",padding:"2px 8px",borderRadius:12,fontSize:11,fontWeight:600,background:r+"22",color:r}),resolveBtn:{padding:"4px 10px",background:"#1a7f37",border:"none",borderRadius:4,color:"#fff",fontSize:11,cursor:"pointer"},loading:{color:"#656d76",fontSize:14},expandBtn:{background:"none",border:"none",color:"#0969da",cursor:"pointer",fontSize:12}};function Zd(){const[r,e]=h.useState([]),[n,s]=h.useState(!0),[i,o]=h.useState("all"),[a,l]=h.useState(null),c=()=>{s(!0);const u={};i==="unresolved"&&(u.resolved="false"),i==="resolved"&&(u.resolved="true"),M.getErrors(u).then(e).finally(()=>s(!1))};h.useEffect(()=>{c()},[i]);const d=async u=>{await M.resolveError(u),e(f=>f.map(p=>p.id===u?{...p,resolved:!0,resolved_at:new Date().toISOString()}:p))};return t.jsxs("div",{children:[t.jsx("h1",{style:ce.h1,children:"Fehler-Logs"}),t.jsx("div",{style:ce.filters,children:["all","unresolved","resolved"].map(u=>t.jsx("button",{style:ce.filterBtn(i===u),onClick:()=>o(u),children:u==="all"?"Alle":u==="unresolved"?"Offen":"Gelöst"},u))}),n?t.jsx("p",{style:ce.loading,children:"Lade..."}):t.jsx("div",{style:ce.card,children:t.jsxs("table",{style:ce.table,children:[t.jsx("thead",{children:t.jsxs("tr",{children:[t.jsx("th",{style:ce.th,children:"Schwere"}),t.jsx("th",{style:ce.th,children:"Typ"}),t.jsx("th",{style:ce.th,children:"Nachricht"}),t.jsx("th",{style:ce.th,children:"Datum"}),t.jsx("th",{style:ce.th,children:"Status"}),t.jsx("th",{style:ce.th})]})}),t.jsxs("tbody",{children:[r.map(u=>t.jsxs(t.Fragment,{children:[t.jsxs("tr",{children:[t.jsx("td",{style:ce.td,children:t.jsx("span",{style:ce.badge(u.severity==="critical"?"#cf222e":u.severity==="error"?"#9a6700":"#656d76"),children:u.severity})}),t.jsx("td",{style:ce.td,children:u.error_type}),t.jsxs("td",{style:{...ce.td,maxWidth:250,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[u.message,u.stack_trace&&t.jsx("button",{style:ce.expandBtn,onClick:()=>l(a===u.id?null:u.id),children:a===u.id?" weniger":" mehr"})]}),t.jsx("td",{style:{...ce.td,color:"#656d76",whiteSpace:"nowrap"}
93,children:new Date(u.created_at).toLocaleString("de-DE")}),t.jsx("td",{style:ce.td,children:t.jsx("span",{style:ce.badge(u.resolved?"#1a7f37":"#9a6700"),children:u.resolved?"Gelöst":"Offen"})}),t.jsx("td",{style:ce.td,children:!u.resolved&&t.jsx("button",{style:ce.resolveBtn,onClick:()=>d(u.id),children:"Lösen"})})]},u.id),a===u.id&&u.stack_trace&&t.jsx("tr",{children:t.jsx("td",{colSpan:6,style:{...ce.td,background:"#f6f8fa"},children:t.jsx("pre",{style:{color:"#656d76",fontSize:11,whiteSpace:"pre-wrap",margin:0,maxHeight:200,overflow:"auto"},children:u.stack_trace})})},u.id+"-detail")]})),r.length===0&&t.jsx("tr",{children:t.jsx("td",{colSpan:6,style:{...ce.td,color:"#656d76",textAlign:"center"},children:"Keine Fehler"})})]})]})})]})}const _e={h1:{fontSize:22,fontWeight:600,margin:"0 0 24px",color:"#1f2328"},card:{background:"#ffffff",border:"1px solid #e5e7eb",borderRadius:12,boxShadow:"0 1px 2px rgba(0,0,0,0.05)",overflow:"hidden"},table:{width:"100%",borderCollapse:"collapse"},th:{textAlign:"left",padding:"10px 16px",color:"#656d76",fontSize:11,fontWeight:600,textTransform:"uppercase",borderBottom:"1px solid #e5e7eb"},td:{padding:"12px 16px",color:"#1f2328",fontSize:13,borderBottom:"1px solid #f0f0f0"},loading:{color:"#656d76",fontSize:14}};function Yd(){const[r,e]=h.useState([]),[n,s]=h.useState(!0);return h.useEffect(()=>{M.getLogs().then(e).finally(()=>s(!1))},[]),n?t.jsx("p",{style:_e.loading,children:"Lade Logs..."}):t.jsxs("div",{children:[t.jsx("h1",{style:_e.h1,children:"Admin-Aktivitätslog"}),t.jsx("div",{style:_e.card,children:t.jsxs("table",{style:_e.table,children:[t.jsx("thead",{children:t.jsxs("tr",{children:[t.jsx("th",{style:_e.th,children:"Admin"}),t.jsx("th",{style:_e.th,children:"Aktion"}),t.jsx("th",{style:_e.th,children:"Ziel"}),t.jsx("th",{style:_e.th,children:"Details"}),t.jsx("th",{style:_e.th,children:"IP"}),t.jsx("th",{style:_e.th,children:"Datum"})]})}),t.jsxs("tbody",{children:[r.map(i=>{var o,a;return t.jsxs("tr",{children:[t.jsx("td",{style:_e.td,children:((o=i.profiles)==null?void 0:o.full_name)||((a=i.profiles)==null?void 0:a.email)||", "}),t.jsx("td",{style:_e.td,children:t.jsx("code",{style:{color:"#0969da",fontSize:12},children:i.action})}),t.jsx("td",{style:_e.td,children:i.target_type?`${i.target_type}${i.target_id?`: ${i.target_id.slice(0,8)}...`:""}`:", "}),t.jsx("td",{style:{..._e.td,maxWidth:200,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"#656d76"},children:i.details&&Object.keys(i.details).length>0?JSON.stringify(i.details):", "}),t.jsx("td",{style:{..._e.td,color:"#656d76",fontFamily:"monospace",fontSize:11},children:i.ip_address||", "}),t.jsx("td",{style:{..._e.td,color:"#656d76",whiteSpace:"nowrap"},children:new Date(i.created_at).toLocaleString("de-DE")})]},i.id)}),r.length===0&&t.jsx("tr",{children:t.jsx("td",{colSpan:6,style:{..._e.td,color:"#656d76",textAlign:"center"},children:"Keine Logs"})})]})]})})]})}const xe={h1:{fontSize:22,fontWeight:600,margin:"0 0 24px",color:"#1f2328"},card:{background:"#ffffff",border:"1px solid #e5e7eb",borderRadius:12,boxShadow:"0 1px 2px rgba(0,0,0,0.05)",padding:24,marginBottom:24},cardTitle:{fontSize:14,fontWeight:600,color:"#1f2328",margin:"0 0 16px"},row:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 0",borderBottom:"1px solid #f0f0f0"},label:{color:"#656d76",fontSize:13,flex:"0 0 200px"},input:{padding:"6px 10px",background:"#f6f8fa",border:"1px solid #e5e7eb",borderRadius:4,color:"#1f2328",fontSize:13,width:260,boxSizing:"border-box"},saveBtn:{padding:"6px 12px",background:"#1a7f37",border:"none",borderRadius:4,color:"#fff",fontSize:12,fontWeight:600,cursor:"pointer",marginLeft:8},toggleBtn:r=>({padding:"6px 16px",borderRadius:20,border:"none",fontSize:12,fontWeight:600,cursor:"pointer",background:r?"#1a7f37":"#e5e7eb",color:r?"#fff":"#656d76"}),testBtn:{padding:"8px 16px",background:"#0969da",border:"none",borderRadius:6,color:"#fff",fontSize:13,fontWeight:600,cursor:"pointer"},success:{color:"#1a7f37",fontSize:12,marginTop:8},error:{color:"#cf222e",fontSize:12,marginTop:8},loading:{color:"#656d76",fontSize:14}},Ks=[{key:"google",label:"Google"},{key:"trustpilot",label:"Trustpilot"},{key:"tripadvisor",label:"TripAdvisor"},{key:"trusted_shops",label:"Trusted Shops"},{key:"yelp",label:"Yelp"},{key:"provenexpert",label:"ProvenExpert"}],Xd={telegram_bot_token:"Telegram Bot Token",telegram_chat_id:"Telegram Chat ID",telegram_alerts_enabled:"Telegram Alerts aktiv"};function Qd(){const[r,e]=h.useState([]),[n,s]=h.useState(!0),[i,o]=h.useState({}),[a,l]=h.useState({}),[c,d]=h.useState({}),[u,f]=h.useState("");h.useEffect(()=>{M.getSettings().then(b=>{e(b);const y={};b.forEach(k=>{y[k.key]=typeof k.value=="string"?k.value:JSON.stringify(k.value)}),Ks.forEach(k=>{y[`scrape_limit_full_${k.key}`]||(y[`scrape_limit_full_${k.key}`]=""),y[`scrape_limit_incremental_${k.key}`]||(y[`scrape_limit_incremental_${k.key}`]="")}),o(y)}).finally(()=>s(!1))},[]);const p=async b=>{l(y=>({...y,[b]:!0}));try{let y=i[b];y==="true"?y=!0:y==="false"?y=!1:!isNaN(y)&&y!==""&&(y=Number(y)),await M.updateSetting(b,y),d(k=>({...k,[b]:!0})),setTimeout(()=>d(k=>({...k,[b]:!1})),2e3),e(k=>k.find(T=>T.key===b)?k.map(T=>T.key===b?{...T,value:y}:T):[...k,{key:b,value:y}])}catch(y){alert("Fehler: "+y.message)}finally{l(y=>({...y,[b]:!1}))}},x=async b=>{const y=r.find(S=>S.key===b),k=!(y!=null&&y.value);o(S=>({...S,[b]:String(k)})),l(S=>({...S,[b]:!0}));try{await M.updateSetting(b,k),e(S=>S.map(T=>T.key===b?{...T,value:k}:T))}finally{l(S=>({...S,[b]:!1}))}},g=async()=>{f("testing");try{const b=await M.testTelegram();f(b.success?"success":"error")}catch{f("error")}},v=()=>t.jsx("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:t.jsx("path",{d:"M3.5 8.5l3 3 6-7"})});if(n)return t.jsx("p",{style:xe.loading,children:"Lade Einstellungen..."});const m=r.filter(b=>b.key.startsWith("telegram_")),w={google:1500,trustpilot:1500,tripadvisor:1500,trusted_shops:1500,yelp:1500,provenexpert:1500},_={google:50,trustpilot:50,tripadvisor:50,trusted_shops:30,yelp:50,provenexpert:20};return t.jsxs("div",{children:[t.jsx("h1",{style:xe.h1,children:"Einstellungen"}),t.jsxs("div",{style:xe.card,children:[t.jsx("h3",{style:xe.cardTitle,children:"Scraping-Limits pro Plattform"}),t.jsx("div",{style:{fontSize:12,color:"#8c959f",marginBottom:16},children:"Full Crawl = Erster Abruf aller Reviews. Inkrementell = RegelmäÃiger Sync neuer Reviews."}),t.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:13},children:[t.jsx("thead",{children:t.jsxs("tr",{style:{borderBottom:"2px s
93olid #e5e7eb",textAlign:"left"},children:[t.jsx("th",{style:{padding:"8px 0",color:"#656d76",fontWeight:600},children:"Plattform"}),t.jsx("th",{style:{padding:"8px 0",color:"#656d76",fontWeight:600},children:"Full Crawl"}),t.jsx("th",{style:{padding:"8px 0",color:"#656d76",fontWeight:600},children:"Inkrementell"})]})}),t.jsx("tbody",{children:Ks.map(b=>{const y=`scrape_limit_full_${b.key}`,k=`scrape_limit_incremental_${b.key}`;return t.jsxs("tr",{style:{borderBottom:"1px solid #f0f0f0"},children:[t.jsx("td",{style:{padding:"10px 0",fontWeight:500,color:"#1f2328"},children:b.label}),t.jsx("td",{style:{padding:"10px 0"},children:t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[t.jsx("input",{style:{...xe.input,width:90},type:"number",min:"10",max:"10000",placeholder:String(w[b.key]),value:i[y]??"",onChange:S=>o(T=>({...T,[y]:S.target.value}))}),t.jsx("button",{style:{...xe.saveBtn,opacity:a[y]?.5:1,marginLeft:0},onClick:()=>p(y),disabled:a[y],children:c[y]?t.jsx(v,{}):"Speichern"})]})}),t.jsx("td",{style:{padding:"10px 0"},children:t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[t.jsx("input",{style:{...xe.input,width:90},type:"number",min:"5",max:"1000",placeholder:String(_[b.key]),value:i[k]??"",onChange:S=>o(T=>({...T,[k]:S.target.value}))}),t.jsx("button",{style:{...xe.saveBtn,opacity:a[k]?.5:1,marginLeft:0},onClick:()=>p(k),disabled:a[k],children:c[k]?t.jsx(v,{}):"Speichern"})]})})]},b.key)})})]})]}),t.jsxs("div",{style:xe.card,children:[t.jsx("h3",{style:xe.cardTitle,children:"Telegram-Integration"}),m.map(b=>t.jsxs("div",{style:xe.row,children:[t.jsx("span",{style:xe.label,children:Xd[b.key]||b.key}),b.key==="telegram_alerts_enabled"?t.jsx("button",{style:xe.toggleBtn(b.value===!0),onClick:()=>x(b.key),disabled:a[b.key],children:b.value?"Aktiv":"Inaktiv"}):t.jsxs("div",{style:{display:"flex",alignItems:"center"},children:[t.jsx("input",{style:xe.input,type:b.key==="telegram_bot_token"?"password":"text",value:i[b.key]??"",onChange:y=>o(k=>({...k,[b.key]:y.target.value})),placeholder:b.key==="telegram_bot_token"?"Bot-Token eingeben...":"Chat-ID eingeben..."}),t.jsx("button",{style:{...xe.saveBtn,opacity:a[b.key]?.5:1},onClick:()=>p(b.key),disabled:a[b.key],children:c[b.key]?t.jsx(v,{}):"Speichern"})]})]},b.key)),t.jsxs("div",{style:{marginTop:20},children:[t.jsx("button",{style:{...xe.testBtn,opacity:u==="testing"?.5:1},onClick:g,disabled:u==="testing",children:u==="testing"?"Teste...":"Telegram-Verbindung testen"}),u==="success"&&t.jsx("p",{style:xe.success,children:"Testnachricht erfolgreich gesendet!"}),u==="error"&&t.jsx("p",{style:xe.error,children:"Fehler. Prüfe Bot-Token und Chat-ID."})]})]})]})}const $={h1:{fontSize:22,fontWeight:600,margin:"0 0 24px",color:"#1f2328"},h2:{fontSize:16,fontWeight:600,margin:"0 0 12px",color:"#1f2328"},card:{background:"#ffffff",border:"1px solid #e5e7eb",borderRadius:12,boxShadow:"0 1px 2px rgba(0,0,0,0.05)",overflowX:"auto",marginBottom:24},table:{width:"100%",minWidth:1100,borderCollapse:"collapse",tableLayout:"auto"},th:{textAlign:"left",padding:"10px 12px",color:"#656d76",fontSize:11,fontWeight:600,textTransform:"uppercase",borderBottom:"1px solid #e5e7eb",whiteSpace:"nowrap"},td:{padding:"10px 12px",color:"#1f2328",fontSize:13,borderBottom:"1px solid #f0f0f0"},badge:r=>({display:"inline-block",padding:"2px 8px",borderRadius:12,fontSize:11,fontWeight:600,background:r+"22",color:r}),loading:{color:"#656d76",fontSize:14},sectionLabel:{fontSize:12,color:"#656d76",marginBottom:8}},Ai={google:{logo:"https://www.google.com/s2/favicons?domain=google.com&sz=64",name:"Google"},trustpilot:{logo:"https://www.google.com/s2/favicons?domain=trustpilot.com&sz=64",name:"Trustpilot"},tripadvisor:{logo:"https://www.google.com/s2/favicons?domain=tripadvisor.com&sz=64",name:"Tripadvisor"},trusted_shops:{logo:"https://www.google.com/s2/favicons?domain=trustedshops.de&sz=64",name:"Trusted Shops"},provenexpert:{logo:"https://www.google.com/s2/favicons?domain=provenexpert.com&sz=64",name:"ProvenExpert"}
93,yelp:{logo:"https://www.google.com/s2/favicons?domain=yelp.com&sz=64",name:"Yelp"}};function eu(r){const e=r.reviews_found||0;if(!e)return null;const n=r.platform;return n==="trustpilot"?Math.ceil(e/20)*.006:n==="tripadvisor"?Math.ceil(e/10)*.006:n==="trusted_shops"?Math.ceil(e/20)*.006:n==="google"||n==="yelp"?e*.003:n==="provenexpert"?Math.ceil(e/10)*(150*(49/15e4)):null}function tu(r){if(r.status==="failed")return{label:"Fehlgeschlagen",color:"#cf222e"};const e=r.reviews_total||0,n=r.reviews_analyzed||0,s=r.has_report,i=r.reviews_found||0;if(r.status==="completed"&&s)return{label:"Abgeschlossen",color:"#1a7f37"};if(r.status==="completed"&&e>0&&n>=e&&!s){const o=r.completed_at?new Date(r.completed_at).getTime():0;return(Date.now()-o)/6e4>10?{label:"Report ausstehend",color:"#9a6700"}:{label:"Report wird erstellt...",color:"#8250df"}}return r.status==="completed"&&e>0&&n<e?{label:`Analyse ${Math.round(n/e*100)}%`,color:"#0969da"}:r.status==="completed"?{label:"Fertig",color:"#1a7f37"}:i===0?{label:"Scraping...",color:"#9a6700"}:{label:`Scraping (${i})...`,color:"#9a6700"}}function Js({jobs:r,showUser:e=!1}){return r.length===0?t.jsx("div",{style:$.card,children:t.jsx("div",{style:{padding:24,textAlign:"center",color:"#656d76",fontSize:13},children:"Keine Jobs"})}):t.jsx("div",{style:$.card,children:t.jsxs("table",{style:$.table,children:[t.jsx("thead",{children:t.jsxs("tr",{children:[t.jsx("th",{style:$.th,children:"Status"}),e&&t.jsx("th",{style:$.th,children:"Benutzer"}),t.jsx("th",{style:$.th,children:"Unternehmen"}),t.jsx("th",{style:$.th,children:"Plattform"}),t.jsx("th",{style:$.th,children:"Gefunden"}),t.jsx("th",{style:$.th,children:"Neu"}),t.jsx("th",{style:$.th,children:"Kosten"}),t.jsx("th",{style:$.th,children:"Fortschritt"}),t.jsx("th",{style:$.th,children:"Fehler"}),t.jsx("th",{style:$.th,children:"Datum"})]})}),t.jsx("tbody",{children:r.map(n=>{var d,u;const s=Ai[n.platform]||{logo:null,name:n.platform},i=((d=n.companies)==null?void 0:d.name)||"",o=n.profile_url||null,a=tu(n),l=n.status==="running"||n.status==="pending",c=t.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:6},children:[s.logo&&t.jsx("img",{src:s.logo,alt:s.name,style:{width:16,height:16,borderRadius:3,flexShrink:0}}),t.jsx("span",{style:{fontSize:13},children:s.name})]});return t.jsxs("tr",{children:[t.jsx("td",{style:$.td,children:t.jsx("span",{style:$.badge(n.status==="completed"?"#1a7f37":n.status==="failed"?"#cf222e":"#9a6700"),children:n.status==="completed"?"Fertig":n.status==="failed"?"Fehler":"Läuft"})}),e&&t.jsx("td",{style:{...$.td,color:"#656d76",fontSize:12},children:n.user_name||", "}),t.jsx("td",{style:$.td,children:i||((u=n.company_id)==null?void 0:u.slice(0,8))+"..."}),t.jsx("td",{style:$.td,children:o?t.jsx("a",{href:o,target:"_blank",rel:"noopener noreferrer",style:{textDecoration:"none",color:"#1f2328"},children:c}):c}),t.jsx("td",{style:$.td,children:l&&!n.reviews_found?"":n.reviews_found??""}),t.jsx("td",{style:$.td,children:l&&!n.reviews_new?"":n.reviews_new??""}),t.jsx("td",{style:{...$.td,color:"#656d76",fontSize:12},children:(()=>{const f=eu(n);return f!=null?`~$${f.toFixed(2)}`:""})()}),t.jsx("td",{style:$.td,children:t.jsx("span",{style:{fontSize:12,fontWeight:500,color:a.color},children:a.label})}),t.jsx("td",{style:{...$.td,color:"#cf222e",maxWidth:280,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:n.error_message||"",children:n.error_message||""}),t.jsx("td",{style:{...$.td,color:"#656d76",whiteSpace:"nowrap"},children:n.started_at?new Date(n.started_at).toLocaleString("de-DE"):""})]},n.id)})})]})})}function ru(){const[r,e]=h.useState([]),[n,s]=h.useState(!0);h.useEffect(()=>{const g=()=>M.getJobs().then(e).catch(()=>{});g().finally(()=>s(!1));const v=setInterval(g,1e4);return()=>clearInterval(v)},[]);const[i,o]=h.useState([]),[a,l]=h.useState([]);if(h.useEffect(()=>{const g=()=>{var m;return(m=M.getSettings)==null?void 0:m.call(M).then(w=>{const _=(w||[]).filter(y=>{var k;return((k=y.key)==null?void 0:k.startsWith("competitors:"))&&!y.key.includes("ai_query")&&!y.key.includes("suggestions")&&!y.key.includes("search")&&!y.key.includes("status")&&!y.key.includes("selected")&&!y.key.includes("email_sent")}).map(y=>{var C,z;const k=y.key.replace("competitors:",""),S=typeof y.value=="string"?JSON.parse(y.value):y.value,T=(S==null?void 0:S.competitors)||
93((C=S==null?void 0:S.results)==null?void 0:C.competitors)||[],V=(S==null?void 0:S.analyzedAt)||((z=S==null?void 0:S.results)==null?void 0:z.analyzedAt)||null;return{companyId:k,competitors:T,analyzedAt:V,raw:S}}).filter(y=>y.competitors.length>0);o(_);const b=(w||[]).filter(y=>{var k;return(k=y.key)==null?void 0:k.startsWith("competitors:status:")}).map(y=>{const k=y.key.replace("competitors:status:",""),S=typeof y.value=="string"?JSON.parse(y.value):y.value;return{companyId:k,...S}});l(b)}).catch(()=>{})};g();const v=setInterval(g,1e4);return()=>clearInterval(v)},[]),n)return t.jsx("p",{style:$.loading,children:"Lade Jobs..."});const c={},d=[...r].sort((g,v)=>new Date(g.started_at)-new Date(v.started_at));for(const g of d){const v=`${g.company_id}:${g.platform}`;c[v]||(c[v]=0),c[v]++}const u={},f=[],p=[],x=[...r].sort((g,v)=>new Date(v.started_at)-new Date(g.started_at));for(const g of x){const v=`${g.company_id}:${g.platform}`;u[v]||(u[v]=0),u[v]++,(g.job_type?g.job_type==="initial":u[v]===c[v])?f.push(g):p.push(g)}return t.jsxs("div",{children:[t.jsxs("h1",{style:$.h1,children:["Jobs (",r.length,")"]}),t.jsxs("h2",{style:$.h2,children:["Erstanalyse (",f.length,")"]}),t.jsx("p",{style:$.sectionLabel,children:"Erster Scrape nach Plattform-Verbindung"}),t.jsx(Js,{jobs:f,showUser:!0}),t.jsxs("h2",{style:{...$.h2,marginTop:32},children:["Wettbewerbsvergleiche (",i.length,")"]}),t.jsx("p",{style:$.sectionLabel,children:"Analysierte Wettbewerber pro Unternehmen"}),a.filter(g=>g.status==="scraping"||g.status==="analyzing").length>0&&t.jsx("div",{style:{...$.card,borderColor:"#d97706",marginBottom:12},children:a.filter(g=>g.status==="scraping"||g.status==="analyzing").map(g=>{var b,y;const v=((y=(b=r.find(k=>k.company_id===g.companyId))==null?void 0:b.companies)==null?void 0:y.name)||g.companyId.slice(0,8)+"...",m=(g.competitors||[]).length,w=g.currentCompetitor&&m>0?Math.max(0,g.competitors.indexOf(g.currentCompetitor)):0,_=g.status==="analyzing"?90:m>0?Math.round((w+.5)/m*80):0;return t.jsxs("div",{style:{padding:"14px 18px",borderBottom:"1px solid #f0f0f0"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,marginBottom:8},children:[t.jsx("span",{style:$.badge("#d97706"),children:g.status==="analyzing"?"Analysiert...":"Scraping..."}),t.jsx("span",{style:{fontSize:13,fontWeight:600},children:v}),t.jsx("span",{style:{fontSize:12,color:"#656d76"},children:g.status==="scraping"&&g.currentCompetitor?`${g.currentCompetitor} (${w+1}/${m})`:(g.competitors||[]).join(", ")}),t.jsxs("span",{style:{fontSize:12,fontWeight:600,color:"#d97706",marginLeft:"auto"},children:[_,"%"]}),g.startedAt&&t.jsx("span",{style:{fontSize:11,color:"#9ca3af"},children:new Date(g.startedAt).toLocaleTimeString("de-DE")})]}),t.jsx("div",{style:{height:4,backgroundColor:"#f3f4f6",borderRadius:2,overflow:"hidden"},children:t.jsx("div",{style:{height:"100%",width:`${_}%`,backgroundColor:"#d97706",borderRadius:2,transition:"width 0.5s ease"}})})]},g.companyId)})}),i.length===0&&a.filter(g=>g.status==="scraping"||g.status==="analyzing").length===0?t.jsx("div",{style:$.card,children:t.jsx("div",{style:{padding:24,textAlign:"center",color:"#656d76",fontSize:13},children:"Keine Wettbewerbsanalysen"})}):t.jsx("div",{style:$.card,children:t.jsxs("table",{style:$.table,children:[t.jsx("thead",{children:t.jsxs("tr",{children:[t.jsx("th",{style:$.th,children:"Unternehmen"}),t.jsx("th",{style:$.th,children:"Wettbewerber"}),t.jsx("th",{style:$.th,children:"Plattform"}),t.jsx("th",{style:$.th,children:"Rating"}),t.jsx("th",{style:$.th,children:"Reviews"}),t.jsx("th",{style:$.th,children:"Antwort-Rate"}),t.jsx("th",{style:$.th,children:"Link"}),t.jsx("th",{style:$.th,children:"Analysiert / Kosten"})]})}),t.jsx("tbody",{children:[...i].sort((g,v)=>new Date(v.analyzedAt||0)-new Date(g.analyzedAt||0)).flatMap(g=>{var m,w;const v=((w=(m=r.find(_=>_.company_id===g.companyId))==null?void 0:m.companies)==null?void 0:w.name)||g.companyId.slice(0,8)+"...";return g.competitors.map((_,b)=>{var V,C,z,H;const y=_.source||((V=_.sources)!=null&&V.includes("Trustpilot")?"trustpilot":null)||((C=_.sources)!=null&&C.includes("Trusted Shops")?"trusted_shops":null)||((z=_.sources)!=null&&z.includes("ProvenExpert")?"provenexpert":null)||((H=_.sources)!=null&&H.includes("Yelp")?"yelp":null)||(_.trustpilotUrl?"trustpilot":_.trustedShopsUrl?"trusted_shops":"google"),k=Ai[y]||{logo:null,name:y},S=_.trustpilotUrl||_.trustedShopsUrl||_.mapsUrl||_.sourceUrl||_.website||"",T=_.responseRate!=null?`${Math.round(_.responseRate)}%`:_.replyRate!=null?`${Math.round(_.replyRate)}%`:", ";return t.jsxs("tr",{children:[b===0?t.jsx("td",{style:{...$.td,fontWeight:600},rowSpan:g.competitors.length,children:v}):null,t.jsx("td",{style:$.td,children:_.name||", "}),t.jsx("td",{style:$.td,children:t.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:6},children:[k.logo&&t.jsx("img",{src:k.logo,alt:k.name,style:{width:16,height:16,borderRadius:3}}),k.name]})}),t.jsx("td",{style:$.td,children:_.rating!=null?Number(_.rating).toFixed(1):", "}),t.jsx("td",{style:$.td,children:_.reviewsCount!=null?_.reviewsCount.toLocaleStr
93ing("de-DE"):", "}),t.jsx("td",{style:$.td,children:T}),t.jsx("td",{style:$.td,children:S?t.jsx("a",{href:S,target:"_blank",rel:"noopener noreferrer",style:{color:"#0969da",fontSize:12},children:"â Ãffnen"}):", "}),b===0?(()=>{const G=g.competitors.reduce((ne,re)=>{var D,Y;const J=re.reviewsScraped||re.reviewsCount||0,ke=re.source||((D=re.sources)!=null&&D.includes("Trustpilot")?"trustpilot":null)||((Y=re.sources)!=null&&Y.includes("Trusted Shops")?"trusted_shops":null)||(re.trustpilotUrl?"trustpilot":re.trustedShopsUrl?"trusted_shops":"google");return ke==="trustpilot"||ke==="trusted_shops"?ne+Math.ceil(Math.min(J,50)/20)*.006:ke==="google"?ne+Math.min(J,50)*.003:ne},0),O=g.competitors.length*.01,F=G+O;return t.jsxs("td",{style:{...$.td,color:"#656d76",fontSize:12},rowSpan:g.competitors.length,children:[t.jsx("div",{children:g.analyzedAt?new Date(g.analyzedAt).toLocaleString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit"}):", "}),t.jsxs("div",{style:{marginTop:4,fontWeight:600,color:"#1f2328"},children:["~$",F.toFixed(2)]})]})})():null]},`${g.companyId}-${b}`)})})})]})}),t.jsxs("h2",{style:{...$.h2,marginTop:32},children:["Wiederkehrend (",p.length,")"]}),t.jsx("p",{style:$.sectionLabel,children:"Automatische Re-Scrapes durch den Scheduler"}),t.jsx(Js,{jobs:p})]})}const Qe='-apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif',U={h1:{fontSize:22,fontWeight:600,margin:"0 0 24px",color:"#1f2328"},card:{background:"#fff",border:"1px solid #e5e7eb",borderRadius:12,boxShadow:"0 1px 2px rgba(0,0,0,0.05)",padding:24},label:{display:"block",fontSize:12,fontWeight:600,color:"#24292f",marginBottom:6},input:{width:"100%",padding:"8px 12px",border:"1px solid #d0d7de",borderRadius:8,fontSize:13,fontFamily:Qe,outline:"none",boxSizing:"border-box"},hint:{fontSize:11,color:"#8c959f",marginTop:4},btn:{padding:"10px 24px",borderRadius:8,border:"none",fontSize:14,fontWeight:600,cursor:"pointer",fontFamily:Qe}},wn=({size:r=14,color:e="#16a34a"})=>t.jsx("svg",{width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:e,strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:t.jsx("polyline",{points:"20 6 9 17 4 12"})}),Vr=({size:r=14,color:e="#9ca3af"})=>t.jsxs("svg",{width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:e,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[t.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),t.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]}),nu=({size:r=14,color:e="currentColor"})=>t.jsxs("svg",{width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:e,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[t.jsx("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}),t.jsx("polyline",{points:"15 3 21 3 21 9"}),t.jsx("line",{x1:"10",y1:"14",x2:"21",y2:"3"})]}),su=({size:r=14,color:e="currentColor"})=>t.jsxs("svg",{width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:e,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[t.jsx("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),t.jsx("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]}),Ri=({size:r=14,color:e="currentColor"})=>t.jsx("svg",{width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:e,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:t.jsx("path",{d:"M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z"})}),Ti={1:"Analyse gestartet",2:"Erste Erkenntnisse",3:"Analyse fertig + Login"};function Mt(r){return r?new Date(r).toLocaleDateString("de-DE",{day:"2-digit",month:"short",year:"2-digit"}):", "}function iu(){const[r,e]=h.useState([]),[n,s]=h.useState(!0),[i,o]=h.useState(""),[a,l]=h.useState(null),[c,d]=h.useState("");h.useEffect(()=>{let f=!1;return M.getOnboarding().then(p=>{f||e(p.customers||[])}).catch(p=>{f||d(p.message)}).finally(()=>{f||s(!1)}),()=>{f=!0}},[]);const u=()=>{const f=r.find(p=>p.id===i);f&&l(f)};return t.jsxs("div",{style:{...U.card,marginBottom:16,maxWidth:640,background:"#f8fafc"},children:[t.jsx("div",{style:{fontSize:13,fontWeight:600,color:"#24292f",marginBottom:10},children:"Bestehenden Kunden bearbeiten"}),t.jsxs("div",{style:{display:"flex",gap:10,alignItems:"center"},children:[t.jsxs("select",{value:i,onChange:f=>o(f.target.value),disabled:n||!!c,style:{...U.input,flex:1,cursor:n?"wait":"pointer"},children:[t.jsx("option",{value:"",children:n?"Wird geladenâ¦":c?`Fehler: ${c}`:"Kunde auswählenâ¦"}),r.map(f=>t.jsxs("option",{value:f.id,children:[f.name||", ",f.owner_email?` · ${f.owner_email}`:""]},f.id))]}),t.jsxs("button",{onClick:u,disabled:!i,style:{...U.btn,padding:"8px 16px",background:i?"#0969da":"#9ca3af",color:"#fff",fontSize:13,display:"inline-flex",alignItems:"center",gap:6},children:[t.jsx(Ri,{size:13,color:"#fff"})," Profil öffnen"]})]}),t.jsx("p",{style:{...U.hint,marginTop:8},children:"Preise, Branche, Name und Notizen lassen sich pro Kunde bearbeiten, die Ãnderungen landen im Kundenprofil, ohne dass ein neuer Account angelegt wird."}),a&&t.jsx(Ii,{customer:a,onClose:()=>
93l(null),onSaved:({name:f})=>{f&&e(p=>p.map(x=>x.id===a.id?{...x,name:f}:x))}})]})}function Ii({customer:r,onClose:e,onSaved:n}){const[s,i]=h.useState(!0),[o,a]=h.useState(r.name||""),[l,c]=h.useState(""),[d,u]=h.useState(""),[f,p]=h.useState(""),[x,g]=h.useState(""),[v,m]=h.useState(!1),[w,_]=h.useState("");h.useEffect(()=>{let y=!1;return M.getOnboardingProfile(r.id).then(k=>{var S,T,V,C;y||(a(((S=k.company)==null?void 0:S.name)||""),c(((T=k.company)==null?void 0:T.industry)||""),u(((V=k.pricing)==null?void 0:V.monthly_cents)!=null?(k.pricing.monthly_cents/100).toString():""),p(((C=k.pricing)==null?void 0:C.erstanalyse_cents)!=null?(k.pricing.erstanalyse_cents/100).toString():""),g(k.notes||""))}).catch(k=>{y||_(k.message)}).finally(()=>{y||i(!1)}),()=>{y=!0}},[r.id]);const b=async()=>{m(!0),_("");try{await M.saveOnboardingProfile(r.id,{name:o.trim(),industry:l.trim(),monthlyPrice:d.trim(),erstanalysePrice:f.trim(),notes:x}),n({name:o.trim()}),e()}catch(y){_(y.message),m(!1)}};return t.jsx("div",{style:{position:"fixed",inset:0,background:"rgba(15, 23, 42, 0.55)",zIndex:1e3,display:"flex",alignItems:"center",justifyContent:"center",padding:16},children:t.jsxs("div",{style:{background:"#fff",borderRadius:14,boxShadow:"0 20px 60px rgba(0,0,0,0.25)",width:"100%",maxWidth:560,display:"flex",flexDirection:"column",overflow:"hidden"},children:[t.jsxs("div",{style:{padding:"18px 24px",borderBottom:"1px solid #e5e7eb",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:11,fontWeight:600,color:"#8c959f",textTransform:"uppercase",letterSpacing:.6},children:"Kunden-Profil"}),t.jsx("div",{style:{fontSize:16,fontWeight:700,color:"#24292f",marginTop:2},children:r.name||", "}),r.owner_email&&t.jsx("div",{style:{fontSize:12,color:"#656d76",marginTop:2},children:r.owner_email})]}),t.jsx("button",{onClick:e,style:{border:"none",background:"transparent",cursor:"pointer",padding:6,color:"#656d76"},title:"SchlieÃen",children:t.jsx(Vr,{size:18,color:"#656d76"})})]}),t.jsx("div",{style:{padding:20,display:"flex",flexDirection:"column",gap:14},children:s?t.jsx("div",{style:{color:"#8c959f",fontSize:13},children:"Profil wird geladenâ¦"}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{children:[t.jsx("label",{style:U.label,children:"Firmenname"}),t.jsx("input",{style:U.input,value:o,onChange:y=>a(y.target.value)})]}),t.jsxs("div",{children:[t.jsx("label",{style:U.label,children:"Branche"}),t.jsx("input",{style:U.input,value:l,onChange:y=>c(y.target.value),placeholder:"z.B. Zahnarztpraxis"})]}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12},children:[t.jsxs("div",{children:[t.jsx("label",{style:U.label,children:"Erstanalyse (EUR)"}),t.jsx("input",{style:U.input,type:"number",min:"0",step:"1",value:f,onChange:y=>p(y.target.value),placeholder:"z.B. 349"})]}),t.jsxs("div",{children:[t.jsx("label",{style:U.label,children:"Monatlich (EUR)"}),t.jsx("input",{style:U.input,type:"number",min:"0",step:"1",value:d,onChange:y=>u(y.target.value),placeholder:"z.B. 99"})]})]}),t.jsxs("div",{children:[t.jsx("label",{style:U.label,children:"Interne Notizen"}),t.jsx("textarea",{value:x,onChange:y=>g(y.target.value),style:{...U.input,minHeight:90,resize:"vertical",fontFamily:Qe,fontSize:13,lineHeight:1.5},placeholder:"Gesprächsnotizen, Besonderheitenâ¦"})]})]})}),t.jsxs("div",{style:{padding:"14px 24px",borderTop:"1px solid #e5e7eb",display:"flex",alignItems:"center",gap:12},children:[w&&t.jsx("span",{style:{color:"#dc2626",fontSize:12},children:w}),t.jsxs("div",{style:{marginLeft:"auto",display:"flex",gap:8},children:[t.jsx("button",{onClick:e,style:{...U.btn,padding:"8px 14px",background:"#fff",border:"1px solid #d0d7de",color:"#24292f",fontSize:13},children:"Abbrechen"}),t.jsx("button",{onClick:b,disabled:v||s,style:{...U.btn,padding:"8px 14px",background:v||s?"#9ca3af":"#0969da",color:"#fff",fontSize:13},children:v?"Speichereâ¦":"Speichern"})]})]})]})})}function ou({initialHtml:r,onChange:e}){const n=h.useRef(null),s=(a,l)=>{var c,d;(c=n.current)==null||c.focus(),document.execCommand(a,!1,l),e(((d=n.current)==null?void 0:d.innerHTML)||"")},i=()=>{const a=prompt("Link-URL eingeben:");a&&s("createLink",a)},o={padding:"4px 10px",borderRadius:6,border:"1px solid #d0d7de",background:"#fff",fontSize:12,fontWeight:500,color:"#24292f",cursor:"pointer",fontFamily:Qe};return t.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",minHeight:0},children:[t.jsxs("div",{style:{display:"flex",gap:6,marginBottom:6,flexWrap:"wrap"},children:[t.jsx("button",{type:"button",onClick:()=>s("bold"),style:{...o,fontWeight:700},title:"Fett (âB)",children:"B"}),t.jsx("button",{type:"button",onClick:()=>s("italic"),style:{...o,fontStyle:"italic"},title:"Kursiv (âI)",children:"I"}),t.jsx("button",{type:"button",onClick:()=>s("underline"),style:{...o,textDecoration:"underline"},title:"Unterstrichen",children:"U"}),t.jsx("button",{type:"button",onClick:i,style:o,title:"Link einfügen",children:"Link"}),t.jsx("button",{type:"button",onClick:()=>s("insertUnorderedList"),style:o,title:"Aufzählung",children:"⢠Liste"}),t.jsx("button",{type:"button",onClick:()=>s("removeFormat"),style:o,title:"Formatierung entfernen",children:"Format leeren"})]}),t.jsx("div",{ref:n,contentEditable:!0,suppressContentEditableWarning:!0,dangerouslySetInnerHTML:{__html:r},onInput:a=>e(a.currentTarget.innerHTML),style:{flex:1,minHeight:320,padding:"14px 16px",border:"1px solid #d0d7de",borderRadius:8,background:"#fff",fontSize:13,lineHeight:1.6,fontFamily:Qe,color:"#24292f",outline:"none",overflow:"auto"}}
93),t.jsx("div",{style:{fontSize:10,color:"#8c959f",marginTop:4},children:"Hinweis: Tastatur-Kürzel wie âB (fett), âI (kursiv) funktionieren direkt."})]})}function au({customer:r,step:e,onClose:n,onSent:s}){const[i,o]=h.useState(!0),[a,l]=h.useState(""),[c,d]=h.useState(""),[u,f]=h.useState(null),[p,x]=h.useState(null),[g,v]=h.useState(!1),[m,w]=h.useState("");h.useEffect(()=>{let b=!1;return o(!0),w(""),f(null),M.getOnboardingDraft(r.id,e).then(y=>{b||(l(y.subject||""),d(y.html||""),f(y.html||""),x(y.sent_at||null))}).catch(y=>{b||w(y.message)}).finally(()=>{b||o(!1)}),()=>{b=!0}},[r.id,e]);const _=async()=>{if(!a.trim()||!c.trim()){w("Betreff und Inhalt dürfen nicht leer sein.");return}v(!0),w("");try{const b=await M.sendOnboardingMail(r.id,e,{subject:a,html:c});s(e,b.sent_at),n()}catch(b){w(b.message),v(!1)}};return t.jsx("div",{style:{position:"fixed",inset:0,background:"rgba(15, 23, 42, 0.55)",zIndex:1e3,display:"flex",alignItems:"center",justifyContent:"center",padding:16},children:t.jsxs("div",{style:{background:"#fff",borderRadius:14,boxShadow:"0 20px 60px rgba(0,0,0,0.25)",width:"100%",maxWidth:1080,maxHeight:"92vh",display:"flex",flexDirection:"column",overflow:"hidden"},children:[t.jsxs("div",{style:{padding:"18px 24px",borderBottom:"1px solid #e5e7eb",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[t.jsxs("div",{children:[t.jsxs("div",{style:{fontSize:11,fontWeight:600,color:"#8c959f",textTransform:"uppercase",letterSpacing:.6},children:["Mail #",e]}),t.jsxs("div",{style:{fontSize:16,fontWeight:700,color:"#24292f",marginTop:2},children:[Ti[e],", ",r.name]}),r.owner_email&&t.jsxs("div",{style:{fontSize:12,color:"#656d76",marginTop:2},children:["Empfänger: ",r.owner_email]}),p&&t.jsxs("div",{style:{fontSize:11,color:"#16a34a",marginTop:4},children:["Bereits gesendet am ",Mt(p),", erneutes Senden überschreibt"]})]}),t.jsx("button",{onClick:n,style:{border:"none",background:"transparent",cursor:"pointer",padding:6,color:"#656d76"},title:"SchlieÃen",children:t.jsx(Vr,{size:18,color:"#656d76"})})]}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",minHeight:0,flex:1},children:[t.jsx("div",{style:{padding:20,borderRight:"1px solid #e5e7eb",display:"flex",flexDirection:"column",gap:12,overflowY:"auto"},children:i||u===null?t.jsx("div",{style:{color:"#8c959f",fontSize:13},children:"Entwurf wird geladenâ¦"}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{children:[t.jsx("label",{style:U.label,children:"Betreff"}),t.jsx("input",{style:U.input,value:a,onChange:b=>l(b.target.value)})]}),t.jsx("label",{style:U.label,children:"Inhalt"}),t.jsx(ou,{initialHtml:u,onChange:d})]})}),t.jsxs("div",{style:{background:"#f8fafc",display:"flex",flexDirection:"column"},children:[t.jsx("div",{style:{padding:"10px 16px",fontSize:11,fontWeight:600,color:"#8c959f",textTransform:"uppercase",letterSpacing:.6,borderBottom:"1px solid #e5e7eb",background:"#fff"},children:"Vorschau"}),t.jsx("iframe",{title:"Mail-Vorschau",srcDoc:c,sandbox:"",style:{flex:1,width:"100%",border:"none",background:"#fff"}})]})]}),t.jsxs("div",{style:{padding:"14px 24px",borderTop:"1px solid #e5e7eb",display:"flex",alignItems:"center",gap:12},children:[m&&t.jsx("span",{style:{color:"#dc2626",fontSize:12},children:m}),t.jsxs("div",{style:{marginLeft:"auto",display:"flex",gap:8},children:[t.jsx("button",{onClick:n,style:{...U.btn,padding:"8px 14px",background:"#fff",border:"1px solid #d0d7de",color:"#24292f",fontSize:13},children:"Abbrechen"}),t.jsxs("button",{onClick:_,disabled:g||i,style:{...U.btn,padding:"8px 14px",background:g||i?"#9ca3af":"#0969da",color:"#fff",fontSize:13,display:"inline-flex",alignItems:"center",gap:6},children:[t.jsx(su,{size:13,color:"#fff"}),g?"Wird gesendetâ¦":p?"Erneut senden":"Mail senden"]})]})]})]})})}function lu(){var v;const[r,e]=h.useState(null),[n,s]=h.useState(!0),[i,o]=h.useState(""),[a,l]=h.useState(null),[c,d]=h.useState(null),u=h.useCallback(async()=>{s(!0),o("");try{const m=await M.getOnboarding();e(m)}catch(m){o(m.message)}finally{s(!1)}},[]);h.useEffect(()=>{u()},[u]);const f=(m,w)=>{a&&e(_=>_&&{..._,customers:_.customers.map(b=>b.id===a.customer.id?{...b,mails:{...b.mails,[m]:{sent:!0,sent_at:w}}}:b)})},p=({customer:m,step:w})=>{var b;const _=((b=m.mails)==null?void 0:b[w])||{sent:!1};return t.jsxs("button",{onClick:()=>l({customer:m,step:w}),title:`${Ti[w]}${_.sent_at?`, gesendet am ${Mt(_.sent_at)}`:""}`,style:{display:"inline-flex",alignItems:"center",gap:6,padding:"4px 10px",borderRadius:8,background:_.sent?"#f0fdf4":"#fff",border:`1px solid ${_.sent?"#bbf7d0":"#e5e7eb"}`,cursor:"pointer",fontSize:12,fontWeight:500,color:"#24292f",fontFamily:Qe},children:[_.sent?t.jsx(wn,{size:12}):t.jsx(Vr,{size:12,color:"#9ca3af"}),t.jsx("span",{children:w})]})},x=async(m,w)=>{const _=w==="kickoff"?"kickoff_call_at":"followup_call_at",b=!!m[_],y=b?null:new Date().toISOString();e(k=>k&&{...k,customers:k.customers.map(S=>S.id===m.id?{...S,[_]:y}:S)});try{await M.toggleOnboardingMeeting(m.id,w,!b)}catch(k){e(S=>S&&{...S,customers:S.customers.map(T=>T.id===m.id?{...T,[_]:b?new Date().toISOString():null}:T)}),alert(k.message)}},g=({customer:m,which:w,label:_})=>{const b=w==="kickoff"?"kickoff_call_at":"followup_call_at",y=!!m[b];return t.jsxs("button",{onClick:()=>x(m,w),title:y?`${_} erledigt am ${Mt(m[b])}, klicken zum Zurücksetzen`:`${_}, klicken, um als erledigt zu markieren`,style:{display:"inline-flex",alignItems:"center",gap:5,padding:"4px 10px",borderRadius:8,background:y?"#f0fdf4":"#fff",border:`1px solid ${y?"#bbf7d0":"#e5e7eb"}`,cursor:"pointer",fontSize:12,fontWeight:500,color:"#24292f",fontFamily:Qe,whiteSpace:"nowrap"},children:[y?t.jsx(wn,{size:12}):t.jsx(Vr,{size:12,color:"#9ca3af"}),t.jsx("span",{children:y?Mt(m[b]):", "})]})};return n?t.jsx("div",{style:{color:"#8c959f"},children:"Wird geladenâ¦"}):i?t.jsx("div",{style:{color:"#dc2626"},children:i}):(v=r==null?void 0:r.customers)!=null&&v.length?t.jsxs("div",{children:[t.jsx("div",{style:{background:"#fff",border:"1px solid #e5e7eb",borderRadius:12,overflow:"hidden"},children:t.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:13},children:[t.jsx("thead",{style:{background:"#f6f8fa",borderBottom:"1px solid #e5e7eb"},children:t.jsxs("tr",{children:[t.jsx(xt,{children:"Kunde"}),t.jsx(xt,{children:"Onboarding"}),t.jsx(xt,{children:"Analyse fertig"}),t.jsx(xt,{children:"Kickoff-Call"}),t.jsx(xt,{children:"Follow-up (2 Wo.)"}),t.jsx(xt,{style:{textAlign:"center"},children:"Mails"}),t.jsx(xt,{style:{textAlign:"right"},children:"Aktion"})]})}),t.jsx("tbody",{children:r.customers.map(m=>t.jsxs("tr",{style:{borderBottom:"1px solid #eaecef"},children:[t.jsxs(bt,{children:[t.jsx("div",{style:{fontWeight:600,color:"#24292f"},children:m.name||", "}),m.owner_email&&t.jsx("div",{style:{fontSize:11,color:"#8c959f",marginTop:2},children:m.owner_email})]}),t.jsx(bt,{style:{color:"#656d76"}
93,children:Mt(m.onboarded_at)}),t.jsx(bt,{children:m.analysis_ready_at?t.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4,color:"#16a34a",fontWeight:600},children:[t.jsx(wn,{size:12})," ",Mt(m.analysis_ready_at)]}):t.jsx("span",{style:{color:"#8c959f"},children:"läuftâ¦"})}),t.jsx(bt,{children:t.jsx(g,{customer:m,which:"kickoff",label:"Kickoff-Call"})}),t.jsx(bt,{children:t.jsx(g,{customer:m,which:"followup",label:"Follow-up-Gespräch"})}),t.jsx(bt,{style:{textAlign:"center"},children:t.jsxs("div",{style:{display:"inline-flex",gap:6},children:[t.jsx(p,{customer:m,step:1}),t.jsx(p,{customer:m,step:2}),t.jsx(p,{customer:m,step:3})]})}),t.jsx(bt,{style:{textAlign:"right"},children:t.jsxs("div",{style:{display:"inline-flex",gap:6},children:[t.jsx("button",{onClick:()=>d(m),title:"Profil bearbeiten (Preise, Notizen)",style:{display:"inline-flex",alignItems:"center",gap:5,padding:"6px 10px",borderRadius:8,background:"#fff",color:"#24292f",border:"1px solid #d0d7de",fontSize:12,fontWeight:500,cursor:"pointer",fontFamily:Qe},children:t.jsx(Ri,{size:12})}),t.jsxs("a",{href:m.preview_url,target:"_blank",rel:"noopener noreferrer",style:{display:"inline-flex",alignItems:"center",gap:5,padding:"6px 12px",borderRadius:8,background:"#0969da",color:"#fff",textDecoration:"none",fontSize:12,fontWeight:600},children:[t.jsx(nu,{size:12,color:"#fff"})," Dashboard"]})]})})]},m.id))})]})}),a&&t.jsx(au,{customer:a.customer,step:a.step,onClose:()=>l(null),onSent:f}),c&&t.jsx(Ii,{customer:c,onClose:()=>d(null),onSaved:({name:m})=>e(w=>w&&{...w,customers:w.customers.map(_=>_.id===c.id?{..._,name:m||_.name}:_)})})]}):t.jsx("div",{style:{color:"#8c959f"},children:"Noch keine Onboardings."})}function xt({children:r,style:e}){return t.jsx("th",{style:{textAlign:"left",padding:"10px 14px",fontSize:11,fontWeight:700,color:"#656d76",textTransform:"uppercase",letterSpacing:.5,...e},children:r})}function bt({children:r,style:e}){return t.jsx("td",{style:{padding:"12px 14px",verticalAlign:"middle",...e},children:r})}const Br=r=>{const e=(r||"").trim();return!e||/^https?:\/\//i.test(e)?e:`https://${e}`},Gs=[{key:"google",label:"Google Maps",placeholder:"https://www.google.com/maps/place/...",pattern:/^https?:\/\/(www\.)?google\.[a-z.]+\/maps\/place\/.+/i,hint:"URL muss mit google.com/maps/place/ beginnen"},{key:"trustpilot",label:"Trustpilot",placeholder:"https://de.trustpilot.com/review/...",pattern:/^https?:\/\/([a-z]{2}\.)?trustpilot\.com\/review\/.+/i,hint:"URL muss mit trustpilot.com/review/ beginnen"},{key:"tripadvisor",label:"TripAdvisor",placeholder:"https://www.tripadvisor.de/Restaurant_Review-...",pattern:/^https?:\/\/(www\.)?tripadvisor\.[a-z.]+\/(Restaurant_Review|Hotel_Review|Attraction_Review)-.+/i,hint:"URL muss eine TripAdvisor Review-Seite sein"},{key:"yelp",label:"Yelp",placeholder:"https://www.yelp.de/biz/..."},{key:"trusted_shops",label:"Trusted Shops",placeholder:"https://www.trustedshops.de/bewertung/...",pattern:/^https?:\/\/(www\.)?trustedshops\.[a-z]+\/bewertung\/.+/i,hint:"URL muss mit trustedshops.de/bewertung/ beginnen"},{key:"provenexpert",label:"ProvenExpert",placeholder:"https://www.provenexpert.com/firmenname/",pattern:/^https?:\/\/(www\.)?provenexpert\.com\/.+/i,hint:"URL muss mit provenexpert.com/ beginnen"}];function cu(){var T,V;const[r,e]=h.useState("overview"),[n,s]=h.useState({email:"",companyName:"",customerName:"",monthlyPrice:"",erstanalysePrice:""}),[i,o]=h.useState({}),[a,l]=h.useState([]),[c,d]=h.useState({name:"",platform:"google",url:""}),[u,f]=h.useState(!1),[p,x]=h.useState(null),[g,v]=h.useState(""),m=(C,z)=>s(H=>({...H,[C]:z})),w=(C,z)=>o(H=>({...H,[C]:z})),_=[{key:"google",label:"Google",placeholder:"https://www.google.com/maps/place/..."},{key:"trustpilot",label:"Trustpilot",placeholder:"https://de.trustpilot.com/review/..."},{key:"tripadvisor",label:"TripAdvisor",placeholder:"https://www.tripadvisor.de/..."},{key:"yelp",label:"Yelp",placeholder:"https://www.yelp.de/biz/..."},{key:"provenexpert",label:"ProvenExpert",placeholder:"https://www.provenexpert.com/..."},{key:"trusted_shops",label:"Trusted Shops",placeholder:"https://www.trustedshops.de/bewertung/..."}],b=()=>{!c.name.trim()||!c.url.trim()||a.length>=5||(l(C=>[...C,{name:c.name.trim(),platform:c.platform,url:Br(c.url)}]),d({name:"",platform:c.platform,url:""}))},y=C=>l(z=>z.filter((H,G)=>G!==C)),k=async C=>
93{if(C.preventDefault(),!n.email||!n.companyName||!n.customerName){v("Bitte alle Pflichtfelder ausfüllen.");return}if(!n.erstanalysePrice||Number(n.erstanalysePrice)<=0){v("Bitte einen Erstanalyse-Preis angeben.");return}if(!n.monthlyPrice||Number(n.monthlyPrice)<=0){v("Bitte einen monatlichen Preis angeben.");return}const z=Object.fromEntries(Object.entries(i).filter(([,H])=>H.trim()).map(([H,G])=>[H,Br(G)]));if(Object.keys(z).length===0){v("Mindestens eine Plattform muss angegeben werden.");return}for(const[H,G]of Object.entries(z)){const O=Gs.find(F=>F.key===H);if(O!=null&&O.pattern&&!O.pattern.test(G)){v(`Ungültige ${O.label} URL: ${O.hint}`);return}}f(!0),v("");try{const H=await M.onboardCustomer({...n,platforms:z,competitors:a.length>0?a:void 0});x(H)}catch(H){v(H.message||"Fehler beim Onboarding")}finally{f(!1)}};if(p&&r==="new")return t.jsxs("div",{children:[t.jsx("h1",{style:U.h1,children:"Kunde angelegt"}),t.jsxs("div",{style:{...U.card,maxWidth:560},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,marginBottom:20},children:[t.jsx("div",{style:{width:40,height:40,borderRadius:"50%",backgroundColor:"#dafbe1",display:"flex",alignItems:"center",justifyContent:"center"},children:t.jsx("svg",{width:"20",height:"20",viewBox:"0 0 16 16",fill:"#1a7f37",children:t.jsx("path",{d:"M13.78 4.22a.75.75 0 0 1 0 1.06l-7.25 7.25a.75.75 0 0 1-1.06 0L2.22 9.28a.75.75 0 0 1 1.06-1.06L6 10.94l6.72-6.72a.75.75 0 0 1 1.06 0Z"})})}),t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:16,fontWeight:600,color:"#1a7f37"},children:p.message}),t.jsx("div",{style:{fontSize:12,color:"#656d76",marginTop:2},children:"Login-Daten wurden per E-Mail versendet."})]})]}),t.jsxs("div",{style:{background:"#f6f8fa",borderRadius:8,padding:16,marginBottom:16},children:[t.jsx("div",{style:{fontSize:12,fontWeight:600,color:"#24292f",marginBottom:8},children:"Zugangsdaten"}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"100px 1fr",gap:"6px 12px",fontSize:13},children:[t.jsx("span",{style:{color:"#656d76"},children:"E-Mail:"}),t.jsx("span",{style:{fontWeight:500},children:n.email}),t.jsx("span",{style:{color:"#656d76"},children:"Passwort:"}),t.jsx("span",{style:{fontWeight:600,fontFamily:"monospace",background:"#fff8c5",padding:"2px 8px",borderRadius:4},children:p.password})]})]}),t.jsxs("div",{style:{fontSize:12,color:"#656d76",marginBottom:16},children:["Plattformen: ",((T=p.platforms)==null?void 0:T.join(", "))||"keine",t.jsx("br",{}),"Scraping und Analyse laufen automatisch im Hintergrund."]}),t.jsx("button",{onClick:()=>{x(null),s({email:"",companyName:"",customerName:"",monthlyPrice:"",erstanalysePrice:""}),o({})},style:{...U.btn,backgroundColor:"#0969da",color:"#fff"},children:"Weiteren Kunden anlegen"})]})]});const S=({id:C,label:z})=>t.jsx("button",{onClick:()=>e(C),style:{padding:"8px 16px",border:"none",background:"transparent",fontSize:14,fontWeight:r===C?600:500,color:r===C?"#0969da":"#656d76",borderBottom:r===C?"2px solid #0969da":"2px solid transparent",cursor:"pointer",fontFamily:Qe,marginBottom:-1},children:z});return t.jsxs("div",{children:[t.jsx("h1",{style:U.h1,children:"Kunden-Onboarding"}),t.jsxs("div",{style:{display:"flex",gap:4,borderBottom:"1px solid #e5e7eb",marginBottom:20},children:[t.jsx(S,{id:"overview",label:"Ãbersicht"}),t.jsx(S,{id:"new",label:"Neuen Kunden anlegen"})]}),r==="overview"&&t.jsx(lu,{}),r==="new"&&t.jsxs(t.Fragment,{children:[t.jsx(iu,{}),t.jsxs("form",{onSubmit:k,style:{maxWidth:640},children:[t.jsxs("div",{style:{...U.card,marginBottom:16},children:[t.jsx("div",{style:{fontSize:14,fontWeight:600,color:"#24292f",marginBottom:16,paddingBottom:12,borderBottom:"1px solid #eaecef"},children:"Kundendaten"}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:16,marginBottom:16},children:[t.jsxs("div",{children:[t.jsx("label",{style:U.label,children:"Kundenname *"}),t.jsx("input",{style:U.input,value:n.customerName,onChange:C=>m("customerName",C.target.value),placeholder:"Max Mustermann"})]}),t.jsxs("div",{children:[t.jsx("label",{style:U.label,children:"E-Mail-Adresse *"}),t.jsx("input",{style:U.input,type:"email",value:n.email,onChange:C=>m("email",C.target.value),placeholder:"[email protected]"})]})]}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:16},children:[t.jsxs("div",{children:[t.jsx("label",{style:U.label,children:"Firmenname *"}),t.jsx("input",{style:U.input,value:n.companyName,onChange:C=>m("companyName",C.target.value),placeholder:"Muster GmbH"})]}),t.jsxs("div",{children:[t.jsx("label",{style:U.label,children:"Erstanalyse-Preis (EUR) *"}),t.jsx("input",{style:U.input,type:"number",min:"0",step:"1",value:n.er
93stanalysePrice,onChange:C=>m("erstanalysePrice",C.target.value),placeholder:"z.B. 349"})]}),t.jsxs("div",{children:[t.jsx("label",{style:U.label,children:"Monatlicher Preis (EUR) *"}),t.jsx("input",{style:U.input,type:"number",min:"0",step:"1",value:n.monthlyPrice,onChange:C=>m("monthlyPrice",C.target.value),placeholder:"z.B. 99"})]})]}),t.jsx("p",{style:U.hint,children:"Passwort wird automatisch generiert und per E-Mail versendet."})]}),t.jsxs("div",{style:{...U.card,marginBottom:16},children:[t.jsx("div",{style:{fontSize:14,fontWeight:600,color:"#24292f",marginBottom:16,paddingBottom:12,borderBottom:"1px solid #eaecef"},children:"Bewertungsplattformen"}),t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:12},children:Gs.map(C=>t.jsxs("div",{children:[t.jsx("label",{style:U.label,children:C.label}),t.jsx("input",{style:{...U.input,...i[C.key]&&C.pattern&&!C.pattern.test(Br(i[C.key]))?{borderColor:"#cf222e"}:{}},value:i[C.key]||"",onChange:z=>w(C.key,z.target.value),placeholder:C.placeholder}),i[C.key]&&C.pattern&&!C.pattern.test(Br(i[C.key]))&&t.jsx("p",{style:{...U.hint,color:"#cf222e"},children:C.hint})]},C.key))}),t.jsx("p",{style:U.hint,children:"Mindestens eine Plattform angeben. Leere Felder werden ignoriert."})]}),t.jsxs("div",{style:{...U.card,marginBottom:16},children:[t.jsx("div",{style:{fontSize:14,fontWeight:600,color:"#24292f",marginBottom:16,paddingBottom:12,borderBottom:"1px solid #eaecef"},children:"Wettbewerber (optional)"}),a.length>0&&t.jsx("div",{style:{marginBottom:12,display:"flex",flexDirection:"column",gap:6},children:a.map((C,z)=>{var H;return t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"8px 12px",backgroundColor:"#f6f8fa",borderRadius:8,border:"1px solid #e5e7eb"},children:[t.jsx("span",{style:{fontSize:12,fontWeight:600,color:"#24292f",flex:1},children:C.name}),t.jsx("span",{style:{fontSize:11,color:"#656d76",backgroundColor:"#fff",padding:"2px 8px",borderRadius:4,border:"1px solid #e5e7eb"},children:((H=_.find(G=>G.key===C.platform))==null?void 0:H.label)||C.platform}),t.jsx("button",{type:"button",onClick:()=>y(z),style:{background:"none",border:"none",cursor:"pointer",color:"#cf222e",fontSize:16,padding:"0 4px",lineHeight:1},children:"Ã"})]},z)})}),a.length<5&&t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr auto 2fr auto",gap:8,alignItems:"end"},children:[t.jsxs("div",{children:[t.jsx("label",{style:U.label,children:"Firmenname"}),t.jsx("input",{style:U.input,value:c.name,onChange:C=>d(z=>({...z,name:C.target.value})),placeholder:"Konkurrent GmbH"})]}),t.jsxs("div",{children:[t.jsx("label",{style:U.label,children:"Plattform"}),t.jsx("select",{style:{...U.input,cursor:"pointer"},value:c.platform,onChange:C=>d(z=>({...z,platform:C.target.value})),children:_.map(C=>t.jsx("option",{value:C.key,children:C.label},C.key))})]}),t.jsxs("div",{children:[t.jsx("label",{style:U.label,children:"URL"}),t.jsx("input",{style:U.input,value:c.url,onChange:C=>d(z=>({...z,url:C.target.value})),placeholder:((V=_.find(C=>C.key===c.platform))==null?void 0:V.placeholder)||""})]}),t.jsx("button",{type:"button",onClick:b,disabled:!c.name.trim()||!c.url.trim(),style:{...U.btn,backgroundColor:c.name.trim()&&c.url.trim()?"#0969da":"#d0d7de",color:"#fff",padding:"8px 14px",fontSize:13},children:"+"})]}),t.jsx("p",{style:U.hint,children:"Bis zu 5 Wettbewerber. URLs werden bei der Wettbewerbsanalyse im Dashboard genutzt."})]}),g&&t.jsx("div",{style:{padding:"10px 16px",backgroundColor:"#ffebe9",border:"1px solid #ffcecb",borderRadius:8,fontSize:13,color:"#cf222e",marginBottom:16},children:g}),t.jsx("button",{type:"submit",disabled:u,style:{...U.btn,backgroundColor:"#1a7f37",color:"#fff",width:"100%",opacity:u?.6:1},children:u?"Wird erstellt...":"Account erstellen & Analyse starten"})]})]})]})}function du(){return t.jsxs("div",{children:[t.jsx("h1",{style:{fontSize:22,fontWeight:600,margin:"0 0 24px",color:"#1f2328"},children:"Debug"}),t.jsx("div",{style:{background:"#fff",border:"1px solid #e5e7eb",borderRadius:12,padding:24},children:t.jsx("p",{style:{color:"#656d76",fontSize:13},children:"Debug-Informationen werden hier angezeigt."})})]})}const Q={h1:{fontSize:22,fontWeight:600,margin:"0 0 24px",color:"#1f2328"},card:{background:"#ffffff",border:"1px solid #e5e7eb",borderRadius:12,boxShadow:"0 1px 2px rgba(0,0,0,0.05)",overflow:"hidden"},table:{width:"100%",borderCollapse:"collapse"},th:{textAlign:"left",padding:"10px 16px",color:"#656d76",fontSize:11,fontWeight:600,textTransform:"uppercase",borderBottom:"1px solid #e5e7eb"},td:{padding:"12px 16px",color:"#1f2328",fontSize:13,borderBottom:"1px solid #f0f
930f0",verticalAlign:"top"},loading:{color:"#656d76",fontSize:14},kpiRow:{display:"flex",gap:16,marginBottom:24,flexWrap:"wrap"},kpiCard:{flex:"1 1 180px",background:"#ffffff",border:"1px solid #e5e7eb",borderRadius:12,padding:"20px 24px",boxShadow:"0 1px 2px rgba(0,0,0,0.05)"},kpiValue:{fontSize:28,fontWeight:700,color:"#1f2328",margin:0},kpiLabel:{fontSize:12,color:"#656d76",margin:"4px 0 0",fontWeight:500},filterRow:{display:"flex",gap:8,marginBottom:16,flexWrap:"wrap"},filterBtn:{padding:"6px 14px",borderRadius:20,border:"1px solid #d0d7de",background:"#f6f8fa",color:"#656d76",fontSize:12,fontWeight:500,cursor:"pointer",transition:"all 0.15s"},filterBtnActive:{padding:"6px 14px",borderRadius:20,border:"1px solid #0969da",background:"#eff6ff",color:"#0969da",fontSize:12,fontWeight:600,cursor:"pointer",transition:"all 0.15s"}},uu={topic_correction:"Topic-Korrektur",recommendation_dismissed:"Nicht relevant",recommendation_completed:"Umgesetzt",accuracy_rating:"Bewertung",task_not_relevant:"Task irrelevant"},hu={topic_correction:{background:"#ddf4ff",color:"#0969da",border:"1px solid #b6d9fc"},recommendation_dismissed:{background:"#fff1e5",color:"#bc4c00",border:"1px solid #ffd8b5"},recommendation_completed:{background:"#dafbe1",color:"#1a7f37",border:"1px solid #aceebb"},accuracy_rating:{background:"#fbefff",color:"#8250df",border:"1px solid #e2c4f2"},task_not_relevant:{background:"#fff0f0",color:"#cf222e",border:"1px solid #fdcece"}},fu={background:"#f0f0f0",color:"#656d76",border:"1px solid #d0d7de"};function pu({type:r}){const e=hu[r]||fu;return t.jsx("span",{style:{display:"inline-block",padding:"3px 10px",borderRadius:12,fontSize:11,fontWeight:600,whiteSpace:"nowrap",...e},children:uu[r]||r})}function gu(r){const{type:e,data:n}=r;if(!n)return", ";if(e==="topic_correction"){const s=[];return n.originalTopic&&s.push(`"${n.originalTopic}"`),n.correctedTopic&&s.push(`â "${n.correctedTopic}"`),n.reviewText&&s.push(`Review: "${n.reviewText.slice(0,80)}${n.reviewText.length>80?"...":""}"`),s.join(" ")||JSON.stringify(n)}if(e==="recommendation_dismissed"||e==="recommendation_completed")return n.recommendation||n.title||JSON.stringify(n);if(e==="accuracy_rating"){const s=[];return n.rating!=null&&s.push(n.rating>0?"ð Positiv":"ð Negativ"),n.comment&&s.push(`"${n.comment}"`),n.section&&s.push(`(${n.section})`),s.join(" ")||JSON.stringify(n)}if(e==="task_not_relevant"){const s=[];return n.massnahmeTitle&&s.push(`MaÃnahme: ${n.massnahmeTitle}`),n.taskTitle&&s.push(`Task: "${n.taskTitle}"`),s.join(", ")||JSON.stringify(n)}if(typeof n=="object"){const{companyId:s,...i}=n,o=Object.keys(i);return o.length===0?", ":o.map(a=>`${a}: ${i[a]}`).join(", ")}return String(n)}function mu(){const[r,e]=h.useState([]),[n,s]=h.useState({}),[i,o]=h.useState(!0),[a,l]=h.useState("all"),[c,d]=h.useState(null);if(h.useEffect(()=>{M.getFeedback().then(f=>{e(f.items||[]),s(f.stats||{})}).catch(f=>d(f.message)).finally(()=>o(!1))},[]),i)return t.jsx("p",{style:Q.loading,children:"Lade Feedback..."});if(c)return t.jsxs("p",{style:{color:"#cf222e",fontSize:14},children:["Fehler: ",c]});const u=a==="all"?r:r.filter(f=>f.type===a);return t.jsxs("div",{children:[t.jsx("h1",{style:Q.h1,children:"Nutzer-Feedback"}),t.jsxs("div",{style:Q.kpiRow,children:[t.jsxs("div",{style:Q.kpiCard,children:[t.jsx("p",{style:Q.kpiValue,children:n.total||0}),t.jsx("p",{style:Q.kpiLabel,children:"Gesamt"})]}),t.jsxs("div",{style:Q.kpiCard,children:[t.jsx("p",{style:{...Q.kpiValue,color:"#0969da"},children:n.topic_correction||0}),t.jsx("p",{style:Q.kpiLabel,children:"Topic-Korrekturen"})]}),t.jsxs("div",{style:Q.kpiCard,children:[t.jsx("p",{style:{...Q.kpiValue,color:"#bc4c00"},children:n.recommendation_dismissed||0}),t.jsx("p",{style:Q.kpiLabel,children:"Nicht relevant"})]}),t.jsxs("div",{style:Q.kpiCard,children:[t.jsx("p",{style:{...Q.kpiValue,color:"#1a7f37"},children:n.recommendation_completed||0}),t.jsx("p",{style:Q.kpiLabel,children:"Umgesetzt"})]}),t.jsxs("div",{style:Q.kpiCard,children:[t.jsx("p",{style:{...Q.kpiValue,color:"#8250df"},children:n.accuracy_rating||0}),t.jsx("p",{style:Q.kpiLabel,children:"Bewertungen"})]}),t.jsxs("div",{style:Q.kpiCard,children:[t.jsx("p",{style:{...Q.kpiValue,color:"#cf222e"},children:n.task_not_relevant||0}),t.jsx("p",{style:Q.kpiLabel,children:"Task irrelevant"})]})]}),t.jsx("div",{style:Q.filterRow,children:[{key:"all",label:`Alle (${n.total||0})`},{key:"topic_correction",label:`Korrekturen (${n.topic_correction||0})`},{key:"recommendation_dismissed",label:`Nicht relevant (${n.recommendation_dismissed||
930})`},{key:"recommendation_completed",label:`Umgesetzt (${n.recommendation_completed||0})`},{key:"accuracy_rating",label:`Bewertungen (${n.accuracy_rating||0})`},{key:"task_not_relevant",label:`Task irrelevant (${n.task_not_relevant||0})`}].map(f=>t.jsx("button",{style:a===f.key?Q.filterBtnActive:Q.filterBtn,onClick:()=>l(f.key),children:f.label},f.key))}),t.jsx("div",{style:Q.card,children:t.jsxs("table",{style:Q.table,children:[t.jsx("thead",{children:t.jsxs("tr",{children:[t.jsx("th",{style:Q.th,children:"Datum"}),t.jsx("th",{style:Q.th,children:"Unternehmen"}),t.jsx("th",{style:Q.th,children:"Typ"}),t.jsx("th",{style:Q.th,children:"Details"})]})}),t.jsxs("tbody",{children:[u.map((f,p)=>t.jsxs("tr",{children:[t.jsx("td",{style:{...Q.td,whiteSpace:"nowrap",color:"#656d76"},children:new Date(f.createdAt).toLocaleString("de-DE",{day:"2-digit",month:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit"})}),t.jsx("td",{style:{...Q.td,fontWeight:500},children:f.companyName||", "}),t.jsx("td",{style:Q.td,children:t.jsx(pu,{type:f.type})}),t.jsx("td",{style:{...Q.td,maxWidth:400,overflow:"hidden",textOverflow:"ellipsis",color:"#656d76",fontSize:12},children:gu(f)})]},p)),u.length===0&&t.jsx("tr",{children:t.jsx("td",{colSpan:4,style:{...Q.td,color:"#656d76",textAlign:"center",padding:"32px 16px"},children:"Kein Feedback vorhanden"})})]})]})})]})}const _n='-apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif',Te={layout:{display:"flex",minHeight:"100vh",background:"#f6f8fa",fontFamily:_n,color:"#1f2328"},sidebar:{width:240,background:"#ffffff",borderRight:"1px solid #e5e7eb",display:"flex",flexDirection:"column",flexShrink:0,height:"100vh",position:"sticky",top:0},sidebarHeader:{padding:"12px 12px",borderBottom:"1px solid #eaecef",display:"flex",alignItems:"center",gap:10,minHeight:52},sidebarTitle:{color:"#24292f",fontSize:15,fontWeight:700,margin:0},sidebarSubtitle:{color:"#656d76",fontSize:11,margin:"4px 0 0"},nav:{padding:"8px",flex:1},navSection:{fontSize:11,fontWeight:600,color:"#656d76",textTransform:"uppercase",letterSpacing:"0.04em",padding:"6px 8px 4px",margin:0},navLink:{display:"flex",alignItems:"center",gap:8,padding:"7px 10px",borderRadius:8,color:"#656d76",textDecoration:"none",fontSize:13,fontWeight:400,marginBottom:2,transition:"all 0.15s",borderLeft:"3px solid transparent"},navLinkActive:{background:"#eff6ff",color:"#0969da",fontWeight:600,borderLeft:"3px solid #0969da"},main:{flex:1,overflow:"auto"},content:{padding:32,maxWidth:1600,margin:"0 auto"},logoutBtn:{margin:"0 8px 16px",padding:"7px 12px",background:"#f6f8fa",border:"1px solid #d0d7de",borderRadius:8,color:"#656d76",fontSize:12,cursor:"pointer",textAlign:"left",display:"flex",alignItems:"center",gap:8,transition:"background 0.15s"},loading:{minHeight:"100vh",background:"#f6f8fa",display:"flex",alignItems:"center",justifyContent:"center",color:"#656d76",fontFamily:_n},errorPage:{minHeight:"100vh",background:"#f6f8fa",display:"flex",alignItems:"center",justifyContent:"center",color:"#cf222e",fontFamily:_n,fontSize:18}},yu=[{to:"",label:"Dashboard",end:!0,icon:t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",children:[t.jsx("rect",{x:"1.5",y:"1.5",width:"5",height:"5",rx:"1"}),t.jsx("rect",{x:"9.5",y:"1.5",width:"5",height:"5",rx:"1"}),t.jsx("rect",{x:"1.5",y:"9.5",width:"5",height:"5",rx:"1"}),t.jsx("rect",{x:"9.5",y:"9.5",width:"5",height:"5",rx:"1"})]})},{to:"users",label:"Benutzer",icon:t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",children:[t.jsx("circle",{cx:"6",cy:"4.5",r:"2.5"}),t.jsx("path",{d:"M1 14c0-2.76 2.24-5 5-5h0c2.76 0 5 2.24 5 5"}),t.jsx("circle",{cx:"12",cy:"5",r:"1.8",strokeWidth:"1.2"}),t.jsx("path",{d:"M13 9.5c1.5.5 2.5 2 2.5 4.5",strokeWidth:"1.2"})]})},{to:"jobs",label:"Scrape Jobs",icon:t.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinejoin:"round",children:t.jsx("path",{d:"M8.5 1L3 9h4.5l-1 6L12 7H7.5l1-6z"})})},{to:"errors",label:"Fehler-Logs",icon:t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinejoin:"round",children:[t.jsx("path",{d:"M7.134 2.5a1 1 0 011.732 0l5.196 9A1 1 0 0113.196 13H2.804a1 1 0 01-.866-1.5l5.196-9z"}),t.jsx("path",{d:"M8 6v3",strokeLinecap:"round"}),t.jsx("circle",{cx:"8",cy:"11",r:".6",fill:"currentColor",stroke:"none"})]})},{to:"logs",label:"Admin-Logs",icon:t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",children:[t.jsx("rect",{x:"2",y:"1.5",width:"12",height:"13",rx:"1.5"}),t.jsx("path",{d:"M5 5h6M5 8h6M5 11h4",strokeWidth:"1.2"})]})},{to:"settings",label:"Einstellungen",icon:t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",children:[t.jsx("circle",{cx:"8",cy:"8",r:"2"}),t.jsx("path",{d:"M8 1v2M8 13v2M1 8h2M13 8h2M3.05 3.05l1.41 1.41M11.54 11.54l1.41 1.41M3.05 12.95l1.41-1.41
93M11.54 4.46l1.41-1.41",strokeWidth:"1.2"})]})},{to:"feedback",label:"Feedback",icon:t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[t.jsx("path",{d:"M1 3.5A1.5 1.5 0 012.5 2h11A1.5 1.5 0 0115 3.5v7a1.5 1.5 0 01-1.5 1.5H5l-3 3v-3H2.5A1.5 1.5 0 011 10.5v-7z"}),t.jsx("path",{d:"M5 6h6M5 9h4",strokeWidth:"1.2"})]})},{to:"debug",label:"Debug",icon:t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",children:[t.jsx("path",{d:"M5.5 3.5L3 1M10.5 3.5L13 1"}),t.jsx("rect",{x:"4",y:"3.5",width:"8",height:"9",rx:"4"}),t.jsx("path",{d:"M1 7h3M12 7h3M1 10.5h3M12 10.5h3M8 3.5v9",strokeWidth:"1.2"})]})}],xu=()=>t.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[t.jsx("path",{d:"M6 2H3.5A1.5 1.5 0 002 3.5v9A1.5 1.5 0 003.5 14H6"}),t.jsx("path",{d:"M11 11l3-3-3-3"}),t.jsx("path",{d:"M14 8H6"})]}),bu=Dn.createContext(!1),vu=()=>t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[t.jsx("path",{d:"M1 8s2.5-5 7-5 7 5 7 5-2.5 5-7 5-7-5-7-5z"}),t.jsx("circle",{cx:"8",cy:"8",r:"2"})]}),wu=()=>t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[t.jsx("path",{d:"M2 2l12 12"}),t.jsx("path",{d:"M6.5 6.5a2 2 0 002.8 2.8"}),t.jsx("path",{d:"M4.2 4.2C2.7 5.4 1 8 1 8s2.5 5 7 5c1.3 0 2.5-.4 3.5-1"}),t.jsx("path",{d:"M11.8 11.8C13.3 10.6 15 8 15 8s-2.5-5-7-5c-.7 0-1.3.1-1.9.3"})]});function _u({noToken:r=!1}){const e=qr(),n=r?null:e.token;Se();const[s,i]=h.useState(r?!0:null),[o,a]=h.useState(null),[l,c]=h.useState(null),[d,u]=h.useState(!0),[f,p]=h.useState(null),x=h.useRef(null),[g,v]=h.useState(()=>{try{return sessionStorage.getItem("admin_censored")==="true"}catch{return!1}}),m=()=>{v(y=>{const k=!y;try{sessionStorage.setItem("admin_censored",String(k))}catch{}return k})};h.useEffect(()=>{r||M.validateToken(n).then(y=>{i(y)}).catch(()=>i(!1))},[n,r]),h.useEffect(()=>{if(!s)return;Je.auth.getSession().then(async({data:{session:k}})=>{if(k){const{data:S}=await Je.from("profiles").select("id, full_name, role").eq("id",k.user.id).single();(S==null?void 0:S.role)==="admin"&&(a(k),c(S))}}).finally(()=>u(!1));const{data:{subscription:y}}=Je.auth.onAuthStateChange(k=>{k==="SIGNED_OUT"&&(a(null),c(null))});return()=>y.unsubscribe()},[s]),h.useEffect(()=>{async function y(){try{const S=await M.getVersion();S!=null&&S.version&&(x.current&&x.current!==S.version?(p(S.version+" ð"),setTimeout(()=>p(S.version),5e3)):p(S.version),x.current=S.version)}catch{}}y();const k=setInterval(y,1e4);return()=>clearInterval(k)},[]);const w=(y,k)=>{a(y),c(k)},_=async()=>{await Je.auth.signOut(),a(null),c(null)};if(s===null)return t.jsx("div",{style:Te.loading,children:"Validierung..."});if(!s)return t.jsx("div",{style:Te.errorPage,children:"404 -- Seite nicht gefunden"});if(d)return t.jsx("div",{style:Te.loading});if(!o)return t.jsx(Ud,{onLogin:w});const b=r?"":`/admin/${n}`;return t.jsxs(bu.Provider,{value:g,children:[g&&t.jsx("style",{children:` 94 /* Only blur elements explicitly marked as sensitive */ 95 .admin-censor-content [data-sensitive], 96 .admin-censor-content [data-sensitive] * { 97 filter: blur(5px) !important; 98 user-select: none !important; 99 } 100 `}),t.jsxs("div",{style:Te.layout,className:g?"admin-censor-content":"",children:[t.jsxs("aside",{style:Te.sidebar,children:[t.jsxs("div",{style:Te.sidebarHeader,children:[t.jsx("div",{style:{width:32,height:32,borderRadius:"50%",background:"linear-gradient(135deg, #0969da, #1f6feb)",display:"flex",alignItems:"center",justifyContent:"center",color:"#fff",fontSize:14,fontWeight:700,flexShrink:0},children:"A"}),t.jsxs("div",{style:{minWidth:0,flex:1},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[t.jsx("p",{style:Te.sidebarTitle,children:"Admin Panel"}),t.jsx("button",{onClick:m,title:g?"Daten einblenden":"Daten ausblenden",style:{background:g?"#fff3cd":"transparent",border:g?"1px solid #e9c46a":"1px solid transparent",borderRadius:6,padding:4,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",color:g?"#b45309":"#656d76",transition:"all 0.2s",flexShrink:0},children:g?t.jsx(wu,{}):t.jsx(vu,{})})]}),t.jsxs("p",{style:Te.sidebarSubtitle,children:[f?`v${f}`:", "," · ",(l==null?void 0:l.full_name)||"--"]})]})]}),t.jsxs("nav",{style:Te.nav,children:[t.jsx("p",{style:Te.navSection,children:"Navigation"}),yu.map(y=>t.jsxs(Zs,{to:`${b}/${y.to}`,end:y.end,style:({isActive:k})=>({...Te.navLink,...k?Te.navLinkActive:{}}),children:[t.jsx("span",{style:{display:"flex",flexShrink:0},children:y.icon}),t.jsx("span",{children:y.label})]},y.to))]}),t.jsx("div",{style:{padding:"12px 8px",borderTop:"1px solid #eaecef"},children:t.jsxs("button",{style:Te.logoutBtn,onClick:_,children:[t.jsx(xu,{}),"Abmelden"]})})]}),t.jsx("main",{style:Te.main,children:t.jsx("div",{style:{...Te.content,filter:"none",userSelect:"auto",pointerEvents:"auto",transition:"filter 0.3s ease"},children:t.jsxs(pr,{children:[t.jsx(K,{index:!0,element:t.jsx(Nd,{})}),t.jsx(K,{path:"users",element:t.jsx(Kd,{basePath:b})}),t.jsx(K,{path:"users/:id",element:t.jsx(Gd,{basePath:b})}),t.jsx(K,{path:"onboard",element:t.jsx(cu,{})}),t.jsx(K,{path:"jobs",element:t.jsx(ru,{})}),t.jsx(K,{path:"errors",element:t.jsx(Zd,{})}),t.jsx(K,{path:"logs",element:t.jsx(Yd,{})}),t.jsx(K,{path:"settings",element:t.jsx(Qd,{})}),t.jsx(K,{path:"feedback",element:t.jsx(mu,{})}),t.jsx(K,{path:"debug",element:t.jsx(du,{})}),t.jsx(K,{path:"*",element:t.jsx(ee,{to:b,replace:!0})})]})})})]})]})}const ju=h.lazy(()=>Ee(()=>import("./DemoShell-kZD-1Lh6.js"),__vite__mapDeps([10,1,5,6])).then(r=>({default:r.DemoShell}))),Su=h.lazy(()=>Ee(()=>import("./UpgradePage-CZ8BaBrH.js"),__vite__mapDeps([0,1])).then(r=>({default:r.UpgradePage})));function ku(){const r=Se();return h.useEffect(()=>{ie.auth.getSession().then(async({data:{session:e}})=>{if(e){try{const{data:n}=await ie.from("profiles").select("company_id, role, onboarding_done").eq("id",e.user.id).single();if(n!=null&&n.company_id&&!n.onboarding_done&&n.role!=="owner"){r("/invite-onboarding",{replace:!0});return}}catch{}r("/onboarding",{replace:!0})}else r("/login",{replace:!0,state:{message:"E-Mail bestätigt! Sie können sich jetzt anmelden."}})})},[]),null}function Eu(){return h.useEffect(()=>{window.location.replace("https://admin.optimavo.de")},[]),null}const qn=window.location.hostname==="demo.optimavo.de",Cu=window.location.hostname==="admin.optimavo.de";function Au(){const{session:r,profile:e,subscription:n,hasActivePlatforms:s,loading:i,refreshProfile:o}=$e(),[a,l]=h.useState(!1);if(qn)return t.jsx(h.Suspense,{fallback:null,children:t.jsx(ju,{})});if((()=>{try{const x=new URLSearchParams(window.location.search).get("preview");if(x){try{sessionStorage.setItem("optimavo_preview_company_id",x)}catch{}return!0}try{return!!sessionStorage.getItem("optimavo_preview_company_id")}catch{return!1}}catch{return!1}})())return t.jsx(ir,{});const d=window.location.search.includes("session_id=");if(d)try{sessionStorage.setItem("just_upgraded","1")}catch{}const u=(()=>{try{return!!sessionStorage.getItem("just_upgraded")}catch{return!1}})();if(h.useEffect(()=>{if(!d||!r||a)return;const g=new URLSearchParams(window.location.search).get("session_id");g&&(l(!0),fetch("https://review-scraper-production-9324.up.railway.app/billing/verify-checkout",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:g})}).then(v=>v.json()).then(()=>o()).catch(()=>{}).finally(()=>l(!1)))},[d,r]),i||a)return t.jsx("div",{style:{minHeight:"100vh",display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:"#f6f8fa"},children:t.jsx("div",{style:{width:48,height:64,overflow:"hidden"},children:t.jsx("img",{src:"/loading-animation.gif",alt:"Ladenâ¦",style:{width:64,height:64,objectFit:"contain",marginLeft:-2}})})});if(!r)return t.jsx(ee,{to:"/login",replace:!0});if(!e||!e.onboarding_done)return e!=null&&e.company_id&&(e==null?void 0:e.role)!=="owner"?t.jsx(ee,{to:"/invite-onboarding",replace:!0}):t.jsx(ee,{to:"/onboarding",replace:!0});const f=!!n&&(n.plan==="erstanalyse"||n.plan==="monitoring"),p=s;return d||u?t.jsx(ir,{}):!p&&f?t.jsx(ir,{}):p?t.jsx(ir,{}):t.jsx(ir,{})}function Ru(){const{session:r,profile:e,loading:n}=$e();return qn?t.jsx(ee,{to:"/dashboard",replace:!0}):n?null:r&&(e!=null&&e.onboarding_done)?t.jsx(ee,{to:"/dashboard",replace:!0}
100):r&&(e!=null&&e.company_id)&&(e==null?void 0:e.role)!=="owner"&&!(e!=null&&e.onboarding_done)?t.jsx(ee,{to:"/invite-onboarding",replace:!0}):r?t.jsx(ee,{to:"/onboarding",replace:!0}):t.jsx(ee,{to:"/login",replace:!0})}function Tu(){return Cu?t.jsx(pr,{children:t.jsx(K,{path:"/*",element:t.jsx(_u,{noToken:!0})})}):t.jsxs(pr,{children:[t.jsx(K,{path:"/auth/callback",element:t.jsx(ku,{})}),t.jsx(K,{path:"/login",element:qn?t.jsx(ee,{to:"/dashboard",replace:!0}):t.jsx(Hc,{children:t.jsx(qc,{})})}),t.jsx(K,{path:"/register",element:t.jsx(ee,{to:"/login",replace:!0})}),t.jsx(K,{path:"/logout",element:t.jsx(Jc,{})}),t.jsx(K,{path:"/reset-password",element:t.jsx(Gc,{})}),t.jsx(K,{path:"/admin/*",element:t.jsx(Eu,{})}),t.jsx(K,{path:"/invite-onboarding",element:t.jsx(Bs,{children:t.jsx(ad,{})})}),t.jsx(K,{path:"/onboarding/*",element:t.jsx(Bs,{children:t.jsx(id,{})})}),t.jsx(K,{path:"/upgrade",element:t.jsx(h.Suspense,{fallback:t.jsx("div",{style:{minHeight:"100vh",display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:"#f8fafc"},children:t.jsx("div",{style:{width:48,height:64,overflow:"hidden"},children:t.jsx("img",{src:"/loading-animation.gif",alt:"Ladenâ¦",style:{width:64,height:64,objectFit:"contain",marginLeft:-2}})})}),children:t.jsx(Su,{})})}),t.jsx(K,{path:"/kontakt",element:t.jsx(Dd,{})}),t.jsx(K,{path:"/",element:t.jsx(Ru,{})}),t.jsx(K,{path:"/*",element:t.jsx(Au,{})})]})}class Iu extends h.Component{constructor(e){super(e),this.state={hasError:!1,error:null}}static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidCatch(e,n){console.error("[TopLevelErrorBoundary]",e.message),Do(e,{extra:{componentStack:n==null?void 0:n.componentStack}}),sessionStorage.getItem("_eb_reloaded")||(sessionStorage.setItem("_eb_reloaded","1"),setTimeout(()=>window.location.reload(),2e3))}render(){if(this.state.hasError){const e=sessionStorage.getItem("_eb_reloaded");return t.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",minHeight:"100vh",gap:16,fontFamily:"-apple-system, BlinkMacSystemFont, sans-serif",backgroundColor:"#f6f8fa"},children:[t.jsx("div",{style:{fontSize:16,fontWeight:600,color:"#24292f"},children:e?"Es ist ein Fehler aufgetreten":"Dashboard wird neu geladen..."}),e&&t.jsx("button",{onClick:()=>{sessionStorage.removeItem("_eb_reloaded"),window.location.reload()},style:{padding:"10px 20px",borderRadius:8,border:"1px solid #d0d7de",background:"#fff",cursor:"pointer",fontSize:14,fontWeight:500},children:"Erneut versuchen"})]})}return this.props.children}}ro.createRoot(document.getElementById("root")).render(t.jsx(Dn.StrictMode,{children:t.jsx(Iu,{children:t.jsx(Yi,{children:t.jsxs(yc,{children:[t.jsx(Tu,{}),t.jsx(Ac,{}),t.jsx(Mc,{})]})})})}));export{Ei as D,Ee as _,Jt as a,qt as b,fd as c,t as j,ie as s,$e as u};
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.